context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public static class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, null, "exe")]
[InlineData("", "", "")]
[InlineData("file", "file.exe", null)]
[InlineData("file.", "file.exe", "")]
[InlineData("file.exe", "file", "exe")]
[InlineData("file.exe", "file", ".exe")]
[InlineData("file.exe", "file.txt", "exe")]
[InlineData("file.exe", "file.txt", ".exe")]
[InlineData("file.txt.exe", "file.txt.bin", "exe")]
[InlineData("dir/file.exe", "dir/file.t", "exe")]
[InlineData("dir/file.t", "dir/file.exe", "t")]
[InlineData("dir/file.exe", "dir/file", "exe")]
public static void ChangeExtension(string expected, string path, string newExtension)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Fact]
public static void GetDirectoryName()
{
Assert.Null(Path.GetDirectoryName(null));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(string.Empty));
Assert.Equal(string.Empty, Path.GetDirectoryName("."));
Assert.Equal(string.Empty, Path.GetDirectoryName(".."));
Assert.Equal(string.Empty, Path.GetDirectoryName("baz"));
Assert.Equal("dir", Path.GetDirectoryName(Path.Combine("dir", "baz")));
Assert.Equal(Path.Combine("dir", "baz"), Path.GetDirectoryName(Path.Combine("dir", "baz", "bar")));
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetDirectoryName_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData(".exe", "file.exe")]
[InlineData("", "file")]
[InlineData(null, null)]
[InlineData("", "file.")]
[InlineData(".s", "file.s")]
[InlineData("", "test/file")]
[InlineData(".extension", "test/file.extension")]
public static void GetExtension(string expected, string path)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(".e xe", "file.e xe")]
[InlineData(". ", "file. ")]
[InlineData(". ", " file. ")]
[InlineData(".extension", " file.extension")]
[InlineData(".exten\tsion", "file.exten\tsion")]
public static void GetExtension_Unix(string expected, string path)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[Fact]
public static void GetFileName()
{
Assert.Equal(null, Path.GetFileName(null));
Assert.Equal(string.Empty, Path.GetFileName(string.Empty));
Assert.Equal(".", Path.GetFileName("."));
Assert.Equal("..", Path.GetFileName(".."));
Assert.Equal("file", Path.GetFileName("file"));
Assert.Equal("file.", Path.GetFileName("file."));
Assert.Equal("file.exe", Path.GetFileName("file.exe"));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("baz", "file.exe")));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileName(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
[Fact]
public static void GetFileNameWithoutExtension()
{
Assert.Equal(null, Path.GetFileNameWithoutExtension(null));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(string.Empty));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file"));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file.exe"));
Assert.Equal("file", Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(string.Empty));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
[InlineData(@"\\?\UNC\test\unc\path\to\something", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b", @"\\?\UNC\a\b")]
[InlineData(@"\\?\UNC\a\b\", @"\\?\UNC\a\b")]
[InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), (IEnumerable<char>)Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Throws<ArgumentException>(() => Path.ChangeExtension(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, bad, bad, bad, bad));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(bad));
Assert.Throws<ArgumentException>(() => Path.GetExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileName(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileNameWithoutExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(bad));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(bad));
Assert.Throws<ArgumentException>(() => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, null);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(string.Empty));
}
[Fact]
public static void GetFullPath_BasicExpansions()
{
string curDir = Directory.GetCurrentDirectory();
// Current directory => current directory
Assert.Equal(curDir, Path.GetFullPath(curDir));
// "." => current directory
Assert.Equal(curDir, Path.GetFullPath("."));
// ".." => up a directory
Assert.Equal(Path.GetDirectoryName(curDir), Path.GetFullPath(".."));
// "dir/./././." => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, ".", ".", ".", ".", ".")));
// "dir///." => "dir"
Assert.Equal(curDir, Path.GetFullPath(curDir + new string(Path.DirectorySeparatorChar, 3) + "."));
// "dir/../dir/./../dir" => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir))));
// "C:\somedir\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "somedir", "..")));
// "C:\." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), ".")));
// "C:\..\..\..\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", "..")));
// "C:\\\" => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3)));
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(curDir, Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_URIFormatNotSupported()
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath("http://www.microsoft.com"));
Assert.Throws<ArgumentException>(() => Path.GetFullPath("file://www.microsoft.com"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
[InlineData(@"bad::$DATA")]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo\.")]
[InlineData(@"\\?\C:\Foo\..")]
public static void GetFullPath_Windows_ArgumentExceptionPaths(string path)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', 255) + @"\"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.Equal(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
Assert.Equal(path, Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\server\share", @"\\server\share")]
[InlineData(@"\\server\share", @" \\server\share")]
[InlineData(@"\\server\share\dir", @"\\server\share\dir")]
[InlineData(@"\\server\share", @"\\server\share\.")]
[InlineData(@"\\server\share", @"\\server\share\..")]
[InlineData(@"\\server\share\", @"\\server\share\ ")]
[InlineData(@"\\server\ share\", @"\\server\ share\")]
[InlineData(@"\\?\UNC\server\share", @"\\?\UNC\server\share")]
[InlineData(@"\\?\UNC\server\share\dir", @"\\?\UNC\server\share\dir")]
[InlineData(@"\\?\UNC\server\share\. ", @"\\?\UNC\server\share\. ")]
[InlineData(@"\\?\UNC\server\share\.. ", @"\\?\UNC\server\share\.. ")]
[InlineData(@"\\?\UNC\server\share\ ", @"\\?\UNC\server\share\ ")]
[InlineData(@"\\?\UNC\server\ share\", @"\\?\UNC\server\ share\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\server\")]
[InlineData(@"\\server\\")]
[InlineData(@"\\server\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server")]
[InlineData(@"\\?\UNC\server\")]
[InlineData(@"\\?\UNC\server\\")]
[InlineData(@"\\?\UNC\server\..")]
[InlineData(@"\\?\UNC\server\share\.")]
[InlineData(@"\\?\UNC\server\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(invalidPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
// Make sure the shortened name expands back to the original one
Assert.Equal(tempFilePath, Path.GetFullPath(sb.ToString()));
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
using DebugCallback = Interop.Http.DebugCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary>
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
/// <summary>Maximum content length where we'll use COPYPOSTFIELDS to let libcurl dup the content.</summary>
private const int InMemoryPostContentLimit = 32 * 1024; // arbitrary limit; could be tweaked in the future based on experimentation
/// <summary>Debugging flag used to enable CURLOPT_VERBOSE to dump to stderr when not redirecting it to the event source.</summary>
private static readonly bool s_curlDebugLogging = Environment.GetEnvironmentVariable("CURLHANDLER_DEBUG_VERBOSE") == "true";
internal readonly CurlHandler _handler;
internal readonly MultiAgent _associatedMultiAgent;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal Stream _requestContentStream;
internal long? _requestContentStreamStartingPosition;
internal bool _inMemoryPostContent;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal SendTransferState _sendTransferState;
internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, MultiAgent agent, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
Debug.Assert(handler != null, $"Expected non-null {nameof(handler)}");
Debug.Assert(agent != null, $"Expected non-null {nameof(agent)}");
Debug.Assert(requestMessage != null, $"Expected non-null {nameof(requestMessage)}");
_handler = handler;
_associatedMultiAgent = agent;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
_responseMessage = new CurlResponseMessage(this);
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
EventSourceTrace("Configuring request.");
// Before setting any other options, turn on curl's debug tracing
// if desired. CURLOPT_VERBOSE may also be set subsequently if
// EventSource tracing is enabled.
if (s_curlDebugLogging)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
}
// Before actually configuring the handle based on the state of the request,
// do any necessary cleanup of the request object.
SanitizeRequestMessage();
// Configure the handle
SetUrl();
SetNetworkingOptions();
SetMultithreading();
SetTimeouts();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler._useDefaultCredentials ? GetDefaultCredentialAndAuth() : _handler.GetCredentials(_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
EventSourceTrace("Done configuring request.");
}
public void EnsureResponseMessagePublished()
{
// If the response message hasn't been published yet, do any final processing of it before it is.
if (!Task.IsCompleted)
{
EventSourceTrace("Publishing response message");
// On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length
// headers are removed from the response. Do the same thing here.
DecompressionMethods dm = _handler.AutomaticDecompression;
if (dm != DecompressionMethods.None)
{
HttpContentHeaders contentHeaders = _responseMessage.Content.Headers;
IEnumerable<string> encodings;
if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings))
{
foreach (string encoding in encodings)
{
if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) ||
((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase)))
{
contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding);
contentHeaders.Remove(HttpKnownHeaderNames.ContentLength);
break;
}
}
}
}
}
// Now ensure it's published.
bool completedTask = TrySetResult(_responseMessage);
Debug.Assert(completedTask || Task.IsCompletedSuccessfully,
"If the task was already completed, it should have been completed successfully; " +
"we shouldn't be completing as successful after already completing as failed.");
// If we successfully transitioned it to be completed, we also handed off lifetime ownership
// of the response to the owner of the task. Transition our reference on the EasyRequest
// to be weak instead of strong, so that we don't forcibly keep it alive.
if (completedTask)
{
Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper");
_selfStrongToWeakReference.MakeWeak();
}
}
public void CleanupAndFailRequest(Exception error)
{
try
{
Cleanup();
}
catch (Exception exc)
{
// This would only happen in an aggregious case, such as a Stream failing to seek when
// it claims to be able to, but in case something goes very wrong, make sure we don't
// lose the exception information.
error = new AggregateException(error, exc);
}
finally
{
FailRequest(error);
}
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
EventSourceTrace("Failing request: {0}", error);
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is InvalidOperationException || error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream. Also don't dispose of the request content
// stream; that'll be handled by the disposal of the request content by the HttpClient,
// and doing it here prevents reuse by an intermediate handler sitting between the client
// and this handler.
// However, if we got an original position for the request stream, we seek back to that position,
// for the corner case where the stream does get reused before it's disposed by the HttpClient
// (if the same request object is used multiple times from an intermediate handler, we'll be using
// ReadAsStreamAsync, which on the same request object will return the same stream object, which
// we've already advanced).
if (_requestContentStream != null && _requestContentStream.CanSeek)
{
Debug.Assert(_requestContentStreamStartingPosition.HasValue, "The stream is seekable, but we don't have a starting position?");
_requestContentStream.Position = _requestContentStreamStartingPosition.GetValueOrDefault();
}
// Dispose of the underlying easy handle. We're no longer processing it.
_easyHandle?.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
_requestHeaders?.Dispose();
// Dispose native callback resources
_callbackHandle?.Dispose();
// Release any send transfer state, which will return its buffer to the pool
_sendTransferState?.Dispose();
}
private void SanitizeRequestMessage()
{
// Make sure Transfer-Encoding and Content-Length make sense together.
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
}
}
private void SetUrl()
{
Uri requestUri = _requestMessage.RequestUri;
long scopeId;
if (IsLinkLocal(requestUri, out scopeId))
{
// Uri.AbsoluteUri doesn't include the ScopeId/ZoneID, so if it is link-local,
// we separately pass the scope to libcurl.
EventSourceTrace("ScopeId: {0}", scopeId);
SetCurlOption(CURLoption.CURLOPT_ADDRESS_SCOPE, scopeId);
}
EventSourceTrace("Url: {0}", requestUri);
string idnHost = requestUri.IdnHost;
string url = requestUri.Host == idnHost ?
requestUri.AbsoluteUri :
new UriBuilder(requestUri) { Host = idnHost }.Uri.AbsoluteUri;
SetCurlOption(CURLoption.CURLOPT_URL, url);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
private static bool IsLinkLocal(Uri url, out long scopeId)
{
IPAddress ip;
if (IPAddress.TryParse(url.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal)
{
scopeId = ip.ScopeId;
return true;
}
scopeId = 0;
return false;
}
private void SetNetworkingOptions()
{
// Disable the TCP Nagle algorithm. It's disabled by default starting with libcurl 7.50.2,
// and when enabled has a measurably negative impact on latency in key scenarios
// (e.g. POST'ing small-ish data).
SetCurlOption(CURLoption.CURLOPT_TCP_NODELAY, 1L);
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetTimeouts()
{
// Set timeout limit on the connect phase.
SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, int.MaxValue);
// Override the default DNS cache timeout. libcurl defaults to a 1 minute
// timeout, but we extend that to match the Windows timeout of 10 minutes.
const int DnsCacheTimeoutSeconds = 10 * 60;
SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections);
}
/// <summary>
/// When a Location header is received along with a 3xx status code, it's an indication
/// that we're likely to redirect. Prepare the easy handle in case we do.
/// </summary>
internal void SetPossibleRedirectForLocationHeader(string location)
{
// Reset cookies in case we redirect. Below we'll set new cookies for the
// new location if we have any.
if (_handler._useCookies)
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
}
// Parse the location string into a relative or absolute Uri, then combine that
// with the current request Uri to get the new location.
var updatedCredentials = default(KeyValuePair<NetworkCredential, CURLAUTH>);
Uri newUri;
if (Uri.TryCreate(_requestMessage.RequestUri, location.Trim(), out newUri))
{
// Just as with WinHttpHandler, for security reasons, we drop the server credential if it is
// anything other than a CredentialCache. We allow credentials in a CredentialCache since they
// are specifically tied to URIs.
updatedCredentials = _handler._useDefaultCredentials ?
GetDefaultCredentialAndAuth() :
GetCredentials(newUri, _handler.Credentials as CredentialCache, s_orderedAuthTypes);
// Reset proxy - it is possible that the proxy has different credentials for the new URI
SetProxyOptions(newUri);
// Set up new cookies
if (_handler._useCookies)
{
SetCookieOption(newUri);
}
}
// Set up the new credentials, either for the new Uri if we were able to get it,
// or to empty creds if we couldn't.
SetCredentialsOptions(updatedCredentials);
// Set the headers again. This is a workaround for libcurl's limitation in handling
// headers with empty values.
SetRequestHeaders();
}
private void SetContentLength(CURLoption lengthOption)
{
Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE);
if (_requestMessage.Content == null)
{
// Tell libcurl there's no data to be sent.
SetCurlOption(lengthOption, 0L);
return;
}
long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength;
if (contentLengthOpt != null)
{
long contentLength = contentLengthOpt.GetValueOrDefault();
if (contentLength <= int.MaxValue)
{
// Tell libcurl how much data we expect to send.
SetCurlOption(lengthOption, contentLength);
}
else
{
// Similarly, tell libcurl how much data we expect to send. However,
// as the amount is larger than a 32-bit value, switch to the "_LARGE"
// equivalent libcurl options.
SetCurlOption(
lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE,
contentLength);
}
EventSourceTrace("Set content length: {0}", contentLength);
return;
}
// There is content but we couldn't determine its size. Don't set anything.
}
private void SetVerb()
{
EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
// Set the content length if we have one available. We must set POSTFIELDSIZE before setting
// COPYPOSTFIELDS, as the setting of COPYPOSTFIELDS uses the size to know how much data to read
// out; if POSTFIELDSIZE is not done before, COPYPOSTFIELDS will look for a null terminator, and
// we don't necessarily have one.
SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE);
// For most content types and most HTTP methods, we use a callback that lets libcurl
// get data from us if/when it wants it. However, as an optimization, for POSTs that
// use content already known to be entirely in memory, we hand that data off to libcurl
// ahead of time. This not only saves on costs associated with all of the async transfer
// between the content and libcurl, it also lets libcurl do larger writes that can, for
// example, enable fewer packets to be sent on the wire.
var inMemContent = _requestMessage.Content as ByteArrayContent;
ArraySegment<byte> contentSegment;
if (inMemContent != null &&
inMemContent.TryGetBuffer(out contentSegment) &&
contentSegment.Count <= InMemoryPostContentLimit) // skip if we'd be forcing libcurl to allocate/copy a large buffer
{
// Only pre-provide the content if the content still has its ContentLength
// and if that length matches the segment. If it doesn't, something has been overridden,
// and we should rely on reading from the content stream to get the data.
long? contentLength = inMemContent.Headers.ContentLength;
if (contentLength.HasValue && contentLength.GetValueOrDefault() == contentSegment.Count)
{
_inMemoryPostContent = true;
// Debug double-check array segment; this should all have been validated by the ByteArrayContent
Debug.Assert(contentSegment.Array != null, "Expected non-null byte content array");
Debug.Assert(contentSegment.Count >= 0, $"Expected non-negative byte content count {contentSegment.Count}");
Debug.Assert(contentSegment.Offset >= 0, $"Expected non-negative byte content offset {contentSegment.Offset}");
Debug.Assert(contentSegment.Array.Length - contentSegment.Offset >= contentSegment.Count,
$"Expected offset {contentSegment.Offset} + count {contentSegment.Count} to be within array length {contentSegment.Array.Length}");
// Hand the data off to libcurl with COPYPOSTFIELDS for it to copy out the data. (The alternative
// is to use POSTFIELDS, which would mean we'd need to pin the array in the ByteArrayContent for the
// duration of the request. Often with a ByteArrayContent, the data will be small and the copy cheap.)
unsafe
{
fixed (byte* inMemContentPtr = contentSegment.Array)
{
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, new IntPtr(inMemContentPtr + contentSegment.Offset));
EventSourceTrace("Set post fields rather than using send content callback");
}
}
}
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
EventSourceTrace("HTTP version: {0}", v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
EventSourceTrace("Unsupported protocol: {0}", v);
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
EventSourceTrace<string>("Encoding: {0}", encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (!_handler._useProxy)
{
// Explicitly disable the use of a proxy. This will prevent libcurl from using
// any proxy, including ones set via environment variable.
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("UseProxy false, disabling proxy");
return;
}
if (_handler.Proxy == null)
{
// UseProxy was true, but Proxy was null. Let libcurl do its default handling,
// which includes checking the http_proxy environment variable.
EventSourceTrace("UseProxy true, Proxy null, using default proxy");
// Since that proxy set in an environment variable might require a username and password,
// use the default proxy credentials if there are any. Currently only NetworkCredentials
// are used, as we can't query by the proxy Uri, since we don't know it.
SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential);
return;
}
// Custom proxy specified.
Uri proxyUri;
try
{
// Should we bypass a proxy for this URI?
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy");
return;
}
// Get the proxy Uri for this request.
proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
EventSourceTrace("GetProxy returned null, using default.");
return;
}
}
catch (PlatformNotSupportedException)
{
// WebRequest.DefaultWebProxy throws PlatformNotSupportedException,
// in which case we should use the default rather than the custom proxy.
EventSourceTrace("PlatformNotSupportedException from proxy, using default");
return;
}
// Configure libcurl with the gathered proxy information
// uri.AbsoluteUri/ToString() omit IPv6 scope IDs. SerializationInfoString ensures these details
// are included, but does not properly handle international hosts. As a workaround we check whether
// the host is a link-local IP address, and based on that either return the SerializationInfoString
// or the AbsoluteUri. (When setting the request Uri itself, we instead use CURLOPT_ADDRESS_SCOPE to
// set the scope id and the url separately, avoiding these issues and supporting versions of libcurl
// prior to v7.37 that don't support parsing scope IDs out of the url's host. As similar feature
// doesn't exist for proxies.)
IPAddress ip;
string proxyUrl = IPAddress.TryParse(proxyUri.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal ?
proxyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped) :
proxyUri.AbsoluteUri;
EventSourceTrace<string>("Proxy: {0}", proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(
proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes);
SetProxyCredentials(credentialScheme.Key);
}
private void SetProxyCredentials(NetworkCredential credentials)
{
if (credentials == CredentialCache.DefaultCredentials)
{
EventSourceTrace("DefaultCredentials set for proxy. Skipping.");
}
else if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
// Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode
// them in order to allow, for example, a colon in the username.
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
WebUtility.UrlEncode(credentials.UserName) + ":" + WebUtility.UrlEncode(credentials.Password) :
string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain));
EventSourceTrace("Proxy credentials set.");
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
EventSourceTrace("Credentials cleared.");
SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
credentials.Domain + "\\" + credentials.UserName;
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
EventSourceTrace("Credentials set.");
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetDefaultCredentialAndAuth() =>
new KeyValuePair<NetworkCredential, CURLAUTH>(CredentialCache.DefaultNetworkCredentials, CURLAUTH.Negotiate);
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookies)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
EventSourceTrace<string>("Cookies: {0}", cookieValues);
}
}
internal void SetRequestHeaders()
{
var slist = new SafeCurlSListHandle();
bool suppressContentType;
if (_requestMessage.Content != null)
{
// Add content request headers
AddRequestHeaders(_requestMessage.Content.Headers, slist);
suppressContentType = _requestMessage.Content.Headers.ContentType == null;
}
else
{
suppressContentType = true;
}
if (suppressContentType)
{
// Remove the Content-Type header libcurl adds by default.
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType));
}
// Add request headers
AddRequestHeaders(_requestMessage.Headers, slist);
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding));
}
// Since libcurl adds an Expect header if it sees enough post data, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.ExpectContinue.HasValue &&
!_requestMessage.Headers.ExpectContinue.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoExpect));
}
if (!slist.IsInvalid)
{
SafeCurlSListHandle prevList = _requestHeaders;
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
prevList?.Dispose();
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal bool ServerCertificateValidationCallbackAcceptsAll => ReferenceEquals(
_handler.ServerCertificateCustomValidationCallback,
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator);
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback,
DebugCallback debugCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
ThrowOOMIfInvalid(_callbackHandle);
// If we're sending data as part of the request and it wasn't already added as
// in-memory data, add callbacks for sending request data.
if (!_inMemoryPostContent && _requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
}
if (NetEventSource.IsEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
_easyHandle,
debugCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
if (curlResult != CURLcode.CURLE_OK)
{
EventSourceTrace("Failed to register debug callback.");
}
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
return Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
if (string.Equals(header.Key, HttpKnownHeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase))
{
// avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE
continue;
}
string headerKeyAndValue;
string[] values = header.Value as string[];
Debug.Assert(values != null, "Implementation detail, but expected Value to be a string[]");
if (values != null && values.Length < 2)
{
// 0 or 1 values
headerKeyAndValue = values.Length == 0 || string.IsNullOrEmpty(values[0]) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + values[0];
}
else
{
// Either Values wasn't a string[], or it had 2 or more items. Both are handled by GetHeaderString.
string headerValue = headers.GetHeaderString(header.Key);
headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon needed by libcurl; see above
header.Key + ": " + headerValue;
}
ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue));
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
private static void ThrowOOMIfFalse(bool appendResult)
{
if (!appendResult)
{
ThrowOOM();
}
}
private static void ThrowOOMIfInvalid(SafeHandle handle)
{
if (handle.IsInvalid)
{
ThrowOOM();
}
}
private static void ThrowOOM()
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
internal sealed class SendTransferState : IDisposable
{
internal byte[] Buffer { get; private set; }
internal int Offset { get; set; }
internal int Count { get; set; }
internal Task<int> Task { get; private set; }
public SendTransferState(int bufferLength)
{
Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}");
Buffer = ArrayPool<byte>.Shared.Rent(bufferLength);
}
public void Dispose()
{
byte[] b = Buffer;
if (b != null)
{
Buffer = null;
ArrayPool<byte>.Shared.Return(b);
}
}
public void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
Task = task;
Offset = offset;
Count = count;
}
}
internal void StoreLastEffectiveUri()
{
IntPtr urlCharPtr; // do not free; will point to libcurl private memory
CURLcode urlResult = Interop.Http.EasyGetInfoPointer(_easyHandle, Interop.Http.CURLINFO.CURLINFO_EFFECTIVE_URL, out urlCharPtr);
if (urlResult == CURLcode.CURLE_OK && urlCharPtr != IntPtr.Zero)
{
string url = Marshal.PtrToStringAnsi(urlCharPtr);
if (url != _requestMessage.RequestUri.OriginalString)
{
Uri finalUri;
if (Uri.TryCreate(url, UriKind.Absolute, out finalUri))
{
_requestMessage.RequestUri = finalUri;
}
}
return;
}
Debug.Fail("Expected to be able to get the last effective Uri from libcurl");
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName);
}
private void EventSourceTrace(string message, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Xml;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using log4net;
using log4net.Config;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
namespace OpenSim.Server.Base
{
public class ServicesServerBase : ServerBase
{
// Logger
//
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// Command line args
//
protected string[] m_Arguments;
public string ConfigDirectory
{
get;
private set;
}
// Run flag
//
private bool m_Running = true;
// Handle all the automagical stuff
//
public ServicesServerBase(string prompt, string[] args) : base()
{
// Save raw arguments
//
m_Arguments = args;
// Read command line
//
ArgvConfigSource argvConfig = new ArgvConfigSource(args);
argvConfig.AddSwitch("Startup", "console", "c");
argvConfig.AddSwitch("Startup", "logfile", "l");
argvConfig.AddSwitch("Startup", "inifile", "i");
argvConfig.AddSwitch("Startup", "prompt", "p");
argvConfig.AddSwitch("Startup", "logconfig", "g");
// Automagically create the ini file name
//
string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
string iniFile = fileName + ".ini";
string logConfig = null;
IConfig startupConfig = argvConfig.Configs["Startup"];
if (startupConfig != null)
{
// Check if a file name was given on the command line
//
iniFile = startupConfig.GetString("inifile", iniFile);
//
// Check if a prompt was given on the command line
prompt = startupConfig.GetString("prompt", prompt);
//
// Check for a Log4Net config file on the command line
logConfig =startupConfig.GetString("logconfig",logConfig);
}
// Find out of the file name is a URI and remote load it
// if it's possible. Load it as a local file otherwise.
//
Uri configUri;
try
{
if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp)
{
XmlReader r = XmlReader.Create(iniFile);
Config = new XmlConfigSource(r);
}
else
{
Config = new IniConfigSource(iniFile);
}
}
catch (Exception e)
{
System.Console.WriteLine("Error reading from config source. {0}", e.Message);
Environment.Exit(1);
}
// Merge the configuration from the command line into the
// loaded file
//
Config.Merge(argvConfig);
// Refresh the startupConfig post merge
//
if (Config.Configs["Startup"] != null)
{
startupConfig = Config.Configs["Startup"];
}
ConfigDirectory = startupConfig.GetString("ConfigDirectory", ".");
prompt = startupConfig.GetString("Prompt", prompt);
// Allow derived classes to load config before the console is
// opened.
//
ReadConfig();
// Create main console
//
string consoleType = "local";
if (startupConfig != null)
consoleType = startupConfig.GetString("console", consoleType);
if (consoleType == "basic")
{
MainConsole.Instance = new CommandConsole(prompt);
}
else if (consoleType == "rest")
{
MainConsole.Instance = new RemoteConsole(prompt);
((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
}
else
{
MainConsole.Instance = new LocalConsole(prompt);
}
m_console = MainConsole.Instance;
if (logConfig != null)
{
FileInfo cfg = new FileInfo(logConfig);
XmlConfigurator.Configure(cfg);
}
else
{
XmlConfigurator.Configure();
}
LogEnvironmentInformation();
RegisterCommonAppenders(startupConfig);
if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
{
CreatePIDFile(startupConfig.GetString("PIDFile"));
}
RegisterCommonCommands();
RegisterCommonComponents(Config);
// Allow derived classes to perform initialization that
// needs to be done after the console has opened
//
Initialise();
}
public bool Running
{
get { return m_Running; }
}
public virtual int Run()
{
Watchdog.Enabled = true;
MemoryWatchdog.Enabled = true;
while (m_Running)
{
try
{
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
RemovePIDFile();
return 0;
}
protected override void ShutdownSpecific()
{
m_Running = false;
m_log.Info("[CONSOLE] Quitting");
base.ShutdownSpecific();
}
protected virtual void ReadConfig()
{
}
protected virtual void Initialise()
{
}
}
}
| |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace MahApps.Metro.Controls
{
public class DataGridNumericUpDownColumn : DataGridBoundColumn
{
private static Style _defaultEditingElementStyle;
private static Style _defaultElementStyle;
private double minimum = (double)NumericUpDown.MinimumProperty.DefaultMetadata.DefaultValue;
private double maximum = (double)NumericUpDown.MaximumProperty.DefaultMetadata.DefaultValue;
private double interval = (double)NumericUpDown.IntervalProperty.DefaultMetadata.DefaultValue;
private string stringFormat = (string)NumericUpDown.StringFormatProperty.DefaultMetadata.DefaultValue;
private bool hideUpDownButtons = (bool)NumericUpDown.HideUpDownButtonsProperty.DefaultMetadata.DefaultValue;
private double upDownButtonsWidth = (double)NumericUpDown.UpDownButtonsWidthProperty.DefaultMetadata.DefaultValue;
private Binding foregroundBinding;
static DataGridNumericUpDownColumn()
{
ElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultElementStyle));
EditingElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle));
}
public static Style DefaultEditingElementStyle
{
get
{
if (_defaultEditingElementStyle == null)
{
Style style = new Style(typeof(NumericUpDown));
style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top));
style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled));
style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled));
style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0d)));
style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center));
style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d));
style.Seal();
_defaultEditingElementStyle = style;
}
return _defaultEditingElementStyle;
}
}
public static Style DefaultElementStyle
{
get
{
if (_defaultElementStyle == null)
{
Style style = new Style(typeof(NumericUpDown));
style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top));
style.Setters.Add(new Setter(UIElement.IsHitTestVisibleProperty, false));
style.Setters.Add(new Setter(UIElement.FocusableProperty, false));
style.Setters.Add(new Setter(NumericUpDown.HideUpDownButtonsProperty, true));
style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0d)));
style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Transparent));
style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled));
style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled));
style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center));
style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d));
style.Setters.Add(new Setter(ControlsHelper.DisabledVisualElementVisibilityProperty, Visibility.Collapsed));
style.Seal();
_defaultElementStyle = style;
}
return _defaultElementStyle;
}
}
internal void ApplyBinding(DependencyObject target, DependencyProperty property)
{
BindingBase binding = Binding;
if (binding != null)
{
BindingOperations.SetBinding(target, property, binding);
}
else
{
BindingOperations.ClearBinding(target, property);
}
}
private static void ApplyBinding(BindingBase binding, DependencyObject target, DependencyProperty property)
{
if (binding != null)
{
BindingOperations.SetBinding(target, property, binding);
}
else
{
BindingOperations.ClearBinding(target, property);
}
}
internal void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element)
{
Style style = PickStyle(isEditing, defaultToElementStyle);
if (style != null)
{
element.Style = style;
}
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
return GenerateNumericUpDown(true, cell);
}
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
NumericUpDown generateNumericUpDown = GenerateNumericUpDown(false, cell);
generateNumericUpDown.HideUpDownButtons = true;
return generateNumericUpDown;
}
private NumericUpDown GenerateNumericUpDown(bool isEditing, DataGridCell cell)
{
NumericUpDown numericUpDown = (cell != null) ? (cell.Content as NumericUpDown) : null;
if (numericUpDown == null)
{
numericUpDown = new NumericUpDown();
// create binding to cell foreground to get changed brush from selection
foregroundBinding = new Binding("Foreground") { Source = cell, Mode = BindingMode.OneWay };
}
ApplyStyle(isEditing, true, numericUpDown);
ApplyBinding(numericUpDown, NumericUpDown.ValueProperty);
if (!isEditing)
{
// bind to cell foreground to get changed brush from selection
ApplyBinding(foregroundBinding, numericUpDown, Control.ForegroundProperty);
}
else
{
// no foreground change for editing
BindingOperations.ClearBinding(numericUpDown, Control.ForegroundProperty);
}
numericUpDown.Minimum = Minimum;
numericUpDown.Maximum = Maximum;
numericUpDown.StringFormat = StringFormat;
numericUpDown.Interval = Interval;
numericUpDown.InterceptArrowKeys = true;
numericUpDown.InterceptMouseWheel = true;
numericUpDown.Speedup = true;
numericUpDown.HideUpDownButtons = HideUpDownButtons;
numericUpDown.UpDownButtonsWidth = UpDownButtonsWidth;
return numericUpDown;
}
private Style PickStyle(bool isEditing, bool defaultToElementStyle)
{
Style style = isEditing ? EditingElementStyle : ElementStyle;
if (isEditing && defaultToElementStyle && (style == null))
{
style = ElementStyle;
}
return style;
}
public double Minimum
{
get { return minimum; }
set { minimum = value; }
}
public double Maximum
{
get { return maximum; }
set { maximum = value; }
}
public double Interval
{
get { return interval; }
set { interval = value; }
}
public string StringFormat
{
get { return stringFormat; }
set { stringFormat = value; }
}
public bool HideUpDownButtons
{
get { return hideUpDownButtons; }
set { hideUpDownButtons = value; }
}
public double UpDownButtonsWidth
{
get { return upDownButtonsWidth; }
set { upDownButtonsWidth = value; }
}
}
}
| |
/*
* Copyright (c) 2006, Clutch, Inc.
* Original Author: Jeff Cesnik
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
namespace OpenMetaverse
{
/// <summary>
/// Base UDP server
/// </summary>
public abstract class OpenSimUDPBase
{
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// This method is called when an incoming packet is received
/// </summary>
/// <param name="buffer">Incoming packet buffer</param>
public abstract void PacketReceived(UDPPacketBuffer buffer);
/// <summary>UDP port to bind to in server mode</summary>
protected int m_udpPort;
/// <summary>Local IP address to bind to in server mode</summary>
protected IPAddress m_localBindAddress;
/// <summary>UDP socket, used in either client or server mode</summary>
private Socket m_udpSocket;
/// <summary>Flag to process packets asynchronously or synchronously</summary>
private bool m_asyncPacketHandling;
/// <summary>
/// Are we to use object pool(s) to reduce memory churn when receiving data?
/// </summary>
public bool UsePools { get; protected set; }
/// <summary>
/// Pool to use for handling data. May be null if UsePools = false;
/// </summary>
protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; }
/// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary>
public bool IsRunningInbound { get; private set; }
/// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
/// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
public bool IsRunningOutbound { get; private set; }
/// <summary>
/// Number of UDP receives.
/// </summary>
public int UdpReceives { get; private set; }
/// <summary>
/// Number of UDP sends
/// </summary>
public int UdpSends { get; private set; }
/// <summary>
/// Number of receives over which to establish a receive time average.
/// </summary>
private readonly static int s_receiveTimeSamples = 500;
/// <summary>
/// Current number of samples taken to establish a receive time average.
/// </summary>
private int m_currentReceiveTimeSamples;
/// <summary>
/// Cumulative receive time for the sample so far.
/// </summary>
private int m_receiveTicksInCurrentSamplePeriod;
/// <summary>
/// The average time taken for each require receive in the last sample.
/// </summary>
public float AverageReceiveTicksForLastSamplePeriod { get; private set; }
#region PacketDropDebugging
/// <summary>
/// For debugging purposes only... random number generator for dropping
/// outbound packets.
/// </summary>
private Random m_dropRandomGenerator;
/// <summary>
/// For debugging purposes only... parameters for a simplified
/// model of packet loss with bursts, overall drop rate should
/// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability)
/// which is about 1% for parameters 0.0015 and 0.15
/// </summary>
private double m_dropProbability = 0.0030;
private double m_dropLengthProbability = 0.15;
private bool m_dropState = false;
/// <summary>
/// For debugging purposes only... parameters to control the time
/// duration over which packet loss bursts can occur, if no packets
/// have been sent for m_dropResetTicks milliseconds, then reset the
/// state of the packet dropper to its default.
/// </summary>
private int m_dropLastTick = 0;
private int m_dropResetTicks = 500;
/// <summary>
/// Debugging code used to simulate dropped packets with bursts
/// </summary>
private bool DropOutgoingPacket()
{
double rnum = m_dropRandomGenerator.NextDouble();
// if the connection has been idle for awhile (more than m_dropResetTicks) then
// reset the state to the default state, don't continue a burst
int curtick = Util.EnvironmentTickCount();
if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks)
m_dropState = false;
m_dropLastTick = curtick;
// if we are dropping packets, then the probability of dropping
// this packet is the probability that we stay in the burst
if (m_dropState)
{
m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false;
}
else
{
m_dropState = (rnum < m_dropProbability) ? true : false;
}
return m_dropState;
}
#endregion PacketDropDebugging
/// <summary>
/// Default constructor
/// </summary>
/// <param name="bindAddress">Local IP address to bind the server to</param>
/// <param name="port">Port to listening for incoming UDP packets on</param>
/// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
public OpenSimUDPBase(IPAddress bindAddress, int port)
{
m_localBindAddress = bindAddress;
m_udpPort = port;
// for debugging purposes only, initializes the random number generator
// used for simulating packet loss
// m_dropRandomGenerator = new Random();
}
/// <summary>
/// Start inbound UDP packet handling.
/// </summary>
/// <param name="recvBufferSize">The size of the receive buffer for
/// the UDP socket. This value is passed up to the operating system
/// and used in the system networking stack. Use zero to leave this
/// value as the default</param>
/// <param name="asyncPacketHandling">Set this to true to start
/// receiving more packets while current packet handler callbacks are
/// still running. Setting this to false will complete each packet
/// callback before the next packet is processed</param>
/// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
/// on the socket to get newer versions of Windows to behave in a sane
/// manner (not throwing an exception when the remote side resets the
/// connection). This call is ignored on Mono where the flag is not
/// necessary</remarks>
public virtual void StartInbound(int recvBufferSize, bool asyncPacketHandling)
{
m_asyncPacketHandling = asyncPacketHandling;
if (!IsRunningInbound)
{
m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
const int SIO_UDP_CONNRESET = -1744830452;
IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
m_log.DebugFormat(
"[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
ipep.Address, ipep.Port);
m_udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
try
{
// This udp socket flag is not supported under mono,
// so we'll catch the exception and continue
m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
}
catch (SocketException)
{
m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
}
// On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
// we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
// leading to a confusing bug.
// By default, Windows does not allow two sockets to bind to the same port.
m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
if (recvBufferSize != 0)
m_udpSocket.ReceiveBufferSize = recvBufferSize;
m_udpSocket.Bind(ipep);
IsRunningInbound = true;
// kick off an async receive. The Start() method will return, the
// actual receives will occur asynchronously and will be caught in
// AsyncEndRecieve().
AsyncBeginReceive();
}
}
/// <summary>
/// Start outbound UDP packet handling.
/// </summary>
public virtual void StartOutbound()
{
m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
IsRunningOutbound = true;
}
public virtual void StopInbound()
{
if (IsRunningInbound)
{
m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
IsRunningInbound = false;
m_udpSocket.Close();
}
}
public virtual void StopOutbound()
{
m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
IsRunningOutbound = false;
}
public virtual bool EnablePools()
{
if (!UsePools)
{
Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
UsePools = true;
return true;
}
return false;
}
public virtual bool DisablePools()
{
if (UsePools)
{
UsePools = false;
// We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
return true;
}
return false;
}
private void AsyncBeginReceive()
{
UDPPacketBuffer buf;
// FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
// on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
// Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
// if (UsePools)
// buf = Pool.GetObject();
// else
buf = new UDPPacketBuffer();
if (IsRunningInbound)
{
try
{
// kick off an async read
m_udpSocket.BeginReceiveFrom(
//wrappedBuffer.Instance.Data,
buf.Data,
0,
UDPPacketBuffer.BUFFER_SIZE,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
//wrappedBuffer);
buf);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.ConnectionReset)
{
m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
bool salvaged = false;
while (!salvaged)
{
try
{
m_udpSocket.BeginReceiveFrom(
//wrappedBuffer.Instance.Data,
buf.Data,
0,
UDPPacketBuffer.BUFFER_SIZE,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
//wrappedBuffer);
buf);
salvaged = true;
}
catch (SocketException) { }
catch (ObjectDisposedException) { return; }
}
m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
}
}
catch (ObjectDisposedException e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
}
catch (Exception e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
}
}
}
private void AsyncEndReceive(IAsyncResult iar)
{
// Asynchronous receive operations will complete here through the call
// to AsyncBeginReceive
if (IsRunningInbound)
{
UdpReceives++;
// Asynchronous mode will start another receive before the
// callback for this packet is even fired. Very parallel :-)
if (m_asyncPacketHandling)
AsyncBeginReceive();
try
{
// get the buffer that was created in AsyncBeginReceive
// this is the received data
UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
int startTick = Util.EnvironmentTickCount();
// get the length of data actually read from the socket, store it with the
// buffer
buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
// call the abstract method PacketReceived(), passing the buffer that
// has just been filled from the socket read.
PacketReceived(buffer);
// If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
// then a particular stat may be inaccurate due to a race condition. We won't worry about this
// since this should be rare and won't cause a runtime problem.
if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
{
AverageReceiveTicksForLastSamplePeriod
= (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
m_receiveTicksInCurrentSamplePeriod = 0;
m_currentReceiveTimeSamples = 0;
}
else
{
m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
m_currentReceiveTimeSamples++;
}
}
catch (SocketException se)
{
m_log.Error(
string.Format(
"[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
UdpReceives, se.ErrorCode),
se);
}
catch (ObjectDisposedException e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
}
catch (Exception e)
{
m_log.Error(
string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
}
finally
{
// if (UsePools)
// Pool.ReturnObject(buffer);
// Synchronous mode waits until the packet callback completes
// before starting the receive to fetch another packet
if (!m_asyncPacketHandling)
AsyncBeginReceive();
}
}
}
public void AsyncBeginSend(UDPPacketBuffer buf)
{
// if (IsRunningOutbound)
// {
// This is strictly for debugging purposes to simulate dropped
// packets when testing throttles & retransmission code
// if (DropOutgoingPacket())
// return;
try
{
m_udpSocket.BeginSendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint,
AsyncEndSend,
buf);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
// }
}
void AsyncEndSend(IAsyncResult result)
{
try
{
// UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
m_udpSocket.EndSendTo(result);
UdpSends++;
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ChannelResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.IpMessaging.V1.Service
{
public class ChannelResource : Resource
{
public sealed class ChannelTypeEnum : StringEnum
{
private ChannelTypeEnum(string value) : base(value) {}
public ChannelTypeEnum() {}
public static implicit operator ChannelTypeEnum(string value)
{
return new ChannelTypeEnum(value);
}
public static readonly ChannelTypeEnum Public = new ChannelTypeEnum("public");
public static readonly ChannelTypeEnum Private = new ChannelTypeEnum("private");
}
private static Request BuildFetchRequest(FetchChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Fetch(FetchChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> FetchAsync(FetchChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchChannelOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchChannelOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static bool Delete(DeleteChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteChannelOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteChannelOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Create(CreateChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> CreateAsync(CreateChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="attributes"> The attributes </param>
/// <param name="type"> The type </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Create(string pathServiceSid,
string friendlyName = null,
string uniqueName = null,
string attributes = null,
ChannelResource.ChannelTypeEnum type = null,
ITwilioRestClient client = null)
{
var options = new CreateChannelOptions(pathServiceSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, Type = type};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="attributes"> The attributes </param>
/// <param name="type"> The type </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> CreateAsync(string pathServiceSid,
string friendlyName = null,
string uniqueName = null,
string attributes = null,
ChannelResource.ChannelTypeEnum type = null,
ITwilioRestClient client = null)
{
var options = new CreateChannelOptions(pathServiceSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, Type = type};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ResourceSet<ChannelResource> Read(ReadChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ChannelResource>.FromJson("channels", response.Content);
return new ResourceSet<ChannelResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ChannelResource>> ReadAsync(ReadChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ChannelResource>.FromJson("channels", response.Content);
return new ResourceSet<ChannelResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="type"> The type </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ResourceSet<ChannelResource> Read(string pathServiceSid,
List<ChannelResource.ChannelTypeEnum> type = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadChannelOptions(pathServiceSid){Type = type, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="type"> The type </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ChannelResource>> ReadAsync(string pathServiceSid,
List<ChannelResource.ChannelTypeEnum> type = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadChannelOptions(pathServiceSid){Type = type, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ChannelResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ChannelResource>.FromJson("channels", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ChannelResource> NextPage(Page<ChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<ChannelResource>.FromJson("channels", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ChannelResource> PreviousPage(Page<ChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<ChannelResource>.FromJson("channels", response.Content);
}
private static Request BuildUpdateRequest(UpdateChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Update(UpdateChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Channel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> UpdateAsync(UpdateChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="attributes"> The attributes </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Channel </returns>
public static ChannelResource Update(string pathServiceSid,
string pathSid,
string friendlyName = null,
string uniqueName = null,
string attributes = null,
ITwilioRestClient client = null)
{
var options = new UpdateChannelOptions(pathServiceSid, pathSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="attributes"> The attributes </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Channel </returns>
public static async System.Threading.Tasks.Task<ChannelResource> UpdateAsync(string pathServiceSid,
string pathSid,
string friendlyName = null,
string uniqueName = null,
string attributes = null,
ITwilioRestClient client = null)
{
var options = new UpdateChannelOptions(pathServiceSid, pathSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ChannelResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ChannelResource object represented by the provided JSON </returns>
public static ChannelResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ChannelResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The sid
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The friendly_name
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The unique_name
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The attributes
/// </summary>
[JsonProperty("attributes")]
public string Attributes { get; private set; }
/// <summary>
/// The type
/// </summary>
[JsonProperty("type")]
[JsonConverter(typeof(StringEnumConverter))]
public ChannelResource.ChannelTypeEnum Type { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The created_by
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
/// <summary>
/// The members_count
/// </summary>
[JsonProperty("members_count")]
public int? MembersCount { get; private set; }
/// <summary>
/// The messages_count
/// </summary>
[JsonProperty("messages_count")]
public int? MessagesCount { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ChannelResource()
{
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.AIPlatform.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedSpecialistPoolServiceClientSnippets
{
/// <summary>Snippet for CreateSpecialistPool</summary>
public void CreateSpecialistPoolRequestObject()
{
// Snippet: CreateSpecialistPool(CreateSpecialistPoolRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
CreateSpecialistPoolRequest request = new CreateSpecialistPoolRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
SpecialistPool = new SpecialistPool(),
};
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = specialistPoolServiceClient.CreateSpecialistPool(request);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceCreateSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateSpecialistPoolAsync</summary>
public async Task CreateSpecialistPoolRequestObjectAsync()
{
// Snippet: CreateSpecialistPoolAsync(CreateSpecialistPoolRequest, CallSettings)
// Additional: CreateSpecialistPoolAsync(CreateSpecialistPoolRequest, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
CreateSpecialistPoolRequest request = new CreateSpecialistPoolRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
SpecialistPool = new SpecialistPool(),
};
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = await specialistPoolServiceClient.CreateSpecialistPoolAsync(request);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceCreateSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateSpecialistPool</summary>
public void CreateSpecialistPool()
{
// Snippet: CreateSpecialistPool(string, SpecialistPool, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
SpecialistPool specialistPool = new SpecialistPool();
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = specialistPoolServiceClient.CreateSpecialistPool(parent, specialistPool);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceCreateSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateSpecialistPoolAsync</summary>
public async Task CreateSpecialistPoolAsync()
{
// Snippet: CreateSpecialistPoolAsync(string, SpecialistPool, CallSettings)
// Additional: CreateSpecialistPoolAsync(string, SpecialistPool, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
SpecialistPool specialistPool = new SpecialistPool();
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = await specialistPoolServiceClient.CreateSpecialistPoolAsync(parent, specialistPool);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceCreateSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateSpecialistPool</summary>
public void CreateSpecialistPoolResourceNames()
{
// Snippet: CreateSpecialistPool(LocationName, SpecialistPool, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
SpecialistPool specialistPool = new SpecialistPool();
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = specialistPoolServiceClient.CreateSpecialistPool(parent, specialistPool);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceCreateSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateSpecialistPoolAsync</summary>
public async Task CreateSpecialistPoolResourceNamesAsync()
{
// Snippet: CreateSpecialistPoolAsync(LocationName, SpecialistPool, CallSettings)
// Additional: CreateSpecialistPoolAsync(LocationName, SpecialistPool, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
SpecialistPool specialistPool = new SpecialistPool();
// Make the request
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> response = await specialistPoolServiceClient.CreateSpecialistPoolAsync(parent, specialistPool);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, CreateSpecialistPoolOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceCreateSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetSpecialistPool</summary>
public void GetSpecialistPoolRequestObject()
{
// Snippet: GetSpecialistPool(GetSpecialistPoolRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
// Make the request
SpecialistPool response = specialistPoolServiceClient.GetSpecialistPool(request);
// End snippet
}
/// <summary>Snippet for GetSpecialistPoolAsync</summary>
public async Task GetSpecialistPoolRequestObjectAsync()
{
// Snippet: GetSpecialistPoolAsync(GetSpecialistPoolRequest, CallSettings)
// Additional: GetSpecialistPoolAsync(GetSpecialistPoolRequest, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
GetSpecialistPoolRequest request = new GetSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
};
// Make the request
SpecialistPool response = await specialistPoolServiceClient.GetSpecialistPoolAsync(request);
// End snippet
}
/// <summary>Snippet for GetSpecialistPool</summary>
public void GetSpecialistPool()
{
// Snippet: GetSpecialistPool(string, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/specialistPools/[SPECIALIST_POOL]";
// Make the request
SpecialistPool response = specialistPoolServiceClient.GetSpecialistPool(name);
// End snippet
}
/// <summary>Snippet for GetSpecialistPoolAsync</summary>
public async Task GetSpecialistPoolAsync()
{
// Snippet: GetSpecialistPoolAsync(string, CallSettings)
// Additional: GetSpecialistPoolAsync(string, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/specialistPools/[SPECIALIST_POOL]";
// Make the request
SpecialistPool response = await specialistPoolServiceClient.GetSpecialistPoolAsync(name);
// End snippet
}
/// <summary>Snippet for GetSpecialistPool</summary>
public void GetSpecialistPoolResourceNames()
{
// Snippet: GetSpecialistPool(SpecialistPoolName, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
SpecialistPoolName name = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]");
// Make the request
SpecialistPool response = specialistPoolServiceClient.GetSpecialistPool(name);
// End snippet
}
/// <summary>Snippet for GetSpecialistPoolAsync</summary>
public async Task GetSpecialistPoolResourceNamesAsync()
{
// Snippet: GetSpecialistPoolAsync(SpecialistPoolName, CallSettings)
// Additional: GetSpecialistPoolAsync(SpecialistPoolName, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
SpecialistPoolName name = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]");
// Make the request
SpecialistPool response = await specialistPoolServiceClient.GetSpecialistPoolAsync(name);
// End snippet
}
/// <summary>Snippet for ListSpecialistPools</summary>
public void ListSpecialistPoolsRequestObject()
{
// Snippet: ListSpecialistPools(ListSpecialistPoolsRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
ListSpecialistPoolsRequest request = new ListSpecialistPoolsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ReadMask = new FieldMask(),
};
// Make the request
PagedEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPools(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (SpecialistPool item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSpecialistPoolsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSpecialistPoolsAsync</summary>
public async Task ListSpecialistPoolsRequestObjectAsync()
{
// Snippet: ListSpecialistPoolsAsync(ListSpecialistPoolsRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
ListSpecialistPoolsRequest request = new ListSpecialistPoolsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ReadMask = new FieldMask(),
};
// Make the request
PagedAsyncEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPoolsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SpecialistPool item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSpecialistPoolsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSpecialistPools</summary>
public void ListSpecialistPools()
{
// Snippet: ListSpecialistPools(string, string, int?, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPools(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (SpecialistPool item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSpecialistPoolsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSpecialistPoolsAsync</summary>
public async Task ListSpecialistPoolsAsync()
{
// Snippet: ListSpecialistPoolsAsync(string, string, int?, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPoolsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SpecialistPool item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSpecialistPoolsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSpecialistPools</summary>
public void ListSpecialistPoolsResourceNames()
{
// Snippet: ListSpecialistPools(LocationName, string, int?, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPools(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (SpecialistPool item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSpecialistPoolsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSpecialistPoolsAsync</summary>
public async Task ListSpecialistPoolsResourceNamesAsync()
{
// Snippet: ListSpecialistPoolsAsync(LocationName, string, int?, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListSpecialistPoolsResponse, SpecialistPool> response = specialistPoolServiceClient.ListSpecialistPoolsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SpecialistPool item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSpecialistPoolsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SpecialistPool item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SpecialistPool> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SpecialistPool item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPool</summary>
public void DeleteSpecialistPoolRequestObject()
{
// Snippet: DeleteSpecialistPool(DeleteSpecialistPoolRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
DeleteSpecialistPoolRequest request = new DeleteSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
Force = false,
};
// Make the request
Operation<Empty, DeleteOperationMetadata> response = specialistPoolServiceClient.DeleteSpecialistPool(request);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceDeleteSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPoolAsync</summary>
public async Task DeleteSpecialistPoolRequestObjectAsync()
{
// Snippet: DeleteSpecialistPoolAsync(DeleteSpecialistPoolRequest, CallSettings)
// Additional: DeleteSpecialistPoolAsync(DeleteSpecialistPoolRequest, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteSpecialistPoolRequest request = new DeleteSpecialistPoolRequest
{
SpecialistPoolName = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]"),
Force = false,
};
// Make the request
Operation<Empty, DeleteOperationMetadata> response = await specialistPoolServiceClient.DeleteSpecialistPoolAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceDeleteSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPool</summary>
public void DeleteSpecialistPool()
{
// Snippet: DeleteSpecialistPool(string, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/specialistPools/[SPECIALIST_POOL]";
// Make the request
Operation<Empty, DeleteOperationMetadata> response = specialistPoolServiceClient.DeleteSpecialistPool(name);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceDeleteSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPoolAsync</summary>
public async Task DeleteSpecialistPoolAsync()
{
// Snippet: DeleteSpecialistPoolAsync(string, CallSettings)
// Additional: DeleteSpecialistPoolAsync(string, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/specialistPools/[SPECIALIST_POOL]";
// Make the request
Operation<Empty, DeleteOperationMetadata> response = await specialistPoolServiceClient.DeleteSpecialistPoolAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceDeleteSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPool</summary>
public void DeleteSpecialistPoolResourceNames()
{
// Snippet: DeleteSpecialistPool(SpecialistPoolName, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
SpecialistPoolName name = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]");
// Make the request
Operation<Empty, DeleteOperationMetadata> response = specialistPoolServiceClient.DeleteSpecialistPool(name);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceDeleteSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteSpecialistPoolAsync</summary>
public async Task DeleteSpecialistPoolResourceNamesAsync()
{
// Snippet: DeleteSpecialistPoolAsync(SpecialistPoolName, CallSettings)
// Additional: DeleteSpecialistPoolAsync(SpecialistPoolName, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
SpecialistPoolName name = SpecialistPoolName.FromProjectLocationSpecialistPool("[PROJECT]", "[LOCATION]", "[SPECIALIST_POOL]");
// Make the request
Operation<Empty, DeleteOperationMetadata> response = await specialistPoolServiceClient.DeleteSpecialistPoolAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, DeleteOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceDeleteSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateSpecialistPool</summary>
public void UpdateSpecialistPoolRequestObject()
{
// Snippet: UpdateSpecialistPool(UpdateSpecialistPoolRequest, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
UpdateSpecialistPoolRequest request = new UpdateSpecialistPoolRequest
{
SpecialistPool = new SpecialistPool(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> response = specialistPoolServiceClient.UpdateSpecialistPool(request);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceUpdateSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateSpecialistPoolAsync</summary>
public async Task UpdateSpecialistPoolRequestObjectAsync()
{
// Snippet: UpdateSpecialistPoolAsync(UpdateSpecialistPoolRequest, CallSettings)
// Additional: UpdateSpecialistPoolAsync(UpdateSpecialistPoolRequest, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateSpecialistPoolRequest request = new UpdateSpecialistPoolRequest
{
SpecialistPool = new SpecialistPool(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> response = await specialistPoolServiceClient.UpdateSpecialistPoolAsync(request);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceUpdateSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateSpecialistPool</summary>
public void UpdateSpecialistPool()
{
// Snippet: UpdateSpecialistPool(SpecialistPool, FieldMask, CallSettings)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = SpecialistPoolServiceClient.Create();
// Initialize request argument(s)
SpecialistPool specialistPool = new SpecialistPool();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> response = specialistPoolServiceClient.UpdateSpecialistPool(specialistPool, updateMask);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> retrievedResponse = specialistPoolServiceClient.PollOnceUpdateSpecialistPool(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateSpecialistPoolAsync</summary>
public async Task UpdateSpecialistPoolAsync()
{
// Snippet: UpdateSpecialistPoolAsync(SpecialistPool, FieldMask, CallSettings)
// Additional: UpdateSpecialistPoolAsync(SpecialistPool, FieldMask, CancellationToken)
// Create client
SpecialistPoolServiceClient specialistPoolServiceClient = await SpecialistPoolServiceClient.CreateAsync();
// Initialize request argument(s)
SpecialistPool specialistPool = new SpecialistPool();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> response = await specialistPoolServiceClient.UpdateSpecialistPoolAsync(specialistPool, updateMask);
// Poll until the returned long-running operation is complete
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
SpecialistPool result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<SpecialistPool, UpdateSpecialistPoolOperationMetadata> retrievedResponse = await specialistPoolServiceClient.PollOnceUpdateSpecialistPoolAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
SpecialistPool retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Concurrency;
using System.Threading;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Input.Raw;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.Threading;
#nullable enable
namespace Avalonia
{
/// <summary>
/// Encapsulates a Avalonia application.
/// </summary>
/// <remarks>
/// The <see cref="Application"/> class encapsulates Avalonia application-specific
/// functionality, including:
/// - A global set of <see cref="DataTemplates"/>.
/// - A global set of <see cref="Styles"/>.
/// - A <see cref="FocusManager"/>.
/// - An <see cref="InputManager"/>.
/// - Registers services needed by the rest of Avalonia in the <see cref="RegisterServices"/>
/// method.
/// - Tracks the lifetime of the application.
/// </remarks>
public class Application : AvaloniaObject, IDataContextProvider, IGlobalDataTemplates, IGlobalStyles, IResourceHost, IApplicationPlatformEvents
{
/// <summary>
/// The application-global data templates.
/// </summary>
private DataTemplates? _dataTemplates;
private readonly Lazy<IClipboard?> _clipboard =
new Lazy<IClipboard?>(() => (IClipboard?)AvaloniaLocator.Current.GetService(typeof(IClipboard)));
private readonly Styler _styler = new Styler();
private Styles? _styles;
private IResourceDictionary? _resources;
private bool _notifyingResourcesChanged;
private Action<IReadOnlyList<IStyle>>? _stylesAdded;
private Action<IReadOnlyList<IStyle>>? _stylesRemoved;
/// <summary>
/// Defines the <see cref="DataContext"/> property.
/// </summary>
public static readonly StyledProperty<object?> DataContextProperty =
StyledElement.DataContextProperty.AddOwner<Application>();
/// <inheritdoc/>
public event EventHandler<ResourcesChangedEventArgs>? ResourcesChanged;
public event EventHandler<UrlOpenedEventArgs>? UrlsOpened;
/// <summary>
/// Creates an instance of the <see cref="Application"/> class.
/// </summary>
public Application()
{
Name = "Avalonia Application";
}
/// <summary>
/// Gets or sets the Applications's data context.
/// </summary>
/// <remarks>
/// The data context property specifies the default object that will
/// be used for data binding.
/// </remarks>
public object? DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
/// <summary>
/// Gets the current instance of the <see cref="Application"/> class.
/// </summary>
/// <value>
/// The current instance of the <see cref="Application"/> class.
/// </value>
public static Application? Current
{
get { return AvaloniaLocator.Current.GetService<Application>(); }
}
/// <summary>
/// Gets or sets the application's global data templates.
/// </summary>
/// <value>
/// The application's global data templates.
/// </value>
public DataTemplates DataTemplates => _dataTemplates ?? (_dataTemplates = new DataTemplates());
/// <summary>
/// Gets the application's focus manager.
/// </summary>
/// <value>
/// The application's focus manager.
/// </value>
public IFocusManager? FocusManager
{
get;
private set;
}
/// <summary>
/// Gets the application's input manager.
/// </summary>
/// <value>
/// The application's input manager.
/// </value>
public InputManager? InputManager
{
get;
private set;
}
/// <summary>
/// Gets the application clipboard.
/// </summary>
public IClipboard? Clipboard => _clipboard.Value;
/// <summary>
/// Gets the application's global resource dictionary.
/// </summary>
public IResourceDictionary Resources
{
get => _resources ??= new ResourceDictionary(this);
set
{
value = value ?? throw new ArgumentNullException(nameof(value));
_resources?.RemoveOwner(this);
_resources = value;
_resources.AddOwner(this);
}
}
/// <summary>
/// Gets the application's global styles.
/// </summary>
/// <value>
/// The application's global styles.
/// </value>
/// <remarks>
/// Global styles apply to all windows in the application.
/// </remarks>
public Styles Styles => _styles ??= new Styles(this);
/// <inheritdoc/>
bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null;
/// <inheritdoc/>
bool IResourceNode.HasResources => (_resources?.HasResources ?? false) ||
(((IResourceNode?)_styles)?.HasResources ?? false);
/// <summary>
/// Gets the styling parent of the application, which is null.
/// </summary>
IStyleHost? IStyleHost.StylingParent => null;
/// <inheritdoc/>
bool IStyleHost.IsStylesInitialized => _styles != null;
/// <summary>
/// Application lifetime, use it for things like setting the main window and exiting the app from code
/// Currently supported lifetimes are:
/// - <see cref="IClassicDesktopStyleApplicationLifetime"/>
/// - <see cref="ISingleViewApplicationLifetime"/>
/// - <see cref="IControlledApplicationLifetime"/>
/// </summary>
public IApplicationLifetime? ApplicationLifetime { get; set; }
event Action<IReadOnlyList<IStyle>> IGlobalStyles.GlobalStylesAdded
{
add => _stylesAdded += value;
remove => _stylesAdded -= value;
}
event Action<IReadOnlyList<IStyle>> IGlobalStyles.GlobalStylesRemoved
{
add => _stylesRemoved += value;
remove => _stylesRemoved -= value;
}
/// <summary>
/// Initializes the application by loading XAML etc.
/// </summary>
public virtual void Initialize() { }
/// <inheritdoc/>
bool IResourceNode.TryGetResource(object key, out object? value)
{
value = null;
return (_resources?.TryGetResource(key, out value) ?? false) ||
Styles.TryGetResource(key, out value);
}
void IResourceHost.NotifyHostedResourcesChanged(ResourcesChangedEventArgs e)
{
ResourcesChanged?.Invoke(this, e);
}
void IStyleHost.StylesAdded(IReadOnlyList<IStyle> styles)
{
_stylesAdded?.Invoke(styles);
}
void IStyleHost.StylesRemoved(IReadOnlyList<IStyle> styles)
{
_stylesRemoved?.Invoke(styles);
}
/// <summary>
/// Register's the services needed by Avalonia.
/// </summary>
public virtual void RegisterServices()
{
AvaloniaSynchronizationContext.InstallIfNeeded();
FocusManager = new FocusManager();
InputManager = new InputManager();
AvaloniaLocator.CurrentMutable
.Bind<IAccessKeyHandler>().ToTransient<AccessKeyHandler>()
.Bind<IGlobalDataTemplates>().ToConstant(this)
.Bind<IGlobalStyles>().ToConstant(this)
.Bind<IFocusManager>().ToConstant(FocusManager)
.Bind<IInputManager>().ToConstant(InputManager)
.Bind<IKeyboardNavigationHandler>().ToTransient<KeyboardNavigationHandler>()
.Bind<IStyler>().ToConstant(_styler)
.Bind<IScheduler>().ToConstant(AvaloniaScheduler.Instance)
.Bind<IDragDropDevice>().ToConstant(DragDropDevice.Instance);
// TODO: Fix this, for now we keep this behavior since someone might be relying on it in 0.9.x
if (AvaloniaLocator.Current.GetService<IPlatformDragSource>() == null)
AvaloniaLocator.CurrentMutable
.Bind<IPlatformDragSource>().ToTransient<InProcessDragSource>();
var clock = new RenderLoopClock();
AvaloniaLocator.CurrentMutable
.Bind<IGlobalClock>().ToConstant(clock)
.GetService<IRenderLoop>()?.Add(clock);
}
public virtual void OnFrameworkInitializationCompleted()
{
}
void IApplicationPlatformEvents.RaiseUrlsOpened(string[] urls)
{
UrlsOpened?.Invoke(this, new UrlOpenedEventArgs (urls));
}
private void NotifyResourcesChanged(ResourcesChangedEventArgs e)
{
if (_notifyingResourcesChanged)
{
return;
}
try
{
_notifyingResourcesChanged = true;
ResourcesChanged?.Invoke(this, ResourcesChangedEventArgs.Empty);
}
finally
{
_notifyingResourcesChanged = false;
}
}
private void ThisResourcesChanged(object sender, ResourcesChangedEventArgs e)
{
NotifyResourcesChanged(e);
}
private string? _name;
/// <summary>
/// Defines Name property
/// </summary>
public static readonly DirectProperty<Application, string?> NameProperty =
AvaloniaProperty.RegisterDirect<Application, string?>("Name", o => o.Name, (o, v) => o.Name = v);
/// <summary>
/// Application name to be used for various platform-specific purposes
/// </summary>
public string? Name
{
get => _name;
set => SetAndRaise(NameProperty, ref _name, value);
}
}
}
| |
using System;
using System.Data;
using System.Web.Security;
using Codentia.Common.Data;
using Codentia.Common.Helper;
using Codentia.Common.Logging;
using Codentia.Common.Logging.BL;
using Codentia.Common.Membership.Providers;
namespace Codentia.Common.Membership
{
/// <summary>
/// This class exposes methods to create, read, update and delete data related to Users
/// </summary>
public static class SystemUserData
{
/// <summary>
/// Get All email addresses for a system user
/// </summary>
/// <param name="systemUserId">Id of the user to retrieve an address for</param>
/// <returns>DataTable - EmailAddresses</returns>
public static DataTable GetEmailAddressesForSystemUser(int systemUserId)
{
return GetEmailAddressesForSystemUser(Guid.Empty, systemUserId);
}
/// <summary>
/// Get All email addresses for a system user
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="systemUserId">Id of the user to retrieve an address for</param>
/// <returns>DataTable - EmailAddresses</returns>
public static DataTable GetEmailAddressesForSystemUser(Guid txnId, int systemUserId)
{
// TODO: This should be made obsolete in a future version
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
};
DataTable result = DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_GetEmailAddresses", spParams, txnId);
if (result == null || result.Rows.Count == 0)
{
throw new ArgumentException(string.Format("systemUserId: {0} does not exist", systemUserId));
}
return result;
}
/// <summary>
/// Gets the system user.
/// </summary>
/// <param name="systemUserId">The system user id.</param>
/// <returns>DataTable - SystemUser</returns>
public static DataSet GetSystemUser(int systemUserId)
{
return GetSystemUser(Guid.Empty, systemUserId);
}
/// <summary>
/// Retrieve a specific system user.
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="systemUserId">The SystemUserId</param>
/// <returns>DataTable - Systemuser</returns>
public static DataSet GetSystemUser(Guid txnId, int systemUserId)
{
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId)
};
DataSet result = DbInterface.ExecuteProcedureDataSet(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_GetById", spParams, txnId);
if (result == null || result.Tables.Count == 0 || result.Tables[0].Rows.Count == 0)
{
throw new ArgumentException(string.Format("systemUserId: {0} does not exist", systemUserId));
}
return result;
}
/// <summary>
/// Retrieve a specific system user
/// </summary>
/// <param name="emailAddress">Primary email address to retrieve user for</param>
/// <returns>DataTable - SystemUser</returns>
public static DataSet GetSystemUser(string emailAddress)
{
return GetSystemUser(Guid.Empty, emailAddress);
}
/// <summary>
/// Retrieve a specific system user
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddress">Primary email address to retrieve user for</param>
/// <returns>DataTable - SystemUser</returns>
public static DataSet GetSystemUser(Guid txnId, string emailAddress)
{
ParameterCheckHelper.CheckIsValidEmailAddress(emailAddress, 255, "emailAddress");
DbParameter[] spParams =
{
new DbParameter("@EmailAddress", DbType.StringFixedLength, 255, emailAddress)
};
DataSet result = DbInterface.ExecuteProcedureDataSet(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_GetByEmail", spParams, txnId);
if (result == null || result.Tables.Count == 0 || result.Tables[0].Rows.Count == 0)
{
throw new ArgumentException(string.Format("emailAddress: {0} does not exist", emailAddress));
}
return result;
}
/// <summary>
/// Check if a specified system user exists or not
/// </summary>
/// <param name="systemUserId">Id of the user to check</param>
/// <returns>true if SystemUser exists</returns>
public static bool SystemUserExists(int systemUserId)
{
return SystemUserExists(Guid.Empty, systemUserId);
}
/// <summary>
/// Check if a specified system user exists or not
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="systemUserId">Id of the user to check</param>
/// <returns>true if SystemUser exists</returns>
public static bool SystemUserExists(Guid txnId, int systemUserId)
{
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
new DbParameter("@Exists", DbType.Boolean, ParameterDirection.Output, false)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_ExistsById", spParams, txnId);
return Convert.ToBoolean(spParams[1].Value);
}
/// <summary>
/// Sets the role.
/// </summary>
/// <param name="systemUserId">The system user id.</param>
/// <param name="roleName">Name of the role.</param>
public static void SetRole(int systemUserId, string roleName)
{
SetRole(Guid.Empty, systemUserId, roleName);
}
/// <summary>
/// Sets the role.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="systemUserId">The system user id.</param>
/// <param name="roleName">Name of the role.</param>
public static void SetRole(Guid txnId, int systemUserId, string roleName)
{
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
ParameterCheckHelper.CheckIsValidString(roleName, "roleName", false);
if (!Roles.RoleExists(roleName))
{
throw new ArgumentException(string.Format("roleName: {0} does not exist", roleName));
}
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
new DbParameter("@RoleName", DbType.StringFixedLength, 50, roleName)
};
spParams[0].Value = systemUserId;
spParams[1].Value = roleName;
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_SetRole", spParams, txnId);
LogManager.Instance.AddToLog(LogMessageType.Information, "SystemUserData", string.Format("SetRole SystemUser Id={0}, roleName={1}", systemUserId, roleName));
}
/// <summary>
/// Creates the system user.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="membershipUserId">The membership user id.</param>
/// <param name="firstName">The first name.</param>
/// <param name="surname">The surname.</param>
/// <param name="hasNewsLetter">if set to <c>true</c> [has news letter].</param>
/// <param name="primaryEmailAddressId">The primary email address id.</param>
/// <param name="phoneNumber">The phone number.</param>
/// <returns>The systemUserId</returns>
public static int CreateSystemUser(Guid txnId, Guid membershipUserId, string firstName, string surname, bool hasNewsLetter, int primaryEmailAddressId, string phoneNumber)
{
int systemUserId = 0;
// validate membership user
if (!MembershipUserExists(txnId, membershipUserId))
{
throw new ArgumentException(string.Format("MembershipUser {0} does not exist", membershipUserId));
}
// nullable parameter check (validate other parameters)
ParameterCheckHelper.CheckIsValidId(primaryEmailAddressId, "primaryEmailAddressId");
if (!ContactData.EmailAddressExists(txnId, primaryEmailAddressId))
{
throw new ArgumentException(string.Format("primaryEmailAddressId: {0} does not exist", primaryEmailAddressId));
}
int alreadyAssociatedSystemUserId = ContactData.GetSystemUserIdForEmailAddress(txnId, primaryEmailAddressId);
if (alreadyAssociatedSystemUserId > 0)
{
throw new ArgumentException("Email address has already been registered");
}
try
{
DbParameter[] spParams =
{
new DbParameter("@UserId", DbType.Guid, membershipUserId),
new DbParameter("@FirstName", DbType.StringFixedLength, 100, firstName),
new DbParameter("@Surname", DbType.StringFixedLength, 100, surname),
new DbParameter("@PrimaryEmailAddressId", DbType.Int32, primaryEmailAddressId),
new DbParameter("@HasNewsLetter", DbType.Boolean, hasNewsLetter),
new DbParameter("@PhoneNumberId", DbType.Int32),
new DbParameter("@SystemUserId", DbType.Int32, ParameterDirection.Output, 0)
};
if (!string.IsNullOrEmpty(phoneNumber))
{
spParams[5].Value = ContactData.CreatePhoneNumber(txnId, phoneNumber);
}
else
{
spParams[5].Value = DBNull.Value;
}
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_Create", spParams, txnId);
systemUserId = Convert.ToInt32(spParams[6].Value);
}
catch (Exception ex)
{
LogManager.Instance.AddToLog(LogMessageType.Information, "SystemUserData", string.Format("ROLLED BACK: Created SystemUser Id={0} with parameters firstName={1}, surname={2}, hasNewsLetter={3}, primaryEmailAddressId={4}, phoneNumber={5} errorText={6}", systemUserId, firstName, surname, hasNewsLetter, primaryEmailAddressId, phoneNumber, ex.Message));
throw ex;
}
LogManager.Instance.AddToLog(LogMessageType.Information, "SystemUserData", string.Format("Created SystemUser Id={0} with parameters firstName={1}, surname={2}, hasNewsLetter={3}, primaryEmailAddressId={4}, phoneNumber={5}", systemUserId, firstName, surname, hasNewsLetter, primaryEmailAddressId, phoneNumber));
return systemUserId;
}
/// <summary>
/// Gets the system user.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>DataTable - SystemUser</returns>
public static DataTable GetSystemUser(Guid userId)
{
ParameterCheckHelper.CheckIsValidGuid(userId, "userId");
DbParameter[] spParams =
{
new DbParameter("@UserId", DbType.Guid, userId)
};
DataTable systemUserData = DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_GetByUserId", spParams);
return systemUserData;
}
/// <summary>
/// Updates the system user.
/// </summary>
/// <param name="systemUserId">The system user id.</param>
/// <param name="firstName">The first name.</param>
/// <param name="surname">The surname.</param>
/// <param name="hasNewsLetter">if set to <c>true</c> [has news letter].</param>
/// <param name="phoneNumber">The phone number.</param>
public static void UpdateSystemUser(int systemUserId, string firstName, string surname, bool hasNewsLetter, string phoneNumber)
{
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
ParameterCheckHelper.CheckIsValidString(firstName, "first name", false);
ParameterCheckHelper.CheckIsValidString(surname, "surname", false);
Guid txnId = Guid.NewGuid();
try
{
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
new DbParameter("@FirstName", DbType.StringFixedLength, 100, firstName),
new DbParameter("@Surname", DbType.StringFixedLength, 100, surname),
new DbParameter("@HasNewsLetter", DbType.Boolean, hasNewsLetter),
new DbParameter("@PhoneNumberId", DbType.Int32)
};
if (!string.IsNullOrEmpty(phoneNumber))
{
spParams[4].Value = ContactData.CreatePhoneNumber(txnId, phoneNumber);
}
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_Update", spParams, txnId);
DbInterface.CommitTransaction(txnId);
}
catch (Exception ex)
{
DbInterface.RollbackTransaction(txnId);
LogManager.Instance.AddToLog(LogMessageType.Information, "SystemUserData", string.Format("ROLLED BACK: Updated SystemUser Id={0} with parameters firstName={1}, surname={2}, hasNewsLetter={3}, phoneNumber={4}: ErrorText: {5}", systemUserId, firstName, surname, hasNewsLetter, phoneNumber, ex.Message));
throw ex;
}
LogManager.Instance.AddToLog(LogMessageType.Information, "SystemUserData", string.Format("Updated SystemUser Id={0} with parameters firstName={1}, surname={2}, hasNewsLetter={3}, phoneNumber={4}", systemUserId, firstName, surname, hasNewsLetter, phoneNumber));
}
/// <summary>
/// Sets the force password.
/// </summary>
/// <param name="systemUserId">The system user id.</param>
public static void SetForcePassword(int systemUserId)
{
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_SetForcePassword", spParams);
}
/// <summary>
/// Associates the system user to email address.
/// </summary>
/// <param name="emailAddressId">The email address id.</param>
/// <param name="systemUserId">The system user id.</param>
/// <param name="emailAddressOrder">The email address order.</param>
public static void AssociateSystemUserToEmailAddress(int emailAddressId, int systemUserId, int emailAddressOrder)
{
ParameterCheckHelper.CheckIsValidId(emailAddressId, "emailAddressId");
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
ParameterCheckHelper.CheckIsValidId(emailAddressOrder, "emailAddressOrder");
if (!ContactData.EmailAddressExists(emailAddressId))
{
throw new ArgumentException(string.Format("emailAddressId: {0} does not exist", emailAddressId));
}
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId),
new DbParameter("@EmailAddressOrder", DbType.Int32, emailAddressOrder)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_AssociateToEmailAddress", spParams);
}
/// <summary>
/// Dissociates the system user from email address.
/// </summary>
/// <param name="emailAddressId">The email address identifier.</param>
/// <param name="systemUserId">The system user identifier.</param>
/// <exception cref="System.ArgumentException">Email address does not exist</exception>
public static void DissociateSystemUserFromEmailAddress(int emailAddressId, int systemUserId)
{
ParameterCheckHelper.CheckIsValidId(emailAddressId, "emailAddressId");
ParameterCheckHelper.CheckIsValidId(systemUserId, "systemUserId");
if (!ContactData.EmailAddressExists(emailAddressId))
{
throw new ArgumentException(string.Format("emailAddressId: {0} does not exist", emailAddressId));
}
DbParameter[] spParams =
{
new DbParameter("@SystemUserId", DbType.Int32, systemUserId),
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.SystemUser_DissociateFromEmailAddress", spParams);
}
private static bool MembershipUserExists(Guid txnId, Guid userId)
{
ParameterCheckHelper.CheckIsValidGuid(userId, "userId");
bool exists = false;
DbParameter[] spParams =
{
new DbParameter("@UserId", DbType.Guid, userId),
new DbParameter("@Exists", DbType.Boolean, ParameterDirection.Output, false)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.MembershipUser_ExistsById", spParams, txnId);
exists = Convert.ToBoolean(spParams[1].Value);
return exists;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Sax.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.
#pragma warning disable 1717
namespace Android.Sax
{
/// <summary>
/// <para>Listens for the end of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndElementListener", AccessFlags = 1537)]
public partial interface IEndElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of an element. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 1025)]
void End() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the beginning of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/StartElementListener
/// </java-name>
[Dot42.DexImport("android/sax/StartElementListener", AccessFlags = 1537)]
public partial interface IStartElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the beginning of an element.</para><para></para>
/// </summary>
/// <java-name>
/// start
/// </java-name>
[Dot42.DexImport("start", "(Lorg/xml/sax/Attributes;)V", AccessFlags = 1025)]
void Start(global::Org.Xml.Sax.IAttributes attributes) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the end of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndTextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndTextElementListener", AccessFlags = 1537)]
public partial interface IEndTextElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of a text element with the body of the element.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void End(string body) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the beginning and ending of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/TextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/TextElementListener", AccessFlags = 1537)]
public partial interface ITextElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndTextElementListener
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Listens for the beginning and ending of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/ElementListener
/// </java-name>
[Dot42.DexImport("android/sax/ElementListener", AccessFlags = 1537)]
public partial interface IElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndElementListener
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>The root XML element. The entry point for this API. Not safe for concurrent use.</para><para>For example, passing this XML:</para><para><pre>
/// <feed xmlns='>
/// <entry>
/// <id>bob</id>
/// </entry>
/// </feed>
/// </pre></para><para>to this code:</para><para><pre>
/// static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
///
/// ...
///
/// RootElement root = new RootElement(ATOM_NAMESPACE, "feed");
/// Element entry = root.getChild(ATOM_NAMESPACE, "entry");
/// entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(
/// new EndTextElementListener() {
/// public void end(String body) {
/// System.out.println("Entry ID: " + body);
/// }
/// });
///
/// XMLReader reader = ...;
/// reader.setContentHandler(root.getContentHandler());
/// reader.parse(...);
/// </pre></para><para>would output:</para><para><pre>
/// Entry ID: bob
/// </pre> </para>
/// </summary>
/// <java-name>
/// android/sax/RootElement
/// </java-name>
[Dot42.DexImport("android/sax/RootElement", AccessFlags = 33)]
public partial class RootElement : global::Android.Sax.Element
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new root element with the given name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string uri, string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new root element with the given name. Uses an empty string as the namespace.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
public virtual global::Org.Xml.Sax.IContentHandler GetContentHandler() /* MethodBuilder.Create */
{
return default(global::Org.Xml.Sax.IContentHandler);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RootElement() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
public global::Org.Xml.Sax.IContentHandler ContentHandler
{
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
get{ return GetContentHandler(); }
}
}
/// <summary>
/// <para>An XML element. Provides access to child elements and hooks to listen for events related to this element.</para><para><para>RootElement </para></para>
/// </summary>
/// <java-name>
/// android/sax/Element
/// </java-name>
[Dot42.DexImport("android/sax/Element", AccessFlags = 33)]
public partial class Element
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal Element() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Sets start and end element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setElementListener
/// </java-name>
[Dot42.DexImport("setElementListener", "(Landroid/sax/ElementListener;)V", AccessFlags = 1)]
public virtual void SetElementListener(global::Android.Sax.IElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets start and end text element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setTextElementListener
/// </java-name>
[Dot42.DexImport("setTextElementListener", "(Landroid/sax/TextElementListener;)V", AccessFlags = 1)]
public virtual void SetTextElementListener(global::Android.Sax.ITextElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the start of this element. </para>
/// </summary>
/// <java-name>
/// setStartElementListener
/// </java-name>
[Dot42.DexImport("setStartElementListener", "(Landroid/sax/StartElementListener;)V", AccessFlags = 1)]
public virtual void SetStartElementListener(global::Android.Sax.IStartElementListener startElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this element. </para>
/// </summary>
/// <java-name>
/// setEndElementListener
/// </java-name>
[Dot42.DexImport("setEndElementListener", "(Landroid/sax/EndElementListener;)V", AccessFlags = 1)]
public virtual void SetEndElementListener(global::Android.Sax.IEndElementListener endElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this text element. </para>
/// </summary>
/// <java-name>
/// setEndTextElementListener
/// </java-name>
[Dot42.DexImport("setEndTextElementListener", "(Landroid/sax/EndTextElementListener;)V", AccessFlags = 1)]
public virtual void SetEndTextElementListener(global::Android.Sax.IEndTextElementListener endTextElementListener) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.11: Abstract superclass for synthetic environment PDUs
/// </summary>
[Serializable]
[XmlRoot]
public partial class SyntheticEnvironmentFamilyPdu : Pdu, IEquatable<SyntheticEnvironmentFamilyPdu>
{
/// <summary>
/// Initializes a new instance of the <see cref="SyntheticEnvironmentFamilyPdu"/> class.
/// </summary>
public SyntheticEnvironmentFamilyPdu()
{
ProtocolFamily = (byte)9;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(SyntheticEnvironmentFamilyPdu left, SyntheticEnvironmentFamilyPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(SyntheticEnvironmentFamilyPdu left, SyntheticEnvironmentFamilyPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
return marshalSize;
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public virtual void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<SyntheticEnvironmentFamilyPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("</SyntheticEnvironmentFamilyPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <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)
{
return this == obj as SyntheticEnvironmentFamilyPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(SyntheticEnvironmentFamilyPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
return result;
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
using System;
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// RopCreateFolder request buffer structure.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RopCreateFolderRequest : ISerializable
{
/// <summary>
/// This value specifies the type of remote operation. For this operation, this field is set to 0x1C.
/// </summary>
public byte RopId;
/// <summary>
/// This value specifies the logon associated with this operation.
/// </summary>
public byte LogonId;
/// <summary>
/// This index specifies the location in the Server Object Handle Table
/// where the handle for the input Server Object is stored.
/// </summary>
public byte InputHandleIndex;
/// <summary>
/// This index specifies the location in the Server Object Handle Table
/// where the handle for the output Server Object will be stored.
/// </summary>
public byte OutputHandleIndex;
/// <summary>
/// The possible values for this enumeration are specified in [MS-OXCFOLD].
/// This value specifies what type of folder to create.
/// </summary>
public byte FolderType;
/// <summary>
/// This value specifies whether the DisplayName and Comment are specified in Unicode or ASCII.
/// </summary>
public byte UseUnicodeStrings;
/// <summary>
/// This value specifies whether this operation opens or fails when a folder already exists.
/// </summary>
public byte OpenExisting;
/// <summary>
/// Reserved. This field MUST be set to 0x00.
/// </summary>
public byte Reserved;
/// <summary>
/// Null-terminated string. This value specifies the name of the created folder.
/// If UseUnicodeStrings is non-zero, the string is composed of Unicode characters.
/// If UseUnicodeStrings is zero, the string is composed of ASCII characters.
/// </summary>
public byte[] DisplayName;
/// <summary>
/// Null-terminated string. This value specifies the folder comment that is associated with the created folder.
/// If UseUnicodeStrings is non-zero, the string is composed of Unicode characters.
/// If UseUnicodeStrings is zero, the string is composed of ASCII characters.
/// </summary>
public byte[] Comment;
/// <summary>
/// Serialize the ROP request buffer.
/// </summary>
/// <returns>The ROP request buffer serialized.</returns>
public byte[] Serialize()
{
int index = 0;
int bufSize = sizeof(byte) * 8;
if (this.DisplayName != null)
{
bufSize += this.DisplayName.Length;
}
if (this.Comment != null)
{
bufSize += this.Comment.Length;
}
byte[] serializeBuffer = new byte[bufSize];
serializeBuffer[index++] = this.RopId;
serializeBuffer[index++] = this.LogonId;
serializeBuffer[index++] = this.InputHandleIndex;
serializeBuffer[index++] = this.OutputHandleIndex;
serializeBuffer[index++] = this.FolderType;
serializeBuffer[index++] = this.UseUnicodeStrings;
serializeBuffer[index++] = this.OpenExisting;
serializeBuffer[index++] = this.Reserved;
if (this.DisplayName != null)
{
Array.Copy(this.DisplayName, 0, serializeBuffer, index, this.DisplayName.Length);
index += this.DisplayName.Length;
}
if (this.Comment != null)
{
Array.Copy(this.Comment, 0, serializeBuffer, index, this.Comment.Length);
index += this.Comment.Length;
}
return serializeBuffer;
}
/// <summary>
/// Return the size of this structure.
/// </summary>
/// <returns>The size of this structure.</returns>
public int Size()
{
int size = sizeof(byte) * 8;
if (this.DisplayName != null)
{
size += this.DisplayName.Length;
}
if (this.Comment != null)
{
size += this.Comment.Length;
}
return size;
}
}
/// <summary>
/// RopCreateFolder response buffer structure.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RopCreateFolderResponse : IDeserializable
{
/// <summary>
/// This value specifies the type of remote operation. For this operation, this field is set to 0x1C.
/// </summary>
public byte RopId;
/// <summary>
/// This index MUST be set to the OutputHandleIndex specified in the request.
/// </summary>
public byte OutputHandleIndex;
/// <summary>
/// This value specifies the status of the remote operation. For successful response, this field is set to 0x00000000.
/// For failure response, this field is set to a value other than 0x00000000.
/// </summary>
public uint ReturnValue;
/// <summary>
/// This value identifies the folder created or opened.
/// </summary>
public ulong FolderId;
/// <summary>
/// This value indicates whether an existing folder was opened or a new folder was created.
/// </summary>
public byte IsExistingFolder;
/// <summary>
/// This field is present if the IsExistingFolder field is non-zero and is not present otherwise.
/// This value indicates whether there are rules associated with the folder.
/// </summary>
public byte? HasRules;
/// <summary>
/// This field is present if the IsExistingFolder field is non-zero and is not present otherwise.
/// This value indicates whether the server is an active replica of this folder.
/// </summary>
public byte? IsGhosted;
/// <summary>
/// This field is present if both IsExistingFolder and IsGhosted are non-zero and is not present otherwise.
/// This value specifies the number of strings in the Servers field.
/// </summary>
public ushort? ServerCount;
/// <summary>
/// This field is present if both IsExistingFolder and IsGhosted are non-zero and is not present otherwise.
/// This value specifies the number of values in Servers that refers to lowest cost servers.
/// </summary>
public ushort? CheapServerCount;
/// <summary>
/// These strings specify which servers have replicas of this folder.
/// </summary>
public string[] Servers;
/// <summary>
/// Deserialize the ROP response buffer.
/// </summary>
/// <param name="ropBytes">ROPs bytes in response.</param>
/// <param name="startIndex">The start index of this ROP.</param>
/// <returns>The size of response buffer structure.</returns>
public int Deserialize(byte[] ropBytes, int startIndex)
{
// Because HasRules is byte type, has default value 0, can't check it whether present
// Set HasRules to null to decide it present, if equal 0xFF means not present else present
this.HasRules = null;
int index = startIndex;
this.RopId = ropBytes[index++];
this.OutputHandleIndex = ropBytes[index++];
this.ReturnValue = (uint)BitConverter.ToInt32(ropBytes, index);
index += sizeof(uint);
// Only success response has below fields
if (this.ReturnValue == 0)
{
this.FolderId = (ulong)BitConverter.ToInt64(ropBytes, index);
index += sizeof(ulong);
this.IsExistingFolder = ropBytes[index++];
if (this.IsExistingFolder != 0)
{
this.HasRules = ropBytes[index++];
this.IsGhosted = ropBytes[index++];
if (this.IsGhosted != 0)
{
this.ServerCount = (ushort)BitConverter.ToInt16(ropBytes, index);
index += sizeof(ushort);
this.CheapServerCount = (ushort)BitConverter.ToInt16(ropBytes, index);
index += sizeof(ushort);
if (this.ServerCount > 0)
{
this.Servers = new string[(ushort)this.ServerCount];
for (int i = 0; i < this.ServerCount; i++)
{
int bytesLen = 0;
// Find the string with '\0' end
for (int j = index; j < ropBytes.Length; j++)
{
bytesLen++;
if (ropBytes[j] == 0)
{
break;
}
}
this.Servers[i] = Encoding.ASCII.GetString(ropBytes, index, bytesLen);
index += bytesLen;
}
}
}
}
}
return index - startIndex;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Events;
using Marten.Events.CodeGeneration;
using Marten.Events.Operations;
using Marten.Exceptions;
using Marten.Internal;
using Marten.Internal.Operations;
using Marten.Internal.Sessions;
using Weasel.Postgresql;
using Marten.Services;
using Marten.Storage;
using Marten.Testing.Events.Aggregation;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Events
{
[Collection("v4events")]
public class appending_events_workflow_specs
{
private readonly ITestOutputHelper _output;
public appending_events_workflow_specs(ITestOutputHelper output)
{
_output = output;
}
public class EventMetadataChecker : DocumentSessionListenerBase
{
public override Task AfterCommitAsync(IDocumentSession session, IChangeSet commit, CancellationToken token)
{
var events = commit.GetEvents();
foreach (var @event in events)
{
@event.TenantId.ShouldNotBeNull();
@event.Timestamp.ShouldNotBe(DateTime.MinValue);
}
return Task.CompletedTask;
}
}
[Theory]
[MemberData(nameof(Data))]
public void generate_operation_builder(TestCase @case)
{
EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options)
.ShouldNotBeNull();
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_fetch_stream_async(TestCase @case)
{
await @case.Store.Advanced.Clean.CompletelyRemoveAllAsync();
@case.StartNewStream(new TestOutputMartenLogger(_output));
using var query = @case.Store.QuerySession();
var (builder, _) = EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options);
var handler = builder.QueryForStream(@case.ToEventStream());
var state = await query.As<QuerySession>().ExecuteHandlerAsync(handler, CancellationToken.None);
state.ShouldNotBeNull();
}
[Theory]
[MemberData(nameof(Data))]
public void can_fetch_stream_sync(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
@case.StartNewStream();
using var query = @case.Store.QuerySession();
var (builder, _) = EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options);
var handler = builder.QueryForStream(@case.ToEventStream());
var state = query.As<QuerySession>().ExecuteHandler(handler);
state.ShouldNotBeNull();
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_insert_a_new_stream(TestCase @case)
{
// This is just forcing the store to start the event storage
@case.Store.Advanced.Clean.CompletelyRemoveAll();
@case.StartNewStream();
var stream = @case.CreateNewStream();
var (builder, _) = EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options);
var op = builder.InsertStream(stream);
using var session = @case.Store.LightweightSession();
session.QueueOperation(op);
await session.SaveChangesAsync();
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_update_the_version_of_an_existing_stream_happy_path(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
var stream = @case.StartNewStream(new TestOutputMartenLogger(_output));
stream.ExpectedVersionOnServer = 4;
stream.Version = 10;
var (builder, _) = EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options);
var op = builder.UpdateStreamVersion(stream);
using var session = @case.Store.LightweightSession();
session.QueueOperation(op);
session.Logger = new TestOutputMartenLogger(_output);
await session.SaveChangesAsync();
var handler = builder.QueryForStream(stream);
var state = session.As<QuerySession>().ExecuteHandler(handler);
state.Version.ShouldBe(10);
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_update_the_version_of_an_existing_stream_sad_path(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
var stream = @case.StartNewStream();
stream.ExpectedVersionOnServer = 3; // it's actually 4, so this should fail
stream.Version = 10;
var (builder, _) = EventDocumentStorageGenerator.GenerateStorage(@case.Store.Options);
var op = builder.UpdateStreamVersion(stream);
using var session = @case.Store.LightweightSession();
session.QueueOperation(op);
await Should.ThrowAsync<EventStreamUnexpectedMaxEventIdException>(() => session.SaveChangesAsync());
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_establish_the_tombstone_stream_from_scratch(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
@case.Store.Tenancy.Default.EnsureStorageExists(typeof(IEvent));
var operation = new EstablishTombstoneStream(@case.Store.Events);
using var session = @case.Store.LightweightSession();
var batch = new UpdateBatch(new []{operation});
await batch.ApplyChangesAsync((IMartenSession) session, CancellationToken.None);
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
(await session.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamId)).ShouldNotBeNull();
}
else
{
(await session.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamKey)).ShouldNotBeNull();
}
}
[Theory]
[MemberData(nameof(Data))]
public async Task can_re_run_the_tombstone_stream(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
@case.Store.Tenancy.Default.EnsureStorageExists(typeof(IEvent));
var operation = new EstablishTombstoneStream(@case.Store.Events);
using var session = @case.Store.LightweightSession();
var batch = new UpdateBatch(new []{operation});
await batch.ApplyChangesAsync((IMartenSession) session, CancellationToken.None);
await batch.ApplyChangesAsync((IMartenSession) session, CancellationToken.None);
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
(await session.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamId)).ShouldNotBeNull();
}
else
{
(await session.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamKey)).ShouldNotBeNull();
}
}
[Theory]
[MemberData(nameof(Data))]
public async Task exercise_tombstone_workflow_async(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
using var session = @case.Store.LightweightSession();
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
session.Events.Append(Guid.NewGuid(), new AEvent(), new BEvent(), new CEvent());
}
else
{
session.Events.Append(Guid.NewGuid().ToString(), new AEvent(), new BEvent(), new CEvent());
}
session.QueueOperation(new FailingOperation());
await Should.ThrowAsync<DivideByZeroException>(async () =>
{
await session.SaveChangesAsync();
});
using var session2 = @case.Store.LightweightSession();
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
(await session2.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamId)).ShouldNotBeNull();
var events = await session2.Events.FetchStreamAsync(EstablishTombstoneStream.StreamId);
events.Any().ShouldBeTrue();
foreach (var @event in events)
{
@event.Data.ShouldBeOfType<Tombstone>();
}
}
else
{
(await session2.Events.FetchStreamStateAsync(EstablishTombstoneStream.StreamKey)).ShouldNotBeNull();
var events = await session2.Events.FetchStreamAsync(EstablishTombstoneStream.StreamKey);
events.Any().ShouldBeTrue();
foreach (var @event in events)
{
@event.Data.ShouldBeOfType<Tombstone>();
}
}
}
[Theory]
[MemberData(nameof(Data))]
public void exercise_tombstone_workflow_sync(TestCase @case)
{
@case.Store.Advanced.Clean.CompletelyRemoveAll();
using var session = @case.Store.LightweightSession();
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
session.Events.Append(Guid.NewGuid(), new AEvent(), new BEvent(), new CEvent());
}
else
{
session.Events.Append(Guid.NewGuid().ToString(), new AEvent(), new BEvent(), new CEvent());
}
session.QueueOperation(new FailingOperation());
Should.Throw<DivideByZeroException>(() =>
{
session.SaveChanges();
});
using var session2 = @case.Store.LightweightSession();
if (@case.Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
session2.Events.FetchStreamState(EstablishTombstoneStream.StreamId).ShouldNotBeNull();
var events = session2.Events.FetchStream(EstablishTombstoneStream.StreamId);
events.Any().ShouldBeTrue();
foreach (var @event in events)
{
@event.Data.ShouldBeOfType<Tombstone>();
}
}
else
{
session2.Events.FetchStreamState(EstablishTombstoneStream.StreamKey).ShouldNotBeNull();
var events = session2.Events.FetchStream(EstablishTombstoneStream.StreamKey);
events.Any().ShouldBeTrue();
foreach (var @event in events)
{
@event.Data.ShouldBeOfType<Tombstone>();
}
}
}
public static IEnumerable<object[]> Data()
{
return cases().Select(x => new object[] {x});
}
private static IEnumerable<TestCase> cases()
{
yield return new TestCase("Streams as Guid, Vanilla", e => e.StreamIdentity = StreamIdentity.AsGuid);
yield return new TestCase("Streams as String, Vanilla", e => e.StreamIdentity = StreamIdentity.AsString);
yield return new TestCase("Streams as Guid, Multi-tenanted", e =>
{
e.StreamIdentity = StreamIdentity.AsGuid;
e.TenancyStyle = TenancyStyle.Conjoined;
});
yield return new TestCase("Streams as String, Multi-tenanted", e =>
{
e.StreamIdentity = StreamIdentity.AsString;
e.TenancyStyle = TenancyStyle.Conjoined;
});
}
public class TestCase : IDisposable
{
private readonly string _description;
private Lazy<DocumentStore> _store;
public TestCase(string description, Action<EventGraph> config)
{
_description = description;
_store = new Lazy<DocumentStore>(() =>
{
var store = DocumentStore.For(opts =>
{
config(opts.EventGraph);
opts.Connection(ConnectionSource.ConnectionString);
opts.DatabaseSchemaName = "v4events";
opts.AutoCreateSchemaObjects = AutoCreate.All;
});
store.Advanced.Clean.CompletelyRemoveAll();
return store;
});
StreamId = Guid.NewGuid();
TenantId = "KC";
}
internal DocumentStore Store => _store.Value;
public StreamAction StartNewStream(IMartenSessionLogger logger = null)
{
var events = new object[] {new AEvent(), new BEvent(), new CEvent(), new DEvent()};
using var session = Store.Events.TenancyStyle == TenancyStyle.Conjoined
? Store.LightweightSession(TenantId)
: Store.LightweightSession();
session.Listeners.Add(new EventMetadataChecker());
if (logger != null)
{
session.Logger = logger;
}
if (Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
session.Events.StartStream(StreamId, events);
session.SaveChanges();
var stream = StreamAction.Append(Store.Events, StreamId);
stream.Version = 4;
stream.TenantId = TenantId;
return stream;
}
else
{
session.Events.StartStream(StreamId.ToString(), events);
session.SaveChanges();
var stream = StreamAction.Start(Store.Events, StreamId.ToString(), new AEvent());
stream.Version = 4;
stream.TenantId = TenantId;
return stream;
}
}
public StreamAction CreateNewStream()
{
var events = new IEvent[] {new Event<AEvent>(new AEvent())};
var stream = Store.Events.StreamIdentity == StreamIdentity.AsGuid ? StreamAction.Start(Guid.NewGuid(), events) : StreamAction.Start(Guid.NewGuid().ToString(), events);
stream.TenantId = TenantId;
stream.Version = 1;
return stream;
}
public string TenantId { get; set; }
public Guid StreamId { get; }
public void Dispose()
{
if (_store.IsValueCreated)
{
_store.Value.Dispose();
}
}
public override string ToString()
{
return _description;
}
public StreamAction ToEventStream()
{
if (Store.Events.StreamIdentity == StreamIdentity.AsGuid)
{
var stream = StreamAction.Start(Store.Events, StreamId, new AEvent());
stream.TenantId = TenantId;
return stream;
}
else
{
var stream = StreamAction.Start(Store.Events, StreamId.ToString(), new AEvent());
stream.TenantId = TenantId;
return stream;
}
}
}
public class FailingOperation: IStorageOperation
{
public void ConfigureCommand(CommandBuilder builder, IMartenSession session)
{
builder.Append("select 1");
}
public Type DocumentType => GetType();
public void Postprocess(DbDataReader reader, IList<Exception> exceptions)
{
throw new DivideByZeroException("Boom!");
}
public Task PostprocessAsync(DbDataReader reader, IList<Exception> exceptions, CancellationToken token)
{
exceptions.Add(new DivideByZeroException("Boom!"));
return Task.CompletedTask;
}
public OperationRole Role()
{
return OperationRole.Other;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Dapper;
using LL.Repository;
using AngularJSAuthRefreshToken.AspNetIdentity.Properties;
using AngularJSAuthRefreshToken.Data.Browser;
namespace AngularJSAuthRefreshToken.AspNetIdentity
{
public class UserStore : BaseRepository,
IUserLoginStore<IdentityUser, string>,
IUserClaimStore<IdentityUser, string>,
IUserRoleStore<IdentityUser, string>,
IUserPasswordStore<IdentityUser, string>,
IUserSecurityStampStore<IdentityUser, string>,
IQueryableUserStore<IdentityUser, string>,
IUserEmailStore<IdentityUser, string>,
IUserPhoneNumberStore<IdentityUser, string>,
IUserTwoFactorStore<IdentityUser, string>,
IUserLockoutStore<IdentityUser, string>,
IUserStore<IdentityUser, string>,
IUserStore<IdentityUser>,
IUserBrowser
{
public UserStore(IDbContext dbContext) : base(dbContext) { }
public IQueryable<IdentityUser> Users
{
get
{
ThrowIfDisposed();
return _dbContext.GetUsers();
}
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<DateTimeOffset>(user.LockoutEndDateUtc.HasValue ?
new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc)) :
default(DateTimeOffset));
}
public Task SetLockoutEndDateAsync(IdentityUser user, DateTimeOffset lockoutEnd)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEndDateUtc =
((lockoutEnd == DateTimeOffset.MinValue) ? null : new DateTime?(lockoutEnd.UtcDateTime));
return Task.FromResult<int>(0);
}
public Task<int> IncrementAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount++;
return Task.FromResult<int>(user.AccessFailedCount);
}
public Task ResetAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount = 0;
return Task.FromResult<int>(0);
}
public Task<int> GetAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<int>(user.AccessFailedCount);
}
public Task<bool> GetLockoutEnabledAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.LockoutEnabled);
}
public Task SetLockoutEnabledAsync(IdentityUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnabled = enabled;
return Task.FromResult<int>(0);
}
public virtual Task<IList<Claim>> GetClaimsAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return _dbContext.GetClaimsAsync(user);
}
public virtual Task AddClaimAsync(IdentityUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
return _dbContext.AddClaimAsync(user, claim);
}
public virtual Task RemoveClaimAsync(IdentityUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
return _dbContext.RemoveClaimAsync(user, claim);
}
public Task<bool> GetEmailConfirmedAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.EmailConfirmed);
}
public Task SetEmailConfirmedAsync(IdentityUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.EmailConfirmed = confirmed;
return Task.FromResult<int>(0);
}
public Task SetEmailAsync(IdentityUser user, string email)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.Email = email;
return Task.FromResult<int>(0);
}
public Task<string> GetEmailAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.Email);
}
public Task<IdentityUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
return _dbContext.FindByEmailAsync(email);
}
public virtual Task<IdentityUser> FindByIdAsync(string userId)
{
ThrowIfDisposed();
return _dbContext.GetUserByIdAsync(userId);
}
public virtual Task<IdentityUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
return _dbContext.FindByNameAsync(userName);
}
public virtual async Task CreateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await _dbContext.InsertOrUpdateAsync(user);
}
public virtual async Task DeleteAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await _dbContext.DeleteAsync(user);
}
public virtual async Task UpdateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await _dbContext.InsertOrUpdateAsync(user);
}
public virtual Task<IdentityUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null)
{
throw new ArgumentNullException("login");
}
return _dbContext.FindAsync(login);
}
public virtual Task AddLoginAsync(IdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
return _dbContext.AddLoginAsync(user, login);
}
public virtual Task RemoveLoginAsync(IdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
return _dbContext.RemoveLoginAsync(user, login);
}
public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return _dbContext.GetLoginsAsync(user);
}
public Task SetPasswordHashAsync(IdentityUser user, string passwordHash)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
return Task.FromResult<int>(0);
}
public Task<string> GetPasswordHashAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(IdentityUser user)
{
return Task.FromResult<bool>(user.PasswordHash != null);
}
public Task SetPhoneNumberAsync(IdentityUser user, string phoneNumber)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumber = phoneNumber;
return Task.FromResult<int>(0);
}
public Task<string> GetPhoneNumberAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.PhoneNumber);
}
public Task<bool> GetPhoneNumberConfirmedAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.PhoneNumberConfirmed);
}
public Task SetPhoneNumberConfirmedAsync(IdentityUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumberConfirmed = confirmed;
return Task.FromResult<int>(0);
}
public virtual async Task AddToRoleAsync(IdentityUser user, string name)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await _dbContext.AddToRoleAsync(user, name);
}
public virtual async Task RemoveFromRoleAsync(IdentityUser user, string name)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
await _dbContext.RemoveFromRoleAsync(user, name);
}
public virtual Task<IList<string>> GetRolesAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return _dbContext.GetRolesAsync(user);
}
public virtual Task<bool> IsInRoleAsync(IdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
return _dbContext.IsInRoleAsync(user, roleName);
}
public Task SetSecurityStampAsync(IdentityUser user, string stamp)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
return Task.FromResult<int>(0);
}
public Task<string> GetSecurityStampAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.SecurityStamp);
}
public Task SetTwoFactorEnabledAsync(IdentityUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.TwoFactorEnabled = enabled;
return Task.FromResult<int>(0);
}
public Task<bool> GetTwoFactorEnabledAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.TwoFactorEnabled);
}
public async Task<PagedResult<DTO.IdentityUser>> Browser(BrowserContext context)
{
ThrowIfDisposed();
return await _dbContext.BrowseUsers(context);
}
}
}
| |
//
// Mono.Security.Cryptography SHA224 class implementation
// based on SHA256Managed class implementation (mscorlib.dll)
//
// Authors:
// Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2001
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.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.Security.Cryptography;
namespace Mono.Security.Cryptography {
public class SHA224Managed : SHA224 {
private const int BLOCK_SIZE_BYTES = 64;
private uint[] _H;
private ulong count;
private byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth.
private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed.
public SHA224Managed ()
{
_H = new uint [8];
_ProcessingBuffer = new byte [BLOCK_SIZE_BYTES];
Initialize ();
}
private uint Ch (uint u, uint v, uint w)
{
return (u&v) ^ (~u&w);
}
private uint Maj (uint u, uint v, uint w)
{
return (u&v) ^ (u&w) ^ (v&w);
}
private uint Ro0 (uint x)
{
return ((x >> 7) | (x << 25))
^ ((x >> 18) | (x << 14))
^ (x >> 3);
}
private uint Ro1 (uint x)
{
return ((x >> 17) | (x << 15))
^ ((x >> 19) | (x << 13))
^ (x >> 10);
}
private uint Sig0 (uint x)
{
return ((x >> 2) | (x << 30))
^ ((x >> 13) | (x << 19))
^ ((x >> 22) | (x << 10));
}
private uint Sig1 (uint x)
{
return ((x >> 6) | (x << 26))
^ ((x >> 11) | (x << 21))
^ ((x >> 25) | (x << 7));
}
protected override void HashCore (byte[] rgb, int start, int size)
{
int i;
State = 1;
if (_ProcessingBufferCount != 0) {
if (size < (BLOCK_SIZE_BYTES - _ProcessingBufferCount)) {
System.Buffer.BlockCopy (rgb, start, _ProcessingBuffer, _ProcessingBufferCount, size);
_ProcessingBufferCount += size;
return;
}
else {
i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount);
System.Buffer.BlockCopy (rgb, start, _ProcessingBuffer, _ProcessingBufferCount, i);
ProcessBlock (_ProcessingBuffer, 0);
_ProcessingBufferCount = 0;
start += i;
size -= i;
}
}
for (i=0; i<size-size%BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES) {
ProcessBlock (rgb, start+i);
}
if (size%BLOCK_SIZE_BYTES != 0) {
System.Buffer.BlockCopy (rgb, size-size%BLOCK_SIZE_BYTES+start, _ProcessingBuffer, 0, size%BLOCK_SIZE_BYTES);
_ProcessingBufferCount = size%BLOCK_SIZE_BYTES;
}
}
protected override byte[] HashFinal ()
{
byte[] hash = new byte[28];
int i, j;
ProcessFinalBlock (_ProcessingBuffer, 0, _ProcessingBufferCount);
for (i=0; i<7; i++) {
for (j=0; j<4; j++) {
hash[i*4+j] = (byte)(_H[i] >> (24-j*8));
}
}
State = 0;
return hash;
}
public override void Initialize ()
{
count = 0;
_ProcessingBufferCount = 0;
_H[0] = 0xC1059ED8;
_H[1] = 0x367CD507;
_H[2] = 0x3070DD17;
_H[3] = 0xF70E5939;
_H[4] = 0xFFC00B31;
_H[5] = 0x68581511;
_H[6] = 0x64F98FA7;
_H[7] = 0xBEFA4FA4;
}
private void ProcessBlock (byte[] inputBuffer, int inputOffset)
{
uint a, b, c, d, e, f, g, h;
uint t1, t2;
int i;
uint[] buff;
count += BLOCK_SIZE_BYTES;
buff = new uint[64];
for (i=0; i<16; i++) {
buff[i] = ((uint)(inputBuffer[inputOffset+4*i]) << 24)
| ((uint)(inputBuffer[inputOffset+4*i+1]) << 16)
| ((uint)(inputBuffer[inputOffset+4*i+2]) << 8)
| ((uint)(inputBuffer[inputOffset+4*i+3]));
}
for (i=16; i<64; i++) {
buff[i] = Ro1(buff[i-2]) + buff[i-7] + Ro0(buff[i-15]) + buff[i-16];
}
a = _H[0];
b = _H[1];
c = _H[2];
d = _H[3];
e = _H[4];
f = _H[5];
g = _H[6];
h = _H[7];
for (i=0; i<64; i++) {
t1 = h + Sig1(e) + Ch(e,f,g) + SHAConstants.K1 [i] + buff[i];
t2 = Sig0(a) + Maj(a,b,c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
_H[0] += a;
_H[1] += b;
_H[2] += c;
_H[3] += d;
_H[4] += e;
_H[5] += f;
_H[6] += g;
_H[7] += h;
}
private void ProcessFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount)
{
ulong total = count + (ulong)inputCount;
int paddingSize = (56 - (int)(total % BLOCK_SIZE_BYTES));
if (paddingSize < 1)
paddingSize += BLOCK_SIZE_BYTES;
byte[] fooBuffer = new byte[inputCount+paddingSize+8];
for (int i=0; i<inputCount; i++) {
fooBuffer[i] = inputBuffer[i+inputOffset];
}
fooBuffer[inputCount] = 0x80;
for (int i=inputCount+1; i<inputCount+paddingSize; i++) {
fooBuffer[i] = 0x00;
}
// I deal in bytes. The algorithm deals in bits.
ulong size = total << 3;
AddLength (size, fooBuffer, inputCount+paddingSize);
ProcessBlock (fooBuffer, 0);
if (inputCount+paddingSize+8 == 128) {
ProcessBlock(fooBuffer, 64);
}
}
internal void AddLength (ulong length, byte[] buffer, int position)
{
buffer [position++] = (byte)(length >> 56);
buffer [position++] = (byte)(length >> 48);
buffer [position++] = (byte)(length >> 40);
buffer [position++] = (byte)(length >> 32);
buffer [position++] = (byte)(length >> 24);
buffer [position++] = (byte)(length >> 16);
buffer [position++] = (byte)(length >> 8);
buffer [position] = (byte)(length);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Xml
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class XSLTTransform : Page
{
private MainPage rootPage;
public XSLTTransform()
{
this.InitializeComponent();
Scenario5Init();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
async void XsltInit()
{
try
{
Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("xsltTransform");
Windows.Storage.StorageFile xmlFile = await storageFolder.GetFileAsync("xmlContent.xml");
Windows.Storage.StorageFile xsltFile = await storageFolder.GetFileAsync("xslContent.xml");
// load xml file
Windows.Data.Xml.Dom.XmlDocument doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(xmlFile);
Scenario.RichEditBoxSetMsg(scenario5Xml, doc.GetXml(), false);
// load xslt file
doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(xsltFile);
// Display xml and xslt file content in the input fields
Scenario.RichEditBoxSetMsg(scenario5Xslt, doc.GetXml(), false);
Scenario.RichEditBoxSetMsg(scenario5Result, "", true);
}
catch (Exception exp)
{
Scenario.RichEditBoxSetMsg(scenario5Xml, "", false);
Scenario.RichEditBoxSetMsg(scenario5Xslt, "", false);
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
rootPage.NotifyUser("Exception occured while loading xml file!", NotifyType.ErrorMessage);
}
}
void Scenario5Init()
{
XsltInit();
}
/// <summary>
/// This is the click handler for the 'Scenario5BtnTransformToString' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Scenario5BtnTransformToString_Click(object sender, RoutedEventArgs e)
{
scenario5Xml.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
scenario5Xslt.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
Scenario.RichEditBoxSetMsg(scenario5Result, "", true);
Windows.Data.Xml.Dom.XmlDocument doc;
Windows.Data.Xml.Dom.XmlDocument xsltDoc;
String xml;
String xslt;
// Get xml content from xml input field
scenario5Xml.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);
// Get xslt content from xslt input field
scenario5Xslt.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xslt);
if (null == xml || "" == xml.Trim())
{
Scenario.RichEditBoxSetError(scenario5Result, "Source XML can't be empty");
return;
}
if (null == xslt || "" == xslt.Trim())
{
Scenario.RichEditBoxSetError(scenario5Result, "XSL content can't be empty");
return;
}
try
{
// Load xml content
doc = new Windows.Data.Xml.Dom.XmlDocument();
doc.LoadXml(xml);
}
catch (Exception exp)
{
scenario5Xml.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
try
{
// Load xslt content
xsltDoc = new Windows.Data.Xml.Dom.XmlDocument();
xsltDoc.LoadXml(xslt);
}
catch (Exception exp)
{
scenario5Xslt.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
try
{
// Transform xml according to the style sheet declaration specified in xslt file
var xsltProcessor = new Windows.Data.Xml.Xsl.XsltProcessor(xsltDoc);
String transformedStr = xsltProcessor.TransformToString(doc);
Scenario.RichEditBoxSetMsg(scenario5Result, transformedStr, true);
}
catch (Exception exp)
{
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
}
/// <summary>
/// This is the click handler for the 'Scenario5BtnTransformToDocument' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void Scenario5BtnTransformToDocument_Click(object sender, RoutedEventArgs e)
{
scenario5Xml.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
scenario5Xslt.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
Scenario.RichEditBoxSetMsg(scenario5Result, "", true);
Windows.Data.Xml.Dom.XmlDocument doc;
Windows.Data.Xml.Dom.XmlDocument xsltDoc;
String xml;
String xslt;
// Get xml content from xml input field
scenario5Xml.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);
// Get xslt content from xslt input field
scenario5Xslt.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xslt);
if (null == xml || "" == xml.Trim())
{
Scenario.RichEditBoxSetError(scenario5Result, "Source XML can't be empty");
return;
}
if (null == xslt || "" == xslt.Trim())
{
Scenario.RichEditBoxSetError(scenario5Result, "XSL content can't be empty");
return;
}
try
{
// Load xml content
doc = new Windows.Data.Xml.Dom.XmlDocument();
doc.LoadXml(xml);
}
catch (Exception exp)
{
scenario5Xml.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
try
{
// Load xslt content
xsltDoc = new Windows.Data.Xml.Dom.XmlDocument();
xsltDoc.LoadXml(xslt);
}
catch (Exception exp)
{
scenario5Xslt.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
try
{
// Transform xml according to the style sheet declaration specified in xslt file
var xsltProcessor = new Windows.Data.Xml.Xsl.XsltProcessor(xsltDoc);
Windows.Data.Xml.Dom.XmlDocument transformedDocument = xsltProcessor.TransformToDocument(doc);
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile xmlFile = await storageFolder.CreateFileAsync("transformed.xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await transformedDocument.SaveToFileAsync(xmlFile);
Scenario.RichEditBoxSetMsg(scenario5Result, string.Format("The result has been saved to: \n" + xmlFile.Path), true);
}
catch (Exception exp)
{
Scenario.RichEditBoxSetError(scenario5Result, exp.Message);
return;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------------
//
// Description:
// The package properties are a subset of the standard OLE property sets
// SummaryInformation and DocumentSummaryInformation, and include such properties
// as Title and Subject.
//
//-----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Globalization; // For CultureInfo
namespace System.IO.Packaging
{
/// <summary>
/// The package properties are a subset of the standard OLE property sets
/// SummaryInformation and DocumentSummaryInformation, and include such properties
/// as Title and Subject.
/// </summary>
/// <remarks>
/// <para>Setting a property to null deletes this property. 'null' is never strictly speaking
/// a property value, but an absence indicator.</para>
/// </remarks>
internal class PartBasedPackageProperties : PackageProperties
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal PartBasedPackageProperties(Package package)
{
_package = package;
// Initialize literals as Xml Atomic strings.
_nameTable = PackageXmlStringTable.NameTable;
ReadPropertyValuesFromPackage();
// No matter what happens during initialization, the dirty flag should not be set.
_dirty = false;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <value>
/// The primary creator. The identification is environment-specific and
/// can consist of a name, email address, employee ID, etc. It is
/// recommended that this value be only as verbose as necessary to
/// identify the individual.
/// </value>
public override string Creator
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Creator);
}
set
{
RecordNewBinding(PackageXmlEnum.Creator, value);
}
}
/// <value>
/// The title.
/// </value>
public override string Title
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Title);
}
set
{
RecordNewBinding(PackageXmlEnum.Title, value);
}
}
/// <value>
/// The topic of the contents.
/// </value>
public override string Subject
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Subject);
}
set
{
RecordNewBinding(PackageXmlEnum.Subject, value);
}
}
/// <value>
/// The category. This value is typically used by UI applications to create navigation
/// controls.
/// </value>
public override string Category
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Category);
}
set
{
RecordNewBinding(PackageXmlEnum.Category, value);
}
}
/// <value>
/// A delimited set of keywords to support searching and indexing. This
/// is typically a list of terms that are not available elsewhere in the
/// properties.
/// </value>
public override string Keywords
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Keywords);
}
set
{
RecordNewBinding(PackageXmlEnum.Keywords, value);
}
}
/// <value>
/// The description or abstract of the contents.
/// </value>
public override string Description
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Description);
}
set
{
RecordNewBinding(PackageXmlEnum.Description, value);
}
}
/// <value>
/// The type of content represented, generally defined by a specific
/// use and intended audience. Example values include "Whitepaper",
/// "Security Bulletin", and "Exam". (This property is distinct from
/// MIME content types as defined in RFC 2616.)
/// </value>
public override string ContentType
{
get
{
string contentType = GetPropertyValue(PackageXmlEnum.ContentType) as string;
return contentType;
}
set
{
RecordNewBinding(PackageXmlEnum.ContentType, value);
}
}
/// <value>
/// The status of the content. Example values include "Draft",
/// "Reviewed", and "Final".
/// </value>
public override string ContentStatus
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.ContentStatus);
}
set
{
RecordNewBinding(PackageXmlEnum.ContentStatus, value);
}
}
/// <value>
/// The version number. This value is set by the user or by the application.
/// </value>
public override string Version
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Version);
}
set
{
RecordNewBinding(PackageXmlEnum.Version, value);
}
}
/// <value>
/// The revision number. This value indicates the number of saves or
/// revisions. The application is responsible for updating this value
/// after each revision.
/// </value>
public override string Revision
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Revision);
}
set
{
RecordNewBinding(PackageXmlEnum.Revision, value);
}
}
/// <value>
/// The creation date and time.
/// </value>
public override Nullable<DateTime> Created
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Created);
}
set
{
RecordNewBinding(PackageXmlEnum.Created, value);
}
}
/// <value>
/// The date and time of the last modification.
/// </value>
public override Nullable<DateTime> Modified
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Modified);
}
set
{
RecordNewBinding(PackageXmlEnum.Modified, value);
}
}
/// <value>
/// The user who performed the last modification. The identification is
/// environment-specific and can consist of a name, email address,
/// employee ID, etc. It is recommended that this value be only as
/// verbose as necessary to identify the individual.
/// </value>
public override string LastModifiedBy
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.LastModifiedBy);
}
set
{
RecordNewBinding(PackageXmlEnum.LastModifiedBy, value);
}
}
/// <value>
/// The date and time of the last printing.
/// </value>
public override Nullable<DateTime> LastPrinted
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.LastPrinted);
}
set
{
RecordNewBinding(PackageXmlEnum.LastPrinted, value);
}
}
/// <value>
/// A language of the intellectual content of the resource
/// </value>
public override string Language
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Language);
}
set
{
RecordNewBinding(PackageXmlEnum.Language, value);
}
}
/// <value>
/// A unique identifier.
/// </value>
public override string Identifier
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Identifier);
}
set
{
RecordNewBinding(PackageXmlEnum.Identifier, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Invoked from Package.Flush.
// The expectation is that whatever is currently dirty will get flushed.
internal void Flush()
{
if (!_dirty)
return;
// Make sure there is a part to write to and that it contains
// the expected start markup.
EnsureXmlWriter();
// Write the property elements and clear _dirty.
SerializeDirtyProperties();
// add closing markup and close the writer.
CloseXmlWriter();
}
// Invoked from Package.Close.
internal void Close()
{
Flush();
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// The property store is implemented as a hash table of objects.
// Keys are taken from the set of string constants defined in this
// class and compared by their references rather than their values.
private object GetPropertyValue(PackageXmlEnum propertyName)
{
_package.ThrowIfWriteOnly();
if (!_propertyDictionary.ContainsKey(propertyName))
return null;
return _propertyDictionary[propertyName];
}
// Shim function to adequately cast the result of GetPropertyValue.
private Nullable<DateTime> GetDateTimePropertyValue(PackageXmlEnum propertyName)
{
object valueObject = GetPropertyValue(propertyName);
if (valueObject == null)
return null;
// If an object is there, it will be a DateTime (not a Nullable<DateTime>).
return (Nullable<DateTime>)valueObject;
}
// Set new property value.
// Override that sets the initializing flag to false to reflect the default
// situation: recording a binding to implement a value assignment.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value)
{
RecordNewBinding(propertyenum, value, false /* not invoked at construction */, null);
}
// Set new property value.
// Null value is passed for deleting a property.
// While initializing, we are not assigning new values, and so the dirty flag should
// stay untouched.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value, bool initializing, XmlReader reader)
{
// If we are reading values from the package, reader cannot be null
Debug.Assert(!initializing || reader != null);
if (!initializing)
_package.ThrowIfReadOnly();
// Case of an existing property.
if (_propertyDictionary.ContainsKey(propertyenum))
{
// Parsing should detect redundant entries.
if (initializing)
{
throw new XmlException(SR.Format(SR.DuplicateCorePropertyName, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Nullable<DateTime> values can be checked against null
if (value == null) // a deletion
{
_propertyDictionary.Remove(propertyenum);
}
else // an update
{
_propertyDictionary[propertyenum] = value;
}
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
// Case of an initial value being set for a property.
else
{
_propertyDictionary.Add(propertyenum, value);
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
}
// Initialize object from property values found in package.
// All values will remain null if the package is not enabled for reading.
private void ReadPropertyValuesFromPackage()
{
Debug.Assert(_propertyPart == null); // This gets called exclusively from constructor.
// Don't try to read properties from the package it does not have read access
if (_package.FileOpenAccess == FileAccess.Write)
return;
_propertyPart = GetPropertyPart();
if (_propertyPart == null)
return;
ParseCorePropertyPart(_propertyPart);
}
// Locate core properties part using the package relationship that points to it.
private PackagePart GetPropertyPart()
{
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
PackageRelationship corePropertiesRelationship = GetCorePropertiesRelationship();
if (corePropertiesRelationship == null)
return null;
// Retrieve the part referenced by its target URI.
if (corePropertiesRelationship.TargetMode != TargetMode.Internal)
throw new FileFormatException(SR.NoExternalTargetForMetadataRelationship);
PackagePart propertiesPart = null;
Uri propertiesPartUri = PackUriHelper.ResolvePartUri(
PackUriHelper.PackageRootUri,
corePropertiesRelationship.TargetUri);
if (!_package.PartExists(propertiesPartUri))
throw new FileFormatException(SR.DanglingMetadataRelationship);
propertiesPart = _package.GetPart(propertiesPartUri);
if (!propertiesPart.ValidatedContentType.AreTypeAndSubTypeEqual(s_coreDocumentPropertiesContentType))
{
throw new FileFormatException(SR.WrongContentTypeForPropertyPart);
}
return propertiesPart;
}
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
private PackageRelationship GetCorePropertiesRelationship()
{
PackageRelationship propertiesPartRelationship = null;
foreach (PackageRelationship rel
in _package.GetRelationshipsByType(CoreDocumentPropertiesRelationshipType))
{
if (propertiesPartRelationship != null)
{
throw new FileFormatException(SR.MoreThanOneMetadataRelationships);
}
propertiesPartRelationship = rel;
}
return propertiesPartRelationship;
}
// Deserialize properties part.
private void ParseCorePropertyPart(PackagePart part)
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.NameTable = _nameTable;
using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read))
// Create a reader that uses _nameTable so as to use the set of tag literals
// in effect as a set of atomic identifiers.
using (XmlReader reader = XmlReader.Create(stream, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
if (reader.MoveToContent() != XmlNodeType.Element
|| (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace)
|| (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties))
{
throw new XmlException(SR.CorePropertiesElementExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// The schema is closed and defines no attributes on the root element.
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Iterate through property elements until EOF. Note the proper closing of all
// open tags is checked by the reader itself.
// This loop deals only with depth-1 start tags. Handling of element content
// is delegated to dedicated functions.
int attributesCount;
while (reader.Read() && reader.MoveToContent() != XmlNodeType.None)
{
// Ignore end-tags. We check element errors on opening tags.
if (reader.NodeType == XmlNodeType.EndElement)
continue;
// Any content markup that is not an element here is unexpected.
if (reader.NodeType != XmlNodeType.Element)
{
throw new XmlException(SR.PropertyStartTagExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element below the root should open at level 1 exclusively.
if (reader.Depth != 1)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader);
// Property elements can occur in any order (xsd:all).
object localName = reader.LocalName;
PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName);
String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex);
if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error.
{
throw new XmlException(
SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element not in the valid core properties namespace is unexpected.
// The following is an object comparison, not a string comparison.
if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex)))
{
throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (String.CompareOrdinal(valueType, "String") == 0)
{
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader);
}
else if (String.CompareOrdinal(valueType, "DateTime") == 0)
{
int allowedAttributeCount = (object)reader.NamespaceURI ==
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace)
? 1 : 0;
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != allowedAttributeCount)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (allowedAttributeCount != 0)
{
ValidateXsiType(reader,
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace),
W3cdtf);
}
RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader);
}
else // An unexpected element is an error.
{
Debug.Assert(false, "Unknown value type for properties");
}
}
}
}
// This method validates xsi:type="dcterms:W3CDTF"
// The valude of xsi:type is a qualified name. It should have a prefix that matches
// the xml namespace (ns) within the scope and the name that matches name
// The comparisons should be case-sensitive comparisons
internal static void ValidateXsiType(XmlReader reader, Object ns, string name)
{
// Get the value of xsi;type
String typeValue = reader.GetAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// Missing xsi:type
if (typeValue == null)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
int index = typeValue.IndexOf(':');
// The valude of xsi:type is not a qualified name
if (index == -1)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Check the following conditions
// The namespace of the prefix (string before ":") matches "ns"
// The name (string after ":") matches "name"
if (!Object.ReferenceEquals(ns, reader.LookupNamespace(typeValue.Substring(0, index)))
|| String.CompareOrdinal(name, typeValue.Substring(index + 1, typeValue.Length - index - 1)) != 0)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
// Expect to find text data and return its value.
private string GetStringData(XmlReader reader)
{
if (reader.IsEmptyElement)
return string.Empty;
reader.Read();
if (reader.MoveToContent() == XmlNodeType.EndElement)
return string.Empty;
// If there is any content in the element, it should be text content and nothing else.
if (reader.NodeType != XmlNodeType.Text)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return reader.Value;
}
// Expect to find text data and return its value as DateTime.
private Nullable<DateTime> GetDateData(XmlReader reader)
{
string data = GetStringData(reader);
DateTime dateTime;
try
{
// Note: No more than 7 second decimals are accepted by the
// list of formats given. There currently is no method that
// would perform XSD-compliant parsing.
dateTime = DateTime.ParseExact(data, s_dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException exc)
{
throw new XmlException(SR.XsdDateTimeExpected,
exc, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return dateTime;
}
// Make sure there is a part to write to and that it contains
// the expected start markup.
private void EnsureXmlWriter()
{
if (_xmlWriter != null)
return;
EnsurePropertyPart(); // Should succeed or throw an exception.
Stream writerStream = new IgnoreFlushAndCloseStream(_propertyPart.GetStream(FileMode.Create, FileAccess.Write));
_xmlWriter = XmlWriter.Create(writerStream, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 });
WriteXmlStartTagsForPackageProperties();
}
// Create a property part if none exists yet.
private void EnsurePropertyPart()
{
if (_propertyPart != null)
return;
// If _propertyPart is null, no property part existed when this object was created,
// and this function is being called for the first time.
// However, when read access is available, we can afford the luxury of checking whether
// a property part and its referring relationship got correctly created in the meantime
// outside of this class.
// In write-only mode, it is impossible to perform this check, and the external creation
// scenario will result in an exception being thrown.
if (_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite)
{
_propertyPart = GetPropertyPart();
if (_propertyPart != null)
return;
}
CreatePropertyPart();
}
// Create a new property relationship pointing to a new property part.
// If only this class is used for manipulating property relationships, there cannot be a
// pre-existing dangling property relationship.
// No check is performed here for other classes getting misused insofar as this function
// has to work in write-only mode.
private void CreatePropertyPart()
{
_propertyPart = _package.CreatePart(GeneratePropertyPartUri(), s_coreDocumentPropertiesContentType.ToString());
_package.CreateRelationship(_propertyPart.Uri, TargetMode.Internal,
CoreDocumentPropertiesRelationshipType);
}
private Uri GeneratePropertyPartUri()
{
string propertyPartName = DefaultPropertyPartNamePrefix
+ Guid.NewGuid().ToString(GuidStorageFormatString)
+ DefaultPropertyPartNameExtension;
return PackUriHelper.CreatePartUri(new Uri(propertyPartName, UriKind.Relative));
}
private void WriteXmlStartTagsForPackageProperties()
{
_xmlWriter.WriteStartDocument();
// <coreProperties
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(PackageXmlEnum.CoreProperties), // local name
PackageXmlStringTable.GetXmlString(PackageXmlEnum.PackageCorePropertiesNamespace)); // namespace
// xmlns:dc
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespace));
// xmlns:dcterms
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublincCoreTermsNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
// xmlns:xsi
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
}
// Write the property elements and clear _dirty.
private void SerializeDirtyProperties()
{
// Create a property element for each non-null entry.
foreach (KeyValuePair<PackageXmlEnum, Object> entry in _propertyDictionary)
{
Debug.Assert(entry.Value != null);
PackageXmlEnum propertyNamespace = PackageXmlStringTable.GetXmlNamespace(entry.Key);
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(entry.Key),
PackageXmlStringTable.GetXmlString(propertyNamespace));
if (entry.Value is Nullable<DateTime>)
{
if (propertyNamespace == PackageXmlEnum.DublinCoreTermsNamespace)
{
// xsi:type=
_xmlWriter.WriteStartAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// "dcterms:W3CDTF"
_xmlWriter.WriteQualifiedName(W3cdtf,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
_xmlWriter.WriteEndAttribute();
}
// Use sortable ISO 8601 date/time pattern. Include second fractions down to the 100-nanosecond interval,
// which is the definition of a "tick" for the DateTime type.
_xmlWriter.WriteString(XmlConvert.ToString(((Nullable<DateTime>)entry.Value).Value.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffffffZ"));
}
else
{
// The following uses the fact that ToString is virtual.
_xmlWriter.WriteString(entry.Value.ToString());
}
_xmlWriter.WriteEndElement();
}
// Mark properties as saved.
_dirty = false;
}
// Add end markup and close the writer.
private void CloseXmlWriter()
{
// Close the root element.
_xmlWriter.WriteEndElement();
// Close the writer itself.
_xmlWriter.Dispose();
// Make sure we know it's closed.
_xmlWriter = null;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private fields
//
//------------------------------------------------------
#region Private Fields
private Package _package;
private PackagePart _propertyPart;
private XmlWriter _xmlWriter;
// Table of objects from the closed set of literals defined below.
// (Uses object comparison rather than string comparison.)
private const int NumCoreProperties = 16;
private Dictionary<PackageXmlEnum, Object> _propertyDictionary = new Dictionary<PackageXmlEnum, Object>(NumCoreProperties);
private bool _dirty = false;
// This System.Xml.NameTable makes sure that we use the same references to strings
// throughout (including when parsing Xml) and so can perform reference comparisons
// rather than value comparisons.
private NameTable _nameTable;
// Literals.
private static readonly ContentType s_coreDocumentPropertiesContentType
= new ContentType("application/vnd.openxmlformats-package.core-properties+xml");
private const string CoreDocumentPropertiesRelationshipType
= "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
private const string DefaultPropertyPartNamePrefix =
"/package/services/metadata/core-properties/";
private const string W3cdtf = "W3CDTF";
private const string DefaultPropertyPartNameExtension = ".psmdcp";
private const string GuidStorageFormatString = @"N"; // N - simple format without adornments
private static PackageXmlEnum[] s_validProperties = new PackageXmlEnum[] {
PackageXmlEnum.Creator,
PackageXmlEnum.Identifier,
PackageXmlEnum.Title,
PackageXmlEnum.Subject,
PackageXmlEnum.Description,
PackageXmlEnum.Language,
PackageXmlEnum.Created,
PackageXmlEnum.Modified,
PackageXmlEnum.ContentType,
PackageXmlEnum.Keywords,
PackageXmlEnum.Category,
PackageXmlEnum.Version,
PackageXmlEnum.LastModifiedBy,
PackageXmlEnum.ContentStatus,
PackageXmlEnum.Revision,
PackageXmlEnum.LastPrinted
};
// Array of formats to supply to XmlConvert.ToDateTime or DateTime.ParseExact.
// xsd:DateTime requires full date time in sortable (ISO 8601) format.
// It can be expressed in local time, universal time (Z), or relative to universal time (zzz).
// Negative years are accepted.
// IMPORTANT: Second fractions are recognized only down to 1 tenth of a microsecond because this is the resolution
// of the DateTime type. The Xml standard, however, allows any number of decimals; but XmlConvert only offers
// this very awkward API with an explicit pattern enumeration.
private static readonly string[] s_dateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:sszzz",
@"\-yyyy-MM-ddTHH:mm:ss",
@"\-yyyy-MM-ddTHH:mm:ssZ",
@"\-yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ss.fzzz",
@"\-yyyy-MM-ddTHH:mm:ss.f",
@"\-yyyy-MM-ddTHH:mm:ss.fZ",
@"\-yyyy-MM-ddTHH:mm:ss.fzzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.ffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ff",
@"\-yyyy-MM-ddTHH:mm:ss.ffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffzzz",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.fffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fff",
@"\-yyyy-MM-ddTHH:mm:ss.fffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffzzz",
"yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffff",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffzzz",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffffff",
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffzzz",
};
#endregion Private Fields
}
}
| |
//css_dbg /t:winexe;
using System;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using System.Reflection;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using CSScriptLibrary;
namespace CSSScript
{
public class ShellExForm : System.Windows.Forms.Form
{
int spaceBetweenItems = 2;
private TreeView treeView1;
private Button upBtn;
private Button downBtn;
private Button cancelBtn;
private Button okBtn;
private Button browseBtn;
private Button helpBtn;
private System.ComponentModel.Container components = null;
public bool readOnlyMode = false;
private Button refreshBtn;
private Button editBtn;
public TreeViewEventHandler additionalOnCheckHandler;
public ShellExForm(bool readOnlyMode)
{
this.readOnlyMode = readOnlyMode;
Initialise();
}
public ShellExForm(string baseDirectory)
{
//System.Diagnostics.Debug.Assert(false);
this.baseDirectory = baseDirectory;
Initialise();
}
public ShellExForm()
{
Initialise();
}
void Initialise()
{
InitializeComponent();
upBtn.Text =
downBtn.Text = "";
if (Environment.Version.Major >= 2)
{
// the following code must be generated dynamically as ShellEx is guaranteed to be run
//under CLR 1.1 as part of the installation sequence (config.cs) and 1.1 cannot handle
//"this.treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(this.treeView1_DrawNode);"
treeViewExtension = new AsmHelper(CSScript.LoadCode(treeViewExtensionCode, null, false, this.GetType().Assembly.Location));
treeViewExtension.Invoke("*.Extend", treeView1);
}
}
AsmHelper treeViewExtension;
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.treeView1 = new System.Windows.Forms.TreeView();
this.upBtn = new System.Windows.Forms.Button();
this.downBtn = new System.Windows.Forms.Button();
this.cancelBtn = new System.Windows.Forms.Button();
this.okBtn = new System.Windows.Forms.Button();
this.browseBtn = new System.Windows.Forms.Button();
this.helpBtn = new System.Windows.Forms.Button();
this.refreshBtn = new System.Windows.Forms.Button();
this.editBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.treeView1.HideSelection = false;
this.treeView1.Location = new System.Drawing.Point(12, 12);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(383, 375);
this.treeView1.TabIndex = 0;
this.treeView1.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterCheck);
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// upBtn
//
this.upBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.upBtn.Location = new System.Drawing.Point(413, 23);
this.upBtn.Name = "upBtn";
this.upBtn.Size = new System.Drawing.Size(75, 24);
this.upBtn.TabIndex = 1;
this.upBtn.Text = "Up";
this.upBtn.Click += new System.EventHandler(this.upBtn_Click);
//
// downBtn
//
this.downBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.downBtn.Location = new System.Drawing.Point(413, 52);
this.downBtn.Name = "downBtn";
this.downBtn.Size = new System.Drawing.Size(75, 24);
this.downBtn.TabIndex = 1;
this.downBtn.Text = "Down";
this.downBtn.Click += new System.EventHandler(this.downBtn_Click);
//
// cancelBtn
//
this.cancelBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelBtn.Location = new System.Drawing.Point(413, 363);
this.cancelBtn.Name = "cancelBtn";
this.cancelBtn.Size = new System.Drawing.Size(75, 24);
this.cancelBtn.TabIndex = 2;
this.cancelBtn.Text = "Cancel";
this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click);
//
// okBtn
//
this.okBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okBtn.Location = new System.Drawing.Point(413, 333);
this.okBtn.Name = "okBtn";
this.okBtn.Size = new System.Drawing.Size(75, 24);
this.okBtn.TabIndex = 2;
this.okBtn.Text = "Ok";
this.okBtn.Click += new System.EventHandler(this.okBtn_Click);
//
// browseBtn
//
this.browseBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.browseBtn.Location = new System.Drawing.Point(413, 114);
this.browseBtn.Name = "browseBtn";
this.browseBtn.Size = new System.Drawing.Size(75, 24);
this.browseBtn.TabIndex = 2;
this.browseBtn.Text = "Browse";
this.browseBtn.Click += new System.EventHandler(this.browseBtn_Click);
//
// helpBtn
//
this.helpBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.helpBtn.Location = new System.Drawing.Point(413, 174);
this.helpBtn.Name = "helpBtn";
this.helpBtn.Size = new System.Drawing.Size(75, 24);
this.helpBtn.TabIndex = 2;
this.helpBtn.Text = "Help";
this.helpBtn.Click += new System.EventHandler(this.helpBtn_Click);
//
// refreshBtn
//
this.refreshBtn.Location = new System.Drawing.Point(413, 82);
this.refreshBtn.Name = "refreshBtn";
this.refreshBtn.Size = new System.Drawing.Size(75, 23);
this.refreshBtn.TabIndex = 3;
this.refreshBtn.Text = "Refresh";
this.refreshBtn.Click += new System.EventHandler(this.refreshBtn_Click);
//
// editBtn
//
this.editBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.editBtn.Location = new System.Drawing.Point(413, 144);
this.editBtn.Name = "editBtn";
this.editBtn.Size = new System.Drawing.Size(75, 24);
this.editBtn.TabIndex = 2;
this.editBtn.Text = "Edit";
this.editBtn.Click += new System.EventHandler(this.editBtn_Click);
//
// ShellExForm
//
this.AcceptButton = this.okBtn;
this.CancelButton = this.cancelBtn;
this.ClientSize = new System.Drawing.Size(503, 399);
this.Controls.Add(this.refreshBtn);
this.Controls.Add(this.helpBtn);
this.Controls.Add(this.editBtn);
this.Controls.Add(this.browseBtn);
this.Controls.Add(this.okBtn);
this.Controls.Add(this.cancelBtn);
this.Controls.Add(this.downBtn);
this.Controls.Add(this.upBtn);
this.Controls.Add(this.treeView1);
this.KeyPreview = true;
this.Name = "ShellExForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "CS-Script Advanced Shell Extension";
this.Load += new System.EventHandler(this.Form1_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ShellExForm_KeyDown);
this.ResumeLayout(false);
}
#endregion
private void button1_Click(object sender, System.EventArgs e)
{
this.Close();
}
string _baseDirectory;
public string baseDirectory
{
get
{
//System.Diagnostics.Debug.Assert(false);
return (_baseDirectory = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_SHELLEX_DIR%"));
}
set
{
//System.Diagnostics.Debug.Assert(false);
_baseDirectory = value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.CheckBoxes = true;
RefreshTreeView();
}
public void RefreshTreeView()
{
treeView1.Nodes.Clear();
ReadShellExtensions(baseDirectory);
if (treeView1.Nodes.Count != 0)
treeView1.SelectedNode = treeView1.Nodes[0];
if (readOnlyMode)
{
treeView1.Dock = DockStyle.Fill;
treeView1.BackColor = Color.WhiteSmoke;
foreach (Control c in this.Controls)
if (c is Button)
c.Visible = false;
}
}
public void ReadShellExtensions(string path)
{
int iterator = 0;
ArrayList dirList = new ArrayList();
ArrayList itemsList = new ArrayList();
dirList.Add(path);
while (iterator < dirList.Count)
{
foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString()))
{
dirList.Add(dir);
itemsList.Add(dir);
}
foreach (string file in Directory.GetFiles(dirList[iterator].ToString(), "*.cmd*"))
itemsList.Add(file);
foreach (string file in Directory.GetFiles(dirList[iterator].ToString(), "*.separator"))
itemsList.Add(file);
iterator++;
}
//sort according the ShellExtension sorting algorithm
itemsList.Sort(Sorter.instance);
foreach (string item in itemsList)
Trace.WriteLine(item);
TreeNode dirNode = null;
foreach (string item in itemsList)
{
SEItem shellEx = new SEItem(item);
TreeNode node = new TreeNode(shellEx.ToString());
node.Checked = shellEx.Enabled;
node.Tag = shellEx;
if (dirNode == null)
{
treeView1.Nodes.Add(node);
}
else
{
TreeNode parentNode = dirNode;
SEItem parentShellEx = null;
do
{
parentShellEx = (parentNode.Tag as SEItem);
if (parentShellEx == null)
{
treeView1.Nodes.Add(node);
}
else if (parentShellEx.level == shellEx.level - 1)
{
parentNode.Nodes.Add(node);
break;
}
parentNode = parentNode.Parent;
} while (parentNode != null);
if (parentNode == null)
treeView1.Nodes.Add(node);
}
if (shellEx.isDir)
dirNode = node;
}
treeView1.ExpandAll();
}
class Sorter : IComparer
{
static public Sorter instance = new Sorter();
public int Compare(object x, object y)
{
return SortMethod(x.ToString(), y.ToString());
}
int SortMethod(string x, string y)
{
string[] partsX = x.Split(Path.DirectorySeparatorChar);
string[] partsY = y.Split(Path.DirectorySeparatorChar);
for (int i = 0; i < Math.Min(partsX.Length, partsY.Length); i++)
{
string indexX = partsX[i].Substring(0, Math.Min(2, partsX[i].Length));
string indexY = partsY[i].Substring(0, Math.Min(2, partsX[i].Length));
if (indexX != indexY)
return string.Compare(indexX, indexY);
}
if (partsX.Length < partsY.Length)
return -1;
else if (partsX.Length == partsY.Length)
return 0;
else
return 1;
}
}
#if NET2
Brush treeViewBackBrush = null;
Brush TreeViewBackBrush
{
get
{
if (treeViewBackBrush == null)
treeViewBackBrush = new SolidBrush(treeView1.BackColor);
return treeViewBackBrush;
}
}
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
SEItem item = (SEItem)e.Node.Tag;
Brush b = Brushes.Black;
if (item.isConsole)
b = Brushes.Blue;
if (!item.Enabled)
{
b = Brushes.Gray;
}
else
{
TreeNode parent = e.Node.Parent;
while (parent != null)
{
if (!parent.Checked)
{
b = Brushes.Gray;
break;
}
parent = parent.Parent;
}
}
Rectangle frame = e.Bounds;
if ((e.State & TreeNodeStates.Selected) != 0)
{
frame.Width = (int)e.Graphics.MeasureString(item.ToString(), treeView1.Font).Width;
e.Graphics.FillRectangle(TreeViewBackBrush, frame);
frame.Inflate(-1, -1);
e.Graphics.DrawRectangle(Pens.Red, frame);
}
if (item.isSeparator)
e.Graphics.DrawLine(Pens.Black, frame.Left + 4, frame.Top + frame.Height / 2, frame.Right - 4, frame.Top + frame.Height / 2);
else
e.Graphics.DrawString(item.ToString(), treeView1.Font, b, e.Bounds.Left, e.Bounds.Top + 2);
}
#endif
static string treeViewExtensionCode =
@"using System;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Drawing.Drawing2D;
public class ShellExtCustomDraw
{
static TreeView treeView1;
static public void Extend(TreeView treeView1)
{
ShellExtCustomDraw.treeView1 = treeView1;
treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(treeView1_DrawNode);
treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
}
static Brush treeViewBackBrush = null;
static Brush TreeViewBackBrush
{
get
{
if (treeViewBackBrush == null)
treeViewBackBrush = new SolidBrush(treeView1.BackColor);
return treeViewBackBrush;
}
}
static void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
CSSScript.SEItem item = (CSSScript.SEItem)e.Node.Tag;
Brush b = Brushes.Black;
if (item.isConsole)
b = Brushes.Blue;
if (!item.Enabled)
{
b = Brushes.Gray;
}
else
{
TreeNode parent = e.Node.Parent;
while (parent != null)
{
if (!parent.Checked)
{
b = Brushes.Gray;
break;
}
parent = parent.Parent;
}
}
Rectangle frame = e.Bounds;
if ((e.State & TreeNodeStates.Selected) != 0)
{
frame.Width = (int)e.Graphics.MeasureString(item.ToString(), treeView1.Font).Width;
e.Graphics.FillRectangle(TreeViewBackBrush, frame);
frame.Inflate(-1, -1);
e.Graphics.DrawRectangle(Pens.Red, frame);
}
if (item.isSeparator)
e.Graphics.DrawLine(Pens.Black, frame.Left + 4, frame.Top + frame.Height / 2, frame.Right - 4, frame.Top + frame.Height / 2);
else
e.Graphics.DrawString(item.ToString(), treeView1.Font, b, e.Bounds.Left, e.Bounds.Top + 2);
}
}";
bool ignoreChecking = false;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (!ignoreChecking)
{
SEItem item = (SEItem)e.Node.Tag;
if (readOnlyMode)
{
ignoreChecking = true;
e.Node.Checked = !e.Node.Checked;
ignoreChecking = false;
}
else
{
if (item.isDir) //directories cannot be disabled
{
ignoreChecking = true;
e.Node.Checked = !e.Node.Checked;
ignoreChecking = false;
}
else
{
item.Enabled = !item.Enabled;
//if (item.Enabled)
// e.Node.Expand();
//else
// e.Node.Collapse();
treeView1.Invalidate();
}
}
if (additionalOnCheckHandler != null)
additionalOnCheckHandler(sender, e);
}
}
private void upBtn_Click(object sender, EventArgs e)
{
TreeNode node = treeView1.SelectedNode;
if (node != null)
{
if (node.Index == 0) //first
{
if (node.Parent != null)
{
int nodeIndex = node.Parent.Index;
TreeNodeCollection coll = (node.Parent.Parent == null ? treeView1.Nodes : node.Parent.Parent.Nodes);
node.Remove();
coll.Insert(nodeIndex, node);
}
}
else
{
int nodeIndex = node.Index;
TreeNodeCollection coll = (node.Parent == null ? treeView1.Nodes : node.Parent.Nodes);
if (coll[nodeIndex - 1].Nodes.Count != 0) //has child nodes
{
node.Remove();
coll[nodeIndex - 1].Nodes.Add(node);
}
else
{
node.Remove();
coll.Insert(nodeIndex - 1, node);
}
}
treeView1.SelectedNode = node;
}
treeView1.Select();
}
private void downBtn_Click(object sender, EventArgs e)
{
TreeNode node = treeView1.SelectedNode;
if (node != null)
{
TreeNodeCollection coll = (node.Parent == null ? treeView1.Nodes : node.Parent.Nodes);
if (node.Index == coll.Count - 1) //last
{
if (node.Parent != null)
{
TreeNodeCollection parentColl = node.Parent.Parent == null ? treeView1.Nodes : node.Parent.Parent.Nodes;
int nodeIndex = node.Parent.Index;
node.Remove();
parentColl.Insert(nodeIndex + 1, node);
}
}
else
{
int nodeIndex = node.Index;
if (coll[nodeIndex + 1].Nodes.Count != 0) //has child nodes
{
node.Remove();
coll[nodeIndex].Nodes.Insert(0, node);
}
else
{
node.Remove();
coll.Insert(nodeIndex + 1, node);
}
}
treeView1.SelectedNode = node;
}
treeView1.Select();
}
#region Images
static Image DullImage(Image img)
{
Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(newBitmap))
{
//g.DrawImage(image, 0.0f, 0.0f); //draw original image
ImageAttributes imageAttributes = new ImageAttributes();
int width = img.Width;
int height = img.Height;
float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // red scaling factor of 1
new float[] {0, 1, 0, 0, 0}, // green scaling factor of 1
new float[] {0, 0, 1, 0, 0}, // blue scaling factor of 1
new float[] {0, 0, 0, 1, 0}, // alpha scaling factor of 1
new float[] {.05f, .05f, .05f, 0, 1}}; // three translations of 0.2
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(
img,
new Rectangle(0, 0, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
}
return newBitmap;
}
static Image CreateUpImage()
{
Image img = new Bitmap(25, 25);
using (Graphics g = Graphics.FromImage(img))
{
LinearGradientBrush lgb = new LinearGradientBrush(
new Point(0, 0),
new Point(25, 0),
Color.YellowGreen,
Color.DarkGreen);
int xOffset = -4;
int yOffset = -1;
g.FillPolygon(lgb, new Point[]
{
new Point(15+xOffset,5+yOffset),
new Point(25+xOffset,15+yOffset),
new Point(18+xOffset,15+yOffset),
new Point(18+xOffset,20+yOffset),
new Point(12+xOffset,20+yOffset),
new Point(12+xOffset,15+yOffset),
new Point(5+xOffset,15+yOffset)
});
}
return img;
}
static Image CreateDownImage()
{
Image img = new Bitmap(CreateUpImage());
img.RotateFlip(RotateFlipType.Rotate180FlipX);
return img;
}
Image imgUp = CreateUpImage();
Image imgDown = CreateDownImage();
Image imgUpDisabled = DullImage(CreateUpImage());
Image imgDownDisabled = DullImage(CreateDownImage());
#endregion
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
upBtn.Image = upBtn.Enabled ? imgUp : imgUpDisabled;
downBtn.Image = downBtn.Enabled ? imgDown : imgDownDisabled;
}
private void okBtn_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
try
{
ProcessDirNode(treeView1.Nodes);
RemoveEmptyChildDirs(baseDirectory);
}
finally
{
Cursor = Cursors.Default;
}
}
void RemoveEmptyChildDirs(string path)
{
int iterator = 0;
ArrayList dirList = new ArrayList();
dirList.Add(path);
while (iterator < dirList.Count)
{
foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString()))
dirList.Add(dir);
iterator++;
}
dirList.RemoveAt(0);//remove parent dir
foreach (string dir in dirList)
if (Directory.Exists(dir) && IsDirEmpty(dir))
Directory.Delete(dir, true);
}
bool IsDirEmpty(string path)
{
int iterator = 0;
ArrayList dirList = new ArrayList();
ArrayList fileList = new ArrayList();
dirList.Add(path);
while (iterator < dirList.Count)
{
foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString()))
dirList.Add(dir);
foreach (string file in Directory.GetFiles(dirList[iterator].ToString()))
fileList.Add(file);
iterator++;
}
return fileList.Count == 0;
}
void ProcessFileNode(TreeNode node)
{
SEItem shellEx = (SEItem)node.Tag;
//reconstruct full (File not treeView) path
string newPath = (node.Index * spaceBetweenItems).ToString("D2") + "." + shellEx.GetLogicalFileName();
TreeNode child = node;
TreeNode parent;
while ((parent = child.Parent) != null)
{
newPath = Path.Combine((parent.Index * spaceBetweenItems).ToString("D2") + "." + (parent.Tag as SEItem).GetLogicalFileName(), newPath);
child = parent;
}
newPath = Path.Combine(baseDirectory, newPath);
//Trace.WriteLine(newPath);
if (newPath != shellEx.location)
{
if (!Directory.Exists(Path.GetDirectoryName(newPath)))
Directory.CreateDirectory(Path.GetDirectoryName(newPath));
File.Move(shellEx.location, newPath);
}
}
void ProcessDirNode(TreeNodeCollection nodes)
{
ArrayList dirs = new ArrayList();
foreach (TreeNode node in nodes)
{
if ((node.Tag as SEItem).isDir)
dirs.Add(node);
else
ProcessFileNode(node);
}
foreach (TreeNode node in dirs)
ProcessDirNode(node.Nodes);
}
private void browseBtn_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", "/e, \"" + Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_SHELLEX_DIR%\") + "\"");
}
private void helpBtn_Click(object sender, EventArgs e)
{
Process.Start(Environment.ExpandEnvironmentVariables(@"%windir%\System32\rundll32.exe"),
"\"" + Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_SHELLEX_DIR%\ShellExt.cs.{25D84CB0-7345-11D3-A4A1-0080C8ECFED4}.dll") + "\", Help");
}
private void ShellExForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5)
RefreshTreeView();
}
private void refreshBtn_Click(object sender, EventArgs e)
{
RefreshTreeView();
}
private void editBtn_Click(object sender, EventArgs e)
{
TreeNode node = treeView1.SelectedNode;
if (node != null)
Process.Start("notepad.exe", "\"" + (node.Tag as SEItem).location + "\"");
}
private void cancelBtn_Click(object sender, EventArgs e)
{
Close();
}
}
public class SEItem
{
public SEItem(string path)
{
this.path = path;
this.location = path;
Refresh();
}
public void Refresh()
{
string logicalPath = path;
isDir = !File.Exists(logicalPath);
if (path.EndsWith(".disabled"))
{
enabled = false;
logicalPath = logicalPath.Replace(".disabled", "");
}
else
{
enabled = true;
}
isSeparator = !isDir && (path.EndsWith("separator") || path.EndsWith("separator.disabled"));
isConsole = !isDir && !isSeparator && path.EndsWith(".c.cmd");
level = path.Split(Path.DirectorySeparatorChar).Length - 1;
}
public override string ToString()
{
if (isSeparator)
return "------------------------";
else
{
string[] parts = path.Split(Path.DirectorySeparatorChar);
return parts[parts.Length - 1].Substring(3).Replace(".c.cmd", "").Replace(".cmd", "").Replace(".disabled", "");
}
}
public string GetLogicalFileName()
{
string retval = this.ToString();
if (!isSeparator)
{
if (!isDir)
{
if (isConsole)
retval += ".c";
retval += ".cmd";
}
}
else
{
retval = "separator";
}
if (!enabled)
retval += ".disabled";
return retval;
}
public bool isDir;
public bool isConsole;
public bool isSeparator;
bool enabled = false;
public bool Enabled
{
get { return enabled; }
set
{
if (enabled != value)
{
if (value)
path = path.Substring(0, path.Length - ".disabled".Length);
else
path += ".disabled";
}
enabled = value;
}
}
public string path; //note this.path can be changed during the user operations
public string location; //original value of this.path
public int level;
}
}
class Script
{
const string usage = "Usage: cscscript shellEx [directory] ...\nStarts configuration console for CS-Script Advanced Shell Extension.\n";
static public void Main(string[] args)
{
if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))
Console.WriteLine(usage);
else
if (args.Length == 0)
Application.Run(new CSSScript.ShellExForm());
else
Application.Run(new CSSScript.ShellExForm(args[0]));
}
}
| |
#region License and Terms
//
// NCrontab - Crontab for .NET
// Copyright (c) 2008 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace NCrontab
{
#region Imports
using System;
using System.Collections;
using System.Globalization;
using System.IO;
#endregion
/// <summary>
/// Represents a single crontab field.
/// </summary>
[ Serializable ]
public sealed class CrontabField : ICrontabField
{
readonly BitArray _bits;
/* readonly */ int _minValueSet;
/* readonly */ int _maxValueSet;
readonly CrontabFieldImpl _impl;
/// <summary>
/// Parses a crontab field expression given its kind.
/// </summary>
public static CrontabField Parse(CrontabFieldKind kind, string expression)
{
return TryParse(kind, expression, v => v, e => { throw e(); });
}
public static CrontabField TryParse(CrontabFieldKind kind, string expression)
{
return TryParse(kind, expression, v => v, _ => null);
}
public static T TryParse<T>(CrontabFieldKind kind, string expression, Converter<CrontabField, T> valueSelector, Converter<ExceptionProvider, T> errorSelector)
{
var field = new CrontabField(CrontabFieldImpl.FromKind(kind));
var error = field._impl.TryParse(expression, field.Accumulate, null, e => e);
return error == null ? valueSelector(field) : errorSelector(error);
}
/// <summary>
/// Parses a crontab field expression representing seconds.
/// </summary>
public static CrontabField Seconds(string expression)
{
return Parse(CrontabFieldKind.Second, expression);
}
/// <summary>
/// Parses a crontab field expression representing minutes.
/// </summary>
public static CrontabField Minutes(string expression)
{
return Parse(CrontabFieldKind.Minute, expression);
}
/// <summary>
/// Parses a crontab field expression representing hours.
/// </summary>
public static CrontabField Hours(string expression)
{
return Parse(CrontabFieldKind.Hour, expression);
}
/// <summary>
/// Parses a crontab field expression representing days in any given month.
/// </summary>
public static CrontabField Days(string expression)
{
return Parse(CrontabFieldKind.Day, expression);
}
/// <summary>
/// Parses a crontab field expression representing months.
/// </summary>
public static CrontabField Months(string expression)
{
return Parse(CrontabFieldKind.Month, expression);
}
/// <summary>
/// Parses a crontab field expression representing days of a week.
/// </summary>
public static CrontabField DaysOfWeek(string expression)
{
return Parse(CrontabFieldKind.DayOfWeek, expression);
}
CrontabField(CrontabFieldImpl impl)
{
if (impl == null)
throw new ArgumentNullException("impl");
_impl = impl;
_bits = new BitArray(impl.ValueCount);
_bits.SetAll(false);
_minValueSet = int.MaxValue;
_maxValueSet = -1;
}
/// <summary>
/// Gets the first value of the field or -1.
/// </summary>
public int GetFirst()
{
return _minValueSet < int.MaxValue ? _minValueSet : -1;
}
/// <summary>
/// Gets the next value of the field that occurs after the given
/// start value or -1 if there is no next value available.
/// </summary>
public int Next(int start)
{
if (start < _minValueSet)
return _minValueSet;
var startIndex = ValueToIndex(start);
var lastIndex = ValueToIndex(_maxValueSet);
for (var i = startIndex; i <= lastIndex; i++)
{
if (_bits[i])
return IndexToValue(i);
}
return -1;
}
int IndexToValue(int index)
{
return index + _impl.MinValue;
}
int ValueToIndex(int value)
{
return value - _impl.MinValue;
}
/// <summary>
/// Determines if the given value occurs in the field.
/// </summary>
public bool Contains(int value)
{
return _bits[ValueToIndex(value)];
}
/// <summary>
/// Accumulates the given range (start to end) and interval of values
/// into the current set of the field.
/// </summary>
/// <remarks>
/// To set the entire range of values representable by the field,
/// set <param name="start" /> and <param name="end" /> to -1 and
/// <param name="interval" /> to 1.
/// </remarks>
T Accumulate<T>(int start, int end, int interval, T success, Converter<ExceptionProvider, T> errorSelector)
{
var minValue = _impl.MinValue;
var maxValue = _impl.MaxValue;
if (start == end)
{
if (start < 0)
{
//
// We're setting the entire range of values.
//
if (interval <= 1)
{
_minValueSet = minValue;
_maxValueSet = maxValue;
_bits.SetAll(true);
return success;
}
start = minValue;
end = maxValue;
}
else
{
//
// We're only setting a single value - check that it is in range.
//
if (start < minValue)
return OnValueBelowMinError(start, errorSelector);
if (start > maxValue)
return OnValueAboveMaxError(start, errorSelector);
}
}
else
{
//
// For ranges, if the start is bigger than the end value then
// swap them over.
//
if (start > end)
{
end ^= start;
start ^= end;
end ^= start;
}
if (start < 0)
start = minValue;
else if (start < minValue)
return OnValueBelowMinError(start, errorSelector);
if (end < 0)
end = maxValue;
else if (end > maxValue)
return OnValueAboveMaxError(end, errorSelector);
}
if (interval < 1)
interval = 1;
int i;
//
// Populate the _bits table by setting all the bits corresponding to
// the valid field values.
//
for (i = start - minValue; i <= (end - minValue); i += interval)
_bits[i] = true;
//
// Make sure we remember the minimum value set so far Keep track of
// the highest and lowest values that have been added to this field
// so far.
//
if (_minValueSet > start)
_minValueSet = start;
i += (minValue - interval);
if (_maxValueSet < i)
_maxValueSet = i;
return success;
}
T OnValueAboveMaxError<T>(int value, Converter<ExceptionProvider, T> errorSelector)
{
return errorSelector(
() => new CrontabException(string.Format(
"{0} is higher than the maximum allowable value for the [{3}] field. Value must be between {1} and {2} (all inclusive).",
value, _impl.MinValue, _impl.MaxValue, _impl.Kind)));
}
T OnValueBelowMinError<T>(int value, Converter<ExceptionProvider, T> errorSelector)
{
return errorSelector(
() => new CrontabException(string.Format(
"{0} is lower than the minimum allowable value for the [{3}] field. Value must be between {1} and {2} (all inclusive).",
value, _impl.MinValue, _impl.MaxValue, _impl.Kind)));
}
public override string ToString()
{
return ToString(null);
}
public string ToString(string format)
{
var writer = new StringWriter(CultureInfo.InvariantCulture);
switch (format)
{
case "G":
case null:
Format(writer, true);
break;
case "N":
Format(writer);
break;
default:
throw new FormatException();
}
return writer.ToString();
}
public void Format(TextWriter writer)
{
Format(writer, false);
}
public void Format(TextWriter writer, bool noNames)
{
_impl.Format(this, writer, noNames);
}
}
}
| |
/*
* 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 Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework;
using OpenSim.Region.CoreModules.Framework.EntityTransfer;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Region.CoreModules.World.Land;
using OpenSim.Region.OptionalModules;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Scenes.Tests
{
public class SceneObjectCrossingTests : OpenSimTestCase
{
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
[Test]
public void TestCrossOnSameSimulator()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(sceneA, config, etmA);
SceneHelpers.SetupSceneModules(sceneB, config, etmB);
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = new Vector3(128, 10, 20);
// Cross with a negative value
so1.AbsolutePosition = new Vector3(128, -10, 20);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id));
Assert.NotNull(sceneB.GetSceneObjectGroup(so1Id));
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
/// <remarks>
/// Possibly this should belong in ScenePresenceCrossingTests, though here it is the object that is being moved
/// where the avatar is just a passenger.
/// </remarks>
[Test]
public void TestCrossOnSameSimulatorWithSittingAvatar()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
Vector3 so1StartPos = new Vector3(128, 10, 20);
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
IConfig entityTransferConfig = config.AddConfig("EntityTransfer");
// In order to run a single threaded regression test we do not want the entity transfer module waiting
// for a callback from the destination scene before removing its avatar data.
entityTransferConfig.Set("wait_for_callback", false);
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA);
SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB);
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = so1StartPos;
AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId);
TestClient tc = new TestClient(acd, sceneA);
List<TestClient> destinationTestClients = new List<TestClient>();
EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
ScenePresence sp1SceneA = SceneHelpers.AddScenePresence(sceneA, tc, acd);
sp1SceneA.AbsolutePosition = so1StartPos;
sp1SceneA.HandleAgentRequestSit(sp1SceneA.ControllingClient, sp1SceneA.UUID, so1.UUID, Vector3.Zero);
// Cross
sceneA.SceneGraph.UpdatePrimGroupPosition(
so1.LocalId, new Vector3(so1StartPos.X, so1StartPos.Y - 20, so1StartPos.Z), userId);
SceneObjectGroup so1PostCross;
{
ScenePresence sp1SceneAPostCross = sceneA.GetScenePresence(userId);
Assert.IsTrue(sp1SceneAPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly false");
ScenePresence sp1SceneBPostCross = sceneB.GetScenePresence(userId);
TestClient sceneBTc = ((TestClient)sp1SceneBPostCross.ControllingClient);
sceneBTc.CompleteMovement();
Assert.IsFalse(sp1SceneBPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
Assert.IsTrue(sp1SceneBPostCross.IsSatOnObject);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id), "uck");
so1PostCross = sceneB.GetSceneObjectGroup(so1Id);
Assert.NotNull(so1PostCross);
Assert.AreEqual(1, so1PostCross.GetSittingAvatarsCount());
}
Vector3 so1PostCrossPos = so1PostCross.AbsolutePosition;
// Console.WriteLine("CRISSCROSS");
// Recross
sceneB.SceneGraph.UpdatePrimGroupPosition(
so1PostCross.LocalId, new Vector3(so1PostCrossPos.X, so1PostCrossPos.Y + 20, so1PostCrossPos.Z), userId);
{
ScenePresence sp1SceneBPostReCross = sceneB.GetScenePresence(userId);
Assert.IsTrue(sp1SceneBPostReCross.IsChildAgent, "sp1SceneBPostReCross.IsChildAgent unexpectedly false");
ScenePresence sp1SceneAPostReCross = sceneA.GetScenePresence(userId);
TestClient sceneATc = ((TestClient)sp1SceneAPostReCross.ControllingClient);
sceneATc.CompleteMovement();
Assert.IsFalse(sp1SceneAPostReCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
Assert.IsTrue(sp1SceneAPostReCross.IsSatOnObject);
Assert.IsNull(sceneB.GetSceneObjectGroup(so1Id), "uck2");
SceneObjectGroup so1PostReCross = sceneA.GetSceneObjectGroup(so1Id);
Assert.NotNull(so1PostReCross);
Assert.AreEqual(1, so1PostReCross.GetSittingAvatarsCount());
}
}
/// <summary>
/// Test cross with no prim limit module.
/// </summary>
/// <remarks>
/// XXX: This test may FCbe better off in a specific PrimLimitsModuleTest class in optional module tests in the
/// future (though it is configured as active by default, so not really optional).
/// </remarks>
[Test]
public void TestCrossOnSameSimulatorPrimLimitsOkay()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
LandManagementModule lmmA = new LandManagementModule();
LandManagementModule lmmB = new LandManagementModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
IConfig permissionsConfig = config.AddConfig("Permissions");
permissionsConfig.Set("permissionmodules", "PrimLimitsModule");
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(
sceneA, config, etmA, lmmA, new PrimLimitsModule(), new PrimCountModule());
SceneHelpers.SetupSceneModules(
sceneB, config, etmB, lmmB, new PrimLimitsModule(), new PrimCountModule());
// We must set up the parcel for this to work. Normally this is taken care of by OpenSimulator startup
// code which is not yet easily invoked by tests.
lmmA.EventManagerOnNoLandDataFromStorage();
lmmB.EventManagerOnNoLandDataFromStorage();
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = new Vector3(128, 10, 20);
// Cross with a negative value. We must make this call rather than setting AbsolutePosition directly
// because only this will execute permission checks in the source region.
sceneA.SceneGraph.UpdatePrimGroupPosition(so1.LocalId, new Vector3(128, -10, 20), userId);
Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id));
Assert.NotNull(sceneB.GetSceneObjectGroup(so1Id));
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Original file name:
// Generation date: 4/14/2011 10:22:57 AM
namespace LeaderBoardAccess.LeaderboardDataService
{
/// <summary>
/// There are no comments for LeaderboardEntitySet in the schema.
/// </summary>
public partial class LeaderboardEntitySet : global::System.Data.Services.Client.DataServiceContext
{
/// <summary>
/// Initialize a new LeaderboardEntitySet object.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public LeaderboardEntitySet(global::System.Uri serviceRoot) :
base(serviceRoot)
{
this.ResolveName = new global::System.Func<global::System.Type, string>(this.ResolveNameFromType);
this.ResolveType = new global::System.Func<string, global::System.Type>(this.ResolveTypeFromName);
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// Since the namespace configured for this service reference
/// in Visual Studio is different from the one indicated in the
/// server schema, use type-mappers to map between the two.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
protected global::System.Type ResolveTypeFromName(string typeName)
{
if (typeName.StartsWith("LeaderboardModel", global::System.StringComparison.Ordinal))
{
return this.GetType().Assembly.GetType(string.Concat("LeaderBoardAccess.LeaderboardDataService", typeName.Substring(16)), false);
}
return null;
}
/// <summary>
/// Since the namespace configured for this service reference
/// in Visual Studio is different from the one indicated in the
/// server schema, use type-mappers to map between the two.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
protected string ResolveNameFromType(global::System.Type clientType)
{
if (clientType.Namespace.Equals("LeaderBoardAccess.LeaderboardDataService", global::System.StringComparison.Ordinal))
{
return string.Concat("LeaderboardModel.", clientType.Name);
}
return null;
}
/// <summary>
/// There are no comments for Applications in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<Application> Applications
{
get
{
if ((this._Applications == null))
{
this._Applications = base.CreateQuery<Application>("Applications");
}
return this._Applications;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<Application> _Applications;
/// <summary>
/// There are no comments for CostCenters in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<CostCenter> CostCenters
{
get
{
if ((this._CostCenters == null))
{
this._CostCenters = base.CreateQuery<CostCenter>("CostCenters");
}
return this._CostCenters;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<CostCenter> _CostCenters;
/// <summary>
/// There are no comments for features in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<feature> features
{
get
{
if ((this._features == null))
{
this._features = base.CreateQuery<feature>("features");
}
return this._features;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<feature> _features;
/// <summary>
/// There are no comments for pods in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<pod> pods
{
get
{
if ((this._pods == null))
{
this._pods = base.CreateQuery<pod>("pods");
}
return this._pods;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<pod> _pods;
/// <summary>
/// There are no comments for points in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<point> points
{
get
{
if ((this._points == null))
{
this._points = base.CreateQuery<point>("points");
}
return this._points;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<point> _points;
/// <summary>
/// There are no comments for UserAggregations in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<UserAggregation> UserAggregations
{
get
{
if ((this._UserAggregations == null))
{
this._UserAggregations = base.CreateQuery<UserAggregation>("UserAggregations");
}
return this._UserAggregations;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<UserAggregation> _UserAggregations;
/// <summary>
/// There are no comments for UserAggregationPerDays in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<UserAggregationPerDay> UserAggregationPerDays
{
get
{
if ((this._UserAggregationPerDays == null))
{
this._UserAggregationPerDays = base.CreateQuery<UserAggregationPerDay>("UserAggregationPerDays");
}
return this._UserAggregationPerDays;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<UserAggregationPerDay> _UserAggregationPerDays;
/// <summary>
/// There are no comments for Users in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Data.Services.Client.DataServiceQuery<User> Users
{
get
{
if ((this._Users == null))
{
this._Users = base.CreateQuery<User>("Users");
}
return this._Users;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Data.Services.Client.DataServiceQuery<User> _Users;
/// <summary>
/// There are no comments for Applications in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddToApplications(Application application)
{
base.AddObject("Applications", application);
}
/// <summary>
/// There are no comments for CostCenters in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddToCostCenters(CostCenter costCenter)
{
base.AddObject("CostCenters", costCenter);
}
/// <summary>
/// There are no comments for features in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddTofeatures(feature feature)
{
base.AddObject("features", feature);
}
/// <summary>
/// There are no comments for pods in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddTopods(pod pod)
{
base.AddObject("pods", pod);
}
/// <summary>
/// There are no comments for points in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddTopoints(point point)
{
base.AddObject("points", point);
}
/// <summary>
/// There are no comments for UserAggregations in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddToUserAggregations(UserAggregation userAggregation)
{
base.AddObject("UserAggregations", userAggregation);
}
/// <summary>
/// There are no comments for UserAggregationPerDays in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddToUserAggregationPerDays(UserAggregationPerDay userAggregationPerDay)
{
base.AddObject("UserAggregationPerDays", userAggregationPerDay);
}
/// <summary>
/// There are no comments for Users in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public void AddToUsers(User user)
{
base.AddObject("Users", user);
}
}
/// <summary>
/// There are no comments for LeaderboardModel.Application in the schema.
/// </summary>
/// <KeyProperties>
/// appid
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("appid")]
public partial class Application
{
/// <summary>
/// Create a new Application object.
/// </summary>
/// <param name="appid">Initial value of appid.</param>
/// <param name="appname">Initial value of appname.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static Application CreateApplication(int appid, string appname)
{
Application application = new Application();
application.appid = appid;
application.appname = appname;
return application;
}
/// <summary>
/// There are no comments for Property appid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int appid
{
get
{
return this._appid;
}
set
{
this.OnappidChanging(value);
this._appid = value;
this.OnappidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _appid;
partial void OnappidChanging(int value);
partial void OnappidChanged();
/// <summary>
/// There are no comments for Property appname in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string appname
{
get
{
return this._appname;
}
set
{
this.OnappnameChanging(value);
this._appname = value;
this.OnappnameChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _appname;
partial void OnappnameChanging(string value);
partial void OnappnameChanged();
/// <summary>
/// There are no comments for Property appurl in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string appurl
{
get
{
return this._appurl;
}
set
{
this.OnappurlChanging(value);
this._appurl = value;
this.OnappurlChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _appurl;
partial void OnappurlChanging(string value);
partial void OnappurlChanged();
/// <summary>
/// There are no comments for Property appowner in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string appowner
{
get
{
return this._appowner;
}
set
{
this.OnappownerChanging(value);
this._appowner = value;
this.OnappownerChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _appowner;
partial void OnappownerChanging(string value);
partial void OnappownerChanged();
/// <summary>
/// There are no comments for features in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Collections.ObjectModel.Collection<feature> features
{
get
{
return this._features;
}
set
{
if ((value != null))
{
this._features = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Collections.ObjectModel.Collection<feature> _features = new global::System.Collections.ObjectModel.Collection<feature>();
/// <summary>
/// There are no comments for pods in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Collections.ObjectModel.Collection<pod> pods
{
get
{
return this._pods;
}
set
{
if ((value != null))
{
this._pods = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Collections.ObjectModel.Collection<pod> _pods = new global::System.Collections.ObjectModel.Collection<pod>();
/// <summary>
/// There are no comments for UserAggregations in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Collections.ObjectModel.Collection<UserAggregation> UserAggregations
{
get
{
return this._UserAggregations;
}
set
{
if ((value != null))
{
this._UserAggregations = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Collections.ObjectModel.Collection<UserAggregation> _UserAggregations = new global::System.Collections.ObjectModel.Collection<UserAggregation>();
/// <summary>
/// There are no comments for UserAggregationPerDays in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Collections.ObjectModel.Collection<UserAggregationPerDay> UserAggregationPerDays
{
get
{
return this._UserAggregationPerDays;
}
set
{
if ((value != null))
{
this._UserAggregationPerDays = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Collections.ObjectModel.Collection<UserAggregationPerDay> _UserAggregationPerDays = new global::System.Collections.ObjectModel.Collection<UserAggregationPerDay>();
}
/// <summary>
/// There are no comments for LeaderboardModel.CostCenter in the schema.
/// </summary>
/// <KeyProperties>
/// CostCenterName
/// AddTimestamp
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("CostCenterName", "AddTimestamp")]
public partial class CostCenter
{
/// <summary>
/// Create a new CostCenter object.
/// </summary>
/// <param name="costCenterName">Initial value of CostCenterName.</param>
/// <param name="addTimestamp">Initial value of AddTimestamp.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static CostCenter CreateCostCenter(string costCenterName, global::System.DateTime addTimestamp)
{
CostCenter costCenter = new CostCenter();
costCenter.CostCenterName = costCenterName;
costCenter.AddTimestamp = addTimestamp;
return costCenter;
}
/// <summary>
/// There are no comments for Property CostCenterName in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string CostCenterName
{
get
{
return this._CostCenterName;
}
set
{
this.OnCostCenterNameChanging(value);
this._CostCenterName = value;
this.OnCostCenterNameChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _CostCenterName;
partial void OnCostCenterNameChanging(string value);
partial void OnCostCenterNameChanged();
/// <summary>
/// There are no comments for Property AddTimestamp in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.DateTime AddTimestamp
{
get
{
return this._AddTimestamp;
}
set
{
this.OnAddTimestampChanging(value);
this._AddTimestamp = value;
this.OnAddTimestampChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.DateTime _AddTimestamp;
partial void OnAddTimestampChanging(global::System.DateTime value);
partial void OnAddTimestampChanged();
}
/// <summary>
/// There are no comments for LeaderboardModel.feature in the schema.
/// </summary>
/// <KeyProperties>
/// AppId
/// FeatureId
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("AppId", "FeatureId")]
public partial class feature
{
/// <summary>
/// Create a new feature object.
/// </summary>
/// <param name="appId">Initial value of AppId.</param>
/// <param name="featureId">Initial value of FeatureId.</param>
/// <param name="featureName">Initial value of FeatureName.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static feature Createfeature(int appId, int featureId, string featureName)
{
feature feature = new feature();
feature.AppId = appId;
feature.FeatureId = featureId;
feature.FeatureName = featureName;
return feature;
}
/// <summary>
/// There are no comments for Property AppId in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int AppId
{
get
{
return this._AppId;
}
set
{
this.OnAppIdChanging(value);
this._AppId = value;
this.OnAppIdChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _AppId;
partial void OnAppIdChanging(int value);
partial void OnAppIdChanged();
/// <summary>
/// There are no comments for Property FeatureId in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int FeatureId
{
get
{
return this._FeatureId;
}
set
{
this.OnFeatureIdChanging(value);
this._FeatureId = value;
this.OnFeatureIdChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _FeatureId;
partial void OnFeatureIdChanging(int value);
partial void OnFeatureIdChanged();
/// <summary>
/// There are no comments for Property FeatureName in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string FeatureName
{
get
{
return this._FeatureName;
}
set
{
this.OnFeatureNameChanging(value);
this._FeatureName = value;
this.OnFeatureNameChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _FeatureName;
partial void OnFeatureNameChanging(string value);
partial void OnFeatureNameChanged();
/// <summary>
/// There are no comments for Application in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public Application Application
{
get
{
return this._Application;
}
set
{
this._Application = value;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private Application _Application;
}
/// <summary>
/// There are no comments for LeaderboardModel.pod in the schema.
/// </summary>
/// <KeyProperties>
/// userid
/// appid
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("userid", "appid")]
public partial class pod
{
/// <summary>
/// Create a new pod object.
/// </summary>
/// <param name="userid">Initial value of userid.</param>
/// <param name="appid">Initial value of appid.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static pod Createpod(string userid, int appid)
{
pod pod = new pod();
pod.userid = userid;
pod.appid = appid;
return pod;
}
/// <summary>
/// There are no comments for Property userid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string userid
{
get
{
return this._userid;
}
set
{
this.OnuseridChanging(value);
this._userid = value;
this.OnuseridChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _userid;
partial void OnuseridChanging(string value);
partial void OnuseridChanged();
/// <summary>
/// There are no comments for Property appid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int appid
{
get
{
return this._appid;
}
set
{
this.OnappidChanging(value);
this._appid = value;
this.OnappidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _appid;
partial void OnappidChanging(int value);
partial void OnappidChanged();
/// <summary>
/// There are no comments for Application in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public Application Application
{
get
{
return this._Application;
}
set
{
this._Application = value;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private Application _Application;
}
/// <summary>
/// There are no comments for LeaderboardModel.point in the schema.
/// </summary>
/// <KeyProperties>
/// rowid
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("rowid")]
public partial class point
{
/// <summary>
/// Create a new point object.
/// </summary>
/// <param name="rowid">Initial value of rowid.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static point Createpoint(int rowid)
{
point point = new point();
point.rowid = rowid;
return point;
}
/// <summary>
/// There are no comments for Property userid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string userid
{
get
{
return this._userid;
}
set
{
this.OnuseridChanging(value);
this._userid = value;
this.OnuseridChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _userid;
partial void OnuseridChanging(string value);
partial void OnuseridChanged();
/// <summary>
/// There are no comments for Property appid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> appid
{
get
{
return this._appid;
}
set
{
this.OnappidChanging(value);
this._appid = value;
this.OnappidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _appid;
partial void OnappidChanging(global::System.Nullable<int> value);
partial void OnappidChanged();
/// <summary>
/// There are no comments for Property featureid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> featureid
{
get
{
return this._featureid;
}
set
{
this.OnfeatureidChanging(value);
this._featureid = value;
this.OnfeatureidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _featureid;
partial void OnfeatureidChanging(global::System.Nullable<int> value);
partial void OnfeatureidChanged();
/// <summary>
/// There are no comments for Property points in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> points
{
get
{
return this._points;
}
set
{
this.OnpointsChanging(value);
this._points = value;
this.OnpointsChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _points;
partial void OnpointsChanging(global::System.Nullable<int> value);
partial void OnpointsChanged();
/// <summary>
/// There are no comments for Property inserttime in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<global::System.DateTime> inserttime
{
get
{
return this._inserttime;
}
set
{
this.OninserttimeChanging(value);
this._inserttime = value;
this.OninserttimeChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<global::System.DateTime> _inserttime;
partial void OninserttimeChanging(global::System.Nullable<global::System.DateTime> value);
partial void OninserttimeChanged();
/// <summary>
/// There are no comments for Property updatetime in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<global::System.DateTime> updatetime
{
get
{
return this._updatetime;
}
set
{
this.OnupdatetimeChanging(value);
this._updatetime = value;
this.OnupdatetimeChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<global::System.DateTime> _updatetime;
partial void OnupdatetimeChanging(global::System.Nullable<global::System.DateTime> value);
partial void OnupdatetimeChanged();
/// <summary>
/// There are no comments for Property appverhi in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> appverhi
{
get
{
return this._appverhi;
}
set
{
this.OnappverhiChanging(value);
this._appverhi = value;
this.OnappverhiChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _appverhi;
partial void OnappverhiChanging(global::System.Nullable<int> value);
partial void OnappverhiChanged();
/// <summary>
/// There are no comments for Property appverlo in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> appverlo
{
get
{
return this._appverlo;
}
set
{
this.OnappverloChanging(value);
this._appverlo = value;
this.OnappverloChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _appverlo;
partial void OnappverloChanging(global::System.Nullable<int> value);
partial void OnappverloChanged();
/// <summary>
/// There are no comments for Property osverhi in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> osverhi
{
get
{
return this._osverhi;
}
set
{
this.OnosverhiChanging(value);
this._osverhi = value;
this.OnosverhiChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _osverhi;
partial void OnosverhiChanging(global::System.Nullable<int> value);
partial void OnosverhiChanged();
/// <summary>
/// There are no comments for Property osverlo in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.Nullable<int> osverlo
{
get
{
return this._osverlo;
}
set
{
this.OnosverloChanging(value);
this._osverlo = value;
this.OnosverloChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.Nullable<int> _osverlo;
partial void OnosverloChanging(global::System.Nullable<int> value);
partial void OnosverloChanged();
/// <summary>
/// There are no comments for Property rowid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int rowid
{
get
{
return this._rowid;
}
set
{
this.OnrowidChanging(value);
this._rowid = value;
this.OnrowidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _rowid;
partial void OnrowidChanging(int value);
partial void OnrowidChanged();
}
/// <summary>
/// There are no comments for LeaderboardModel.UserAggregation in the schema.
/// </summary>
/// <KeyProperties>
/// userid
/// appid
/// featureid
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("userid", "appid", "featureid")]
public partial class UserAggregation
{
/// <summary>
/// Create a new UserAggregation object.
/// </summary>
/// <param name="userid">Initial value of userid.</param>
/// <param name="appid">Initial value of appid.</param>
/// <param name="featureid">Initial value of featureid.</param>
/// <param name="totalpoints">Initial value of totalpoints.</param>
/// <param name="uses">Initial value of uses.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static UserAggregation CreateUserAggregation(string userid, int appid, int featureid, int totalpoints, int uses)
{
UserAggregation userAggregation = new UserAggregation();
userAggregation.userid = userid;
userAggregation.appid = appid;
userAggregation.featureid = featureid;
userAggregation.totalpoints = totalpoints;
userAggregation.uses = uses;
return userAggregation;
}
/// <summary>
/// There are no comments for Property userid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string userid
{
get
{
return this._userid;
}
set
{
this.OnuseridChanging(value);
this._userid = value;
this.OnuseridChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _userid;
partial void OnuseridChanging(string value);
partial void OnuseridChanged();
/// <summary>
/// There are no comments for Property appid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int appid
{
get
{
return this._appid;
}
set
{
this.OnappidChanging(value);
this._appid = value;
this.OnappidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _appid;
partial void OnappidChanging(int value);
partial void OnappidChanged();
/// <summary>
/// There are no comments for Property featureid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int featureid
{
get
{
return this._featureid;
}
set
{
this.OnfeatureidChanging(value);
this._featureid = value;
this.OnfeatureidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _featureid;
partial void OnfeatureidChanging(int value);
partial void OnfeatureidChanged();
/// <summary>
/// There are no comments for Property totalpoints in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int totalpoints
{
get
{
return this._totalpoints;
}
set
{
this.OntotalpointsChanging(value);
this._totalpoints = value;
this.OntotalpointsChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _totalpoints;
partial void OntotalpointsChanging(int value);
partial void OntotalpointsChanged();
/// <summary>
/// There are no comments for Property uses in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int uses
{
get
{
return this._uses;
}
set
{
this.OnusesChanging(value);
this._uses = value;
this.OnusesChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _uses;
partial void OnusesChanging(int value);
partial void OnusesChanged();
/// <summary>
/// There are no comments for Application in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public Application Application
{
get
{
return this._Application;
}
set
{
this._Application = value;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private Application _Application;
}
/// <summary>
/// There are no comments for LeaderboardModel.UserAggregationPerDay in the schema.
/// </summary>
/// <KeyProperties>
/// userid
/// appid
/// featureid
/// eventDate
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("userid", "appid", "featureid", "eventDate")]
public partial class UserAggregationPerDay
{
/// <summary>
/// Create a new UserAggregationPerDay object.
/// </summary>
/// <param name="userid">Initial value of userid.</param>
/// <param name="appid">Initial value of appid.</param>
/// <param name="featureid">Initial value of featureid.</param>
/// <param name="eventDate">Initial value of eventDate.</param>
/// <param name="totalpoints">Initial value of totalpoints.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static UserAggregationPerDay CreateUserAggregationPerDay(string userid, int appid, int featureid, global::System.DateTime eventDate, int totalpoints)
{
UserAggregationPerDay userAggregationPerDay = new UserAggregationPerDay();
userAggregationPerDay.userid = userid;
userAggregationPerDay.appid = appid;
userAggregationPerDay.featureid = featureid;
userAggregationPerDay.eventDate = eventDate;
userAggregationPerDay.totalpoints = totalpoints;
return userAggregationPerDay;
}
/// <summary>
/// There are no comments for Property userid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string userid
{
get
{
return this._userid;
}
set
{
this.OnuseridChanging(value);
this._userid = value;
this.OnuseridChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _userid;
partial void OnuseridChanging(string value);
partial void OnuseridChanged();
/// <summary>
/// There are no comments for Property appid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int appid
{
get
{
return this._appid;
}
set
{
this.OnappidChanging(value);
this._appid = value;
this.OnappidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _appid;
partial void OnappidChanging(int value);
partial void OnappidChanged();
/// <summary>
/// There are no comments for Property featureid in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int featureid
{
get
{
return this._featureid;
}
set
{
this.OnfeatureidChanging(value);
this._featureid = value;
this.OnfeatureidChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _featureid;
partial void OnfeatureidChanging(int value);
partial void OnfeatureidChanged();
/// <summary>
/// There are no comments for Property eventDate in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.DateTime eventDate
{
get
{
return this._eventDate;
}
set
{
this.OneventDateChanging(value);
this._eventDate = value;
this.OneventDateChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.DateTime _eventDate;
partial void OneventDateChanging(global::System.DateTime value);
partial void OneventDateChanged();
/// <summary>
/// There are no comments for Property totalpoints in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public int totalpoints
{
get
{
return this._totalpoints;
}
set
{
this.OntotalpointsChanging(value);
this._totalpoints = value;
this.OntotalpointsChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private int _totalpoints;
partial void OntotalpointsChanging(int value);
partial void OntotalpointsChanged();
/// <summary>
/// There are no comments for Application in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public Application Application
{
get
{
return this._Application;
}
set
{
this._Application = value;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private Application _Application;
}
/// <summary>
/// There are no comments for LeaderboardModel.User in the schema.
/// </summary>
/// <KeyProperties>
/// Alias
/// </KeyProperties>
[global::System.Data.Services.Common.DataServiceKeyAttribute("Alias")]
public partial class User
{
/// <summary>
/// Create a new User object.
/// </summary>
/// <param name="fullname">Initial value of Fullname.</param>
/// <param name="alias">Initial value of Alias.</param>
/// <param name="updateTimestamp">Initial value of UpdateTimestamp.</param>
/// <param name="nonADAccount">Initial value of NonADAccount.</param>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public static User CreateUser(string fullname, string alias, global::System.DateTime updateTimestamp, bool nonADAccount)
{
User user = new User();
user.Fullname = fullname;
user.Alias = alias;
user.UpdateTimestamp = updateTimestamp;
user.NonADAccount = nonADAccount;
return user;
}
/// <summary>
/// There are no comments for Property Fullname in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string Fullname
{
get
{
return this._Fullname;
}
set
{
this.OnFullnameChanging(value);
this._Fullname = value;
this.OnFullnameChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _Fullname;
partial void OnFullnameChanging(string value);
partial void OnFullnameChanged();
/// <summary>
/// There are no comments for Property Alias in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string Alias
{
get
{
return this._Alias;
}
set
{
this.OnAliasChanging(value);
this._Alias = value;
this.OnAliasChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _Alias;
partial void OnAliasChanging(string value);
partial void OnAliasChanged();
/// <summary>
/// There are no comments for Property CSP in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string CSP
{
get
{
return this._CSP;
}
set
{
this.OnCSPChanging(value);
this._CSP = value;
this.OnCSPChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _CSP;
partial void OnCSPChanging(string value);
partial void OnCSPChanged();
/// <summary>
/// There are no comments for Property Discipline in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string Discipline
{
get
{
return this._Discipline;
}
set
{
this.OnDisciplineChanging(value);
this._Discipline = value;
this.OnDisciplineChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _Discipline;
partial void OnDisciplineChanging(string value);
partial void OnDisciplineChanged();
/// <summary>
/// There are no comments for Property CostCenterName in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string CostCenterName
{
get
{
return this._CostCenterName;
}
set
{
this.OnCostCenterNameChanging(value);
this._CostCenterName = value;
this.OnCostCenterNameChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private string _CostCenterName;
partial void OnCostCenterNameChanging(string value);
partial void OnCostCenterNameChanged();
/// <summary>
/// There are no comments for Property UpdateTimestamp in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public global::System.DateTime UpdateTimestamp
{
get
{
return this._UpdateTimestamp;
}
set
{
this.OnUpdateTimestampChanging(value);
this._UpdateTimestamp = value;
this.OnUpdateTimestampChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private global::System.DateTime _UpdateTimestamp;
partial void OnUpdateTimestampChanging(global::System.DateTime value);
partial void OnUpdateTimestampChanged();
/// <summary>
/// There are no comments for Property NonADAccount in the schema.
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public bool NonADAccount
{
get
{
return this._NonADAccount;
}
set
{
this.OnNonADAccountChanging(value);
this._NonADAccount = value;
this.OnNonADAccountChanged();
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
private bool _NonADAccount;
partial void OnNonADAccountChanging(bool value);
partial void OnNonADAccountChanged();
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using PdfSharp.Drawing;
using System;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.PdfSharp.Utilities;
namespace TheArtOfDev.HtmlRenderer.PdfSharp.Adapters
{
/// <summary>
/// Adapter for WinForms Graphics for core.
/// </summary>
internal sealed class GraphicsAdapter : RGraphics
{
#region Fields and Consts
/// <summary>
/// The wrapped WinForms graphics object
/// </summary>
private readonly XGraphics _g;
/// <summary>
/// if to release the graphics object on dispose
/// </summary>
private readonly bool _releaseGraphics;
/// <summary>
/// Used to measure and draw strings
/// </summary>
private static readonly XStringFormat _stringFormat;
#endregion
static GraphicsAdapter()
{
_stringFormat = new XStringFormat();
_stringFormat.Alignment = XStringAlignment.Near;
_stringFormat.LineAlignment = XLineAlignment.Near;
}
/// <summary>
/// Init.
/// </summary>
/// <param name="g">the win forms graphics object to use</param>
/// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param>
public GraphicsAdapter(XGraphics g, bool releaseGraphics = false)
: base(PdfSharpAdapter.Instance, new RRect(0, 0, double.MaxValue, double.MaxValue))
{
ArgChecker.AssertArgNotNull(g, "g");
_g = g;
_releaseGraphics = releaseGraphics;
}
public override void PopClip()
{
_clipStack.Pop();
_g.Restore();
}
public override void PushClip(RRect rect)
{
_clipStack.Push(rect);
_g.Save();
_g.IntersectClip(Utils.Convert(rect));
}
public override void PushClipExclude(RRect rect)
{ }
public override Object SetAntiAliasSmoothingMode()
{
var prevMode = _g.SmoothingMode;
_g.SmoothingMode = XSmoothingMode.AntiAlias;
return prevMode;
}
public override void ReturnPreviousSmoothingMode(Object prevMode)
{
if (prevMode != null)
{
_g.SmoothingMode = (XSmoothingMode)prevMode;
}
}
public override RSize MeasureString(string str, RFont font)
{
var fontAdapter = (FontAdapter)font;
var realFont = fontAdapter.Font;
var size = _g.MeasureString(str, realFont, _stringFormat);
if (font.Height < 0)
{
var height = realFont.Height;
var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style);
fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + 1f)));
}
return Utils.Convert(size);
}
public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
{
// there is no need for it - used for text selection
throw new NotSupportedException();
}
public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
{
var xBrush = ((BrushAdapter)_adapter.GetSolidBrush(color)).Brush;
_g.DrawString(str, ((FontAdapter)font).Font, (XBrush)xBrush, point.X, point.Y, _stringFormat);
}
public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
{
return new BrushAdapter(new XTextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect), Utils.Convert(translateTransformLocation)));
}
public override RGraphicsPath GetGraphicsPath()
{
return new GraphicsPathAdapter();
}
public override void Dispose()
{
if (_releaseGraphics)
_g.Dispose();
}
#region Delegate graphics methods
public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
{
_g.DrawLine(((PenAdapter)pen).Pen, x1, y1, x2, y2);
}
public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
{
_g.DrawRectangle(((PenAdapter)pen).Pen, x, y, width, height);
}
public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
{
var xBrush = ((BrushAdapter)brush).Brush;
var xTextureBrush = xBrush as XTextureBrush;
if (xTextureBrush != null)
{
xTextureBrush.DrawRectangle(_g, x, y, width, height);
}
else
{
_g.DrawRectangle((XBrush)xBrush, x, y, width, height);
// handle bug in PdfSharp that keeps the brush color for next string draw
if (xBrush is XLinearGradientBrush)
_g.DrawRectangle(XBrushes.White, 0, 0, 0.1, 0.1);
}
}
public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
{
_g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), XGraphicsUnit.Point);
}
public override void DrawImage(RImage image, RRect destRect)
{
_g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect));
}
public override void DrawPath(RPen pen, RGraphicsPath path)
{
_g.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPath(RBrush brush, RGraphicsPath path)
{
_g.DrawPath((XBrush)((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPolygon(RBrush brush, RPoint[] points)
{
if (points != null && points.Length > 0)
{
_g.DrawPolygon((XBrush)((BrushAdapter)brush).Brush, Utils.Convert(points), XFillMode.Winding);
}
}
#endregion
}
}
| |
using Cake.Common.Diagnostics;
using Cake.Common.IO;
using Cake.Npm;
using Cake.Npm.Publish;
using CK.Text;
using CodeCake.Abstractions;
using CSemVer;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CodeCake
{
public partial class Build
{
abstract class YarnFeed : ArtifactFeed
{
public YarnFeed( YarnArtifactType t )
: base( t )
{
}
/// <summary>
/// Pushes a set of artifacts.
/// </summary>
/// <param name="pushes">The instances to push (that necessary target this feed).</param>
/// <returns>The awaitable.</returns>
public override async Task PushAsync( IEnumerable<ArtifactPush> pushes )
{
var tasks = pushes.Select( p => PublishOnePackageAsync( p ) ).ToArray();
await System.Threading.Tasks.Task.WhenAll( tasks );
await OnAllArtifactsPushed( pushes );
}
protected abstract Task PublishOnePackageAsync( ArtifactPush push );
/// <summary>
/// Called once all the packages are pushed.
/// Does nothing at this level.
/// </summary>
/// <param name="pushes">The instances to push (that necessary target this feed).</param>
/// <returns>The awaitable.</returns>
protected virtual Task OnAllArtifactsPushed( IEnumerable<ArtifactPush> pushes )
{
return System.Threading.Tasks.Task.CompletedTask;
}
}
class YarnLocalFeed : YarnFeed
{
readonly NormalizedPath _pathToLocalFeed;
public override string Name => _pathToLocalFeed;
public YarnLocalFeed( YarnArtifactType t, NormalizedPath pathToLocalFeed )
: base( t )
{
_pathToLocalFeed = pathToLocalFeed;
}
public override Task<IEnumerable<ArtifactPush>> CreatePushListAsync( IEnumerable<ILocalArtifact> artifacts )
{
var result = artifacts.Cast<YarnPublishedProject>()
.Select( a => (A: a, P: _pathToLocalFeed.AppendPart( a.TGZName )) )
.Where( aP => !File.Exists( aP.P ) )
.Select( aP => new ArtifactPush( aP.A, this ) )
.ToList();
return System.Threading.Tasks.Task.FromResult<IEnumerable<ArtifactPush>>( result );
}
protected override Task PublishOnePackageAsync( ArtifactPush p )
{
if( p.Feed != this ) throw new ArgumentException( "ArtifactPush: feed mismatch." );
var project = (YarnPublishedProject)p.LocalArtifact;
var target = _pathToLocalFeed.AppendPart( project.TGZName );
var source = ArtifactType.GlobalInfo.ReleasesFolder.AppendPart( project.TGZName );
Cake.CopyFile( source.Path, target.Path );
return System.Threading.Tasks.Task.CompletedTask;
}
}
abstract class YarnRemoteFeedBase : YarnFeed
{
protected readonly string FeedUri;
public YarnRemoteFeedBase( YarnArtifactType t, string secretKeyName, string feedUri )
: base( t )
{
SecretKeyName = secretKeyName;
FeedUri = feedUri;
}
public override string Name => FeedUri;
public string SecretKeyName { get; }
public string ResolveAPIKey()
{
string output = Cake.InteractiveEnvironmentVariable( SecretKeyName );
if( string.IsNullOrWhiteSpace( output ) )
{
Cake.Warning( "Missing environement variable " + SecretKeyName );
}
return output;
}
protected abstract IDisposable TokenInjector( YarnPublishedProject project );
public override Task<IEnumerable<ArtifactPush>> CreatePushListAsync( IEnumerable<ILocalArtifact> artifacts )
{
var result = artifacts.Cast<YarnPublishedProject>()
.Where( a =>
{
using( TokenInjector( a ) )
{
string viewString = Cake.NpmView( a.Name, a.DirectoryPath );
if( string.IsNullOrEmpty( viewString ) ) return true;
JObject json = JObject.Parse( viewString );
if( json.TryGetValue( "versions", out JToken versions ) )
{
return !((JArray)versions).ToObject<string[]>().Contains( a.ArtifactInstance.Version.ToNormalizedString() );
}
return true;
}
} )
.Select( a => new ArtifactPush( a, this ) )
.ToList();
return System.Threading.Tasks.Task.FromResult<IEnumerable<ArtifactPush>>( result );
}
protected override Task PublishOnePackageAsync( ArtifactPush p )
{
var tags = p.Version.PackageQuality.GetAllQualities().Select( l => l.ToString().ToLowerInvariant() ).ToList();
var project = (YarnPublishedProject)p.LocalArtifact;
using( TokenInjector( project ) )
{
var absTgzPath = Path.GetFullPath( ArtifactType.GlobalInfo.ReleasesFolder.AppendPart( project.TGZName ) );
Cake.NpmPublish(
new NpmPublishSettings()
{
Source = absTgzPath,
WorkingDirectory = project.DirectoryPath.Path,
Tag = tags.First()
} );
foreach( string tag in tags.Skip( 1 ) )
{
Cake.Information( $"Setting tag '{tag}' on '{project.Name}' to '{project.ArtifactInstance.Version.ToNormalizedString()}' version." );
// The FromPath is actually required - if executed outside the relevant directory,
// it will miss the .npmrc with registry configs.
Cake.NpmDistTagAdd( project.Name, project.ArtifactInstance.Version.ToNormalizedString(), tag, s => s.FromPath( project.DirectoryPath.Path ) );
}
}
return System.Threading.Tasks.Task.CompletedTask;
}
}
/// <summary>
/// Feed for a standard NPM server.
/// </summary>
class YarnRemoteFeed : YarnRemoteFeedBase
{
readonly bool _usePassword;
public YarnRemoteFeed( YarnArtifactType t, string secretKeyName, string feedUri, bool usePassword )
: base( t, secretKeyName, feedUri )
{
_usePassword = usePassword;
}
protected override IDisposable TokenInjector( YarnPublishedProject project )
{
return _usePassword
? project.TemporarySetPushTargetAndPasswordLogin( FeedUri, ResolveAPIKey() )
: project.TemporarySetPushTargetAndTokenLogin( FeedUri, ResolveAPIKey() );
}
}
/// <summary>
/// The secret key name is built by <see cref="SignatureVSTSFeed.GetSecretKeyName"/>:
/// "AZURE_FEED_" + Organization.ToUpperInvariant().Replace( '-', '_' ).Replace( ' ', '_' ) + "_PAT".
/// </summary>
/// <param name="organization">Name of the organization.</param>
/// <param name="feedName">Identifier of the feed in Azure, inside the organization.</param>
class AzureYarnFeed : YarnRemoteFeedBase
{
/// <summary>
/// Builds the standardized secret key name from the organization name: this is
/// the Personal Access Token that allows push packages.
/// </summary>
/// <param name="organization">Organization name.</param>
/// <returns>The secret key name to use.</returns>
public static string GetSecretKeyName( string organization )
=> "AZURE_FEED_" + organization.ToUpperInvariant()
.Replace( '-', '_' )
.Replace( ' ', '_' )
+ "_PAT";
public AzureYarnFeed( YarnArtifactType t, string organization, string feedName, string projectName )
: base( t,
GetSecretKeyName( organization ),
projectName != null ?
$"https://pkgs.dev.azure.com/{organization}/{projectName}/_packaging/{feedName}/npm/registry/"
: $"https://pkgs.dev.azure.com/{organization}/_packaging/{feedName}/npm/registry/" )
{
Organization = organization;
FeedName = feedName;
ProjectName = projectName;
}
public string Organization { get; }
public string FeedName { get; }
public string ProjectName { get; }
public override string Name => $"AzureNPM:{Organization}/{FeedName}";
protected override IDisposable TokenInjector( YarnPublishedProject project )
{
return project.TemporarySetPushTargetAndAzurePatLogin( FeedUri, ResolveAPIKey() );
}
/// <summary>
/// Implements Package promotion in @CI, @Exploratory, @Preview, @Latest and @Stable views.
/// </summary>
/// <param name="ctx">The Cake context.</param>
/// <param name="pushes">The set of artifacts to promote.</param>
/// <returns>The awaitable.</returns>
protected override async Task OnAllArtifactsPushed( IEnumerable<ArtifactPush> pushes )
{
var basicAuth = Convert.ToBase64String( Encoding.ASCII.GetBytes( ":" + Cake.InteractiveEnvironmentVariable( SecretKeyName ) ) );
foreach( var p in pushes )
{
bool isNpm = p.Feed.ArtifactType is YarnArtifactType;
string uriProtocol = isNpm ? "npm" : "nuget";
foreach( var view in p.Version.PackageQuality.GetAllQualities() )
{
var url = ProjectName != null ?
$"https://pkgs.dev.azure.com/{Organization}/{ProjectName}/_apis/packaging/feeds/{FeedName}/{uriProtocol}/packagesBatch?api-version=5.0-preview.1"
: $"https://pkgs.dev.azure.com/{Organization}/_apis/packaging/feeds/{FeedName}/{uriProtocol}/packagesBatch?api-version=5.0-preview.1";
using( HttpRequestMessage req = new HttpRequestMessage( HttpMethod.Post, url ) )
{
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( "Basic", basicAuth );
var body = GetPromotionJSONBody( p.Name, p.Version.ToNormalizedString(), view.ToString(), isNpm );
req.Content = new StringContent( body, Encoding.UTF8, "application/json" );
using( var m = await StandardGlobalInfo.SharedHttpClient.SendAsync( req ) )
{
if( m.IsSuccessStatusCode )
{
Cake.Information( $"Package '{p.Name}' promoted to view '@{view}'." );
}
else
{
Cake.Error( $"Package '{p.Name}' promotion to view '@{view}' failed." );
// Throws!
m.EnsureSuccessStatusCode();
}
}
}
}
}
}
string GetPromotionJSONBody( string packageName, string packageVersion, string viewId, bool npm )
{
var bodyFormat = @"{
""data"": {
""viewId"": ""{viewId}""
},
""operation"": 0,
""packages"": [{
""id"": ""{packageName}"",
""version"": ""{packageVersion}"",
""protocolType"": ""{NuGetOrNpm}""
}]
}";
return bodyFormat.Replace( "{NuGetOrNpm}", npm ? "Npm" : "NuGet" )
.Replace( "{viewId}", viewId )
.Replace( "{packageName}", packageName )
.Replace( "{packageVersion}", packageVersion );
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OleDbConnectionStringBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace System.Data.OleDb {
[DefaultProperty("Provider")]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[System.ComponentModel.TypeConverterAttribute(typeof(OleDbConnectionStringBuilder.OleDbConnectionStringBuilderConverter))]
public sealed class OleDbConnectionStringBuilder : DbConnectionStringBuilder {
private enum Keywords { // specific ordering for ConnectionString output construction
// NamedConnection,
FileName,
Provider,
DataSource,
PersistSecurityInfo,
OleDbServices,
}
private static readonly string[] _validKeywords;
private static readonly Dictionary<string,Keywords> _keywords;
private string[] _knownKeywords;
private Dictionary<string,OleDbPropertyInfo> _propertyInfo;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _fileName = DbConnectionStringDefaults.FileName;
private string _dataSource = DbConnectionStringDefaults.DataSource;
private string _provider = DbConnectionStringDefaults.Provider;
private int _oleDbServices = DbConnectionStringDefaults.OleDbServices;
private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
static OleDbConnectionStringBuilder() {
string[] validKeywords = new string[5];
validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource;
validKeywords[(int)Keywords.FileName] = DbConnectionStringKeywords.FileName;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
validKeywords[(int)Keywords.OleDbServices] = DbConnectionStringKeywords.OleDbServices;
validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
validKeywords[(int)Keywords.Provider] = DbConnectionStringKeywords.Provider;
_validKeywords = validKeywords;
Dictionary<string,Keywords> hash = new Dictionary<string,Keywords>(9, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource);
hash.Add(DbConnectionStringKeywords.FileName, Keywords.FileName);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
hash.Add(DbConnectionStringKeywords.OleDbServices, Keywords.OleDbServices);
hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringKeywords.Provider, Keywords.Provider);
Debug.Assert(5 == hash.Count, "initial expected size is incorrect");
_keywords = hash;
}
public OleDbConnectionStringBuilder() : this(null) {
_knownKeywords = _validKeywords;
}
public OleDbConnectionStringBuilder(string connectionString) : base() {
if (!ADP.IsEmpty(connectionString)) {
ConnectionString = connectionString;
}
}
public override object this[string keyword] {
get {
ADP.CheckArgumentNull(keyword, "keyword");
object value;
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
value = GetAt(index);
}
else if (!base.TryGetValue(keyword, out value)) {
Dictionary<string,OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
OleDbPropertyInfo info = dynamic[keyword];
value = info._defaultValue;
}
return value;
}
set {
if (null != value) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
switch(index) {
case Keywords.DataSource: DataSource = ConvertToString(value); break;
case Keywords.FileName: FileName = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
case Keywords.Provider: Provider = ConvertToString(value); break;
case Keywords.OleDbServices: OleDbServices = ConvertToInt32(value); break;
case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
else {
base[keyword] = value;
ClearPropertyDescriptors();
}
}
else {
Remove(keyword);
}
}
}
[DisplayName(DbConnectionStringKeywords.DataSource)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_DataSource)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
//
public string DataSource {
get { return _dataSource; }
set {
SetValue(DbConnectionStringKeywords.DataSource, value);
_dataSource = value;
}
}
[DisplayName(DbConnectionStringKeywords.FileName)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_FileName)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
//
[Editor("System.Windows.Forms.Design.FileNameEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)]
public string FileName {
get { return _fileName; }
set {
SetValue(DbConnectionStringKeywords.FileName, value);
_fileName = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
[DisplayName(DbConnectionStringKeywords.OleDbServices)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_OleDbServices)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(OleDbConnectionStringBuilder.OleDbServicesConverter))]
public int OleDbServices {
get { return _oleDbServices; }
set {
SetValue(DbConnectionStringKeywords.OleDbServices, value);
_oleDbServices = value;
}
}
[DisplayName(DbConnectionStringKeywords.PersistSecurityInfo)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_PersistSecurityInfo)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool PersistSecurityInfo {
get { return _persistSecurityInfo; }
set {
SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
_persistSecurityInfo = value;
}
}
[DisplayName(DbConnectionStringKeywords.Provider)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_Provider)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(OleDbConnectionStringBuilder.OleDbProviderConverter))]
public string Provider {
get { return _provider; }
set {
SetValue(DbConnectionStringKeywords.Provider, value);
_provider = value;
RestartProvider();
}
}
public override ICollection Keys {
get {
string[] knownKeywords = _knownKeywords;
if (null == knownKeywords) {
Dictionary<string,OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
if (0 < dynamic.Count) {
knownKeywords = new string[_validKeywords.Length + dynamic.Count];
_validKeywords.CopyTo(knownKeywords, 0);
dynamic.Keys.CopyTo(knownKeywords, _validKeywords.Length);
}
else {
knownKeywords = _validKeywords;
}
int count = 0;
foreach(string keyword in base.Keys) {
bool flag = true;
foreach(string s in knownKeywords) {
if (StringComparer.OrdinalIgnoreCase.Equals(s, keyword)) {
flag = false;
break;
}
}
if (flag) {
count++;
}
}
if (0 < count) {
string[] tmp = new string[knownKeywords.Length + count];
knownKeywords.CopyTo(tmp, 0);
int index = knownKeywords.Length;
foreach(string keyword in base.Keys) {
bool flag = true;
foreach(string s in knownKeywords) {
if (StringComparer.OrdinalIgnoreCase.Equals(s, keyword)) {
flag = false;
break;
}
}
if (flag) {
tmp[index++] = keyword;
}
}
knownKeywords = tmp;
}
_knownKeywords = knownKeywords;
}
return new System.Data.Common.ReadOnlyCollection<string>(knownKeywords);
}
}
public override bool ContainsKey(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
return _keywords.ContainsKey(keyword) || base.ContainsKey(keyword);
}
private static bool ConvertToBoolean(object value) {
return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
}
private static int ConvertToInt32(object value) {
return DbConnectionStringBuilderUtil.ConvertToInt32(value);
}
private static string ConvertToString(object value) {
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
public override void Clear() {
base.Clear();
for(int i = 0; i < _validKeywords.Length; ++i) {
Reset((Keywords)i);
}
base.ClearPropertyDescriptors();
_knownKeywords = _validKeywords;
}
private object GetAt(Keywords index) {
switch(index) {
case Keywords.DataSource: return DataSource;
case Keywords.FileName: return FileName;
// case Keywords.NamedConnection: return NamedConnection;
case Keywords.OleDbServices: return OleDbServices;
case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
case Keywords.Provider: return Provider;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
public override bool Remove(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
bool value = base.Remove(keyword);
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
Reset(index);
}
else if (value) {
ClearPropertyDescriptors();
}
return value;
}
private void Reset(Keywords index) {
switch(index) {
case Keywords.DataSource:
_dataSource = DbConnectionStringDefaults.DataSource;
break;
case Keywords.FileName:
_fileName = DbConnectionStringDefaults.FileName;
RestartProvider();
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
case Keywords.OleDbServices:
_oleDbServices = DbConnectionStringDefaults.OleDbServices;
break;
case Keywords.PersistSecurityInfo:
_persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
break;
case Keywords.Provider:
_provider = DbConnectionStringDefaults.Provider;
RestartProvider();
break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
private new void ClearPropertyDescriptors() {
base.ClearPropertyDescriptors();
_knownKeywords = null;
}
private void RestartProvider() {
ClearPropertyDescriptors();
_propertyInfo = null;
}
private void SetValue(string keyword, bool value) {
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, int value) {
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, string value) {
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
public override bool TryGetValue(string keyword, out object value) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
value = GetAt(index);
return true;
}
else if (!base.TryGetValue(keyword, out value)) {
Dictionary<string,OleDbPropertyInfo> dynamic = GetProviderInfo(Provider);
OleDbPropertyInfo info;
if (dynamic.TryGetValue(keyword, out info)) {
value = info._defaultValue;
return true;
}
return false;
}
return true;
}
private Dictionary<string,OleDbPropertyInfo> GetProviderInfo(string provider) {
Dictionary<string,OleDbPropertyInfo> providerInfo = _propertyInfo;
if (null == providerInfo) {
providerInfo = new Dictionary<string,OleDbPropertyInfo>(StringComparer.OrdinalIgnoreCase);
if (!ADP.IsEmpty(provider)) {
Dictionary<string,OleDbPropertyInfo> hash = null;
try {
StringBuilder builder = new StringBuilder();
AppendKeyValuePair(builder, DbConnectionStringKeywords.Provider, provider);
OleDbConnectionString constr = new OleDbConnectionString(builder.ToString(), true);
constr.CreatePermissionSet().Demand();
// load provider without calling Initialize or CreateDataSource
using(OleDbConnectionInternal connection = new OleDbConnectionInternal(constr, (OleDbConnection)null)) {
// get all the init property information for the provider
hash = connection.GetPropertyInfo(new Guid[] { OleDbPropertySetGuid.DBInitAll });
foreach(KeyValuePair<string,OleDbPropertyInfo> entry in hash) {
Keywords index;
OleDbPropertyInfo info = entry.Value;
if (!_keywords.TryGetValue(info._description, out index)) {
if ((OleDbPropertySetGuid.DBInit == info._propertySet) &&
((ODB.DBPROP_INIT_ASYNCH == info._propertyID) ||
(ODB.DBPROP_INIT_HWND == info._propertyID) ||
(ODB.DBPROP_INIT_PROMPT == info._propertyID))) {
continue; // skip this keyword
}
providerInfo[info._description] = info;
}
}
// what are the unique propertysets?
List<Guid> listPropertySets= new List<Guid>();
foreach(KeyValuePair<string,OleDbPropertyInfo> entry in hash) {
OleDbPropertyInfo info = entry.Value;
if (!listPropertySets.Contains(info._propertySet)) {
listPropertySets.Add(info._propertySet);
}
}
Guid[] arrayPropertySets = new Guid[listPropertySets.Count];
listPropertySets.CopyTo(arrayPropertySets, 0);
// get all the init property values for the provider
using(PropertyIDSet propidset = new PropertyIDSet(arrayPropertySets)) {
using(IDBPropertiesWrapper idbProperties = connection.IDBProperties()) {
OleDbHResult hr;
using(DBPropSet propset = new DBPropSet(idbProperties.Value, propidset, out hr)) {
// VSDD 671375: OleDbConnectionStringBuilder is ignoring/hiding potential errors of OLEDB provider when reading its properties information
if (0 <= (int)hr) {
int count = propset.PropertySetCount;
for(int i = 0; i < count; ++i) {
Guid propertyset;
tagDBPROP[] props = propset.GetPropertySet(i, out propertyset);
// attach the default property value to the property info
foreach(tagDBPROP prop in props) {
foreach(KeyValuePair<string,OleDbPropertyInfo> entry in hash) {
OleDbPropertyInfo info = entry.Value;
if ((info._propertyID == prop.dwPropertyID) && (info._propertySet == propertyset)) {
info._defaultValue = prop.vValue;
if (null == info._defaultValue) {
if (typeof(string) == info._type) {
info._defaultValue = "";
}
else if (typeof(Int32) == info._type) {
info._defaultValue = 0;
}
else if (typeof(Boolean) == info._type) {
info._defaultValue = false;
}
}
}
}
}
}
}
}
}
}
}
}
catch(System.InvalidOperationException e) {
ADP.TraceExceptionWithoutRethrow(e);
}
catch(System.Data.OleDb.OleDbException e) {
ADP.TraceExceptionWithoutRethrow(e);
}
catch(System.Security.SecurityException e) {
ADP.TraceExceptionWithoutRethrow(e);
}
}
_propertyInfo = providerInfo;
}
return providerInfo;
}
protected override void GetProperties(Hashtable propertyDescriptors) {
Dictionary<string,OleDbPropertyInfo> providerInfo = GetProviderInfo(Provider);
if (0 < providerInfo.Count) {
foreach(OleDbPropertyInfo info in providerInfo.Values) {
Keywords index;
if (!_keywords.TryGetValue(info._description, out index)) { // not a strongly typed property
bool isReadOnly = false;
bool refreshOnChange = false;
Attribute[] attributes;
if (OleDbPropertySetGuid.DBInit == info._propertySet) {
switch(info._propertyID) {
#if DEBUG
case ODB.DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO:
case ODB.DBPROP_INIT_ASYNCH:
case ODB.DBPROP_INIT_DATASOURCE:
case ODB.DBPROP_INIT_HWND:
case ODB.DBPROP_INIT_OLEDBSERVICES:
Debug.Assert(false, "should be handled via strongly typed property");
goto default;
#endif
case ODB.DBPROP_INIT_CATALOG:
case ODB.DBPROP_INIT_LOCATION:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Source),
RefreshPropertiesAttribute.All,
};
break;
case ODB.DBPROP_INIT_TIMEOUT:
case ODB.DBPROP_INIT_GENERALTIMEOUT:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Initialization),
RefreshPropertiesAttribute.All,
};
break;
// 'Password' & 'User ID' will be readonly if 'Integrated Security' exists
case ODB.DBPROP_AUTH_PASSWORD:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
PasswordPropertyTextAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Security),
RefreshPropertiesAttribute.All,
};
isReadOnly = ContainsKey(DbConnectionStringKeywords.IntegratedSecurity);
refreshOnChange = true;
break;
case ODB.DBPROP_AUTH_USERID:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Security),
RefreshPropertiesAttribute.All,
};
isReadOnly = ContainsKey(DbConnectionStringKeywords.IntegratedSecurity);
refreshOnChange = true;
break;
case ODB.DBPROP_AUTH_CACHE_AUTHINFO:
case ODB.DBPROP_AUTH_ENCRYPT_PASSWORD:
case ODB.DBPROP_AUTH_INTEGRATED:
case ODB.DBPROP_AUTH_MASK_PASSWORD:
case ODB.DBPROP_AUTH_PERSIST_ENCRYPTED:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Security),
RefreshPropertiesAttribute.All,
};
refreshOnChange = (ODB.DBPROP_AUTH_INTEGRATED == info._propertyID);
break;
case ODB.DBPROP_INIT_BINDFLAGS:
case ODB.DBPROP_INIT_IMPERSONATION_LEVEL:
case ODB.DBPROP_INIT_LCID:
case ODB.DBPROP_INIT_MODE:
case ODB.DBPROP_INIT_PROTECTION_LEVEL:
case ODB.DBPROP_INIT_PROVIDERSTRING:
case ODB.DBPROP_INIT_LOCKOWNER:
attributes = new Attribute[] {
BrowsableAttribute.Yes,
new ResCategoryAttribute(Res.DataCategory_Advanced),
RefreshPropertiesAttribute.All,
};
break;
default:
Debug.Assert(false, "new standard propertyid");
attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
};
break;
}
}
else if (info._description.EndsWith(" Provider", StringComparison.OrdinalIgnoreCase)) {
attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
new ResCategoryAttribute(Res.DataCategory_Source),
new TypeConverterAttribute(typeof(OleDbConnectionStringBuilder.OleDbProviderConverter)),
};
refreshOnChange = true;
}
else {
attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
new CategoryAttribute(Provider),
};
}
DbConnectionStringBuilderDescriptor descriptor = new DbConnectionStringBuilderDescriptor(info._description,
typeof(OleDbConnectionStringBuilder), info._type, isReadOnly, attributes);
descriptor.RefreshOnChange = refreshOnChange;
propertyDescriptors[info._description] = descriptor;
}
// else strongly typed property already exists, i.e. DataSource
}
}
base.GetProperties(propertyDescriptors);
}
private sealed class OleDbProviderConverter : StringConverter {
private const int DBSOURCETYPE_DATASOURCE_TDP = 1;
private const int DBSOURCETYPE_DATASOURCE_MDP = 3;
private StandardValuesCollection _standardValues;
// converter classes should have public ctor
public OleDbProviderConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
StandardValuesCollection dataSourceNames = _standardValues;
if (null == _standardValues) {
// Get the sources rowset for the SQLOLEDB enumerator
DataTable table = (new OleDbEnumerator()).GetElements();
DataColumn column2 = table.Columns["SOURCES_NAME"];
DataColumn column5 = table.Columns["SOURCES_TYPE"];
//DataColumn column4 = table.Columns["SOURCES_DESCRIPTION"];
System.Collections.Generic.List<string> providerNames = new System.Collections.Generic.List<string>(table.Rows.Count);
foreach(DataRow row in table.Rows) {
int sourceType = (int)row[column5];
if (DBSOURCETYPE_DATASOURCE_TDP == sourceType || DBSOURCETYPE_DATASOURCE_MDP == sourceType) {
string progid = (string)row[column2];
if (!OleDbConnectionString.IsMSDASQL(progid.ToLower(CultureInfo.InvariantCulture))) {
if (0 > providerNames.IndexOf(progid)) {
providerNames.Add(progid);
}
}
}
}
// Create the standard values collection that contains the sources
dataSourceNames = new StandardValuesCollection(providerNames);
_standardValues = dataSourceNames;
}
return dataSourceNames;
}
}
[Flags()] internal enum OleDbServiceValues : int {
DisableAll = unchecked((int)0x00000000),
ResourcePooling = unchecked((int)0x00000001),
TransactionEnlistment = unchecked((int)0x00000002),
ClientCursor = unchecked((int)0x00000004),
AggregationAfterSession = unchecked((int)0x00000008),
EnableAll = unchecked((int)0xffffffff),
Default = ~(ClientCursor | AggregationAfterSession),
};
internal sealed class OleDbServicesConverter : TypeConverter {
private StandardValuesCollection _standardValues;
// converter classes should have public ctor
public OleDbServicesConverter() : base() {
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
// Only know how to convert from a string
return ((typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
string svalue = (value as string);
if (null != svalue) {
Int32 services;
if(Int32.TryParse(svalue, out services)) {
return services;
}
else {
if (svalue.IndexOf(',') != -1) {
int convertedValue = 0;
string[] values = svalue.Split(new char[] {','});
foreach(string v in values) {
convertedValue |= (int)(OleDbServiceValues)Enum.Parse(typeof(OleDbServiceValues), v, true);
}
return (int)convertedValue;;
}
else {
return (int)(OleDbServiceValues)Enum.Parse(typeof(OleDbServiceValues), svalue, true);
}
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
// Only know how to convert to the NetworkLibrary enumeration
return ((typeof(string) == destinationType) || base.CanConvertTo(context, destinationType));
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
if ((typeof(string) == destinationType) && (null != value) && (typeof(Int32) == value.GetType())) {
return Enum.Format(typeof(OleDbServiceValues), ((OleDbServiceValues)(int)value), "G");
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
StandardValuesCollection standardValues = _standardValues;
if (null == standardValues) {
Array objValues = Enum.GetValues(typeof(OleDbServiceValues));
Array.Sort(objValues, 0, objValues.Length);
standardValues = new StandardValuesCollection(objValues);
_standardValues = standardValues;
}
return standardValues;
}
public override bool IsValid(ITypeDescriptorContext context, object value) {
return true;
//return Enum.IsDefined(type, value);
}
}
sealed internal class OleDbConnectionStringBuilderConverter : ExpandableObjectConverter {
// converter classes should have public ctor
public OleDbConnectionStringBuilderConverter() {
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw ADP.ArgumentNull("destinationType");
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
OleDbConnectionStringBuilder obj = (value as OleDbConnectionStringBuilder);
if (null != obj) {
return ConvertToInstanceDescriptor(obj);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbConnectionStringBuilder options) {
Type[] ctorParams = new Type[] { typeof(string) };
object[] ctorValues = new object[] { options.ConnectionString };
System.Reflection.ConstructorInfo ctor = typeof(OleDbConnectionStringBuilder).GetConstructor(ctorParams);
return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues);
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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;
using System.Data;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.Propagator;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Common.Collections;
using Alachisoft.NCache.Common.Pooling;
namespace Alachisoft.NCache.Storage
{
/// <summary>
/// Implements the Heap cache storage option. Also implements ICacheStorage interface.
/// </summary>
class ClrHeapStorageProvider : StorageProviderBase
{
/// <summary> Storage Map </summary>
protected HashVector _itemDict;
protected bool _evictionEnabled;
///// <summary> Size of data, in bytes, stored in store</summary>
/// <summary>
/// Default constructor.
/// </summary>
public ClrHeapStorageProvider()
{
_itemDict = new HashVector(DEFAULT_CAPACITY, 0.7f);
}
/// <summary>
/// Overloaded constructor. The passed in parameters specify the values for maxObjects
/// and maxSizeMB.
/// </summary>
/// <param name="maxDataSize">maximum size of data, in bytes, that store can contain.</param>
public ClrHeapStorageProvider(long maxDataSize)
: base(maxDataSize)
{
_itemDict = new HashVector(DEFAULT_CAPACITY, 0.7f);
}
/// <summary>
/// Overloaded constructor. Takes the properties as a map.
/// </summary>
/// <param name="properties">properties collection</param>
public ClrHeapStorageProvider(IDictionary properties, bool evictionEnabled, ILogger NCacheLog, IAlertPropagator alertPropagator)
: base(properties, evictionEnabled, NCacheLog, alertPropagator)
{
_evictionEnabled = evictionEnabled;
_itemDict = new HashVector(DEFAULT_CAPACITY, 0.7f);
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
lock (_itemDict.SyncRoot)
{
_itemDict.Clear();
_itemDict = null;
}
base.Dispose();
}
#endregion
#region / --- ICacheStorage --- /
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public override long Count { get { return _itemDict.Count; } }
/// <summary>
/// Removes all entries from the store.
/// </summary>
public override void Clear()
{
lock (_itemDict.SyncRoot)
{
_itemDict.Clear();
base.Cleared();
}
}
/// <summary>
/// Determines whether the store contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the store.</param>
/// <returns>true if the store contains an element
/// with the specified key; otherwise, false.</returns>
public override bool Contains(object key)
{
//if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Store.Cont", "");
return _itemDict.ContainsKey(key);
}
/// <summary>
/// Provides implementation of Get method of the ICacheStorage interface.
/// Get an object from the store, specified by the passed in key.
/// </summary>
/// <param name="key">key</param>
/// <returns>object</returns>
public override object Get(object key)
{
try
{
//if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Store.Get", "");
lock (_itemDict.SyncRoot)
{
return _itemDict[key];
}
}
catch (Exception e)
{
Trace.error("ClrHeapStorageProvider.Get()", e.ToString());
return null;
}
}
/// <summary>
/// Get the size of item stored in cache, specified by the passed in key
/// </summary>
/// <param name="key">key</param>
/// <returns>item size</returns>
public override int GetItemSize(object key)
{
try
{
object item = null;
lock (_itemDict.SyncRoot)
{
item = _itemDict[key];
}
var iSizableItem = item as ISizable;
return iSizableItem != null ? (iSizableItem.InMemorySize + Common.MemoryUtil.GetStringSize(key)) : 0;
}
catch (Exception e)
{
Trace.error("ClrHeapStorageProvider.GetItemSize()", e.ToString());
return 0;
}
}
/// <summary>
/// Provides implementation of Add method of the ICacheStorage interface.
/// Add the key value pair to the store.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public override StoreAddResult Add(object key, IStorageEntry item, Boolean allowExtendedSize)
{
try
{
//if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Store.Add", "");
lock (_itemDict.SyncRoot)
{
if (_itemDict.ContainsKey(key))
{
return StoreAddResult.KeyExists;
}
}
StoreStatus status = HasSpace((ISizable)item,Common.MemoryUtil.GetStringSize(key),allowExtendedSize);
CheckIfCacheNearEviction();
if (status == StoreStatus.HasNotEnoughSpace)
{
return StoreAddResult.NotEnoughSpace;
}
lock (_itemDict.SyncRoot)
{
_itemDict.Add(key, item);
base.Added(item , Common.MemoryUtil.GetStringSize(key));
item.MarkInUse(NCModulesConstants.CacheStore);
}
if (status == StoreStatus.NearEviction)
{
return StoreAddResult.SuccessNearEviction;
}
}
catch (OutOfMemoryException e)
{
//Trace.error("ClrHeapStorageProvider.Add()", e.ToString());
return StoreAddResult.NotEnoughSpace;
}
catch (Exception e)
{
//Trace.error("ClrHeapStorageProvider.Add()", e.ToString());
//return StoreAddResult.Failure;
throw e;
}
return StoreAddResult.Success;
}
/// <summary>
/// Provides implementation of Insert method of the ICacheStorage interface.
/// Insert/Add the key value pair to the store.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public override StoreInsResult Insert(object key, IStorageEntry item, Boolean allowExtendedSize)
{
try
{
//if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("Store.Insert", "");
IStorageEntry oldItem = (IStorageEntry)_itemDict[key];
StoreStatus status = HasSpace(oldItem as ISizable, (ISizable)item,Common.MemoryUtil.GetStringSize(key),allowExtendedSize);
if(_evictionEnabled)
CheckIfCacheNearEviction();
if (status == StoreStatus.HasNotEnoughSpace)
{
return StoreInsResult.NotEnoughSpace;
}
lock (_itemDict.SyncRoot)
{
_itemDict[key] = item;
base.Inserted(oldItem, item, Common.MemoryUtil.GetStringSize(key));
}
if (status == StoreStatus.NearEviction)
{
//the store is almost full, need to evict.
return oldItem != null ? StoreInsResult.SuccessOverwriteNearEviction : StoreInsResult.SuccessNearEviction;
}
if (item != null)
item.MarkInUse(NCModulesConstants.CacheStore);
return oldItem != null ? StoreInsResult.SuccessOverwrite : StoreInsResult.Success;
}
catch (OutOfMemoryException e)
{
return StoreInsResult.NotEnoughSpace;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Provides implementation of Remove method of the ICacheStorage interface.
/// Removes an object from the store, specified by the passed in key
/// </summary>
/// <param name="key">key</param>
/// <returns>object</returns>
public override object Remove(object key)
{
IStorageEntry e = (IStorageEntry)Get(key);
if (e != null)
{
lock (_itemDict.SyncRoot)
{
_itemDict.Remove(key);
base.Removed(e , Common.MemoryUtil.GetStringSize(key),e.Type);
e?.MarkInUse(NCModulesConstants.Global);
e?.MarkFree(NCModulesConstants.CacheStore);
}
}
return e;
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
public override IDictionaryEnumerator GetEnumerator()
{
return _itemDict.GetEnumerator();
}
/// <summary>
/// returns the keys
/// </summary>
public override Array Keys
{
get
{
lock (_itemDict.SyncRoot)
{
Array arr = Array.CreateInstance(typeof(object), _itemDict.Keys.Count);
_itemDict.Keys.CopyTo(arr, 0);
return arr;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using Epi.Analysis;
using Epi.Windows.Dialogs;
using Epi.Windows.Analysis;
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Dialog for the HEADEROUT Command inserts text, either a string or the
/// contents of a file, into the output.
/// <remarks>Typical uses might include comments or boilerplate.</remarks>
/// <example>HEADEROUT 'My Fancy Logo.htm'</example>
/// </summary>
public partial class HeaderoutDialog : CommandDesignDialog
{
#region Constructor
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public HeaderoutDialog()
{
InitializeComponent();
Construct();
}
/// <summary>
/// TablesDialog constructor
/// </summary>
/// <param name="frm">The main form</param>
public HeaderoutDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
#endregion Constructor
#region Public Methods
/// <summary>
/// Sets enabled property of OK and Save Only
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
btnSaveOnly.Enabled = inputValid;
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Generates the command text
/// </summary>
protected override void GenerateCommand()
{
StringBuilder sb = new StringBuilder(CommandNames.HEADER);
sb.Append(StringLiterals.SPACE);
sb.Append(1.ToString());
sb.Append(StringLiterals.SPACE);
if (true)
{
sb.Append(Util.InsertInDoubleQuotes(txtTitle.Text));
WordBuilder wb = new WordBuilder(StringLiterals.COMMA);
if (boldToolStripButton.Checked || italicToolStripButton.Checked || underlineToolStripButton.Checked)
{
sb.Append(StringLiterals.SPACE);
if (boldToolStripButton.Checked) wb.Append("BOLD");
if (italicToolStripButton.Checked) wb.Append("ITALIC");
if (underlineToolStripButton.Checked) wb.Append("UNDERLINE");
sb.Append(Util.InsertInParantheses(wb.ToString()));
}
if (!string.IsNullOrEmpty(textFontColorName) && !string.IsNullOrEmpty(fontSizeToolStripDDL.Text))
{
sb.Append(" TEXTFONT ");
if (!string.IsNullOrEmpty(textFontColorName))
{
sb.Append(textFontColorName.ToUpperInvariant());
}
if (!string.IsNullOrEmpty(fontSizeToolStripDDL.Text))
{
sb.Append(StringLiterals.SPACE);
sb.Append(fontSizeToolStripDDL.Text);
}
}
}
CommandText = sb.ToString();
}
/// <summary>
/// Validates user input
/// </summary>
/// <returns>true if there is no error; else false</returns>
protected override bool ValidateInput()
{
base.ValidateInput();
if (string.IsNullOrEmpty(txtTitle.Text))
{
ErrorMessages.Add(SharedStrings.NO_TEXT_VALUE);
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/classic-analysis/how-to-manage-output-header.html");
}
#endregion Protected Methods
#region Private Members
#region Private Enums and Constants
//
#endregion Private Enums and Constants
#region Private Attributes
//
#endregion Private Attributes
#region Private Properties
//
string textFontColorName = string.Empty;
#endregion Private Properties
#region Private Methods
private void Construct()
{
if (!this.DesignMode)
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
this.btnHelp.Click += new EventHandler(this.btnHelp_Click);
this.fontSizeToolStripDDL.SelectedIndexChanged += new EventHandler(fontSizeToolStripDDL_SelectedIndexChanged);
this.defaultToolStripMenuItem.CheckedChanged += new EventHandler(defaultToolStripMenuItem_CheckedChanged);
}
}
private void defaultToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
if (fontSizeToolStripDDL.SelectedIndex > -1)
{
blackToolStripMenuItem.Select();
}
}
private void fontSizeToolStripDDL_SelectedIndexChanged(object sender, EventArgs e)
{
if (fontSizeToolStripDDL.SelectedIndex > -1 && defaultToolStripMenuItem.Selected)
{
blackToolStripMenuItem.Select();
}
}
private void EnableControls()
{
boldToolStripButton.Enabled = true;
italicToolStripButton.Enabled = true;
underlineToolStripButton.Enabled = true;
fontSizeToolStripDDL.Enabled = true;
fontColorToolStripDDL.Enabled = true;
}
private void DisableAndClearControls()
{
fontSizeToolStripDDL.Text = String.Empty;
fontSizeToolStripDDL.Enabled = false;
boldToolStripButton.Checked = false;
boldToolStripButton.Enabled = false;
italicToolStripButton.Checked = false;
italicToolStripButton.Enabled = false;
underlineToolStripButton.Checked = false;
underlineToolStripButton.Enabled = false;
fontColorToolStripDDL.Text = String.Empty;
fontColorToolStripDDL.Enabled = false;
}
#endregion Private Methods
#region Private Event
private void HeaderoutDialog_Load(object sender, EventArgs e)
{
boldToolStripButton.Image = baseImageList.Images[36];
italicToolStripButton.Image = baseImageList.Images[49];
underlineToolStripButton.Image = baseImageList.Images[64];
fontColorToolStripDDL.Image = baseImageList.Images[10];
}
private void btnClear_Click(object sender, System.EventArgs e)
{
txtTitle.Text = String.Empty;
fontColorToolStripDDL.Text = String.Empty;
fontSizeToolStripDDL.Text = String.Empty;
boldToolStripButton.Checked = false;
italicToolStripButton.Checked = false;
underlineToolStripButton.Checked = false;
}
private void fontColorToolStripDDL_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.BackColor.Name.Equals(SystemColors.Control.Name))
textFontColorName = string.Empty;
else
textFontColorName = e.ClickedItem.BackColor.Name;
fontColorToolStripDDL.Text = textFontColorName;
fontColorToolStripDDL.ToolTipText = "Font Color " + textFontColorName;
fontColorToolStripDDL.ForeColor = e.ClickedItem.BackColor;
}
#endregion Private Event
#endregion Private Members
}
}
| |
using UnityEngine;
using System;
using System.Diagnostics;
namespace CommonComponent
{
public enum LogLevel
{
Error,
Warning,
Info,
}
public static class Log
{
public static LogLevel LogLevel = LogLevel.Info;
[Conditional("ENABLE_LOG")]
public static void Info(object msg)
{
if (LogLevel >= LogLevel.Info)
{
UnityEngine.Debug.Log(msg);
}
}
[Conditional("ENABLE_LOG")]
public static void Info(object msg, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Info)
{
UnityEngine.Debug.Log(msg, context);
}
}
[Conditional("ENABLE_LOG")]
public static void InfoFormat(string format, params object[] args)
{
if (LogLevel >= LogLevel.Info)
{
UnityEngine.Debug.LogFormat(format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void InfoFormat(UnityEngine.Object context, string format, params object[] args)
{
if (LogLevel >= LogLevel.Info)
{
UnityEngine.Debug.LogFormat(context, format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void Warning(object msg)
{
if (LogLevel >= LogLevel.Warning)
{
UnityEngine.Debug.LogWarning(msg);
}
}
[Conditional("ENABLE_LOG")]
public static void Warning(object msg, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Info)
{
UnityEngine.Debug.LogWarning(msg, context);
}
}
[Conditional("ENABLE_LOG")]
public static void WarningFormat(string format, params object[] args)
{
if (LogLevel >= LogLevel.Warning)
{
UnityEngine.Debug.LogWarningFormat(format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void WarningFormat(UnityEngine.Object context, string format, params object[] args)
{
if (LogLevel >= LogLevel.Warning)
{
UnityEngine.Debug.LogWarningFormat(context, format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void Error(object msg)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.LogError(msg);
}
}
[Conditional("ENABLE_LOG")]
public static void Error(object msg, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.LogError(msg, context);
}
}
[Conditional("ENABLE_LOG")]
public static void ErrorFormat(string format, params object[] args)
{
if (LogLevel >= LogLevel.Warning)
{
UnityEngine.Debug.LogErrorFormat(format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void ErrorFormat(UnityEngine.Object context, string format, params object[] args)
{
if (LogLevel >= LogLevel.Warning)
{
UnityEngine.Debug.LogErrorFormat(context, format, args);
}
}
[Conditional("ENABLE_LOG")]
public static void Exception(Exception ex)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.LogException(ex);
}
}
[Conditional("ENABLE_LOG")]
public static void Exception(Exception exception, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.LogException(exception, context);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition, context);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition, object message)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition, message);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition, string message)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition, message);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition, object message, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition, message, context);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void Assert(bool condition, string message, UnityEngine.Object context)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.Assert(condition, message, context);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void AssertFormat(bool condition, string format, params object[] args)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.AssertFormat(condition, format, args);
}
}
[Conditional("UNITY_ASSERTIONS")]
public static void AssertFormat(bool condition, UnityEngine.Object context, string format, params object[] args)
{
if (LogLevel >= LogLevel.Error)
{
UnityEngine.Debug.AssertFormat(condition, context, format, 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.
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class RandomStressTest
{
private static readonly TimeSpan TimeLimitDefault = new TimeSpan(0, 0, 10);
private const int ThreadCountDefault = 4;
private const int IterationsPerTableDefault = 50;
private const int MaxColumns = 5000;
private const int MaxRows = 100;
private const int MaxTotal = MaxColumns * 10;
private string[] _connectionStrings;
private string _operationCanceledErrorMessage;
private string _severeErrorMessage;
private SqlRandomTypeInfoCollection _katmaiTypes;
private ManualResetEvent _endEvent;
private int _runningThreads;
private long _totalValues;
private long _totalTables;
private long _totalIterations;
private long _totalTicks;
private RandomizerPool _randPool;
[CheckConnStrSetupFact]
public void TestMain()
{
_operationCanceledErrorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;
_severeErrorMessage = SystemDataResourceManager.Instance.SQL_SevereError;
// pure random
_randPool = new RandomizerPool();
SqlConnectionStringBuilder regularConnectionString = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
regularConnectionString.MultipleActiveResultSets = false;
List<string> connStrings = new List<string>();
connStrings.Add(regularConnectionString.ToString());
connStrings.Add(regularConnectionString.ToString());
regularConnectionString.MultipleActiveResultSets = true;
connStrings.Add(regularConnectionString.ToString());
_connectionStrings = connStrings.ToArray();
_katmaiTypes = SqlRandomTypeInfoCollection.CreateSql2008Collection();
_endEvent = new ManualResetEvent(false);
if (_randPool.ReproMode)
{
_runningThreads = 1;
TestThread();
}
else
{
for (int tcount = 0; tcount < ThreadCountDefault; tcount++)
{
Thread t = new Thread(TestThread);
t.Start();
}
}
}
private void NextConnection(ref SqlConnection con, Randomizer rand)
{
if (con != null)
{
con.Close();
}
string connString = _connectionStrings[rand.Next(_connectionStrings.Length)];
con = new SqlConnection(connString);
con.Open();
}
private void TestThread()
{
try
{
using (var rootScope = _randPool.RootScope<SqlRandomizer>())
{
Stopwatch watch = new Stopwatch();
SqlConnection con = null;
try
{
NextConnection(ref con, rootScope.Current);
if (_randPool.ReproMode)
{
using (var testScope = rootScope.NewScope<SqlRandomizer>())
{
// run only once if repro file is provided
RunTest(con, testScope, _katmaiTypes, watch);
}
}
else
{
while (watch.Elapsed < TimeLimitDefault)
{
using (var testScope = rootScope.NewScope<SqlRandomizer>())
{
RunTest(con, testScope, _katmaiTypes, watch);
}
if (rootScope.Current.Next(100) == 0)
{
// replace the connection
NextConnection(ref con, rootScope.Current);
}
}
}
}
finally
{
if (con != null)
{
con.Close();
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (Interlocked.Decrement(ref _runningThreads) == 0)
_endEvent.Set();
}
}
private void RunTest(SqlConnection con, RandomizerPool.Scope<SqlRandomizer> testScope, SqlRandomTypeInfoCollection types, Stopwatch watch)
{
Exception pendingException = null;
string tempTableName = null;
try
{
// select number of columns to use and null bitmap to test
int columnsCount, rowsCount;
testScope.Current.NextTableDimentions(MaxRows, MaxColumns, MaxTotal, out rowsCount, out columnsCount);
SqlRandomTable table = SqlRandomTable.Create(testScope.Current, types, columnsCount, rowsCount, createPrimaryKeyColumn: true);
long total = (long)rowsCount * columnsCount;
Interlocked.Add(ref _totalValues, total);
Interlocked.Increment(ref _totalTables);
tempTableName = SqlRandomizer.GenerateUniqueTempTableNameForSqlServer();
table.GenerateTableOnServer(con, tempTableName);
long prevTicks = watch.ElapsedTicks;
watch.Start();
if (_randPool.ReproMode)
{
// perform one iteration only
using (var iterationScope = testScope.NewScope<SqlRandomizer>())
{
RunTestIteration(con, iterationScope.Current, table, tempTableName);
Interlocked.Increment(ref _totalIterations);
}
}
else
{
// continue with normal loop
for (int i = 0; i < IterationsPerTableDefault && watch.Elapsed < TimeLimitDefault; i++)
{
using (var iterationScope = testScope.NewScope<SqlRandomizer>())
{
RunTestIteration(con, iterationScope.Current, table, tempTableName);
Interlocked.Increment(ref _totalIterations);
}
}
}
watch.Stop();
Interlocked.Add(ref _totalTicks, watch.ElapsedTicks - prevTicks);
}
catch (Exception e)
{
pendingException = e;
throw;
}
finally
{
// keep the temp table for troubleshooting if debugger is attached
// the thread is going down anyway and connection will be closed
if (pendingException == null && tempTableName != null)
{
// destroy the temp table to free resources on the server
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DROP TABLE " + tempTableName;
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
}
private void RunTestIteration(SqlConnection con, SqlRandomizer rand, SqlRandomTable table, string tableName)
{
// random list of columns
int columnCount = table.Columns.Count;
int[] columnIndices = rand.NextIndices(columnCount);
int selectedCount = rand.NextIntInclusive(1, maxValueInclusive: columnCount);
StringBuilder selectBuilder = new StringBuilder();
table.GenerateSelectFromTableTSql(tableName, selectBuilder, columnIndices, 0, selectedCount);
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = selectBuilder.ToString();
bool cancel = rand.Next(100) == 0; // in 1% of the cases, call Cancel
if (cancel)
{
int cancelAfterMilliseconds = rand.Next(5);
int cancelAfterSpinCount = rand.Next(1000);
ThreadPool.QueueUserWorkItem((object state) =>
{
for (int i = 0; cancel && i < cancelAfterMilliseconds; i++)
{
Thread.Sleep(1);
}
if (cancel && cancelAfterSpinCount > 0)
{
SpinWait.SpinUntil(() => false, new TimeSpan(cancelAfterSpinCount));
}
if (cancel)
{
cmd.Cancel();
}
});
}
int readerRand = rand.NextIntInclusive(0, maxValueInclusive: 256);
CommandBehavior readerBehavior = CommandBehavior.Default;
if (readerRand % 10 == 0)
readerBehavior = CommandBehavior.SequentialAccess;
try
{
using (SqlDataReader reader = cmd.ExecuteReader(readerBehavior))
{
int row = 0;
while (reader.Read())
{
int rowRand = rand.NextIntInclusive();
if (rowRand % 1000 == 0)
{
// abandon this reader
break;
}
else if (rowRand % 25 == 0)
{
// skip the row
row++;
continue;
}
IList<object> expectedRow = table[row];
for (int c = 0; c < reader.FieldCount; c++)
{
if (rand.NextIntInclusive(0, maxValueInclusive: 10) == 0)
{
// skip the column
continue;
}
int expectedTableColumn = columnIndices[c];
object expectedValue = expectedRow[expectedTableColumn];
if (table.Columns[expectedTableColumn].CanCompareValues)
{
Assert.True(expectedValue != null, "FAILED: Null is expected with CanCompareValues");
// read the value same way it was written
object actualValue = table.Columns[expectedTableColumn].Read(reader, c, expectedValue.GetType());
Assert.True(table.Columns[expectedTableColumn].CompareValues(expectedValue, actualValue),
string.Format("FAILED: Data Comparison Failure:\n{0}", table.Columns[expectedTableColumn].BuildErrorMessage(expectedValue, actualValue)));
}
}
row++;
}
}
// keep last - this will stop the cancel task, if it is still active
cancel = false;
}
catch (SqlException e)
{
if (!cancel)
throw;
bool expected = false;
foreach (SqlError error in e.Errors)
{
if (error.Message == _operationCanceledErrorMessage)
{
// ignore this one - expected if canceled
expected = true;
break;
}
else if (error.Message == _severeErrorMessage)
{
// A severe error occurred on the current command. The results, if any, should be discarded.
expected = true;
break;
}
}
if (!expected)
{
// rethrow to the user
foreach (SqlError error in e.Errors)
{
Console.WriteLine("{0} {1}", error.Number, error.Message);
}
throw;
}
}
catch (InvalidOperationException e)
{
bool expected = false;
if (e.Message == _operationCanceledErrorMessage)
{
// "Operation canceled" exception is raised as a SqlException (as one of SqlError objects) and as InvalidOperationException
expected = true;
}
if (!expected)
{
throw;
}
}
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#region CVS Information
/*
* $Source$
* $Author: sontek $
* $Date: 2008-06-16 16:37:58 -0700 (Mon, 16 Jun 2008) $
* $Revision: 275 $
*/
#endregion
using System;
using System.Collections;
using System.IO;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Nodes
{
/// <summary>
/// A set of values that the Project's type can be
/// </summary>
public enum ProjectType
{
/// <summary>
/// The project is a console executable
/// </summary>
Exe,
/// <summary>
/// The project is a windows executable
/// </summary>
WinExe,
/// <summary>
/// The project is a library
/// </summary>
Library,
/// <summary>
/// The project is a website
/// </summary>
Web,
}
/// <summary>
///
/// </summary>
public enum ClrRuntime
{
/// <summary>
///
/// </summary>
Microsoft,
/// <summary>
///
/// </summary>
Mono
}
/// <summary>
/// The version of the .NET framework to use (Required for VS2008)
/// <remarks>We don't need .NET 1.1 in here, it'll default when using vs2003.</remarks>
/// </summary>
public enum FrameworkVersion
{
/// <summary>
/// .NET 2.0
/// </summary>
v2_0,
/// <summary>
/// .NET 3.0
/// </summary>
v3_0,
/// <summary>
/// .NET 3.5
/// </summary>
v3_5,
}
/// <summary>
/// The Node object representing /Prebuild/Solution/Project elements
/// </summary>
[DataNode("Project")]
public class ProjectNode : DataNode
{
#region Fields
private string m_Name = "unknown";
private string m_Path = "";
private string m_FullPath = "";
private string m_AssemblyName;
private string m_AppIcon = "";
private string m_ConfigFile = "";
private string m_DesignerFolder = "";
private string m_Language = "C#";
private ProjectType m_Type = ProjectType.Exe;
private ClrRuntime m_Runtime = ClrRuntime.Microsoft;
private FrameworkVersion m_Framework = FrameworkVersion.v2_0;
private string m_StartupObject = "";
private string m_RootNamespace;
private string m_FilterGroups = "";
private string m_Version = "";
private Guid m_Guid;
private Hashtable m_Configurations;
private ArrayList m_ReferencePaths;
private ArrayList m_References;
private ArrayList m_Authors;
private FilesNode m_Files;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ProjectNode"/> class.
/// </summary>
public ProjectNode()
{
m_Configurations = new Hashtable();
m_ReferencePaths = new ArrayList();
m_References = new ArrayList();
m_Authors = new ArrayList();
}
#endregion
#region Properties
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return m_Name;
}
}
/// <summary>
/// The version of the .NET Framework to compile under
/// </summary>
public FrameworkVersion FrameworkVersion
{
get
{
return this.m_Framework;
}
}
/// <summary>
/// Gets the path.
/// </summary>
/// <value>The path.</value>
public string Path
{
get
{
return m_Path;
}
}
/// <summary>
/// Gets the filter groups.
/// </summary>
/// <value>The filter groups.</value>
public string FilterGroups
{
get
{
return m_FilterGroups;
}
}
/// <summary>
/// Gets the project's version
/// </summary>
/// <value>The project's version.</value>
public string Version
{
get
{
return m_Version;
}
}
/// <summary>
/// Gets the full path.
/// </summary>
/// <value>The full path.</value>
public string FullPath
{
get
{
return m_FullPath;
}
}
/// <summary>
/// Gets the name of the assembly.
/// </summary>
/// <value>The name of the assembly.</value>
public string AssemblyName
{
get
{
return m_AssemblyName;
}
}
/// <summary>
/// Gets the app icon.
/// </summary>
/// <value>The app icon.</value>
public string AppIcon
{
get
{
return m_AppIcon;
}
}
/// <summary>
/// Gets the app icon.
/// </summary>
/// <value>The app icon.</value>
public string ConfigFile
{
get
{
return m_ConfigFile;
}
}
/// <summary>
///
/// </summary>
public string DesignerFolder
{
get
{
return m_DesignerFolder;
}
}
/// <summary>
/// Gets the language.
/// </summary>
/// <value>The language.</value>
public string Language
{
get
{
return m_Language;
}
}
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
public ProjectType Type
{
get
{
return m_Type;
}
}
/// <summary>
/// Gets the runtime.
/// </summary>
/// <value>The runtime.</value>
public ClrRuntime Runtime
{
get
{
return m_Runtime;
}
}
private bool m_GenerateAssemblyInfoFile = false;
/// <summary>
///
/// </summary>
public bool GenerateAssemblyInfoFile
{
get
{
return m_GenerateAssemblyInfoFile;
}
set
{
m_GenerateAssemblyInfoFile = value;
}
}
/// <summary>
/// Gets the startup object.
/// </summary>
/// <value>The startup object.</value>
public string StartupObject
{
get
{
return m_StartupObject;
}
}
/// <summary>
/// Gets the root namespace.
/// </summary>
/// <value>The root namespace.</value>
public string RootNamespace
{
get
{
return m_RootNamespace;
}
}
/// <summary>
/// Gets the configurations.
/// </summary>
/// <value>The configurations.</value>
public ICollection Configurations
{
get
{
return m_Configurations.Values;
}
}
/// <summary>
/// Gets the configurations table.
/// </summary>
/// <value>The configurations table.</value>
public Hashtable ConfigurationsTable
{
get
{
return m_Configurations;
}
}
/// <summary>
/// Gets the reference paths.
/// </summary>
/// <value>The reference paths.</value>
public ArrayList ReferencePaths
{
get
{
return m_ReferencePaths;
}
}
/// <summary>
/// Gets the references.
/// </summary>
/// <value>The references.</value>
public ArrayList References
{
get
{
return m_References;
}
}
/// <summary>
/// Gets the Authors list.
/// </summary>
/// <value>The list of the project's authors.</value>
public ArrayList Authors
{
get
{
return m_Authors;
}
}
/// <summary>
/// Gets the files.
/// </summary>
/// <value>The files.</value>
public FilesNode Files
{
get
{
return m_Files;
}
}
/// <summary>
/// Gets or sets the parent.
/// </summary>
/// <value>The parent.</value>
public override IDataNode Parent
{
get
{
return base.Parent;
}
set
{
base.Parent = value;
if(base.Parent is SolutionNode && m_Configurations.Count < 1)
{
SolutionNode parent = (SolutionNode)base.Parent;
foreach(ConfigurationNode conf in parent.Configurations)
{
m_Configurations[conf.Name] = conf.Clone();
}
}
}
}
/// <summary>
/// Gets the GUID.
/// </summary>
/// <value>The GUID.</value>
public Guid Guid
{
get
{
return m_Guid;
}
}
#endregion
#region Private Methods
private void HandleConfiguration(ConfigurationNode conf)
{
if(String.Compare(conf.Name, "all", true) == 0) //apply changes to all, this may not always be applied first,
//so it *may* override changes to the same properties for configurations defines at the project level
{
foreach(ConfigurationNode confNode in this.m_Configurations.Values)
{
conf.CopyTo(confNode);//update the config templates defines at the project level with the overrides
}
}
if(m_Configurations.ContainsKey(conf.Name))
{
ConfigurationNode parentConf = (ConfigurationNode)m_Configurations[conf.Name];
conf.CopyTo(parentConf);//update the config templates defines at the project level with the overrides
}
else
{
m_Configurations[conf.Name] = conf;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
public override void Parse(XmlNode node)
{
m_Name = Helper.AttributeValue(node, "name", m_Name);
m_Path = Helper.AttributeValue(node, "path", m_Path);
m_FilterGroups = Helper.AttributeValue(node, "filterGroups", m_FilterGroups);
m_Version = Helper.AttributeValue(node, "version", m_Version);
m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon);
m_ConfigFile = Helper.AttributeValue(node, "configFile", m_ConfigFile);
m_DesignerFolder = Helper.AttributeValue(node, "designerFolder", m_DesignerFolder);
m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName);
m_Language = Helper.AttributeValue(node, "language", m_Language);
m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type);
m_Runtime = (ClrRuntime)Helper.EnumAttributeValue(node, "runtime", typeof(ClrRuntime), m_Runtime);
m_Framework = (FrameworkVersion)Helper.EnumAttributeValue(node, "frameworkVersion", typeof(FrameworkVersion), m_Framework);
m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject);
m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace);
string guid = Helper.AttributeValue(node, "guid", Guid.NewGuid().ToString());
m_Guid = new Guid(guid);
m_GenerateAssemblyInfoFile = Helper.ParseBoolean(node, "generateAssemblyInfoFile", false);
if(m_AssemblyName == null || m_AssemblyName.Length < 1)
{
m_AssemblyName = m_Name;
}
if(m_RootNamespace == null || m_RootNamespace.Length < 1)
{
m_RootNamespace = m_Name;
}
m_FullPath = m_Path;
try
{
m_FullPath = Helper.ResolvePath(m_FullPath);
}
catch
{
throw new WarningException("Could not resolve Solution path: {0}", m_Path);
}
Kernel.Instance.CurrentWorkingDirectory.Push();
try
{
Helper.SetCurrentDir(m_FullPath);
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
if(dataNode is ConfigurationNode)
{
HandleConfiguration((ConfigurationNode)dataNode);
}
else if(dataNode is ReferencePathNode)
{
m_ReferencePaths.Add(dataNode);
}
else if(dataNode is ReferenceNode)
{
m_References.Add(dataNode);
}
else if(dataNode is AuthorNode)
{
m_Authors.Add(dataNode);
}
else if(dataNode is FilesNode)
{
m_Files = (FilesNode)dataNode;
}
}
}
finally
{
Kernel.Instance.CurrentWorkingDirectory.Pop();
}
}
#endregion
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Core;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
namespace CartoFeatures.ProSnippet
{
class ProSnippet
{
//style management
#region ProSnippet Group: Style Management
#endregion
public void GetStyleInProjectByName()
{
#region How to get a style in project by name
//Get all styles in the project
var ProjectStyles = Project.Current.GetItems<StyleProjectItem>();
//Get a specific style in the project by name
StyleProjectItem style = ProjectStyles.First(x => x.Name == "NameOfTheStyle");
#endregion
}
public async void CreateNewStyle()
{
// cref: How to create a new style;ArcGIS.Desktop.Mapping.StyleHelper.CreateMobileStyle(ArcGIS.Desktop.Core.Project,System.String)
// cref: How to create a new style;ArcGIS.Desktop.Mapping.StyleHelper.CreateStyle(ArcGIS.Desktop.Core.Project,System.String)
#region How to create a new style
//Full path for the new style file (.stylx) to be created
string styleToCreate = @"C:\Temp\NewStyle.stylx";
await QueuedTask.Run(() => StyleHelper.CreateStyle(Project.Current, styleToCreate));
#endregion
}
public async void AddStyleToProject()
{
// cref: How to add a style to project;ArcGIS.Desktop.Mapping.StyleHelper.AddStyle(ArcGIS.Desktop.Core.Project,System.String)
#region How to add a style to project
//For ArcGIS Pro system styles, just pass in the name of the style to add to the project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, "3D Vehicles"));
//For custom styles, pass in the full path to the style file on disk
string customStyleToAdd = @"C:\Temp\CustomStyle.stylx";
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, customStyleToAdd));
#endregion
}
public async void RemoveStyleFromProject()
{
// cref: How to remove a style from project;ArcGIS.Desktop.Mapping.StyleHelper.RemoveStyle(ArcGIS.Desktop.Core.Project,System.String)
#region How to remove a style from project
//For ArcGIS Pro system styles, just pass in the name of the style to remove from the project
await QueuedTask.Run(() => StyleHelper.RemoveStyle(Project.Current, "3D Vehicles"));
//For custom styles, pass in the full path to the style file on disk
string customStyleToAdd = @"C:\Temp\CustomStyle.stylx";
await QueuedTask.Run(() => StyleHelper.RemoveStyle(Project.Current, customStyleToAdd));
#endregion
}
// cref: How to add a style item to a style;ArcGIS.Desktop.Mapping.StyleHelper.AddItem(ArcGIS.Desktop.Mapping.StyleProjectItem,ArcGIS.Desktop.Mapping.StyleItem)
#region How to add a style item to a style
public Task AddStyleItemAsync(StyleProjectItem style, StyleItem itemToAdd)
{
return QueuedTask.Run(() =>
{
if (style == null || itemToAdd == null)
throw new System.ArgumentNullException();
//Add the item to style
style.AddItem(itemToAdd);
});
}
#endregion
// cref: How to remove a style item from a style;ArcGIS.Desktop.Mapping.StyleHelper.RemoveItem(ArcGIS.Desktop.Mapping.StyleProjectItem,ArcGIS.Desktop.Mapping.StyleItem)
#region How to remove a style item from a style
public Task RemoveStyleItemAsync(StyleProjectItem style, StyleItem itemToRemove)
{
return QueuedTask.Run(() =>
{
if (style == null || itemToRemove == null)
throw new System.ArgumentNullException();
//Remove the item from style
style.RemoveItem(itemToRemove);
});
}
#endregion
#region How to determine if a style can be upgraded
//Pass in the full path to the style file on disk
public async Task<bool> CanUpgradeStyleAsync(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style can be upgraded
return style.CanUpgrade;
}
#endregion
#region How to determine if a style is read-only
//Pass in the full path to the style file on disk
public async Task<bool> IsReadOnly(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style is read-only
return style.IsReadOnly;
}
#endregion
#region How to determine if a style is current
//Pass in the full path to the style file on disk
public async Task<bool> IsCurrent(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style matches the current Pro version
return style.IsCurrent;
}
#endregion
#region How to upgrade a style
//Pass in the full path to the style file on disk
public async Task<bool> UpgradeStyleAsync(string stylePath)
{
bool success = false;
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//Verify that style can be upgraded
if (style.CanUpgrade)
{
success = await QueuedTask.Run(() => StyleHelper.UpgradeStyle(style));
}
//return true if style was upgraded
return success;
}
#endregion
//construct point symbol
#region ProSnippet Group: Symbols
#endregion
public async Task ConstructPointSymbol_1()
{
// cref: How to construct a point symbol of a specific color and size;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructPointSymbol(ArcGIS.Core.CIM.CIMColor,System.Double)
#region How to construct a point symbol of a specific color and size
await QueuedTask.Run(() =>
{
CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0);
});
#endregion
}
public async Task ConstructPointSymbol_2()
{
// cref: How to construct a point symbol of a specific color, size and shape;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructPointSymbol(ArcGIS.Core.CIM.CIMColor,System.Double,ArcGIS.Desktop.Mapping.SimpleMarkerStyle)
#region How to construct a point symbol of a specific color, size and shape
await QueuedTask.Run(() =>
{
CIMPointSymbol starPointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0, SimpleMarkerStyle.Star);
});
#endregion
}
public async Task ConstructPointSymbol_3()
{
// cref: How to construct a point symbol from a marker;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructMarker(ArcGIS.Core.CIM.CIMColor,System.Double,ArcGIS.Desktop.Mapping.SimpleMarkerStyle)
// cref: How to construct a point symbol from a marker;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructPointSymbol(ArcGIS.Core.CIM.CIMMarker)
#region How to construct a point symbol from a marker
await QueuedTask.Run(() =>
{
CIMMarker marker = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.GreenRGB, 8.0, SimpleMarkerStyle.Pushpin);
CIMPointSymbol pointSymbolFromMarker = SymbolFactory.Instance.ConstructPointSymbol(marker);
});
#endregion
}
public async Task ConstructPointSymbol_4()
{
// cref: How to construct a point symbol from a file on disk;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructMarkerFromBitmapSource(System.Windows.Media.Imaging.BitmapSource)
// cref: How to construct a point symbol from a file on disk;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructMarkerFromFile(System.String)
#region How to construct a point symbol from a file on disk
//The following file formats can be used to create the marker: DAE, 3DS, FLT, EMF, JPG, PNG, BMP, GIF
CIMMarker markerFromFile = await QueuedTask.Run(() => SymbolFactory.Instance.ConstructMarkerFromFile(@"C:\Temp\fileName.dae"));
CIMPointSymbol pointSymbolFromFile = SymbolFactory.Instance.ConstructPointSymbol(markerFromFile);
#endregion
}
public void ConstructPointSymbolFromMarkerStream()
{
#region How to construct a point symbol from a in memory graphic
//Create a stream for the image
Image newImage = Image.FromFile(@"C:\PathToImage\Image.png");
var stream = new System.IO.MemoryStream();
newImage.Save(stream, ImageFormat.Png);
stream.Position = 0;
//Create marker using the stream
CIMMarker markerFromStream = SymbolFactory.Instance.ConstructMarkerFromStream(stream);
//Create the point symbol from the marker
CIMPointSymbol pointSymbolFromStream = SymbolFactory.Instance.ConstructPointSymbol(markerFromStream);
#endregion
}
//construct polygon symbol
public void ConstructPolygonSymbol_1()
{
// cref: How to construct a polygon symbol of specific color and fill style;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructPolygonSymbol(ArcGIS.Core.CIM.CIMColor,ArcGIS.Desktop.Mapping.SimpleFillStyle)
#region How to construct a polygon symbol of specific color and fill style
CIMPolygonSymbol polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid);
#endregion
}
public void ConstructPolygonSymbol_2()
{
// cref: How to construct a polygon symbol of specific color, fill style and outline;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructPolygonSymbol(ArcGIS.Core.CIM.CIMColor,ArcGIS.Desktop.Mapping.SimpleFillStyle,ArcGIS.Core.CIM.CIMStroke)
#region How to construct a polygon symbol of specific color, fill style and outline
CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);
CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);
#endregion
}
public void ConstructPolygonSymbol_3()
{
#region How to construct a polygon symbol without an outline
CIMPolygonSymbol fillWithoutOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, null);
#endregion
}
//construct line symbol
public void ContructLineSymbol_1()
{
// cref: How to construct a line symbol of specific color, size and line style;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructLineSymbol(ArcGIS.Core.CIM.CIMColor,System.Double,ArcGIS.Desktop.Mapping.SimpleLineStyle)
#region How to construct a line symbol of specific color, size and line style
CIMLineSymbol lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid);
#endregion
}
public void ContructLineSymbol_2()
{
// cref: How to construct a line symbol from a stroke;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructLineSymbol(ArcGIS.Core.CIM.CIMStroke)
// cref: How to construct a line symbol from a stroke;ArcGIS.Desktop.Mapping.SymbolFactory.ConstructStroke(ArcGIS.Core.CIM.CIMColor,System.Double)
#region How to construct a line symbol from a stroke
CIMStroke stroke = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0);
CIMLineSymbol lineSymbolFromStroke = SymbolFactory.Instance.ConstructLineSymbol(stroke);
#endregion
}
//multilayer symbols
public void ContructMultilayerLineSymbol_1()
{
#region How to construct a multilayer line symbol with circle markers on the line ends
//These methods must be called within the lambda passed to QueuedTask.Run
var lineStrokeRed = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 4.0);
var markerCircle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Circle);
markerCircle.MarkerPlacement = new CIMMarkerPlacementOnVertices()
{
AngleToLine = true,
PlaceOnEndPoints = true,
Offset = 0
};
var lineSymbolWithCircles = new CIMLineSymbol()
{
SymbolLayers = new CIMSymbolLayer[2] { markerCircle, lineStrokeRed }
};
#endregion
}
public void ContructMultilayerLineSymbol_2()
{
#region How to construct a multilayer line symbol with an arrow head on the end
//These methods must be called within the lambda passed to QueuedTask.Run
var markerTriangle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Triangle);
markerTriangle.Rotation = -90; // or -90
markerTriangle.MarkerPlacement = new CIMMarkerPlacementOnLine() { AngleToLine = true, RelativeTo = PlacementOnLineRelativeTo.LineEnd };
var lineSymbolWithArrow = new CIMLineSymbol()
{
SymbolLayers = new CIMSymbolLayer[2] { markerTriangle,
SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 2)
}
};
#endregion
}
//symbol reference
public void GetSymbolReference()
{
// cref: How to get symbol reference from a symbol;ArcGIS.Desktop.Mapping.SymbolExtensionMethods.MakeSymbolReference(ArcGIS.Core.CIM.CIMSymbol)
#region How to get symbol reference from a symbol
CIMPolygonSymbol symbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB);
//Get symbol reference from the symbol
CIMSymbolReference symbolReference = symbol.MakeSymbolReference();
#endregion
}
private static void GetSymbol()
{
#region Modify a point symbol created from a character marker
//create marker from the Font, char index,size,color
var cimMarker = SymbolFactory.Instance.ConstructMarker(125, "Wingdings 3", "Regular", 6, ColorFactory.Instance.BlueRGB) as CIMCharacterMarker;
var polygonMarker = cimMarker.Symbol;
//modifying the polygon's outline and fill
//This is the outline
polygonMarker.SymbolLayers[0] = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB, 2, SimpleLineStyle.Solid);
//This is the fill
polygonMarker.SymbolLayers[1] = SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.BlueRGB);
//create a symbol from the marker
//Note this overload of ConstructPointSymbol does not need to be run within QueuedTask.Run.
var pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(cimMarker);
#endregion
}
private void Fonts()
{
#region Get a List of Available Fonts
//Must use QueuedTask.Run(...)
//returns a tuple per font: (string fontName, List<string> fontStyles)
var fonts = SymbolFactory.Instance.GetAvailableFonts();
foreach(var font in fonts)
{
var styles = string.Join(",", font.fontStyles);
System.Diagnostics.Debug.WriteLine($"{font.fontName}, styles: {styles}");
}
#endregion
#region Get/Set Default Font
//Must use QueuedTask.Run(...)
var def_font = SymbolFactory.Instance.DefaultFont;
System.Diagnostics.Debug.WriteLine($"{def_font.fontName}, styles: {def_font.styleName}");
//set default font - set through application options
//Must use QueuedTask
ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma");
ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma","bold");
#endregion
#region Construct a Text Symbol With Options
QueuedTask.Run(() =>
{
//using the default font
var textSym1 = SymbolFactory.Instance.ConstructTextSymbol();
var textSym2 = SymbolFactory.Instance.ConstructTextSymbol(
ColorFactory.Instance.BlueRGB, 14);
//using a specific font
var textSym3 = SymbolFactory.Instance.ConstructTextSymbol("Arial");
var textSym4 = SymbolFactory.Instance.ConstructTextSymbol(
"Arial", "Narrow Bold");
//or query available fonts to ensure the font is there
var all_fonts = SymbolFactory.Instance.GetAvailableFonts();
var font = all_fonts.FirstOrDefault(f => f.fontName == "Arial");
if (!string.IsNullOrEmpty(font.fontName))
{
var textSym5 = SymbolFactory.Instance.ConstructTextSymbol(font.fontName);
//or with a font+style
var textSym6 = SymbolFactory.Instance.ConstructTextSymbol(
font.fontName, font.fontStyles.First());
}
//overloads - font + color and size, etc
var textSym7 = SymbolFactory.Instance.ConstructTextSymbol(
ColorFactory.Instance.BlueRGB, 14, "Times New Roman", "Italic");
//custom symbol - black stroke, red fill
var poly_symbol = SymbolFactory.Instance.ConstructPolygonSymbol(
SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.RedRGB),
SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1));
var textSym8 = SymbolFactory.Instance.ConstructTextSymbol(
poly_symbol, 14, "Georgia", "Bold");
});
#endregion
}
private static Task CreateSymbolSwatch()
{
return QueuedTask.Run(() => {
#region Create a Swatch for a given symbol
//Note: call within QueuedTask.Run()
CIMSymbol symbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
//You can generate a swatch for a text symbols also.
var si = new SymbolStyleItem()
{
Symbol = symbol,
PatchHeight = 64,
PatchWidth = 64
};
return si.PreviewImage;
#endregion
});
}
private static void SymbolLookup(FeatureLayer featureLayer)
{
#region Lookup Symbol
//Note: Run within QueuedTask.Run
//Get the selection
var selection = featureLayer.GetSelection();
//Get the first Object ID
var firstOID = selection.GetObjectIDs().FirstOrDefault();
//Determine whether the layer's renderer type supports symbol lookup.
if (featureLayer.CanLookupSymbol())
{
//Looks up the symbol for the corresponding feature identified by the object id.
var symbol = featureLayer.LookupSymbol(firstOID, MapView.Active);
var jSon = symbol.ToJson(); //Create a JSON encoding of the symbol
//Do something with symbol
}
#endregion
}
#region ProSnippet Group: Symbol Search
#endregion
//symbol search
// cref: How to search for a specific item in a style;ArcGIS.Desktop.Mapping.StyleHelper.LookupItem(ArcGIS.Desktop.Mapping.StyleProjectItem,ArcGIS.Desktop.Mapping.StyleItemType,System.String)
#region How to search for a specific item in a style
public Task<SymbolStyleItem> GetSymbolFromStyleAsync(StyleProjectItem style, string key)
{
return QueuedTask.Run(() =>
{
if (style == null)
throw new System.ArgumentNullException();
//Search for a specific point symbol in style
SymbolStyleItem item = (SymbolStyleItem)style.LookupItem(StyleItemType.PointSymbol, key);
return item;
});
}
#endregion
// cref: How to search for point symbols in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchSymbols(ArcGIS.Desktop.Mapping.StyleProjectItem,ArcGIS.Desktop.Mapping.StyleItemType,System.String)
#region How to search for point symbols in a style
public Task<IList<SymbolStyleItem>> GetPointSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for point symbols
return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PointSymbol, searchString));
}
#endregion
#region How to search for line symbols in a style
public Task<IList<SymbolStyleItem>> GetLineSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for line symbols
return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.LineSymbol, searchString));
}
#endregion
#region How to search for polygon symbols in a style
public async Task<IList<SymbolStyleItem>> GetPolygonSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for polygon symbols
return await QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PolygonSymbol, searchString));
}
#endregion
// cref: How to search for colors in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchColors(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for colors in a style
public async Task<IList<ColorStyleItem>> GetColorsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for colors
return await QueuedTask.Run(() => style.SearchColors(searchString));
}
#endregion
// cref: How to search for color ramps in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchColorRamps(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for color ramps in a style
public async Task<IList<ColorRampStyleItem>> GetColorRampsFromStyleAsync(StyleProjectItem style, string searchString)
{
//StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...
if (style == null)
throw new System.ArgumentNullException();
//Search for color ramps
//Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..
return await QueuedTask.Run(() => style.SearchColorRamps(searchString));
}
#endregion
// cref: How to search for north arrows in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchNorthArrows(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for north arrows in a style
public Task<IList<NorthArrowStyleItem>> GetNorthArrowsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for north arrows
return QueuedTask.Run(() => style.SearchNorthArrows(searchString));
}
#endregion
// cref: How to search for scale bars in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchScaleBars(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for scale bars in a style
public Task<IList<ScaleBarStyleItem>> GetScaleBarsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for scale bars
return QueuedTask.Run(() => style.SearchScaleBars(searchString));
}
#endregion
// cref: How to search for label placements in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchLabelPlacements(ArcGIS.Desktop.Mapping.StyleProjectItem,ArcGIS.Desktop.Mapping.StyleItemType,System.String)
#region How to search for label placements in a style
public Task<IList<LabelPlacementStyleItem>> GetLabelPlacementsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for standard label placement
return QueuedTask.Run(() => style.SearchLabelPlacements(StyleItemType.StandardLabelPlacement, searchString));
}
#endregion
// cref: How to search for legends in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchLegends(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for legends in a style
public Task<IList<LegendStyleItem>> GetLegendFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchLegends(searchString));
}
#endregion
// cref: How to search for legend items in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchLegendItems(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for legend items in a style
public Task<IList<LegendItemStyleItem>> GetLegendItemsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchLegendItems(searchString));
}
#endregion
// cref: How to search for grids in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchGrids(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for grids in a style
public Task<IList<GridStyleItem>> GetGridsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchGrids(searchString));
}
#endregion
// cref: How to search for map surrounds in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchMapSurrounds(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for map surrounds in a style
public Task<IList<MapSurroundStyleItem>> GetMapSurroundsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchMapSurrounds(searchString));
}
#endregion
// cref: How to search for table frames in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchTableFrames(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for table frames in a style
public Task<IList<TableFrameStyleItem>> GetTableFramesFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchTableFrames(searchString));
}
#endregion
// cref: How to search for table frame fields in a style;ArcGIS.Desktop.Mapping.StyleHelper.SearchTableFrameFields(ArcGIS.Desktop.Mapping.StyleProjectItem,System.String)
#region How to search for table frame fields in a style
public Task<IList<TableFrameFieldStyleItem>> GetTableFrameFieldsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() => style.SearchTableFrameFields(searchString));
}
#endregion
#region ProSnippet Group: Feature Layer Symbology
#endregion
//feature layer symbology
#region How to set symbol for a feature layer symbolized with simple renderer
public Task SetFeatureLayerSymbolAsync(FeatureLayer ftrLayer, CIMSymbol symbolToApply)
{
if (ftrLayer == null || symbolToApply == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() =>
{
//Get simple renderer from the feature layer
CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;
if (currentRenderer == null)
return;
//Set symbol's real world setting to be the same as that of the feature layer
symbolToApply.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);
//Update the symbol of the current simple renderer
currentRenderer.Symbol = symbolToApply.MakeSymbolReference();
//Update the feature layer renderer
ftrLayer.SetRenderer(currentRenderer);
});
}
#endregion
#region How to apply a symbol from style to a feature layer
public Task SetFeatureLayerSymbolFromStyleItemAsync(FeatureLayer ftrLayer, SymbolStyleItem symbolItem)
{
if (ftrLayer == null || symbolItem == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() =>
{
//Get simple renderer from the feature layer
CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;
if (currentRenderer == null)
return;
//Get symbol from the SymbolStyleItem
CIMSymbol symbol = symbolItem.Symbol;
//Set symbol's real world setting to be the same as that of the feature layer
symbol.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);
//Update the symbol of the current simple renderer
currentRenderer.Symbol = symbol.MakeSymbolReference();
//Update the feature layer renderer
ftrLayer.SetRenderer(currentRenderer);
});
}
#endregion
#region How to apply a point symbol from a style to a feature layer
// var map = MapView.Active.Map;
// if (map == null)
// return;
// var pointFeatureLayer =
// map.GetLayersAsFlattenedList()
// .OfType<FeatureLayer>()
// .Where(fl => fl.ShapeType == esriGeometryType.esriGeometryPoint);
// await ApplySymbolToFeatureLayerAsync(pointFeatureLayer.FirstOrDefault(), "Fire Station");
public Task ApplySymbolToFeatureLayerAsync(FeatureLayer featureLayer, string symbolName)
{
return QueuedTask.Run(async () =>
{
//Get the ArcGIS 2D System style from the Project
var arcGIS2DStyle = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ArcGIS 2D");
//Search for the symbolName style items within the ArcGIS 2D style project item.
var items = await QueuedTask.Run(() => arcGIS2DStyle.SearchSymbols(StyleItemType.PointSymbol, symbolName));
//Gets the CIMSymbol
CIMSymbol symbol = items.FirstOrDefault().Symbol;
//Get the renderer of the point feature layer
CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
//Set symbol's real world setting to be the same as that of the feature layer
symbol.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);
//Apply the symbol to the feature layer's current renderer
renderer.Symbol = symbol.MakeSymbolReference();
//Appy the renderer to the feature layer
featureLayer.SetRenderer(renderer);
});
}
#endregion
#region How to apply a color ramp from a style to a feature layer
public async Task ApplyColorRampAsync(FeatureLayer featureLayer, string[] fields)
{
StyleProjectItem style =
Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ColorBrewer Schemes (RGB)");
if (style == null) return;
var colorRampList = await QueuedTask.Run(() => style.SearchColorRamps("Red-Gray (10 Classes)"));
if (colorRampList == null || colorRampList.Count == 0) return;
CIMColorRamp cimColorRamp = null;
CIMRenderer renderer = null;
await QueuedTask.Run(() =>
{
cimColorRamp = colorRampList[0].ColorRamp;
var rendererDef = new UniqueValueRendererDefinition(fields, null, cimColorRamp);
renderer = featureLayer?.CreateRenderer(rendererDef);
featureLayer?.SetRenderer(renderer);
});
}
#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;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
public class EncryptedXml
{
//
// public constant Url identifiers used within the XML Encryption classes
//
public const string XmlEncNamespaceUrl = "http://www.w3.org/2001/04/xmlenc#";
public const string XmlEncElementUrl = "http://www.w3.org/2001/04/xmlenc#Element";
public const string XmlEncElementContentUrl = "http://www.w3.org/2001/04/xmlenc#Content";
public const string XmlEncEncryptedKeyUrl = "http://www.w3.org/2001/04/xmlenc#EncryptedKey";
//
// Symmetric Block Encryption
//
public const string XmlEncDESUrl = "http://www.w3.org/2001/04/xmlenc#des-cbc";
public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public const string XmlEncAES128Url = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
public const string XmlEncAES256Url = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
public const string XmlEncAES192Url = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
//
// Key Transport
//
public const string XmlEncRSA15Url = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
public const string XmlEncRSAOAEPUrl = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
//
// Symmetric Key Wrap
//
public const string XmlEncTripleDESKeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
public const string XmlEncAES128KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
public const string XmlEncAES256KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
public const string XmlEncAES192KeyWrapUrl = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
//
// Message Digest
//
public const string XmlEncSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256";
public const string XmlEncSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512";
//
// private members
//
private XmlDocument _document;
private Evidence _evidence;
private XmlResolver _xmlResolver;
// hash table defining the key name mapping
private const int _capacity = 4; // 4 is a reasonable capacity for
// the key name mapping hash table
private Hashtable _keyNameMapping;
private PaddingMode _padding;
private CipherMode _mode;
private Encoding _encoding;
private string _recipient;
private int _xmlDsigSearchDepthCounter = 0;
private int _xmlDsigSearchDepth;
//
// public constructors
//
public EncryptedXml() : this(new XmlDocument()) { }
public EncryptedXml(XmlDocument document) : this(document, null) { }
public EncryptedXml(XmlDocument document, Evidence evidence)
{
_document = document;
_evidence = evidence;
_xmlResolver = null;
// set the default padding to ISO-10126
_padding = PaddingMode.ISO10126;
// set the default cipher mode to CBC
_mode = CipherMode.CBC;
// By default the encoding is going to be UTF8
_encoding = Encoding.UTF8;
_keyNameMapping = new Hashtable(_capacity);
_xmlDsigSearchDepth = Utils.XmlDsigSearchDepth;
}
/// <summary>
/// This method validates the _xmlDsigSearchDepthCounter counter
/// if the counter is over the limit defined by admin or developer.
/// </summary>
/// <returns>returns true if the limit has reached otherwise false</returns>
private bool IsOverXmlDsigRecursionLimit()
{
if (_xmlDsigSearchDepthCounter > XmlDSigSearchDepth)
{
return true;
}
return false;
}
/// <summary>
/// Gets / Sets the max limit for recursive search of encryption key in signed XML
/// </summary>
public int XmlDSigSearchDepth
{
get
{
return _xmlDsigSearchDepth;
}
set
{
_xmlDsigSearchDepth = value;
}
}
// The evidence of the document being loaded: will be used to resolve external URIs
public Evidence DocumentEvidence
{
get { return _evidence; }
set { _evidence = value; }
}
// The resolver to use for external entities
public XmlResolver Resolver
{
get { return _xmlResolver; }
set { _xmlResolver = value; }
}
// The padding to be used. XML Encryption uses ISO 10126
// but it's nice to provide a way to extend this to include other forms of paddings
public PaddingMode Padding
{
get { return _padding; }
set { _padding = value; }
}
// The cipher mode to be used. XML Encryption uses CBC padding
// but it's nice to provide a way to extend this to include other cipher modes
public CipherMode Mode
{
get { return _mode; }
set { _mode = value; }
}
// The encoding of the XML document
public Encoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
// This is used to specify the EncryptedKey elements that should be considered
// when an EncyptedData references an EncryptedKey using a CarriedKeyName and Recipient
public string Recipient
{
get
{
// an unspecified value for an XmlAttribute is string.Empty
if (_recipient == null)
_recipient = string.Empty;
return _recipient;
}
set { _recipient = value; }
}
//
// private methods
//
private byte[] GetCipherValue(CipherData cipherData)
{
if (cipherData == null)
throw new ArgumentNullException(nameof(cipherData));
WebResponse response = null;
Stream inputStream = null;
if (cipherData.CipherValue != null)
{
return cipherData.CipherValue;
}
else if (cipherData.CipherReference != null)
{
if (cipherData.CipherReference.CipherValue != null)
return cipherData.CipherReference.CipherValue;
Stream decInputStream = null;
// See if the CipherReference is a local URI
if (cipherData.CipherReference.Uri.Length == 0)
{
// self referenced Uri
string baseUri = (_document == null ? null : _document.BaseURI);
TransformChain tc = cipherData.CipherReference.TransformChain;
decInputStream = tc.TransformToOctetStream(_document, _xmlResolver, baseUri);
}
else if (cipherData.CipherReference.Uri[0] == '#')
{
string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri);
// Serialize
inputStream = new MemoryStream(_encoding.GetBytes(GetIdElement(_document, idref).OuterXml));
string baseUri = (_document == null ? null : _document.BaseURI);
TransformChain tc = cipherData.CipherReference.TransformChain;
decInputStream = tc.TransformToOctetStream(inputStream, _xmlResolver, baseUri);
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri);
}
// read the output stream into a memory stream
byte[] cipherValue = null;
using (MemoryStream ms = new MemoryStream())
{
Utils.Pump(decInputStream, ms);
cipherValue = ms.ToArray();
// Close the stream and return
if (response != null)
response.Close();
if (inputStream != null)
inputStream.Close();
decInputStream.Close();
}
// cache the cipher value for Perf reasons in case we call this routine twice
cipherData.CipherReference.CipherValue = cipherValue;
return cipherValue;
}
// Throw a CryptographicException if we were unable to retrieve the cipher data.
throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData);
}
//
// public virtual methods
//
// This describes how the application wants to associate id references to elements
public virtual XmlElement GetIdElement(XmlDocument document, string idValue)
{
return SignedXml.DefaultGetIdElement(document, idValue);
}
// default behaviour is to look for the IV in the CipherValue
public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
int initBytesSize = 0;
// If the Uri is not provided by the application, try to get it from the EncryptionMethod
if (symmetricAlgorithmUri == null)
{
if (encryptedData.EncryptionMethod == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
}
switch (symmetricAlgorithmUri)
{
case EncryptedXml.XmlEncDESUrl:
case EncryptedXml.XmlEncTripleDESUrl:
initBytesSize = 8;
break;
case EncryptedXml.XmlEncAES128Url:
case EncryptedXml.XmlEncAES192Url:
case EncryptedXml.XmlEncAES256Url:
initBytesSize = 16;
break;
default:
// The Uri is not supported.
throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported);
}
byte[] IV = new byte[initBytesSize];
byte[] cipherValue = GetCipherValue(encryptedData.CipherData);
Buffer.BlockCopy(cipherValue, 0, IV, 0, IV.Length);
return IV;
}
// default behaviour is to look for keys defined by an EncryptedKey clause
// either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping
public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
if (encryptedData.KeyInfo == null)
return null;
IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
KeyInfoRetrievalMethod kiRetrievalMethod;
KeyInfoName kiName;
KeyInfoEncryptedKey kiEncKey;
EncryptedKey ek = null;
while (keyInfoEnum.MoveNext())
{
kiName = keyInfoEnum.Current as KeyInfoName;
if (kiName != null)
{
// Get the decryption key from the key mapping
string keyName = kiName.Value;
if ((SymmetricAlgorithm)_keyNameMapping[keyName] != null)
return (SymmetricAlgorithm)_keyNameMapping[keyName];
// try to get it from a CarriedKeyName
XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm);
if (encryptedKeyList != null)
{
foreach (XmlNode encryptedKeyNode in encryptedKeyList)
{
XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement;
EncryptedKey ek1 = new EncryptedKey();
ek1.LoadXml(encryptedKeyElement);
if (ek1.CarriedKeyName == keyName && ek1.Recipient == Recipient)
{
ek = ek1;
break;
}
}
}
break;
}
kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
if (kiRetrievalMethod != null)
{
string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
ek = new EncryptedKey();
ek.LoadXml(GetIdElement(_document, idref));
break;
}
kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
if (kiEncKey != null)
{
ek = kiEncKey.EncryptedKey;
break;
}
}
// if we have an EncryptedKey, decrypt to get the symmetric key
if (ek != null)
{
// now process the EncryptedKey, loop recursively
// If the Uri is not provided by the application, try to get it from the EncryptionMethod
if (symmetricAlgorithmUri == null)
{
if (encryptedData.EncryptionMethod == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
}
byte[] key = DecryptEncryptedKey(ek);
if (key == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
SymmetricAlgorithm symAlg = (SymmetricAlgorithm)CryptoHelpers.CreateFromName(symmetricAlgorithmUri);
symAlg.Key = key;
return symAlg;
}
return null;
}
// Try to decrypt the EncryptedKey given the key mapping
public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
{
if (encryptedKey == null)
throw new ArgumentNullException(nameof(encryptedKey));
if (encryptedKey.KeyInfo == null)
return null;
IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator();
KeyInfoName kiName;
KeyInfoX509Data kiX509Data;
KeyInfoRetrievalMethod kiRetrievalMethod;
KeyInfoEncryptedKey kiEncKey;
EncryptedKey ek = null;
bool fOAEP = false;
while (keyInfoEnum.MoveNext())
{
kiName = keyInfoEnum.Current as KeyInfoName;
if (kiName != null)
{
// Get the decryption key from the key mapping
string keyName = kiName.Value;
object kek = _keyNameMapping[keyName];
if (kek != null)
{
// kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
if (kek is SymmetricAlgorithm)
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek);
// kek is an RSA key: get fOAEP from the algorithm, default to false
fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP);
}
break;
}
kiX509Data = keyInfoEnum.Current as KeyInfoX509Data;
if (kiX509Data != null)
{
X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption);
foreach (X509Certificate2 certificate in collection)
{
using (RSA privateKey = certificate.GetRSAPrivateKey())
{
if (privateKey != null)
{
fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP);
}
}
}
break;
}
kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
if (kiRetrievalMethod != null)
{
string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
ek = new EncryptedKey();
ek.LoadXml(GetIdElement(_document, idref));
try
{
//Following checks if XML dsig processing is in loop and within the limit defined by machine
// admin or developer. Once the recursion depth crosses the defined limit it will throw exception.
_xmlDsigSearchDepthCounter++;
if (IsOverXmlDsigRecursionLimit())
{
//Throw exception once recursion limit is hit.
throw new CryptoSignedXmlRecursionException();
}
else
{
return DecryptEncryptedKey(ek);
}
}
finally
{
_xmlDsigSearchDepthCounter--;
}
}
kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
if (kiEncKey != null)
{
ek = kiEncKey.EncryptedKey;
// recursively process EncryptedKey elements
byte[] encryptionKey = DecryptEncryptedKey(ek);
if (encryptionKey != null)
{
// this is a symmetric algorithm for sure
SymmetricAlgorithm symAlg = (SymmetricAlgorithm)CryptoHelpers.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm);
symAlg.Key = encryptionKey;
return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg);
}
}
}
return null;
}
//
// public methods
//
// defines a key name mapping. Default behaviour is to require the key object
// to be an RSA key or a SymmetricAlgorithm
public void AddKeyNameMapping(string keyName, object keyObject)
{
if (keyName == null)
throw new ArgumentNullException(nameof(keyName));
if (keyObject == null)
throw new ArgumentNullException(nameof(keyObject));
if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA))
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
_keyNameMapping.Add(keyName, keyObject);
}
public void ClearKeyNameMappings()
{
_keyNameMapping.Clear();
}
// Encrypts the given element with the certificate specified. The certificate is added as
// an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly.
public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
using (RSA rsaPublicKey = certificate.GetRSAPublicKey())
{
if (rsaPublicKey == null)
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
// Create the EncryptedData object, using an AES-256 session key by default.
EncryptedData ed = new EncryptedData();
ed.Type = EncryptedXml.XmlEncElementUrl;
ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
// Include the certificate in the EncryptedKey KeyInfo.
EncryptedKey ek = new EncryptedKey();
ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
ek.KeyInfo.AddClause(new KeyInfoX509Data(certificate));
// Create a random AES session key and encrypt it with the public key associated with the certificate.
RijndaelManaged rijn = new RijndaelManaged();
ek.CipherData.CipherValue = EncryptedXml.EncryptKey(rijn.Key, rsaPublicKey, false);
// Encrypt the input element with the random session key that we've created above.
KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);
ed.KeyInfo.AddClause(kek);
ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false);
return ed;
}
}
// Encrypts the given element with the key name specified. A corresponding key name mapping
// has to be defined before calling this method. The key name is added as
// a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly.
public EncryptedData Encrypt(XmlElement inputElement, string keyName)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (keyName == null)
throw new ArgumentNullException(nameof(keyName));
object encryptionKey = null;
if (_keyNameMapping != null)
encryptionKey = _keyNameMapping[keyName];
if (encryptionKey == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey);
// kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm;
RSA rsa = encryptionKey as RSA;
// Create the EncryptedData object, using an AES-256 session key by default.
EncryptedData ed = new EncryptedData();
ed.Type = EncryptedXml.XmlEncElementUrl;
ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
// Include the key name in the EncryptedKey KeyInfo.
string encryptionMethod = null;
if (symKey == null)
{
encryptionMethod = EncryptedXml.XmlEncRSA15Url;
}
else if (symKey is TripleDES)
{
// CMS Triple DES Key Wrap
encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl;
}
else if (symKey is Rijndael || symKey is Aes)
{
// FIPS AES Key Wrap
switch (symKey.KeySize)
{
case 128:
encryptionMethod = EncryptedXml.XmlEncAES128KeyWrapUrl;
break;
case 192:
encryptionMethod = EncryptedXml.XmlEncAES192KeyWrapUrl;
break;
case 256:
encryptionMethod = EncryptedXml.XmlEncAES256KeyWrapUrl;
break;
}
}
else
{
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
EncryptedKey ek = new EncryptedKey();
ek.EncryptionMethod = new EncryptionMethod(encryptionMethod);
ek.KeyInfo.AddClause(new KeyInfoName(keyName));
// Create a random AES session key and encrypt it with the public key associated with the certificate.
RijndaelManaged rijn = new RijndaelManaged();
ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.Key, symKey));
// Encrypt the input element with the random session key that we've created above.
KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);
ed.KeyInfo.AddClause(kek);
ed.CipherData.CipherValue = EncryptData(inputElement, rijn, false);
return ed;
}
// decrypts the document using the defined key mapping in GetDecryptionKey
// The behaviour of this method can be extended because GetDecryptionKey is virtual
// the document is decrypted in place
public void DecryptDocument()
{
// Look for all EncryptedData elements and decrypt them
XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
XmlNodeList encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm);
if (encryptedDataList != null)
{
foreach (XmlNode encryptedDataNode in encryptedDataList)
{
XmlElement encryptedDataElement = encryptedDataNode as XmlElement;
EncryptedData ed = new EncryptedData();
ed.LoadXml(encryptedDataElement);
SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null);
if (symAlg == null)
throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
byte[] decrypted = DecryptData(ed, symAlg);
ReplaceData(encryptedDataElement, decrypted);
}
}
}
// encrypts the supplied arbitrary data
public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm)
{
if (plaintext == null)
throw new ArgumentNullException(nameof(plaintext));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
// save the original symmetric algorithm
CipherMode origMode = symmetricAlgorithm.Mode;
PaddingMode origPadding = symmetricAlgorithm.Padding;
byte[] cipher = null;
try
{
symmetricAlgorithm.Mode = _mode;
symmetricAlgorithm.Padding = _padding;
ICryptoTransform enc = symmetricAlgorithm.CreateEncryptor();
cipher = enc.TransformFinalBlock(plaintext, 0, plaintext.Length);
}
finally
{
// now restore the original symmetric algorithm
symmetricAlgorithm.Mode = origMode;
symmetricAlgorithm.Padding = origPadding;
}
byte[] output = null;
if (_mode == CipherMode.ECB)
{
output = cipher;
}
else
{
byte[] IV = symmetricAlgorithm.IV;
output = new byte[cipher.Length + IV.Length];
Buffer.BlockCopy(IV, 0, output, 0, IV.Length);
Buffer.BlockCopy(cipher, 0, output, IV.Length, cipher.Length);
}
return output;
}
// encrypts the supplied input element
public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml));
return EncryptData(plainText, symmetricAlgorithm);
}
// decrypts the supplied EncryptedData
public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm)
{
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
// get the cipher value and decrypt
byte[] cipherValue = GetCipherValue(encryptedData.CipherData);
// save the original symmetric algorithm
CipherMode origMode = symmetricAlgorithm.Mode;
PaddingMode origPadding = symmetricAlgorithm.Padding;
byte[] origIV = symmetricAlgorithm.IV;
// read the IV from cipherValue
byte[] decryptionIV = null;
if (_mode != CipherMode.ECB)
decryptionIV = GetDecryptionIV(encryptedData, null);
byte[] output = null;
try
{
int lengthIV = 0;
if (decryptionIV != null)
{
symmetricAlgorithm.IV = decryptionIV;
lengthIV = decryptionIV.Length;
}
symmetricAlgorithm.Mode = _mode;
symmetricAlgorithm.Padding = _padding;
ICryptoTransform dec = symmetricAlgorithm.CreateDecryptor();
output = dec.TransformFinalBlock(cipherValue, lengthIV, cipherValue.Length - lengthIV);
}
finally
{
// now restore the original symmetric algorithm
symmetricAlgorithm.Mode = origMode;
symmetricAlgorithm.Padding = origPadding;
symmetricAlgorithm.IV = origIV;
}
return output;
}
// This method replaces an EncryptedData element with the decrypted sequence of bytes
public void ReplaceData(XmlElement inputElement, byte[] decryptedData)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (decryptedData == null)
throw new ArgumentNullException(nameof(decryptedData));
XmlNode parent = inputElement.ParentNode;
if (parent.NodeType == XmlNodeType.Document)
{
// We're replacing the root element, but we can't just wholesale replace the owner
// document's InnerXml, since we need to preserve any other top-level XML elements (such as
// comments or the XML entity declaration. Instead, create a new document with the
// decrypted XML, import it into the existing document, and replace just the root element.
XmlDocument importDocument = new XmlDocument();
importDocument.PreserveWhitespace = true;
string decryptedString = _encoding.GetString(decryptedData);
using (StringReader sr = new StringReader(decryptedString))
{
using (XmlReader xr = XmlReader.Create(sr, Utils.GetSecureXmlReaderSettings(_xmlResolver)))
{
importDocument.Load(xr);
}
}
XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement, true);
parent.RemoveChild(inputElement);
parent.AppendChild(importedNode);
}
else
{
XmlNode dummy = parent.OwnerDocument.CreateElement(parent.Prefix, parent.LocalName, parent.NamespaceURI);
try
{
parent.AppendChild(dummy);
// Replace the children of the dummy node with the sequence of bytes passed in.
// The string will be parsed into DOM objects in the context of the parent of the EncryptedData element.
dummy.InnerXml = _encoding.GetString(decryptedData);
// Move the children of the dummy node up to the parent.
XmlNode child = dummy.FirstChild;
XmlNode sibling = inputElement.NextSibling;
XmlNode nextChild = null;
while (child != null)
{
nextChild = child.NextSibling;
parent.InsertBefore(child, sibling);
child = nextChild;
}
}
finally
{
// Remove the dummy element.
parent.RemoveChild(dummy);
}
// Remove the EncryptedData element
parent.RemoveChild(inputElement);
}
}
//
// public static methods
//
// replaces the inputElement with the provided EncryptedData
public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content)
{
if (inputElement == null)
throw new ArgumentNullException(nameof(inputElement));
if (encryptedData == null)
throw new ArgumentNullException(nameof(encryptedData));
// First, get the XML representation of the EncryptedData object
XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument);
switch (content)
{
case true:
// remove all children of the input element
Utils.RemoveAllChildren(inputElement);
// then append the encrypted data as a child of the input element
inputElement.AppendChild(elemED);
break;
case false:
XmlNode parentNode = inputElement.ParentNode;
// remove the input element from the containing document
parentNode.ReplaceChild(elemED, inputElement);
break;
}
}
// wraps the supplied input key data using the provided symmetric algorithm
public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (symmetricAlgorithm is TripleDES)
{
// CMS Triple DES Key Wrap
return SymmetricKeyWrap.TripleDESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData);
}
else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes)
{
// FIPS AES Key Wrap
return SymmetricKeyWrap.AESKeyWrapEncrypt(symmetricAlgorithm.Key, keyData);
}
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
// encrypts the supplied input key data using an RSA key and specifies whether we want to use OAEP
// padding or PKCS#1 v1.5 padding as described in the PKCS specification
public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
if (useOAEP)
{
RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa);
return rsaFormatter.CreateKeyExchange(keyData);
}
else
{
RSAPKCS1KeyExchangeFormatter rsaFormatter = new RSAPKCS1KeyExchangeFormatter(rsa);
return rsaFormatter.CreateKeyExchange(keyData);
}
}
// decrypts the supplied wrapped key using the provided symmetric algorithm
public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (symmetricAlgorithm == null)
throw new ArgumentNullException(nameof(symmetricAlgorithm));
if (symmetricAlgorithm is TripleDES)
{
// CMS Triple DES Key Wrap
return SymmetricKeyWrap.TripleDESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData);
}
else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes)
{
// FIPS AES Key Wrap
return SymmetricKeyWrap.AESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData);
}
// throw an exception if the transform is not in the previous categories
throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
}
// decrypts the supplied data using an RSA key and specifies whether we want to use OAEP
// padding or PKCS#1 v1.5 padding as described in the PKCS specification
public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP)
{
if (keyData == null)
throw new ArgumentNullException(nameof(keyData));
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
if (useOAEP)
{
RSAOAEPKeyExchangeDeformatter rsaDeformatter = new RSAOAEPKeyExchangeDeformatter(rsa);
return rsaDeformatter.DecryptKeyExchange(keyData);
}
else
{
RSAPKCS1KeyExchangeDeformatter rsaDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsa);
return rsaDeformatter.DecryptKeyExchange(keyData);
}
}
}
}
| |
#region License
//
// PrimitiveArray.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>PrimitiveArray</c> object is used to convert a list of
/// elements to an array of object entries. This in effect performs a
/// serialization and deserialization of primitive elements for the
/// array object. On serialization each primitive type must be checked
/// against the array component type so that it is serialized in a form
/// that can be deserialized dynamically.
/// </code>
/// <array>
/// <entry>example text one</entry>
/// <entry>example text two</entry>
/// <entry>example text three</entry>
/// </array>
/// </code>
/// For the above XML element list the element <c>entry</c> is
/// contained within the array. Each entry element is deserialized as
/// a from a parent XML element, which is specified in the annotation.
/// For serialization the reverse is done, each element taken from the
/// array is written into an element created from the parent element.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Core.Primitive
/// </seealso>
/// <seealso>
/// SimpleFramework.Xml.ElementArray
/// </seealso>
class PrimitiveArray : Converter {
/// <summary>
/// This factory is used to create an array for the contact.
/// </summary>
private readonly ArrayFactory factory;
/// <summary>
/// This performs the serialization of the primitive element.
/// </summary>
private readonly Primitive root;
/// <summary>
/// This is the name that each array element is wrapped with.
/// </summary>
private readonly String parent;
/// <summary>
/// This is the type of object that will be held in the list.
/// </summary>
private readonly Type entry;
/// <summary>
/// Constructor for the <c>PrimitiveArray</c> object. This is
/// given the array type for the contact that is to be converted. An
/// array of the specified type is used to hold the deserialized
/// elements and will be the same length as the number of elements.
/// </summary>
/// <param name="context">
/// this is the context object used for serialization
/// </param>
/// <param name="type">
/// this is the actual field type from the schema
/// </param>
/// <param name="entry">
/// the entry type to be stored within the array
/// </param>
/// <param name="parent">
/// this is the name to wrap the array element with
/// </param>
public PrimitiveArray(Context context, Type type, Type entry, String parent) {
this.factory = new ArrayFactory(context, type);
this.root = new Primitive(context, entry);
this.parent = parent;
this.entry = entry;
}
/// <summary>
/// This <c>read</c> method will read the XML element list from
/// the provided node and deserialize its children as entry types.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node) {
Instance type = factory.GetInstance(node);
Object list = type.Instance;
if(!type.isReference()) {
return Read(node, list);
}
return list;
}
/// <summary>
/// This <c>read</c> method will read the XML element list from
/// the provided node and deserialize its children as entry types.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <param name="list">
/// this is the array to read the array values in to
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node, Object list) {
int length = Array.getLength(list);
for(int pos = 0; true; pos++) {
Position line = node.getPosition();
InputNode next = node.getNext();
if(next == null) {
return list;
}
if(pos >= length){
throw new ElementException("Array length missing or incorrect at %s", line);
}
Array.set(list, pos, root.Read(next));
}
}
/// <summary>
/// This <c>validate</c> method will validate the XML element list
/// from the provided node and validate its children as entry types.
/// This will validate each entry type as a primitive value. In order
/// to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be validated
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node) {
Instance value = factory.GetInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class expect = value.Type;
return Validate(node, expect);
}
return true;
}
/// <summary>
/// This <c>validate</c> method wll validate the XML element list
/// from the provided node and validate its children as entry types.
/// This will validate each entry type as a primitive value. In order
/// to do this the parent string provided forms the element.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be validated
/// </param>
/// <param name="type">
/// this is the array type used to create the array
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node, Class type) {
for(int i = 0; true; i++) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
root.Validate(next);
}
}
/// <summary>
/// This <c>write</c> method will write the specified object
/// to the given XML element as as array entries. Each entry within
/// the given array must be assignable to the array component type.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="source">
/// this is the source object array to be serialized
/// </param>
/// <param name="node">
/// this is the XML element container to be populated
/// </param>
public void Write(OutputNode node, Object source) {
int size = Array.getLength(source);
for(int i = 0; i < size; i++) {
OutputNode child = node.getChild(parent);
if(child == null) {
break;
}
Write(child, source, i);
}
}
/// <summary>
/// This <c>write</c> method will write the specified object
/// to the given XML element as as array entries. Each entry within
/// the given array must be assignable to the array component type.
/// This will deserialize each entry type as a primitive value. In
/// order to do this the parent string provided forms the element.
/// </summary>
/// <param name="source">
/// this is the source object array to be serialized
/// </param>
/// <param name="node">
/// this is the XML element container to be populated
/// </param>
/// <param name="index">
/// this is the position in the array to set the item
/// </param>
public void Write(OutputNode node, Object source, int index) {
Object item = Array.get(source, index);
if(item != null) {
if(!IsOverridden(node, item)) {
root.Write(node, item);
}
}
}
/// <summary>
/// This is used to determine whether the specified value has been
/// overridden by the strategy. If the item has been overridden
/// then no more serialization is require for that value, this is
/// effectively telling the serialization process to stop writing.
/// </summary>
/// <param name="node">
/// the node that a potential override is written to
/// </param>
/// <param name="value">
/// this is the object instance to be serialized
/// </param>
/// <returns>
/// returns true if the strategy overrides the object
/// </returns>
public bool IsOverridden(OutputNode node, Object value) {
return factory.setOverride(entry, value, node);
}
}
}
| |
// 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 Telerik.JustMock.Core.Castle.DynamicProxy.Generators
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization;
internal class ClassProxyGenerator : BaseProxyGenerator
{
public ClassProxyGenerator(ModuleScope scope, Type targetType) : base(scope, targetType)
{
CheckNotGenericTypeDefinition(targetType, "targetType");
EnsureDoesNotImplementIProxyTargetAccessor(targetType, "targetType");
}
public Type GenerateCode(Type[] interfaces, ProxyGenerationOptions options)
{
// make sure ProxyGenerationOptions is initialized
options.Initialize();
interfaces = TypeUtil.GetAllInterfaces(interfaces);
CheckNotGenericTypeDefinitions(interfaces, "interfaces");
ProxyGenerationOptions = options;
var cacheKey = new CacheKey(targetType, interfaces, options);
return ObtainProxyType(cacheKey, (n, s) => GenerateType(n, interfaces, s));
}
protected virtual Type GenerateType(string name, Type[] interfaces, INamingScope namingScope)
{
IEnumerable<ITypeContributor> contributors;
var implementedInterfaces = GetTypeImplementerMapping(interfaces, out contributors, namingScope);
var model = new MetaType();
// Collect methods
foreach (var contributor in contributors)
{
contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model);
}
ProxyGenerationOptions.Hook.MethodsInspected();
var emitter = BuildClassEmitter(name, targetType, implementedInterfaces);
CreateFields(emitter);
CreateTypeAttributes(emitter);
// Constructor
var cctor = GenerateStaticConstructor(emitter);
var constructorArguments = new List<FieldReference>();
foreach (var contributor in contributors)
{
contributor.Generate(emitter, ProxyGenerationOptions);
// TODO: redo it
var mixinContributor = contributor as MixinContributor;
if (mixinContributor != null)
{
constructorArguments.AddRange(mixinContributor.Fields);
}
}
// constructor arguments
var interceptorsField = emitter.GetField("__interceptors");
constructorArguments.Add(interceptorsField);
var selector = emitter.GetField("__selector");
if (selector != null)
{
constructorArguments.Add(selector);
}
GenerateConstructors(emitter, targetType, constructorArguments.ToArray());
GenerateParameterlessConstructor(emitter, targetType, interceptorsField);
// Complete type initializer code body
CompleteInitCacheMethod(cctor.CodeBuilder);
// Crosses fingers and build type
Type proxyType = emitter.BuildType();
InitializeStaticFields(proxyType);
return proxyType;
}
protected virtual IEnumerable<Type> GetTypeImplementerMapping(Type[] interfaces,
out IEnumerable<ITypeContributor> contributors,
INamingScope namingScope)
{
var methodsToSkip = new List<MethodInfo>();
var proxyInstance = new ClassProxyInstanceContributor(targetType, methodsToSkip, interfaces, ProxyTypeConstants.Class);
// TODO: the trick with methodsToSkip is not very nice...
var proxyTarget = new ClassProxyTargetContributor(targetType, methodsToSkip, namingScope) { Logger = Logger };
IDictionary<Type, ITypeContributor> typeImplementerMapping = new Dictionary<Type, ITypeContributor>();
// Order of interface precedence:
// 1. first target
// target is not an interface so we do nothing
var targetInterfaces = targetType.GetAllInterfaces();
var additionalInterfaces = TypeUtil.GetAllInterfaces(interfaces);
// 2. then mixins
var mixins = new MixinContributor(namingScope, false) { Logger = Logger };
if (ProxyGenerationOptions.HasMixins)
{
foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces)
{
if (targetInterfaces.Contains(mixinInterface))
{
// OK, so the target implements this interface. We now do one of two things:
if (additionalInterfaces.Contains(mixinInterface) && typeImplementerMapping.ContainsKey(mixinInterface) == false)
{
AddMappingNoCheck(mixinInterface, proxyTarget, typeImplementerMapping);
proxyTarget.AddInterfaceToProxy(mixinInterface);
}
// we do not intercept the interface
mixins.AddEmptyInterface(mixinInterface);
}
else
{
if (!typeImplementerMapping.ContainsKey(mixinInterface))
{
mixins.AddInterfaceToProxy(mixinInterface);
AddMappingNoCheck(mixinInterface, mixins, typeImplementerMapping);
}
}
}
}
var additionalInterfacesContributor = new InterfaceProxyWithoutTargetContributor(namingScope,
(c, m) => NullExpression.Instance)
{ Logger = Logger };
// 3. then additional interfaces
foreach (var @interface in additionalInterfaces)
{
if (targetInterfaces.Contains(@interface))
{
if (typeImplementerMapping.ContainsKey(@interface))
{
continue;
}
// we intercept the interface, and forward calls to the target type
AddMappingNoCheck(@interface, proxyTarget, typeImplementerMapping);
proxyTarget.AddInterfaceToProxy(@interface);
}
else if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface) == false)
{
additionalInterfacesContributor.AddInterfaceToProxy(@interface);
AddMapping(@interface, additionalInterfacesContributor, typeImplementerMapping);
}
}
// 4. plus special interfaces
#if FEATURE_SERIALIZATION
if (targetType.IsSerializable)
{
AddMappingForISerializable(typeImplementerMapping, proxyInstance);
}
#endif
try
{
AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyInstance, typeImplementerMapping);
}
catch (ArgumentException)
{
HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfaces);
}
contributors = new List<ITypeContributor>
{
proxyTarget,
mixins,
additionalInterfacesContributor,
proxyInstance
};
return typeImplementerMapping.Keys;
}
private void EnsureDoesNotImplementIProxyTargetAccessor(Type type, string name)
{
if (!typeof(IProxyTargetAccessor).IsAssignableFrom(type))
{
return;
}
var message =
string.Format(
"Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?",
typeof(IProxyTargetAccessor));
throw new ArgumentException(message, name);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Runtime.Serialization;
using System.Xml;
using System.Collections;
using NUnit.Framework;
using CWServiceBus.Reflection;
using CWServiceBus.Serializers.XML;
namespace CWServiceBus.Serializers.XML.Test
{
[TestFixture]
public class SerializerTests
{
private int number = 1;
private int numberOfIterations = 100;
[Test]
public void TestMultipleInterfacesDupolicatedPropery()
{
IMessageMapper mapper = new MessageMapper();
var serializer = SerializerFactory.Create<IThird>();
var msgBeforeSerialization = mapper.CreateInstance<IThird>(x => x.FirstName = "Danny");
var count = 0;
using (var stream = new MemoryStream())
{
serializer.Serialize(new[] {msgBeforeSerialization}, stream);
stream.Position = 0;
var reader = XmlReader.Create(stream);
while (reader.Read())
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "FirstName"))
count++;
}
Assert.AreEqual(count, 1);
}
[Test]
public void Generic_properties_should_be_supported()
{
var result = ExecuteSerializer.ForMessage<MessageWithGenericProperty>(m =>
{
m.GenericProperty =
new GenericProperty<string>("test") { WhatEver = "a property" };
});
Assert.AreEqual("a property", result.GenericProperty.WhatEver);
}
[Test]
public void Culture()
{
var serializer = SerializerFactory.Create<MessageWithDouble>();
double val = 65.36;
var msg = new MessageWithDouble { Double = val };
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
var stream = new MemoryStream();
serializer.Serialize(new[] { msg }, stream);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
stream.Position = 0;
var msgArray = serializer.Deserialize(stream);
var m = msgArray[0] as MessageWithDouble;
Assert.AreEqual(val, m.Double);
stream.Dispose();
}
[Test]
public void Comparison()
{
TestInterfaces();
TestDataContractSerializer();
}
[Test]
public void TestInterfaces()
{
IMessageMapper mapper = new MessageMapper();
var serializer = SerializerFactory.Create<IM2>();
var o = mapper.CreateInstance<IM2>();
o.Id = Guid.NewGuid();
o.Age = 10;
o.Address = Guid.NewGuid().ToString();
o.Int = 7;
o.Name = "udi";
o.Uri = new Uri("http://www.UdiDahan.com/");
o.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
o.Some = SomeEnum.B;
o.Start = DateTime.Now;
o.Duration = TimeSpan.Parse("-01:15:27.123");
o.Offset = DateTimeOffset.Now;
o.Lookup = new MyDic();
o.Lookup["1"] = "1";
o.Foos = new Dictionary<string, List<Foo>>();
o.Foos["foo1"] = new List<Foo>(new[] { new Foo { Name = "1", Title = "1" }, new Foo { Name = "2", Title = "2" } });
o.Data = new byte[] { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
o.SomeStrings = new List<string> { "a", "b", "c" };
o.ArrayFoos = new Foo[] { new Foo { Name = "FooArray1", Title = "Mr." }, new Foo { Name = "FooAray2", Title = "Mrs" } };
o.Bars = new Bar[] { new Bar { Name = "Bar1", Length = 1 }, new Bar { Name = "BAr2", Length = 5 } };
o.NaturalNumbers = new HashSet<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
o.Developers = new HashSet<string>(new string[] { "Udi Dahan", "Andreas Ohlund", "Matt Burton", "Jonathan Oliver et al" });
o.Parent = mapper.CreateInstance<IM1>();
o.Parent.Name = "udi";
o.Parent.Age = 10;
o.Parent.Address = Guid.NewGuid().ToString();
o.Parent.Int = 7;
o.Parent.Name = "-1";
o.Parent.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
o.Names = new List<IM1>();
for (int i = 0; i < number; i++)
{
var m1 = mapper.CreateInstance<IM1>();
o.Names.Add(m1);
m1.Age = 10;
m1.Address = Guid.NewGuid().ToString();
m1.Int = 7;
m1.Name = i.ToString();
m1.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
}
o.MoreNames = o.Names.ToArray();
IMessage[] messages = new IMessage[] { o };
Time(messages, serializer);
}
[Test]
public void TestDataContractSerializer()
{
M2 o = CreateM2();
IMessage[] messages = new IMessage[] { o };
DataContractSerializer dcs = new DataContractSerializer(typeof(ArrayList), new Type[] { typeof(M2), typeof(SomeEnum), typeof(M1), typeof(Risk), typeof(List<M1>) });
Stopwatch sw = new Stopwatch();
sw.Start();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = false;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreProcessingInstructions = true;
xrs.ValidationType = ValidationType.None;
xrs.IgnoreWhitespace = true;
xrs.CheckCharacters = false;
xrs.ConformanceLevel = ConformanceLevel.Auto;
for (int i = 0; i < numberOfIterations; i++)
using (MemoryStream stream = new MemoryStream())
DataContractSerialize(xws, dcs, messages, stream);
sw.Stop();
Debug.WriteLine("serialization " + sw.Elapsed);
sw.Reset();
File.Delete("a.xml");
using (FileStream fs = File.Open("a.xml", FileMode.OpenOrCreate))
DataContractSerialize(xws, dcs, messages, fs);
MemoryStream s = new MemoryStream();
DataContractSerialize(xws, dcs, messages, s);
byte[] buffer = s.GetBuffer();
s.Dispose();
sw.Start();
for (int i = 0; i < numberOfIterations; i++)
using (XmlReader reader = XmlReader.Create(new MemoryStream(buffer), xrs))
dcs.ReadObject(reader);
sw.Stop();
Debug.WriteLine("deserializing: " + sw.Elapsed);
}
private void DataContractSerialize(XmlWriterSettings xws, DataContractSerializer dcs, IMessage[] messages, Stream str)
{
ArrayList o = new ArrayList(messages);
using (XmlWriter xwr = XmlWriter.Create(str, xws))
{
dcs.WriteStartObject(xwr, o);
dcs.WriteObjectContent(xwr, o);
dcs.WriteEndObject(xwr);
}
}
private M2 CreateM2()
{
M2 o = new M2();
o.Id = Guid.NewGuid();
o.Age = 10;
o.Address = Guid.NewGuid().ToString();
o.Int = 7;
o.Name = "udi";
o.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
o.Some = SomeEnum.B;
o.Start = DateTime.Now;
o.Duration = TimeSpan.Parse("-01:15:27.123");
o.Offset = DateTimeOffset.Now;
o.Parent = new M1();
o.Parent.Name = "udi";
o.Parent.Age = 10;
o.Parent.Address = Guid.NewGuid().ToString();
o.Parent.Int = 7;
o.Parent.Name = "-1";
o.Parent.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
o.Names = new List<M1>();
for (int i = 0; i < number; i++)
{
var m1 = new M1();
o.Names.Add(m1);
m1.Age = 10;
m1.Address = Guid.NewGuid().ToString();
m1.Int = 7;
m1.Name = i.ToString();
m1.Risk = new Risk { Percent = 0.15D, Annum = true, Accuracy = 0.314M };
}
o.MoreNames = o.Names.ToArray();
return o;
}
private void Time(IMessage[] messages, IMessageSerializer serializer)
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < numberOfIterations; i++)
using (MemoryStream stream = new MemoryStream())
serializer.Serialize(messages, stream);
watch.Stop();
Debug.WriteLine("Serializing: " + watch.Elapsed);
watch.Reset();
MemoryStream s = new MemoryStream();
serializer.Serialize(messages, s);
byte[] buffer = s.GetBuffer();
s.Dispose();
watch.Start();
object[] result = null;
for (int i = 0; i < numberOfIterations; i++)
using (var forDeserializing = new MemoryStream(buffer))
result = serializer.Deserialize(forDeserializing);
watch.Stop();
Debug.WriteLine("Deserializing: " + watch.Elapsed);
}
public void TestSchemaValidation()
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, "schema0.xsd");
settings.Schemas.Add(null, "schema1.xsd");
settings.ValidationType = ValidationType.Schema;
XmlDocument document = new XmlDocument();
document.Load("XMLFile1.xml");
XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
while (rdr.Read()) { }
}
catch (Exception e)
{
string s = e.Message;
}
}
[Test]
public void NestedObjectWithNullPropertiesShouldBeSerialized()
{
var result = ExecuteSerializer.ForMessage<MessageWithNestedObject>(m =>
{
m.NestedObject = new MessageWithNullProperty();
});
Assert.IsNotNull(result.NestedObject);
}
[Test]
public void Messages_with_generic_properties_closing_nullables_should_be_supported()
{
var theTime = DateTime.Now;
var result = ExecuteSerializer.ForMessage<MessageWithGenericPropClosingNullable>(
m => {
m.GenericNullable = new GenericPropertyWithNullable<DateTime?> {TheType = theTime};
m.Whatever = "fdsfsdfsd";
});
Assert.IsNotNull(result.GenericNullable.TheType == theTime);
}
[Test]
public void When_Using_A_Dictionary_With_An_object_As_Key_should_throw()
{
Assert.Throws<NotSupportedException>(() => SerializerFactory.Create<MessageWithDictionaryWithAnObjectAsKey>());
}
[Test]
public void When_Using_A_Dictionary_With_An_Object_As_Value_should_throw()
{
Assert.Throws<NotSupportedException>(() => SerializerFactory.Create<MessageWithDictionaryWithAnObjectAsValue>());
}
}
public class MessageWithGenericPropClosingNullable
{
public GenericPropertyWithNullable<DateTime?> GenericNullable { get; set; }
public string Whatever { get; set; }
}
public class MessageWithNullProperty
{
public string WillBeNull { get; set; }
}
public class MessageWithDouble
{
public double Double { get; set; }
}
public class MessageWithGenericProperty
{
public GenericProperty<string> GenericProperty { get; set; }
public GenericProperty<string> GenericPropertyThatIsNull { get; set; }
}
public class MessageWithNestedObject
{
public MessageWithNullProperty NestedObject { get; set; }
}
public class GenericPropertyWithNullable<T>
{
public T TheType { get; set; }
}
public class GenericProperty<T>
{
private T value;
public GenericProperty(T value)
{
this.value = value;
}
public T ReadOnlyBlob
{
get
{
return value;
}
}
public string WhatEver { get; set; }
}
public class MessageWithDictionaryWithAnObjectAsKey
{
public Dictionary<object, string> Content { get; set; }
}
public class MessageWithDictionaryWithAnObjectAsValue
{
public Dictionary<string, object> Content { get; set; }
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Data;
using System.Text;
using Server;
using Server.Items;
using Server.Mobiles;
namespace Server.Scripts.Commands
{
public class SpawnEditorCommands
{
// Spawner world gem object id
private const int BaseItemId = 0x1F13;
// DataSet and DataTable names used by the Spawn Editor
private const string SpawnDataSetName = "Spawns";
private const string SpawnTablePointName = "Points";
public static void Initialize()
{
Server.Commands.Register( "SpawnShowAll", AccessLevel.Administrator, new CommandEventHandler( ShowSpawnPoints_OnCommand ) );
Server.Commands.Register( "SpawnHideAll", AccessLevel.Administrator, new CommandEventHandler( HideSpawnPoints_OnCommand ) );
Server.Commands.Register( "SpawnWipe", AccessLevel.Administrator, new CommandEventHandler( Wipe_OnCommand ) );
Server.Commands.Register( "SpawnSave", AccessLevel.Administrator, new CommandEventHandler( Save_OnCommand ) );
Server.Commands.Register( "SpawnLoad", AccessLevel.Administrator, new CommandEventHandler( Load_OnCommand ) );
Server.Commands.Register( "SpawnEditorGo", AccessLevel.Administrator, new CommandEventHandler( SpawnEditorGo_OnCommand ) );
}
[Usage( "SpawnEditorGo <map> | <map> <x> <y> [z]" )]
[Description( "Go command used with spawn editor, takes the name of the map as the first parameter." )]
private static void SpawnEditorGo_OnCommand( CommandEventArgs e )
{
Mobile from = e.Mobile;
// Make sure a map name was given at least
if( e.Length >= 1 )
{
// Get the map
Map NewMap = null;
string MapName = e.Arguments[0];
// Convert the xml map value to a real map object
if( string.Compare( MapName, Map.Trammel.Name, true ) == 0 )
NewMap = Map.Trammel;
else if( string.Compare( MapName, Map.Felucca.Name, true ) == 0 )
NewMap = Map.Felucca;
else if( string.Compare( MapName, Map.Ilshenar.Name, true ) == 0 )
NewMap = Map.Ilshenar;
else if( string.Compare( MapName, Map.Malas.Name, true ) == 0 )
NewMap = Map.Malas;
else
{
from.SendMessage( "Map '{0}' does not exist!", MapName );
return;
}
// Now that the map has been determined, continue
// Check if the request is to simply change maps
if( e.Length == 1 )
{
// Map Change ONLY
from.Map = NewMap;
}
else if( e.Length == 3 )
{
// Map & X Y ONLY
if( NewMap != null )
{
int x = e.GetInt32( 1 );
int y = e.GetInt32( 2 );
int z = NewMap.GetAverageZ( x, y );
from.Map = NewMap;
from.Location = new Point3D( x, y, z );
}
}
else if( e.Length == 4 )
{
// Map & X Y Z
from.Map = NewMap;
from.Location = new Point3D( e.GetInt32( 1 ), e.GetInt32( 2 ), e.GetInt32( 3 ) );
}
else
{
from.SendMessage( "Format: SpawnEditorGo <map> | <map> <x> <y> [z]" );
}
}
}
[Usage( "SpawnWipe" )]
[Description( "Wipes ALL spawners from the current map." )]
public static void Wipe_OnCommand( CommandEventArgs e )
{
if( e.Mobile.AccessLevel == AccessLevel.Administrator )
{
e.Mobile.SendMessage( string.Format( "Removing ALL {0} objects from {1} .", "Spawner", e.Mobile.Map ) );
// Delete spawner's in the world based on the mobiles current map
int Count = 0;
ArrayList ToDelete = new ArrayList();
foreach( Item i in World.Items.Values )
{
if( ( i is Spawner ) && ( i.Map == e.Mobile.Map ) && ( i.Deleted == false ) )
{
ToDelete.Add( i );
Count++;
}
}
// Delete the items in the array list
foreach( Item i in ToDelete )
i.Delete();
e.Mobile.SendMessage( string.Format( "Removed {0} {1} objects from {2}.", Count, "Spawner", e.Mobile.Map ) );
}
else
e.Mobile.SendMessage( "You do not have rights to perform this command." );
}
[Usage( "SpawnSave [FileName]" )]
[Description( "Saves all spawner information for the current map to the file specified to be used with the Spawn Editor." )]
public static void Save_OnCommand( CommandEventArgs e )
{
if( e.Mobile.AccessLevel == AccessLevel.Administrator )
{
if( e.Arguments.Length == 1 )
{
int Count = 0;
// Create the data set
DataSet ds = new DataSet( SpawnDataSetName );
// Load the data set up
ds.Tables.Add( SpawnTablePointName );
// Create spawn point schema
ds.Tables[SpawnTablePointName].Columns.Add( "Name" );
ds.Tables[SpawnTablePointName].Columns.Add( "UniqueId" );
ds.Tables[SpawnTablePointName].Columns.Add( "Map" );
ds.Tables[SpawnTablePointName].Columns.Add( "X" );
ds.Tables[SpawnTablePointName].Columns.Add( "Y" );
ds.Tables[SpawnTablePointName].Columns.Add( "Width" );
ds.Tables[SpawnTablePointName].Columns.Add( "Height" );
ds.Tables[SpawnTablePointName].Columns.Add( "CentreX" );
ds.Tables[SpawnTablePointName].Columns.Add( "CentreY" );
ds.Tables[SpawnTablePointName].Columns.Add( "CentreZ" );
ds.Tables[SpawnTablePointName].Columns.Add( "Range" );
ds.Tables[SpawnTablePointName].Columns.Add( "MaxCount" );
ds.Tables[SpawnTablePointName].Columns.Add( "MinDelay" );
ds.Tables[SpawnTablePointName].Columns.Add( "MaxDelay" );
ds.Tables[SpawnTablePointName].Columns.Add( "Team" );
ds.Tables[SpawnTablePointName].Columns.Add( "IsGroup" );
ds.Tables[SpawnTablePointName].Columns.Add( "IsRunning" );
ds.Tables[SpawnTablePointName].Columns.Add( "Objects" );
// Add each spawn point to the new table
foreach( Item i in World.Items.Values )
{
if( ( i.Map == e.Mobile.Map ) && ( i is Spawner ) && ( i.Deleted == false ) )
{
// Cast the item to a spawner
Spawner spawner = (Spawner)i;
// Create a new data row
DataRow dr = ds.Tables[SpawnTablePointName].NewRow();
// Populate the data
dr["Name"] = (string)( spawner.Name.Length == 0 ? ( spawner.GetType().Name + Count ) : ( spawner.Name + Count ) );
// Create a unique ID
dr["UniqueId"] = Guid.NewGuid().ToString();
// Get the map name
dr["Map"] = (string)spawner.Map.Name;
// Calculate the top left based on the centre and home range
dr["X"] = (int)( spawner.Location.X - ( spawner.HomeRange / 2 ) );
dr["Y"] = (int)( spawner.Location.Y - ( spawner.HomeRange / 2 ) );
dr["Width"] = (int)spawner.HomeRange;
dr["Height"] = (int)spawner.HomeRange;
dr["CentreX"] = (int)spawner.Location.X;
dr["CentreY"] = (int)spawner.Location.Y;
dr["CentreZ"] = (int)spawner.Location.Z;
dr["Range"] = (int)spawner.HomeRange;
dr["MaxCount"] = (int)spawner.Count;
dr["MinDelay"] = (int)spawner.MinDelay.TotalMinutes;
dr["MaxDelay"] = (int)spawner.MaxDelay.TotalMinutes;
dr["Team"] = (int)spawner.Team;
dr["IsGroup"] = (bool)spawner.Group;
dr["IsRunning"] = (bool)spawner.Running;
// Create the spawn object list
// Make a copy of the original creatures name list
ArrayList SpawnObjs = new ArrayList( spawner.CreaturesName );
// Sort the list
SpawnObjs.Sort();
// Create the new version of the spawn object list
StringBuilder SpawnObjectList = new StringBuilder();
for( int x = 0; x < SpawnObjs.Count; x++ )
{
string SpawnType = SpawnObjs[x].ToString();
int SpawnCount = 0;
for( int y = x; y < SpawnObjs.Count; y++ )
{
if( SpawnType.ToUpper() == SpawnObjs[y].ToString().ToUpper() )
SpawnCount++;
else
break;
}
// Increment t by the SpawnCount
if( SpawnCount > 0 )
x += ( SpawnCount - 1 );
// Add the spawn object to the spawn object list
// Check if the object separator needs to be included
if( SpawnObjectList.Length > 0 )
SpawnObjectList.Append( ":" );
SpawnObjectList.AppendFormat( "{0}={1}", SpawnType, SpawnCount );
}
// Set the spawn object list
dr["Objects"] = SpawnObjectList.ToString();
// Add the row the the table
ds.Tables[SpawnTablePointName].Rows.Add( dr );
// Increment the count
Count++;
}
}
// Write out the file
ds.WriteXml( e.Arguments[0].ToString() );
// Indicate how many spawners were written
e.Mobile.SendMessage( "{0} spawner(s) in {1} were saved to file {2}.", Count, e.Mobile.Map, e.Arguments[0].ToString() );
}
else
e.Mobile.SendMessage( "Usage: {0} <SpawnFile>", e.Command );
}
else
e.Mobile.SendMessage( "You do not have rights to perform this command." );
}
[Usage( "SpawnLoad [FileName]" )]
[Description( "Load all spawner information from the file created using the Spawn Editor." )]
public static void Load_OnCommand( CommandEventArgs e )
{
if( e.Mobile.AccessLevel == AccessLevel.Administrator )
{
if( e.Arguments.Length == 1 )
{
// Check if the file exists
if( File.Exists( e.Arguments[0].ToString() ) == true )
{
int TotalCount = 0;
int TrammelCount = 0;
int FeluccaCount = 0;
int IlshenarCount = 0;
int MalasCount = 0;
e.Mobile.SendMessage( string.Format( "Loading {0} file {1}.", "Spawner", e.Arguments[0].ToString() ) );
// Create the data set
DataSet ds = new DataSet( SpawnDataSetName );
// Read in the file
ds.ReadXml( e.Arguments[0].ToString() );
// Check that at least a single table was loaded
if( ds.Tables.Count > 0 )
{
// Add each spawn point to the current map
foreach( DataRow dr in ds.Tables[SpawnTablePointName].Rows )
{
// Each row makes up a single spawner
string SpawnName = (string)dr["Name"];
// Try load the GUID (might not work so create a new GUID)
// Don't use it in the normal spawner, but the XmlSpawner does
Guid SpawnId = Guid.NewGuid();
try{ SpawnId = new Guid( (string)dr["UniqueId"] ); }
catch{}
// Get the map (default to the mobiles map)
Map SpawnMap = e.Mobile.Map;
string XmlMapName = e.Mobile.Map.Name;
// Try to get the "map" field, but in case it doesn't exist, catch and discard the exception
try{ XmlMapName = (string)dr["Map"]; }
catch{}
// Convert the xml map value to a real map object
if( string.Compare( XmlMapName, Map.Trammel.Name, true ) == 0 )
{
SpawnMap = Map.Trammel;
TrammelCount++;
}
else if( string.Compare( XmlMapName, Map.Felucca.Name, true ) == 0 )
{
SpawnMap = Map.Felucca;
FeluccaCount++;
}
else if( string.Compare( XmlMapName, Map.Ilshenar.Name, true ) == 0 )
{
SpawnMap = Map.Ilshenar;
IlshenarCount++;
}
else if( string.Compare( XmlMapName, Map.Malas.Name, true ) == 0 )
{
SpawnMap = Map.Malas;
MalasCount++;
}
int SpawnX = int.Parse( (string)dr["X"] );
int SpawnY = int.Parse( (string)dr["Y"] );
int SpawnWidth = int.Parse( (string)dr["Width"] );
int SpawnHeight = int.Parse( (string)dr["Height"] );
int SpawnCentreX = int.Parse( (string)dr["CentreX"] );
int SpawnCentreY = int.Parse( (string)dr["CentreY"] );
int SpawnCentreZ = int.Parse( (string)dr["CentreZ"] );
int SpawnHomeRange = int.Parse( (string)dr["Range"] );
int SpawnMaxCount = int.Parse( (string)dr["MaxCount"] );
TimeSpan SpawnMinDelay = TimeSpan.FromMinutes( int.Parse( (string)dr["MinDelay"] ) );
TimeSpan SpawnMaxDelay = TimeSpan.FromMinutes( int.Parse( (string)dr["MaxDelay"] ) );
int SpawnTeam = int.Parse( (string)dr["Team"] );
bool SpawnIsGroup = bool.Parse( (string)dr["IsGroup"] );
bool SpawnIsRunning = bool.Parse( (string)dr["IsRunning"] );
string SpawnObjects = (string)dr["Objects"];
// Create the creatures name array from the spawn object list
ArrayList CreatureNames = new ArrayList();
// Check if there are any names in the list
if( SpawnObjects.Length > 0 )
{
// Split the string based on the object separator first ':'
string[] SpawnObjectList = SpawnObjects.Split( ':' );
// Parse each item in the array
foreach( string s in SpawnObjectList )
{
// Split the single spawn object item by the max count '='
string[] SpawnObjectDetails = s.Split( '=' );
// Should be two entries
if( SpawnObjectDetails.Length == 2 )
{
// Validate the information
// Make sure the spawn object name part has a valid length
if( SpawnObjectDetails[0].Length > 0 )
{
// Make sure the max count part has a valid length
if( SpawnObjectDetails[1].Length > 0 )
{
int MaxCount = 1;
try
{
MaxCount = int.Parse( SpawnObjectDetails[1] );
}
catch( System.Exception )
{ // Something went wrong, leave the default amount }
}
// Add the required number of creature names to the list of creatures
for( int x = 0; x < MaxCount; x++ )
CreatureNames.Add( SpawnObjectDetails[0].ToString() );
}
}
}
}
}
// Create the spawn
Spawner TheSpawn = new Spawner( SpawnMaxCount, SpawnMinDelay, SpawnMaxDelay, SpawnTeam, SpawnHomeRange, CreatureNames );
// Try to find a valid Z height
int NewZ = SpawnMap.GetAverageZ( SpawnCentreX, SpawnCentreY );
if( SpawnMap.CanFit( SpawnCentreX, SpawnCentreY, NewZ, 16 ) == false )
{
for( int i = 1; i <= 20; ++i )
{
if( SpawnMap.CanFit( SpawnCentreX, SpawnCentreY, NewZ + i, 16 ) )
{
NewZ += i;
break;
}
else if ( SpawnMap.CanFit( SpawnCentreX, SpawnCentreY, NewZ - i, 16 ) )
{
NewZ -= i;
break;
}
}
}
// Place the spawner into the world
TheSpawn.MoveToWorld( new Point3D( SpawnCentreX, SpawnCentreY, NewZ ), SpawnMap );
// Do a total respawn
TheSpawn.Respawn();
// Increment the count
TotalCount++;
}
}
e.Mobile.SendMessage( "{0} spawner(s) were created from file {1} [Trammel={2}, Felucca={3}, Ilshenar={4}, Malas={5}].", TotalCount, e.Arguments[0].ToString(), TrammelCount, FeluccaCount, IlshenarCount, MalasCount );
}
else
e.Mobile.SendMessage( "File {0} does not exist.", e.Arguments[0].ToString() );
}
else
e.Mobile.SendMessage( "Usage: {0} <SpawnFile>", e.Command );
}
else
e.Mobile.SendMessage( "You do not have rights to perform this command." );
}
[Usage( "SpawnShowAll" )]
[Description( "Shows all spawners by making them visible and changing their object id to that of a ships mast for easy visiblity." )]
public static void ShowSpawnPoints_OnCommand( CommandEventArgs e )
{
foreach( Item item in World.Items.Values )
{
if( item is Spawner )
{
item.Visible = true; // Make the spawn item visible to everyone
item.Movable = true; // Make the spawn item movable
item.Hue = 88; // Bright blue colour so its easy to spot
item.ItemID = 0x3E57; // Ship Mast (Very tall, easy to see if beneath other objects)
}
}
}
[Usage( "SpawnHideAll" )]
[Description( "Hides all spawners by making them invisible and reverting them back to their normal object id." )]
public static void HideSpawnPoints_OnCommand( CommandEventArgs e )
{
foreach( Item item in World.Items.Values )
{
if( item is Spawner )
{
item.Visible = false;
item.Movable = false;
item.Hue = 0;
item.ItemID = BaseItemId;
}
}
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Redis/
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2014 Service Stack LLC. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
namespace ServiceStack.Redis
{
public interface IRedisNativeClient
: IDisposable
{
//Redis utility operations
Dictionary<string, string> Info { get; }
long Db { get; set; }
long DbSize { get; }
DateTime LastSave { get; }
void Save();
void BgSave();
void Shutdown();
void BgRewriteAof();
void Quit();
void FlushDb();
void FlushAll();
bool Ping();
string Echo(string text);
void SlaveOf(string hostname, int port);
void SlaveOfNoOne();
byte[][] ConfigGet(string pattern);
void ConfigSet(string item, byte[] value);
void ConfigResetStat();
void ConfigRewrite();
byte[][] Time();
void DebugSegfault();
byte[] Dump(string key);
byte[] Restore(string key, long expireMs, byte[] dumpValue);
void Migrate(string host, int port, string key, int destinationDb, long timeoutMs);
bool Move(string key, int db);
long ObjectIdleTime(string key);
RedisText Role();
RedisData RawCommand(params object[] cmdWithArgs);
RedisData RawCommand(params byte[][] cmdWithBinaryArgs);
string ClientGetName();
void ClientSetName(string client);
void ClientKill(string host);
long ClientKill(string addr = null, string id = null, string type = null, string skipMe = null);
byte[] ClientList();
void ClientPause(int timeOutMs);
//Common key-value Redis operations
byte[][] Keys(string pattern);
long Exists(string key);
long StrLen(string key);
void Set(string key, byte[] value);
void SetEx(string key, int expireInSeconds, byte[] value);
bool Persist(string key);
void PSetEx(string key, long expireInMs, byte[] value);
long SetNX(string key, byte[] value);
void MSet(byte[][] keys, byte[][] values);
void MSet(string[] keys, byte[][] values);
bool MSetNx(byte[][] keys, byte[][] values);
bool MSetNx(string[] keys, byte[][] values);
byte[] Get(string key);
byte[] GetSet(string key, byte[] value);
byte[][] MGet(params byte[][] keysAndArgs);
byte[][] MGet(params string[] keys);
long Del(string key);
long Del(params string[] keys);
long Incr(string key);
long IncrBy(string key, int incrBy);
double IncrByFloat(string key, double incrBy);
long Decr(string key);
long DecrBy(string key, int decrBy);
long Append(string key, byte[] value);
byte[] GetRange(string key, int fromIndex, int toIndex);
long SetRange(string key, int offset, byte[] value);
long GetBit(string key, int offset);
long SetBit(string key, int offset, int value);
string RandomKey();
void Rename(string oldKeyname, string newKeyname);
bool RenameNx(string oldKeyname, string newKeyname);
bool Expire(string key, int seconds);
bool PExpire(string key, long ttlMs);
bool ExpireAt(string key, long unixTime);
bool PExpireAt(string key, long unixTimeMs);
long Ttl(string key);
long PTtl(string key);
//Scan APIs
ScanResult Scan(ulong cursor, int count = 10, string match = null);
ScanResult SScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult ZScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult HScan(string hashId, ulong cursor, int count = 10, string match = null);
//Hyperlog
bool PfAdd(string key, params byte[][] elements);
long PfCount(string key);
void PfMerge(string toKeyId, params string[] fromKeys);
//Redis Sort operation (works on lists, sets or hashes)
byte[][] Sort(string listOrSetId, SortOptions sortOptions);
//Redis List operations
byte[][] LRange(string listId, int startingFrom, int endingAt);
long RPush(string listId, byte[] value);
long RPushX(string listId, byte[] value);
long LPush(string listId, byte[] value);
long LPushX(string listId, byte[] value);
void LTrim(string listId, int keepStartingFrom, int keepEndingAt);
long LRem(string listId, int removeNoOfMatches, byte[] value);
long LLen(string listId);
byte[] LIndex(string listId, int listIndex);
void LInsert(string listId, bool insertBefore, byte[] pivot, byte[] value);
void LSet(string listId, int listIndex, byte[] value);
byte[] LPop(string listId);
byte[] RPop(string listId);
byte[][] BLPop(string listId, int timeOutSecs);
byte[][] BLPop(string[] listIds, int timeOutSecs);
byte[] BLPopValue(string listId, int timeOutSecs);
byte[][] BLPopValue(string[] listIds, int timeOutSecs);
byte[][] BRPop(string listId, int timeOutSecs);
byte[][] BRPop(string[] listIds, int timeOutSecs);
byte[] RPopLPush(string fromListId, string toListId);
byte[] BRPopValue(string listId, int timeOutSecs);
byte[][] BRPopValue(string[] listIds, int timeOutSecs);
byte[] BRPopLPush(string fromListId, string toListId, int timeOutSecs);
//Redis Set operations
byte[][] SMembers(string setId);
long SAdd(string setId, byte[] value);
long SAdd(string setId, byte[][] value);
long SRem(string setId, byte[] value);
byte[] SPop(string setId);
void SMove(string fromSetId, string toSetId, byte[] value);
long SCard(string setId);
long SIsMember(string setId, byte[] value);
byte[][] SInter(params string[] setIds);
void SInterStore(string intoSetId, params string[] setIds);
byte[][] SUnion(params string[] setIds);
void SUnionStore(string intoSetId, params string[] setIds);
byte[][] SDiff(string fromSetId, params string[] withSetIds);
void SDiffStore(string intoSetId, string fromSetId, params string[] withSetIds);
byte[] SRandMember(string setId);
//Redis Sorted Set operations
long ZAdd(string setId, double score, byte[] value);
long ZAdd(string setId, long score, byte[] value);
long ZRem(string setId, byte[] value);
double ZIncrBy(string setId, double incrBy, byte[] value);
double ZIncrBy(string setId, long incrBy, byte[] value);
long ZRank(string setId, byte[] value);
long ZRevRank(string setId, byte[] value);
byte[][] ZRange(string setId, int min, int max);
byte[][] ZRangeWithScores(string setId, int min, int max);
byte[][] ZRevRange(string setId, int min, int max);
byte[][] ZRevRangeWithScores(string setId, int min, int max);
byte[][] ZRangeByScore(string setId, double min, double max, int? skip, int? take);
byte[][] ZRangeByScore(string setId, long min, long max, int? skip, int? take);
byte[][] ZRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
byte[][] ZRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
byte[][] ZRevRangeByScore(string setId, double min, double max, int? skip, int? take);
byte[][] ZRevRangeByScore(string setId, long min, long max, int? skip, int? take);
byte[][] ZRevRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
byte[][] ZRevRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
long ZRemRangeByRank(string setId, int min, int max);
long ZRemRangeByScore(string setId, double fromScore, double toScore);
long ZRemRangeByScore(string setId, long fromScore, long toScore);
long ZCard(string setId);
double ZScore(string setId, byte[] value);
long ZUnionStore(string intoSetId, params string[] setIds);
long ZInterStore(string intoSetId, params string[] setIds);
byte[][] ZRangeByLex(string setId, string min, string max, int? skip = null, int? take = null);
long ZLexCount(string setId, string min, string max);
long ZRemRangeByLex(string setId, string min, string max);
//Redis Hash operations
long HSet(string hashId, byte[] key, byte[] value);
void HMSet(string hashId, byte[][] keys, byte[][] values);
long HSetNX(string hashId, byte[] key, byte[] value);
long HIncrby(string hashId, byte[] key, int incrementBy);
double HIncrbyFloat(string hashId, byte[] key, double incrementBy);
byte[] HGet(string hashId, byte[] key);
byte[][] HMGet(string hashId, params byte[][] keysAndArgs);
long HDel(string hashId, byte[] key);
long HExists(string hashId, byte[] key);
long HLen(string hashId);
byte[][] HKeys(string hashId);
byte[][] HVals(string hashId);
byte[][] HGetAll(string hashId);
//Redis Pub/Sub operations
void Watch(params string[] keys);
void UnWatch();
long Publish(string toChannel, byte[] message);
byte[][] Subscribe(params string[] toChannels);
byte[][] UnSubscribe(params string[] toChannels);
byte[][] PSubscribe(params string[] toChannelsMatchingPatterns);
byte[][] PUnSubscribe(params string[] toChannelsMatchingPatterns);
byte[][] ReceiveMessages();
IRedisSubscription CreateSubscription();
//Redis LUA support
long EvalInt(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
long EvalShaInt(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
string EvalStr(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
string EvalShaStr(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
byte[][] Eval(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
byte[][] EvalSha(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
string CalculateSha1(string luaBody);
byte[][] ScriptExists(params byte[][] sha1Refs);
void ScriptFlush();
void ScriptKill();
byte[] ScriptLoad(string body);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : IDisposable
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private static object s_createProcessLock = new object();
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
#if FEATURE_TRACESWITCH
internal static TraceSwitch _processTracing =
#if DEBUG
new TraceSwitch("processTracing", "Controls debug output from Process component");
#else
null;
#endif
#endif
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets the number of handles that are associated
/// with the process.
/// </para>
/// </devdoc>
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.HandleCount;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveId | State.IsLocal);
ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(_processId);
ProcessModule[] newModulesArray = new ProcessModule[moduleInfos.Length];
for (int i = 0; i < moduleInfos.Length; i++)
{
newModulesArray[i] = new ProcessModule(moduleInfos[i]);
}
ProcessModuleCollection newModules = new ProcessModuleCollection(newModulesArray);
_modules = newModules;
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "value", (int)value, typeof(ProcessPriorityClass)));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
/// .
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// Release the temporary handle we used to get process information.
/// If we used the process handle stored in the process object (we have all access to the handle,) don't release it.
/// </devdoc>
/// <internalonly/>
private void ReleaseProcessHandle(SafeProcessHandle handle)
{
if (handle == null)
{
return;
}
if (_haveProcessHandle && handle == _processHandle)
{
return;
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
handle.Dispose();
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object context, bool wasSignaled)
{
StopWatchingForExit();
RaiseOnExited();
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
internal void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
StopWatchingForExit();
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
#endif
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
//Don't call close on the Readers and writers
//since they might be referenced by somebody else while the
//process is still alive but this method called.
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId);
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle");
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new ProcessWaitHandle(_processHandle);
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), null, -1, true);
}
catch
{
_watchingForExit = false;
throw;
}
}
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are associated with process resources on a
/// remote computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName, string machineName)
{
if (processName == null) processName = String.Empty;
Process[] procs = GetProcesses(machineName);
List<Process> list = new List<Process>();
for (int i = 0; i < procs.Length; i++)
{
if (String.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase))
{
list.Add(procs[i]);
}
else
{
procs[i].Dispose();
}
}
Process[] temp = new Process[list.Count];
list.CopyTo(temp, 0);
return temp;
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")");
#if DEBUG
if (_processTracing.TraceVerbose) {
Debug.Indent();
for (int i = 0; i < processInfos.Length; i++) {
Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName);
}
Debug.Unindent();
}
#endif
#endif
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
}
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
private static Encoding GetEncoding(int codePage)
{
return EncodingHelper.GetSupportedConsoleEncoding(codePage);
}
public static Process Start(string fileName, string userName, SecureString password, string domain)
{
ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
startInfo.UserName = userName;
startInfo.Password = password;
startInfo.Domain = domain;
return Start(startInfo);
}
public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
{
ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments);
startInfo.UserName = userName;
startInfo.Password = password;
startInfo.Domain = domain;
return Start(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException("startInfo");
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
_registeredWaitHandle.Unregister(null);
_waitHandle.Dispose();
_waitHandle = null;
_registeredWaitHandle = null;
}
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
using System;
using System.IO;
using System.Text;
using PrefabEvolution.Migration;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
namespace PrefabEvolution
{
[InitializeOnLoad]
class PECache : ScriptableObject
{
[SerializeField] private PEDictionaryStringList whereCache = new PEDictionaryStringList();
[SerializeField] private PEDictionaryStringList whatCache = new PEDictionaryStringList();
[SerializeField] private bool allAssetsLoaded;
static private List<string> modelPathToApply = new List<string>();
static private PECache instance;
static public PECache Instance
{
get
{
if (instance == null)
{
instance = Resources.FindObjectsOfTypeAll<PECache>().FirstOrDefault();
if (instance == null)
{
instance = CreateInstance<PECache>();
}
SetDontSave();
}
return instance;
}
}
static void SetDontSave()
{
instance.hideFlags = HideFlags.DontSave | HideFlags.DontUnloadUnusedAsset;
}
public void CheckPrefab(params string[] paths)
{
var i = 0;
var prefabsPaths = paths.Where(p => p.EndsWith(".prefab")).ToArray();
foreach (var path in prefabsPaths)
{
if (prefabsPaths.Length > 5 && i++ % 50 == 0)
EditorUtility.DisplayProgressBar("Checking prefab dependencies", path, i / (float)prefabsPaths.Length);
if (prefabsPaths.Length > 5 && !canPrefabContainsNestedInstances(path))
continue;
CheckPrefab(AssetDatabase.AssetPathToGUID(path), PEUtils.GetAssetByPath<GameObject>(path));
if (i % 100 != 0)
continue;
#if UNITY_5
EditorUtility.UnloadUnusedAssetsImmediate();
#else
EditorUtility.UnloadUnusedAssets();
#endif
}
foreach (var path in paths.Where(p => !p.EndsWith(".prefab")))
{
if (!modelPathToApply.Contains(path))
continue;
var importer = AssetImporter.GetAtPath(path);
if (!(importer is ModelImporter))
continue;
var asset = PEUtils.GetAssetByPath<GameObject>(path);
if (asset == null)
continue;
var prefabScript = asset.GetComponent<PEPrefabScript>();
if (prefabScript == null)
continue;
modelPathToApply.Remove(path);
if (PEPrefs.DebugLevel > 0)
Debug.Log("Applying " + path);
prefabScript.Prefab = asset;
prefabScript.BuildLinks();
EditorApplication.delayCall += () => PEUtils.DoApply(prefabScript);
}
EditorUtility.ClearProgressBar();
}
void CheckAllAssets()
{
if (allAssetsLoaded)
return;
allAssetsLoaded = true;
this.whereCache.list.Clear();
this.whatCache.list.Clear();
var startTime = DateTime.Now;
CheckPrefab(AssetDatabase.GetAllAssetPaths());
Debug.Log("CheckTime: " + (DateTime.Now - startTime).TotalMilliseconds);
}
static public void ForceCheckAllAssets()
{
AssetDatabase.GetAllAssetPaths().Foreach(p =>
{
if (p.EndsWith(".prefab"))
setContainsNestedInstances(AssetDatabase.AssetPathToGUID(p), true);
});
Instance.allAssetsLoaded = false;
Instance.CheckAllAssets();
}
private List<string> this[string guid]
{
get
{
CheckAllAssets();
return whereCache[guid];
}
}
public IEnumerable<GameObject> GetPrefabsWithInstances(string guid)
{
var list = this[guid];
if (list == null || list.Count == 0)
yield break;
foreach (var g in this[guid].ToArray())
{
var go = PEUtils.GetAssetByGUID<GameObject>(g);
if (go)
yield return go;
}
}
private void CheckPrefab(string guid, GameObject prefab)
{
if (string.IsNullOrEmpty(guid) || prefab == null)
{
return;
}
var nestedInstances = PEUtils.GetNestedInstances(prefab).ToArray();
foreach (var e in whatCache[guid])
{
whereCache[e].Remove(guid);
}
var rootInstance = prefab.GetComponent<PEPrefabScript>();
if (rootInstance != null)
{
if (rootInstance.PrefabGUID == guid && !string.IsNullOrEmpty(rootInstance.ParentPrefabGUID))
Add(rootInstance.ParentPrefabGUID, guid);
}
foreach (var instance in nestedInstances)
{
if (instance.PrefabGUID != guid)
Add(instance.PrefabGUID, guid);
}
setContainsNestedInstances(guid, nestedInstances.Length > 0 || (rootInstance && !string.IsNullOrEmpty(rootInstance.ParentPrefabGUID)));
}
static string getMetaInfo(string path)
{
path = path + ".meta";
if (!File.Exists(path))
return "";
return FileUtility.ReadAllText(path, Encoding.UTF8);
}
static string getMetaUserData(string meta)
{
var prefix = " userData:";
var indexOfUserData = meta.LastIndexOf(prefix);
var indexOfEOL = meta.IndexOf("\n", indexOfUserData);
if (indexOfEOL == -1)
indexOfEOL = meta.Length - 1;
var start = indexOfUserData + prefix.Length;
var length = indexOfEOL - 1 - start;
return meta.Substring(start, length).Trim();
}
private const string HaveConst = "HaveNested_true";
private const string DontHaveConst = "HaveNested_false";
static void setContainsNestedInstances(string guid, bool state)
{
try
{
var path = AssetDatabase.GUIDToAssetPath(guid);
var importer = AssetImporter.GetAtPath(path);
if (importer == null)
return;
var origData = importer.userData;
var data = origData.Replace(":", "_");
if (data != string.Empty && data != HaveConst && data != DontHaveConst)
return;
var newData = state ? HaveConst : DontHaveConst;
importer.userData = newData;
}
catch (Exception){}
}
static bool canPrefabContainsNestedInstances(string path)
{
try
{
var meta = getMetaInfo(path);
if (meta == string.Empty)
return true;
var data = getMetaUserData(meta).Replace(":", "_");
if (data != HaveConst && data != DontHaveConst)
return true;
return data == HaveConst;
}
catch (Exception)
{
return true;
}
}
void Add(string prefabGuid, string guid)
{
var list = this[prefabGuid];
if (!list.Contains(guid))
list.Add(guid);
list = whatCache[guid];
if (!list.Contains(prefabGuid))
list.Add(prefabGuid);
}
#region Processors
public class PrefabAssetModificationProcessor : UnityEditor.AssetModificationProcessor
{
static void OnWillCreateAsset(string path)
{
Instance.CheckPrefab(path);
}
static string[] OnWillSaveAssets(string[] paths)
{
Instance.CheckPrefab(paths);
return paths;
}
}
public class PrefabPostProcessor : AssetPostprocessor
{
static public void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
Instance.CheckPrefab(importedAssets);
}
}
public class PrefabEvolutionPostProcessor : AssetPostprocessor
{
void OnPostprocessModel(GameObject gameObject)
{
if (PEPrefs.AutoModels)
{
var guid = AssetDatabase.AssetPathToGUID(this.assetPath);
if (string.IsNullOrEmpty(guid))
{
EditorApplication.delayCall += () => AssetDatabase.ImportAsset(this.assetPath);
return;
}
var pi = gameObject.AddComponent<EvolvePrefab>() as PEPrefabScript;
pi.PrefabGUID = guid;
pi.BuildLinks(true);
modelPathToApply.Add(this.assetPath);
}
}
}
#endregion
#region Menu
#if SHOW_DEBUG_MENU
[MenuItem("Prefab Evolution/Show Prefab Cache")]
static public void SelectPrefapCache()
{
Selection.activeObject = Instance;
}
[MenuItem("Prefab Evolution/Update Prefab List")]
static public void UpdatePrefabList()
{
Instance.allAssetsLoaded = false;
Instance.CheckAllAssets();
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ConstructorInitializerSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ConstructorInitializerSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class BaseClass
{
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestThisInvocation()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$3|]) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(b: 2, a: $$
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class Foo
{
public Foo(int a) { }
public Foo() : this($$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("Foo(int a)", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2,$$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2, $$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x, int y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
#if BAR
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo($$";
await TestAsync(markup);
}
[WorkItem(1082601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithBadParameterList()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base{$$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TypingTupleDoesNotDismiss1()
{
var markup = @"
class D { public D(object o) {} }
class C : D
{
public C() [|: base(($$)
|]{}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TypingTupleDoesNotDismiss2()
{
var markup = @"
class D { public D(object o) {} }
class C : D
{
public C() [|: base((1,$$) |]{}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TypingTupleDoesNotDismiss3()
{
var markup = @"
class D { public D(object o) {} }
class C : D
{
public C() [|: base((1, ($$)
|]{}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TypingTupleDoesNotDismiss4()
{
var markup = @"
class D { public D(object o) {} }
class C : D
{
public C() [|: base((1, (2,$$) |]{}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: 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.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public abstract class FileStream_AsyncWrites : FileSystemTest
{
protected virtual string BufferParamName => "buffer";
protected virtual string OffsetParamName => "offset";
protected virtual string CountParamName => "count";
private Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count) =>
WriteAsync(stream, buffer, offset, count, CancellationToken.None);
protected abstract Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken);
[Fact]
public void NullBufferThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, 0, 1)));
}
}
[Fact]
public void NegativeOffsetThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, 1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, 1)));
}
}
[Fact]
public void NegativeCountThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, -1)));
// offset is checked before count
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, -1)));
}
}
[Fact]
public void BufferOutOfBoundsThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// offset out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 1, 1)));
// offset out of bounds for 0 count WriteAsync
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 2, 0)));
// offset out of bounds even for 0 length buffer
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[0], 1, 0)));
// combination offset and count out of bounds
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2)));
// edges
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[0], int.MaxValue, 0)));
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[0], int.MaxValue, int.MaxValue)));
}
}
[Fact]
public void WriteAsyncDisposedThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
// even for noop WriteAsync
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 0)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, -1)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, -1)));
}
}
[Fact]
public void ReadOnlyThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{ }
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Assert.Throws<NotSupportedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
fs.Dispose();
// Disposed checking happens first
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, -1)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, -1)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, -1)));
}
}
[Fact]
public async Task NoopWriteAsyncsSucceed()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// note that these do not succeed synchronously even though they do nothing.
await WriteAsync(fs, new byte[0], 0, 0);
await WriteAsync(fs, new byte[1], 0, 0);
// even though offset is out of bounds of buffer, this is still allowed
// for the last element
await WriteAsync(fs, new byte[1], 1, 0);
await WriteAsync(fs, new byte[2], 1, 0);
Assert.Equal(0, fs.Length);
Assert.Equal(0, fs.Position);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we modified ReadAsync/WriteAsync to complete synchronously here, but that change was not backported to netfx.")]
public void WriteAsyncBufferedCompletesSynchronously()
{
using (FileStream fs = new FileStream(
GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete,
TestBuffer.Length * 2, useAsync: true))
{
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[TestBuffer.Length], 0, TestBuffer.Length));
}
}
[Fact]
public async Task SimpleWriteAsync()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
await WriteAsync(fs, TestBuffer, 0, TestBuffer.Length);
Assert.Equal(TestBuffer.Length, fs.Length);
Assert.Equal(TestBuffer.Length, fs.Position);
fs.Position = 0;
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
public async Task WriteAsyncCancelledFile()
{
const int writeSize = 1024 * 1024;
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
byte[] buffer = new byte[writeSize];
CancellationTokenSource cts = new CancellationTokenSource();
Task writeTask = WriteAsync(fs, buffer, 0, buffer.Length, cts.Token);
cts.Cancel();
try
{
await writeTask;
}
catch (OperationCanceledException oce)
{
// Ideally we'd be doing an Assert.Throws<OperationCanceledException>
// but since cancellation is a race condition we accept either outcome
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
}
[Fact]
public async Task WriteAsyncInternalBufferOverflow()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write, FileShare.None, 3, useAsync: true))
{
// Fill buffer; should trigger flush of full buffer, no additional I/O
await WriteAsync(fs, TestBuffer, 0, 3);
Assert.True(fs.Length == 3);
// Add to next buffer
await WriteAsync(fs, TestBuffer, 0, 1);
Assert.True(fs.Length == 4);
// Complete that buffer; should trigger flush of full buffer, no additional I/O
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 6);
// Add to next buffer
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 8);
// Overflow buffer with amount that could fit in a buffer; should trigger a flush, with additional I/O
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 10);
// Overflow buffer with amount that couldn't fit in a buffer; shouldn't be anything to flush, just an additional I/O
await WriteAsync(fs, TestBuffer, 0, 4);
Assert.True(fs.Length == 14);
}
}
public static IEnumerable<object[]> MemberData_FileStreamAsyncWriting()
{
foreach (bool useAsync in new[] { true, false })
{
if (useAsync && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// We don't have a special async I/O implementation in FileStream on Unix.
continue;
}
foreach (bool preSize in new[] { true, false })
{
foreach (bool cancelable in new[] { true, false })
{
yield return new object[] { useAsync, preSize, false, cancelable, 0x1000, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x1, 0x1, 1000 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x2, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x4000, 0x10, 100 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x1000, 99999, 10 };
}
}
}
}
[Fact]
public Task ManyConcurrentWriteAsyncs()
{
// For inner loop, just test one case
return ManyConcurrentWriteAsyncs(
useAsync: RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
presize: false,
exposeHandle: false,
cancelable: true,
bufferSize: 4096,
writeSize: 1024,
numWrites: 10);
}
[Theory]
[MemberData(nameof(MemberData_FileStreamAsyncWriting))]
[OuterLoop] // many combinations: we test just one in inner loop and the rest outer
public async Task ManyConcurrentWriteAsyncs(
bool useAsync, bool presize, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites)
{
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
CancellationToken cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None;
string path = GetTestFilePath();
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
if (presize)
{
fs.SetLength(totalLength);
}
if (exposeHandle)
{
var ignored = fs.SafeFileHandle;
}
Task[] writes = new Task[numWrites];
for (int i = 0; i < numWrites; i++)
{
writes[i] = WriteAsync(fs, expectedData, i * writeSize, writeSize, cancellationToken);
Assert.Null(writes[i].Exception);
if (useAsync)
{
Assert.Equal((i + 1) * writeSize, fs.Position);
}
}
await Task.WhenAll(writes);
}
byte[] actualData = File.ReadAllBytes(path);
Assert.Equal(expectedData.Length, actualData.Length);
if (useAsync)
{
Assert.Equal<byte>(expectedData, actualData);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task BufferCorrectlyMaintainedWhenReadAndWrite(bool useAsync)
{
string path = GetTestFilePath();
File.WriteAllBytes(path, TestBuffer);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 2, useAsync))
{
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
await WriteAsync(fs, TestBuffer, 0, TestBuffer.Length);
fs.Position = 0;
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
for (int i = 0; i < TestBuffer.Length; i++)
{
Assert.Equal(TestBuffer[i], await ReadByteAsync(fs));
}
}
}
private static async Task<byte> ReadByteAsync(FileStream fs)
{
byte[] oneByte = new byte[1];
Assert.Equal(1, await fs.ReadAsync(oneByte, 0, 1));
return oneByte[0];
}
[Fact, OuterLoop]
public async Task WriteAsyncMiniStress()
{
TimeSpan testRunTime = TimeSpan.FromSeconds(10);
const int MaximumWriteSize = 16 * 1024;
const int NormalWriteSize = 4 * 1024;
Random rand = new Random();
DateTime testStartTime = DateTime.UtcNow;
// Generate data to write (NOTE: Randomizing this is important as some file systems may optimize writing 0s)
byte[] dataToWrite = new byte[MaximumWriteSize];
rand.NextBytes(dataToWrite);
string writeFileName = GetTestFilePath();
do
{
// Create a new token that expires between 100-1000ms
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(rand.Next(100, 1000));
using (var stream = new FileStream(writeFileName, FileMode.Create, FileAccess.Write))
{
do
{
try
{
// 20%: random write size
int bytesToWrite = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumWriteSize) : NormalWriteSize);
if (rand.NextDouble() < 0.1)
{
// 10%: Sync write
stream.Write(dataToWrite, 0, bytesToWrite);
}
else
{
// 90%: Async write
await WriteAsync(stream, dataToWrite, 0, bytesToWrite, tokenSource.Token);
}
}
catch (TaskCanceledException)
{
Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired");
}
} while (!tokenSource.Token.IsCancellationRequested);
}
} while (DateTime.UtcNow - testStartTime <= testRunTime);
}
}
public class FileStream_WriteAsync_AsyncWrites : FileStream_AsyncWrites
{
protected override Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
stream.WriteAsync(buffer, offset, count, cancellationToken);
[Fact]
public void CancelledTokenFastPath()
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
CancellationToken cancelledToken = cts.Token;
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// before read only check
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
fs.Dispose();
// before disposed check
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
// out of bounds checking happens first
Assert.Throws<ArgumentException>(null, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2, cancelledToken)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(CountParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, -1, cancelledToken)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>(OffsetParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, -1, cancelledToken)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>(BufferParamName, () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, -1, cancelledToken)));
}
}
}
public class FileStream_BeginEndWrite_AsyncWrites : FileStream_AsyncWrites
{
protected override Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
Task.Factory.FromAsync(
(callback, state) => stream.BeginWrite(buffer, offset, count, callback, state),
iar => stream.EndWrite(iar),
null);
protected override string BufferParamName => "array";
protected override string CountParamName => "numBytes";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
public class StringInfo
{
[OptionalField(VersionAdded = 2)]
private string _str;
[NonSerialized]
private int[] _indexes;
// Legacy constructor
public StringInfo() : this("") { }
// Primary, useful constructor
public StringInfo(string value)
{
this.String = value;
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
_str = String.Empty;
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if (_str.Length == 0)
{
_indexes = null;
}
}
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (_str.Equals(that._str));
}
return (false);
}
public override int GetHashCode()
{
return _str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes
{
get
{
if ((null == _indexes) && (0 < this.String.Length))
{
_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return (_indexes);
}
}
public string String
{
get
{
return (_str);
}
set
{
if (null == value)
{
throw new ArgumentNullException(nameof(String),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
_str = value;
_indexes = null;
}
}
public int LengthInTextElements
{
get
{
if (null == this.Indexes)
{
// Indexes not initialized, so assume length zero
return (0);
}
return (this.Indexes.Length);
}
}
public string SubstringByTextElements(int startingTextElement)
{
// If the string is empty, no sense going further.
if (null == this.Indexes)
{
// Just decide which error to give depending on the param they gave us....
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
else
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
}
return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement));
}
public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
if (this.String.Length == 0 || startingTextElement >= Indexes.Length)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
if (lengthInTextElements < 0)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum);
}
if (startingTextElement > Indexes.Length - lengthInTextElements)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException);
}
int start = Indexes[startingTextElement];
if (startingTextElement + lengthInTextElements == Indexes.Length)
{
// We are at the last text element in the string and because of that
// must handle the call differently.
return (this.String.Substring(start));
}
else
{
return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
public static string GetNextTextElement(string str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static string GetNextTextElement(string str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return (String.Empty);
}
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| |
/* 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:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 XenAdmin.Network;
using XenAPI;
using XenAdmin.Core;
using System.Xml;
namespace XenAdmin.CustomFields
{
/// <summary>
/// Provide custom fields management support for VMs. The master list of custom fields will be
/// maintained in the pool class using the same conventions as the tags implementation (see
/// XenAdmin.XenSearch.Tags). When persisting the label-value pairs in the VMs, the
/// following key/value convention will be used:
/// "XenCenter.CustomFields.foo1" value
/// "XenCenter.CustomFields.foo2" value
/// </summary>
public class CustomFieldsManager
{
#region These functions deal with caching the list of custom fields
private static readonly CustomFieldsCache customFieldsCache = new CustomFieldsCache();
private const String CUSTOM_FIELD_DELIM = ".";
public const String CUSTOM_FIELD_BASE_KEY = "XenCenter.CustomFields";
public const String CUSTOM_FIELD = "CustomField:";
public static event Action CustomFieldsChanged;
static CustomFieldsManager()
{
OtherConfigAndTagsWatcher.GuiConfigChanged += OtherConfigAndTagsWatcher_GuiConfigChanged;
}
private static void OtherConfigAndTagsWatcher_GuiConfigChanged()
{
InvokeHelper.AssertOnEventThread();
customFieldsCache.RecalculateCustomFields();
OnCustomFieldsChanged();
}
private static void OnCustomFieldsChanged()
{
Action handler = CustomFieldsChanged;
if (handler != null)
{
handler();
}
}
#endregion
#region These functions deal with custom field definitions on the pool object
public static List<CustomFieldDefinition> GetCustomFields()
{
return customFieldsCache.GetCustomFields();
}
public static List<CustomFieldDefinition> GetCustomFields(IXenConnection connection)
{
return customFieldsCache.GetCustomFields(connection);
}
/// <returns>The CustomFieldDefinition with the given name, or null if none is found.</returns>
public static CustomFieldDefinition GetCustomFieldDefinition(string name)
{
foreach (CustomFieldDefinition d in GetCustomFields())
{
if (d.Name == name)
return d;
}
return null;
}
public static void RemoveCustomField(Session session, IXenConnection connection, CustomFieldDefinition definition)
{
List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection);
if (customFields.Remove(definition))
{
SaveCustomFields(session, connection, customFields);
// Remove from all Objects
RemoveCustomFieldsFrom(session, connection.Cache.VMs, definition);
RemoveCustomFieldsFrom(session, connection.Cache.Hosts, definition);
RemoveCustomFieldsFrom(session, connection.Cache.Pools, definition);
RemoveCustomFieldsFrom(session, connection.Cache.SRs, definition);
}
}
public static void AddCustomField(Session session, IXenConnection connection, CustomFieldDefinition customField)
{
List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection);
if (!customFields.Contains(customField))
{
customFields.Add(customField);
SaveCustomFields(session, connection, customFields);
}
}
private static String GetCustomFieldDefinitionXML(List<CustomFieldDefinition> customFieldDefinitions)
{
XmlDocument doc = new XmlDocument();
XmlNode parentNode = doc.CreateElement("CustomFieldDefinitions");
doc.AppendChild(parentNode);
foreach (CustomFieldDefinition customFieldDefinition in customFieldDefinitions)
{
parentNode.AppendChild(customFieldDefinition.ToXmlNode(doc));
}
return doc.OuterXml;
}
#endregion
#region These functions deal with the custom fields themselves
public static string GetCustomFieldKey(CustomFieldDefinition customFieldDefinition)
{
return CUSTOM_FIELD_BASE_KEY + CUSTOM_FIELD_DELIM + customFieldDefinition.Name;
}
private static void RemoveCustomFieldsFrom(Session session, IEnumerable<IXenObject> os, CustomFieldDefinition customFieldDefinition)
{
InvokeHelper.AssertOffEventThread();
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
foreach (IXenObject o in os)
{
Helpers.RemoveFromOtherConfig(session, o, customFieldKey);
}
}
private static void SaveCustomFields(Session session, IXenConnection connection, List<CustomFieldDefinition> customFields)
{
Pool pool = Helpers.GetPoolOfOne(connection);
if (pool != null)
{
String customFieldXML = GetCustomFieldDefinitionXML(customFields);
Helpers.SetGuiConfig(session, pool, CUSTOM_FIELD_BASE_KEY, customFieldXML);
}
}
public static List<CustomField> CustomFieldValues(IXenObject o)
{
//Program.AssertOnEventThread();
List<CustomField> customFields = new List<CustomField>();
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig != null)
{
foreach (CustomFieldDefinition customFieldDefinition in customFieldsCache.GetCustomFields(o.Connection))
{
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
if (!otherConfig.ContainsKey(customFieldKey) || otherConfig[customFieldKey] == String.Empty)
{
continue;
}
object value = ParseValue(customFieldDefinition.Type, otherConfig[customFieldKey]);
if (value != null)
{
customFields.Add(new CustomField(customFieldDefinition, value));
}
}
}
return customFields;
}
// The same as CustomFieldValues(), but with each custom field unwound into an array
public static List<object[]> CustomFieldArrays(IXenObject o)
{
List<object[]> ans = new List<object[]>();
foreach (CustomField cf in CustomFieldValues(o))
{
ans.Add(cf.ToArray());
}
return ans;
}
// Whether the object has any custom fields defined
public static bool HasCustomFields(IXenObject o)
{
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig != null)
{
foreach (CustomFieldDefinition customFieldDefinition in GetCustomFields(o.Connection))
{
string customFieldKey = GetCustomFieldKey(customFieldDefinition);
if (otherConfig.ContainsKey(customFieldKey) && otherConfig[customFieldKey] != String.Empty)
{
return true;
}
}
}
return false;
}
public static Object GetCustomFieldValue(IXenObject o, CustomFieldDefinition customFieldDefinition)
{
Dictionary<String, String> otherConfig = GetOtherConfigCopy(o);
if (otherConfig == null)
return null;
String key = GetCustomFieldKey(customFieldDefinition);
if (!otherConfig.ContainsKey(key))
return null;
String value = otherConfig[key];
if (value == String.Empty)
return null;
return ParseValue(customFieldDefinition.Type, value);
}
private static object ParseValue(CustomFieldDefinition.Types type, string value)
{
switch (type)
{
case CustomFieldDefinition.Types.Date:
DateTime datetime;
if (DateTime.TryParse(value, out datetime))
return datetime;
return null;
case CustomFieldDefinition.Types.String:
return value;
default:
return null;
}
}
private static Dictionary<string, string> GetOtherConfigCopy(IXenObject o)
{
Dictionary<string, string> output = new Dictionary<string, string>();
InvokeHelper.Invoke(delegate()
{
Dictionary<String, String> otherConfig = Helpers.GetOtherConfig(o);
if (otherConfig == null)
{
output = null;
}
else
{
output = new Dictionary<string, string>(otherConfig);
}
});
return output;
}
#endregion
}
}
| |
using System.Text;
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using SpotifyAPI.Web.Http;
namespace SpotifyAPI.Web
{
public class OAuthClient : APIClient, IOAuthClient
{
public OAuthClient() : this(SpotifyClientConfig.CreateDefault()) { }
public OAuthClient(IAPIConnector apiConnector) : base(apiConnector) { }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062")]
public OAuthClient(SpotifyClientConfig config) : base(ValidateConfig(config)) { }
/// <summary>
/// Requests a new token using pkce flow
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
/// </remarks>
/// <returns></returns>1
public Task<PKCETokenResponse> RequestToken(PKCETokenRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Refreshes a token using pkce flow
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
/// </remarks>
/// <returns></returns>1
public Task<PKCETokenResponse> RequestToken(PKCETokenRefreshRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Requests a new token using client_ids and client_secrets.
/// If the token is expired, simply call the funtion again to get a new token
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow
/// </remarks>
/// <returns></returns>1
public Task<ClientCredentialsTokenResponse> RequestToken(ClientCredentialsRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Refresh an already received token via Authorization Code Auth
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
/// </remarks>
/// <returns></returns>
public Task<AuthorizationCodeRefreshResponse> RequestToken(AuthorizationCodeRefreshRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Reequest an initial token via Authorization Code Auth
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
/// </remarks>
/// <returns></returns>
public Task<AuthorizationCodeTokenResponse> RequestToken(AuthorizationCodeTokenRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Swaps out a received code with a access token using a remote server
/// </summary>
/// <param name="request">The request-model which contains required and optional parameters.</param>
/// <remarks>
/// https://developer.spotify.com/documentation/ios/guides/token-swap-and-refresh/
/// </remarks>
/// <returns></returns>
public Task<AuthorizationCodeTokenResponse> RequestToken(TokenSwapTokenRequest request)
{
return RequestToken(request, API);
}
/// <summary>
/// Gets a refreshed access token using an already received refresh token using a remote server
/// </summary>
/// <param name="request"></param>
/// <remarks>
/// https://developer.spotify.com/documentation/ios/guides/token-swap-and-refresh/
/// </remarks>
/// <returns></returns>
public Task<AuthorizationCodeRefreshResponse> RequestToken(TokenSwapRefreshRequest request)
{
return RequestToken(request, API);
}
public static Task<PKCETokenResponse> RequestToken(PKCETokenRequest request, IAPIConnector apiConnector)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("client_id", request.ClientId),
new KeyValuePair<string?, string?>("grant_type", "authorization_code"),
new KeyValuePair<string?, string?>("code", request.Code),
new KeyValuePair<string?, string?>("redirect_uri", request.RedirectUri.ToString()),
new KeyValuePair<string?, string?>("code_verifier", request.CodeVerifier),
};
return SendOAuthRequest<PKCETokenResponse>(apiConnector, form, null, null);
}
public static Task<PKCETokenResponse> RequestToken(PKCETokenRefreshRequest request, IAPIConnector apiConnector)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("client_id", request.ClientId),
new KeyValuePair<string?, string?>("grant_type", "refresh_token"),
new KeyValuePair<string?, string?>("refresh_token", request.RefreshToken),
};
return SendOAuthRequest<PKCETokenResponse>(apiConnector, form, null, null);
}
public static Task<AuthorizationCodeRefreshResponse> RequestToken(
TokenSwapRefreshRequest request, IAPIConnector apiConnector
)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("refresh_token", request.RefreshToken)
};
#pragma warning disable CA2000
return apiConnector.Post<AuthorizationCodeRefreshResponse>(
request.RefreshUri, null, new FormUrlEncodedContent(form)
);
#pragma warning restore CA2000
}
public static Task<AuthorizationCodeTokenResponse> RequestToken(
TokenSwapTokenRequest request, IAPIConnector apiConnector
)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("code", request.Code)
};
#pragma warning disable CA2000
return apiConnector.Post<AuthorizationCodeTokenResponse>(
request.TokenUri, null, new FormUrlEncodedContent(form)
);
#pragma warning restore CA2000
}
public static Task<ClientCredentialsTokenResponse> RequestToken(
ClientCredentialsRequest request, IAPIConnector apiConnector
)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("grant_type", "client_credentials")
};
return SendOAuthRequest<ClientCredentialsTokenResponse>(apiConnector, form, request.ClientId, request.ClientSecret);
}
public static Task<AuthorizationCodeRefreshResponse> RequestToken(
AuthorizationCodeRefreshRequest request, IAPIConnector apiConnector
)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("grant_type", "refresh_token"),
new KeyValuePair<string?, string?>("refresh_token", request.RefreshToken)
};
return SendOAuthRequest<AuthorizationCodeRefreshResponse>(apiConnector, form, request.ClientId, request.ClientSecret);
}
public static Task<AuthorizationCodeTokenResponse> RequestToken(
AuthorizationCodeTokenRequest request, IAPIConnector apiConnector
)
{
Ensure.ArgumentNotNull(request, nameof(request));
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
var form = new List<KeyValuePair<string?, string?>>
{
new KeyValuePair<string?, string?>("grant_type", "authorization_code"),
new KeyValuePair<string?, string?>("code", request.Code),
new KeyValuePair<string?, string?>("redirect_uri", request.RedirectUri.ToString())
};
return SendOAuthRequest<AuthorizationCodeTokenResponse>(apiConnector, form, request.ClientId, request.ClientSecret);
}
private static Task<T> SendOAuthRequest<T>(
IAPIConnector apiConnector,
List<KeyValuePair<string?, string?>> form,
string? clientId,
string? clientSecret)
{
var headers = BuildAuthHeader(clientId, clientSecret);
#pragma warning disable CA2000
return apiConnector.Post<T>(SpotifyUrls.OAuthToken, null, new FormUrlEncodedContent(form), headers);
#pragma warning restore CA2000
}
private static Dictionary<string, string> BuildAuthHeader(string? clientId, string? clientSecret)
{
if (clientId == null || clientSecret == null)
{
return new Dictionary<string, string>();
}
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
return new Dictionary<string, string>
{
{ "Authorization", $"Basic {base64}"}
};
}
private static APIConnector ValidateConfig(SpotifyClientConfig config)
{
Ensure.ArgumentNotNull(config, nameof(config));
return new APIConnector(
config.BaseAddress,
config.Authenticator,
config.JSONSerializer,
config.HTTPClient,
config.RetryHandler,
config.HTTPLogger
);
}
}
}
| |
namespace gView.Framework.UI.Dialogs
{
partial class FormQueryBuilder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormQueryBuilder));
this.cmbMethod = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.lstFields = new System.Windows.Forms.ListBox();
this.label2 = new System.Windows.Forms.Label();
this.lstUniqueValues = new System.Windows.Forms.ListBox();
this.label3 = new System.Windows.Forms.Label();
this.txtWhereClause = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button12 = new System.Windows.Forms.Button();
this.btnCompleteList = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// cmbMethod
//
this.cmbMethod.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbMethod.FormattingEnabled = true;
this.cmbMethod.Items.AddRange(new object[] {
resources.GetString("cmbMethod.Items"),
resources.GetString("cmbMethod.Items1"),
resources.GetString("cmbMethod.Items2"),
resources.GetString("cmbMethod.Items3")});
resources.ApplyResources(this.cmbMethod, "cmbMethod");
this.cmbMethod.Name = "cmbMethod";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// lstFields
//
this.lstFields.FormattingEnabled = true;
resources.ApplyResources(this.lstFields, "lstFields");
this.lstFields.Name = "lstFields";
this.lstFields.SelectedIndexChanged += new System.EventHandler(this.lstFields_SelectedIndexChanged);
this.lstFields.DoubleClick += new System.EventHandler(this.lstFields_DoubleClick);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// lstUniqueValues
//
this.lstUniqueValues.FormattingEnabled = true;
resources.ApplyResources(this.lstUniqueValues, "lstUniqueValues");
this.lstUniqueValues.Name = "lstUniqueValues";
this.lstUniqueValues.DoubleClick += new System.EventHandler(this.lstUniqueValues_DoubleClick);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// txtWhereClause
//
resources.ApplyResources(this.txtWhereClause, "txtWhereClause");
this.txtWhereClause.Name = "txtWhereClause";
//
// button1
//
resources.ApplyResources(this.button1, "button1");
this.button1.Name = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
resources.ApplyResources(this.button2, "button2");
this.button2.Name = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button1_Click);
//
// button3
//
resources.ApplyResources(this.button3, "button3");
this.button3.Name = "button3";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button1_Click);
//
// button4
//
resources.ApplyResources(this.button4, "button4");
this.button4.Name = "button4";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button1_Click);
//
// button5
//
resources.ApplyResources(this.button5, "button5");
this.button5.Name = "button5";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button1_Click);
//
// button6
//
resources.ApplyResources(this.button6, "button6");
this.button6.Name = "button6";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button1_Click);
//
// button7
//
resources.ApplyResources(this.button7, "button7");
this.button7.Name = "button7";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button1_Click);
//
// button8
//
resources.ApplyResources(this.button8, "button8");
this.button8.Name = "button8";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button1_Click);
//
// button9
//
resources.ApplyResources(this.button9, "button9");
this.button9.Name = "button9";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button1_Click);
//
// button10
//
resources.ApplyResources(this.button10, "button10");
this.button10.Name = "button10";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button1_Click);
//
// button11
//
resources.ApplyResources(this.button11, "button11");
this.button11.Name = "button11";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button1_Click);
//
// button12
//
resources.ApplyResources(this.button12, "button12");
this.button12.Name = "button12";
this.button12.UseVisualStyleBackColor = true;
this.button12.Click += new System.EventHandler(this.button1_Click);
//
// btnCompleteList
//
resources.ApplyResources(this.btnCompleteList, "btnCompleteList");
this.btnCompleteList.Name = "btnCompleteList";
this.btnCompleteList.UseVisualStyleBackColor = true;
this.btnCompleteList.Click += new System.EventHandler(this.btnCompleteList_Click);
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// FormQueryBuilder
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.label4);
this.Controls.Add(this.btnCompleteList);
this.Controls.Add(this.button10);
this.Controls.Add(this.button11);
this.Controls.Add(this.button12);
this.Controls.Add(this.button7);
this.Controls.Add(this.button8);
this.Controls.Add(this.button9);
this.Controls.Add(this.button4);
this.Controls.Add(this.button5);
this.Controls.Add(this.button6);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtWhereClause);
this.Controls.Add(this.label3);
this.Controls.Add(this.lstUniqueValues);
this.Controls.Add(this.label2);
this.Controls.Add(this.lstFields);
this.Controls.Add(this.label1);
this.Controls.Add(this.cmbMethod);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "FormQueryBuilder";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FormQueryBuilder_KeyDown);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbMethod;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ListBox lstFields;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListBox lstUniqueValues;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtWhereClause;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.Button btnCompleteList;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
}
}
| |
//
// System.Web.Security.FormsAuthenticationTicket
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002 Ximian, Inc (http://www.ximian.com)
// Copyright (c) 2005 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace System.Web.Security
{
[Serializable]
public sealed class FormsAuthenticationTicket
{
int version;
bool persistent;
DateTime issue_date;
DateTime expiration;
string name;
string cookie_path;
string user_data;
/*
internal void ToStr ()
{
Console.WriteLine ("version: {0}", version);
Console.WriteLine ("persistent: {0}", persistent);
Console.WriteLine ("issue_date: {0}", issue_date);
Console.WriteLine ("expiration: {0}", expiration);
Console.WriteLine ("name: {0}", name);
Console.WriteLine ("cookie_path: {0}", cookie_path);
Console.WriteLine ("user_data: {0}", user_data);
}
*/
internal byte [] ToByteArray ()
{
MemoryStream ms = new MemoryStream ();
BinaryWriter writer = new BinaryWriter (ms);
writer.Write (version);
writer.Write (persistent);
writer.Write (issue_date.Ticks);
writer.Write (expiration.Ticks);
writer.Write (name != null);
if (name != null)
writer.Write (name);
writer.Write (cookie_path != null);
if (cookie_path != null)
writer.Write (cookie_path);
writer.Write (user_data != null);
if (user_data != null)
writer.Write (user_data);
writer.Flush ();
return ms.ToArray ();
}
internal static FormsAuthenticationTicket FromByteArray (byte [] bytes)
{
MemoryStream ms = new MemoryStream (bytes);
BinaryReader reader = new BinaryReader (ms);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket ();
ticket.version = reader.ReadInt32 ();
ticket.persistent = reader.ReadBoolean ();
ticket.issue_date = new DateTime (reader.ReadInt64 ());
ticket.expiration = new DateTime (reader.ReadInt64 ());
if (reader.ReadBoolean ())
ticket.name = reader.ReadString ();
if (reader.ReadBoolean ())
ticket.cookie_path = reader.ReadString ();
if (reader.ReadBoolean ())
ticket.user_data = reader.ReadString ();
return ticket;
}
private FormsAuthenticationTicket ()
{
}
public FormsAuthenticationTicket (int version,
string name,
DateTime issueDate,
DateTime expiration,
bool isPersistent,
string userData)
{
this.version = version;
this.name = name;
this.issue_date = issueDate;
this.expiration = expiration;
this.persistent = isPersistent;
this.user_data = userData;
this.cookie_path = "/";
}
public FormsAuthenticationTicket (int version,
string name,
DateTime issueDate,
DateTime expiration,
bool isPersistent,
string userData,
string cookiePath)
{
this.version = version;
this.name = name;
this.issue_date = issueDate;
this.expiration = expiration;
this.persistent = isPersistent;
this.user_data = userData;
this.cookie_path = cookiePath;
}
public FormsAuthenticationTicket (string name, bool isPersistent, int timeout)
{
this.version = 1;
this.name = name;
this.issue_date = DateTime.Now;
this.persistent = isPersistent;
if (persistent)
expiration = issue_date.AddYears (50);
else
expiration = issue_date.AddMinutes ((double) timeout);
this.user_data = "";
this.cookie_path = "/";
}
internal void SetDates (DateTime issue_date, DateTime expiration)
{
this.issue_date = issue_date;
this.expiration = expiration;
}
internal FormsAuthenticationTicket Clone ()
{
return new FormsAuthenticationTicket (version,
name,
issue_date,
expiration,
persistent,
user_data,
cookie_path);
}
public string CookiePath {
get { return cookie_path; }
}
public DateTime Expiration {
get { return expiration; }
}
public bool Expired {
get { return DateTime.Now > expiration; }
}
public bool IsPersistent {
get { return persistent; }
}
public DateTime IssueDate {
get { return issue_date; }
}
public string Name {
get { return name; }
}
public string UserData {
get { return user_data; }
}
public int Version {
get { return version; }
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Syndication
{
using System.Runtime;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;
// NOTE: This class implements Clone so if you add any members, please update the copy ctor
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public class XmlSyndicationContent : SyndicationContent
{
XmlBuffer contentBuffer;
SyndicationElementExtension extension;
string type;
// Saves the element in the reader to the buffer (attributes preserved)
// Type is populated from type attribute on reader
// Reader must be positioned at an element
public XmlSyndicationContent(XmlReader reader)
{
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
SyndicationFeedFormatter.MoveToStartElement(reader);
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string name = reader.LocalName;
string ns = reader.NamespaceURI;
string value = reader.Value;
if (name == Atom10Constants.TypeTag && ns == string.Empty)
{
this.type = value;
}
else if (!FeedUtils.IsXmlns(name, ns))
{
base.AttributeExtensions.Add(new XmlQualifiedName(name, ns), value);
}
}
reader.MoveToElement();
}
this.type = string.IsNullOrEmpty(this.type) ? Atom10Constants.XmlMediaType : this.type;
this.contentBuffer = new XmlBuffer(int.MaxValue);
using (XmlDictionaryWriter writer = this.contentBuffer.OpenSection(XmlDictionaryReaderQuotas.Max))
{
writer.WriteNode(reader, false);
}
contentBuffer.CloseSection();
contentBuffer.Close();
}
public XmlSyndicationContent(string type, object dataContractExtension, XmlObjectSerializer dataContractSerializer)
{
this.type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
this.extension = new SyndicationElementExtension(dataContractExtension, dataContractSerializer);
}
public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSerializer serializer)
{
this.type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
this.extension = new SyndicationElementExtension(xmlSerializerExtension, serializer);
}
public XmlSyndicationContent(string type, SyndicationElementExtension extension)
{
if (extension == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("extension");
}
this.type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
this.extension = extension;
}
protected XmlSyndicationContent(XmlSyndicationContent source)
: base(source)
{
if (source == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("source");
}
this.contentBuffer = source.contentBuffer;
this.extension = source.extension;
this.type = source.type;
}
public SyndicationElementExtension Extension
{
get
{
return this.extension;
}
}
public override string Type
{
get { return this.type; }
}
public override SyndicationContent Clone()
{
return new XmlSyndicationContent(this);
}
public XmlDictionaryReader GetReaderAtContent()
{
EnsureContentBuffer();
return this.contentBuffer.GetReader(0);
}
public TContent ReadContent<TContent>()
{
return ReadContent<TContent>((DataContractSerializer) null);
}
public TContent ReadContent<TContent>(XmlObjectSerializer dataContractSerializer)
{
if (dataContractSerializer == null)
{
dataContractSerializer = new DataContractSerializer(typeof(TContent));
}
if (this.extension != null)
{
return this.extension.GetObject<TContent>(dataContractSerializer);
}
else
{
Fx.Assert(this.contentBuffer != null, "contentBuffer cannot be null");
using (XmlDictionaryReader reader = this.contentBuffer.GetReader(0))
{
// skip past the content element
reader.ReadStartElement();
return (TContent) dataContractSerializer.ReadObject(reader, false);
}
}
}
public TContent ReadContent<TContent>(XmlSerializer serializer)
{
if (serializer == null)
{
serializer = new XmlSerializer(typeof(TContent));
}
if (this.extension != null)
{
return this.extension.GetObject<TContent>(serializer);
}
else
{
Fx.Assert(this.contentBuffer != null, "contentBuffer cannot be null");
using (XmlDictionaryReader reader = this.contentBuffer.GetReader(0))
{
// skip past the content element
reader.ReadStartElement();
return (TContent) serializer.Deserialize(reader);
}
}
}
// does not write start element or type attribute, writes other attributes and rest of content
protected override void WriteContentsTo(XmlWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (this.extension != null)
{
this.extension.WriteTo(writer);
}
else if (this.contentBuffer != null)
{
using (XmlDictionaryReader reader = this.contentBuffer.GetReader(0))
{
reader.MoveToStartElement();
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
while (reader.Depth >= 1 && reader.ReadState == ReadState.Interactive)
{
writer.WriteNode(reader, false);
}
}
}
}
}
void EnsureContentBuffer()
{
if (this.contentBuffer == null)
{
XmlBuffer tmp = new XmlBuffer(int.MaxValue);
using (XmlDictionaryWriter writer = tmp.OpenSection(XmlDictionaryReaderQuotas.Max))
{
this.WriteTo(writer, Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace);
}
tmp.CloseSection();
tmp.Close();
this.contentBuffer = tmp;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
// XmlTextEncoder
//
// This class does special handling of text content for XML. For example
// it will replace special characters with entities whenever necessary.
internal class XmlTextEncoder
{
//
// Fields
//
// output text writer
private TextWriter _textWriter;
// true when writing out the content of attribute value
private bool _inAttribute;
// quote char of the attribute (when inAttribute)
private char _quoteChar;
// caching of attribute value
private StringBuilder _attrValue;
private bool _cacheAttrValue;
// XmlCharType
private XmlCharType _xmlCharType;
//
// Constructor
//
internal XmlTextEncoder(TextWriter textWriter)
{
_textWriter = textWriter;
_quoteChar = '"';
_xmlCharType = XmlCharType.Instance;
}
//
// Internal methods and properties
//
internal char QuoteChar
{
set
{
_quoteChar = value;
}
}
internal void StartAttribute(bool cacheAttrValue)
{
_inAttribute = true;
_cacheAttrValue = cacheAttrValue;
if (cacheAttrValue)
{
if (_attrValue == null)
{
_attrValue = new StringBuilder();
}
else
{
_attrValue.Length = 0;
}
}
}
internal void EndAttribute()
{
if (_cacheAttrValue)
{
_attrValue.Length = 0;
}
_inAttribute = false;
_cacheAttrValue = false;
}
internal string AttributeValue
{
get
{
if (_cacheAttrValue)
{
return _attrValue.ToString();
}
else
{
return String.Empty;
}
}
}
internal void WriteSurrogateChar(char lowChar, char highChar)
{
if (!XmlCharType.IsLowSurrogate(lowChar) ||
!XmlCharType.IsHighSurrogate(highChar))
{
throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar);
}
_textWriter.Write(highChar);
_textWriter.Write(lowChar);
}
[System.Security.SecurityCritical]
internal void Write(char[] array, int offset, int count)
{
if (null == array)
{
throw new ArgumentNullException("array");
}
if (0 > offset)
{
throw new ArgumentOutOfRangeException("offset");
}
if (0 > count)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > array.Length - offset)
{
throw new ArgumentOutOfRangeException("count");
}
if (_cacheAttrValue)
{
_attrValue.Append(array, offset, count);
}
int endPos = offset + count;
int i = offset;
char ch = (char)0;
for (; ;)
{
int startPos = i;
unsafe
{
while (i < endPos && _xmlCharType.IsAttributeValueChar(ch = array[i]))
{
i++;
}
}
if (startPos < i)
{
_textWriter.Write(array, startPos, i - startPos);
}
if (i == endPos)
{
break;
}
switch (ch)
{
case (char)0x9:
_textWriter.Write(ch);
break;
case (char)0xA:
case (char)0xD:
if (_inAttribute)
{
WriteCharEntityImpl(ch);
}
else
{
_textWriter.Write(ch);
}
break;
case '<':
WriteEntityRefImpl("lt");
break;
case '>':
WriteEntityRefImpl("gt");
break;
case '&':
WriteEntityRefImpl("amp");
break;
case '\'':
if (_inAttribute && _quoteChar == ch)
{
WriteEntityRefImpl("apos");
}
else
{
_textWriter.Write('\'');
}
break;
case '"':
if (_inAttribute && _quoteChar == ch)
{
WriteEntityRefImpl("quot");
}
else
{
_textWriter.Write('"');
}
break;
default:
if (XmlCharType.IsHighSurrogate(ch))
{
if (i + 1 < endPos)
{
WriteSurrogateChar(array[++i], ch);
}
else
{
throw new ArgumentException(SR.Xml_SurrogatePairSplit);
}
}
else if (XmlCharType.IsLowSurrogate(ch))
{
throw XmlConvert.CreateInvalidHighSurrogateCharException(ch);
}
else
{
Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD));
WriteCharEntityImpl(ch);
}
break;
}
i++;
}
}
internal void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (!XmlCharType.IsLowSurrogate(lowChar) ||
!XmlCharType.IsHighSurrogate(highChar))
{
throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar);
}
int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar);
if (_cacheAttrValue)
{
_attrValue.Append(highChar);
_attrValue.Append(lowChar);
}
_textWriter.Write("&#x");
_textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo));
_textWriter.Write(';');
}
[System.Security.SecurityCritical]
internal void Write(string text)
{
if (text == null)
{
return;
}
if (_cacheAttrValue)
{
_attrValue.Append(text);
}
// scan through the string to see if there are any characters to be escaped
int len = text.Length;
int i = 0;
int startPos = 0;
char ch = (char)0;
for (; ;)
{
unsafe
{
while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i]))
{
i++;
}
}
if (i == len)
{
// reached the end of the string -> write it whole out
_textWriter.Write(text);
return;
}
if (_inAttribute)
{
if (ch == 0x9)
{
i++;
continue;
}
}
else
{
if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'')
{
i++;
continue;
}
}
// some character that needs to be escaped is found:
break;
}
char[] helperBuffer = new char[256];
for (; ;)
{
if (startPos < i)
{
WriteStringFragment(text, startPos, i - startPos, helperBuffer);
}
if (i == len)
{
break;
}
switch (ch)
{
case (char)0x9:
_textWriter.Write(ch);
break;
case (char)0xA:
case (char)0xD:
if (_inAttribute)
{
WriteCharEntityImpl(ch);
}
else
{
_textWriter.Write(ch);
}
break;
case '<':
WriteEntityRefImpl("lt");
break;
case '>':
WriteEntityRefImpl("gt");
break;
case '&':
WriteEntityRefImpl("amp");
break;
case '\'':
if (_inAttribute && _quoteChar == ch)
{
WriteEntityRefImpl("apos");
}
else
{
_textWriter.Write('\'');
}
break;
case '"':
if (_inAttribute && _quoteChar == ch)
{
WriteEntityRefImpl("quot");
}
else
{
_textWriter.Write('"');
}
break;
default:
if (XmlCharType.IsHighSurrogate(ch))
{
if (i + 1 < len)
{
WriteSurrogateChar(text[++i], ch);
}
else
{
throw XmlConvert.CreateInvalidSurrogatePairException(text[i], ch);
}
}
else if (XmlCharType.IsLowSurrogate(ch))
{
throw XmlConvert.CreateInvalidHighSurrogateCharException(ch);
}
else
{
Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD));
WriteCharEntityImpl(ch);
}
break;
}
i++;
startPos = i;
unsafe
{
while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i]))
{
i++;
}
}
}
}
[System.Security.SecurityCritical]
internal void WriteRawWithSurrogateChecking(string text)
{
if (text == null)
{
return;
}
if (_cacheAttrValue)
{
_attrValue.Append(text);
}
int len = text.Length;
int i = 0;
char ch = (char)0;
for (; ;)
{
unsafe
{
while (i < len && (_xmlCharType.IsCharData(ch = text[i]) || ch < 0x20))
{
i++;
}
}
if (i == len)
{
break;
}
if (XmlCharType.IsHighSurrogate(ch))
{
if (i + 1 < len)
{
char lowChar = text[i + 1];
if (XmlCharType.IsLowSurrogate(lowChar))
{
i += 2;
continue;
}
else
{
throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, ch);
}
}
throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar);
}
else if (XmlCharType.IsLowSurrogate(ch))
{
throw XmlConvert.CreateInvalidHighSurrogateCharException(ch);
}
else
{
i++;
}
}
_textWriter.Write(text);
return;
}
internal void WriteRaw(string value)
{
if (_cacheAttrValue)
{
_attrValue.Append(value);
}
_textWriter.Write(value);
}
internal void WriteRaw(char[] array, int offset, int count)
{
if (null == array)
{
throw new ArgumentNullException("array");
}
if (0 > count)
{
throw new ArgumentOutOfRangeException("count");
}
if (0 > offset)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count > array.Length - offset)
{
throw new ArgumentOutOfRangeException("count");
}
if (_cacheAttrValue)
{
_attrValue.Append(array, offset, count);
}
_textWriter.Write(array, offset, count);
}
internal void WriteCharEntity(char ch)
{
if (XmlCharType.IsSurrogate(ch))
{
throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar);
}
string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo);
if (_cacheAttrValue)
{
_attrValue.Append("&#x");
_attrValue.Append(strVal);
_attrValue.Append(';');
}
WriteCharEntityImpl(strVal);
}
internal void WriteEntityRef(string name)
{
if (_cacheAttrValue)
{
_attrValue.Append('&');
_attrValue.Append(name);
_attrValue.Append(';');
}
WriteEntityRefImpl(name);
}
internal void Flush()
{
}
//
// Private implementation methods
//
// This is a helper method to workaround the fact that TextWriter does not have a Write method
// for fragment of a string such as Write( string, offset, count).
// The string fragment will be written out by copying into a small helper buffer and then
// calling textWriter to write out the buffer.
private void WriteStringFragment(string str, int offset, int count, char[] helperBuffer)
{
int bufferSize = helperBuffer.Length;
while (count > 0)
{
int copyCount = count;
if (copyCount > bufferSize)
{
copyCount = bufferSize;
}
str.CopyTo(offset, helperBuffer, 0, copyCount);
_textWriter.Write(helperBuffer, 0, copyCount);
offset += copyCount;
count -= copyCount;
}
}
private void WriteCharEntityImpl(char ch)
{
WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo));
}
private void WriteCharEntityImpl(string strVal)
{
_textWriter.Write("&#x");
_textWriter.Write(strVal);
_textWriter.Write(';');
}
private void WriteEntityRefImpl(string name)
{
_textWriter.Write('&');
_textWriter.Write(name);
_textWriter.Write(';');
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: unittest_issues.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace UnitTest.Issues.TestProtos {
/// <summary>Holder for reflection information generated from unittest_issues.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestIssuesReflection {
#region Descriptor
/// <summary>File descriptor for unittest_issues.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UnittestIssuesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChV1bml0dGVzdF9pc3N1ZXMucHJvdG8SD3VuaXR0ZXN0X2lzc3VlcyInCghJ",
"c3N1ZTMwNxobCgpOZXN0ZWRPbmNlGg0KC05lc3RlZFR3aWNlIrABChNOZWdh",
"dGl2ZUVudW1NZXNzYWdlEiwKBXZhbHVlGAEgASgOMh0udW5pdHRlc3RfaXNz",
"dWVzLk5lZ2F0aXZlRW51bRIxCgZ2YWx1ZXMYAiADKA4yHS51bml0dGVzdF9p",
"c3N1ZXMuTmVnYXRpdmVFbnVtQgIQABI4Cg1wYWNrZWRfdmFsdWVzGAMgAygO",
"Mh0udW5pdHRlc3RfaXNzdWVzLk5lZ2F0aXZlRW51bUICEAEiEQoPRGVwcmVj",
"YXRlZENoaWxkIrkCChdEZXByZWNhdGVkRmllbGRzTWVzc2FnZRIaCg5Qcmlt",
"aXRpdmVWYWx1ZRgBIAEoBUICGAESGgoOUHJpbWl0aXZlQXJyYXkYAiADKAVC",
"AhgBEjoKDE1lc3NhZ2VWYWx1ZRgDIAEoCzIgLnVuaXR0ZXN0X2lzc3Vlcy5E",
"ZXByZWNhdGVkQ2hpbGRCAhgBEjoKDE1lc3NhZ2VBcnJheRgEIAMoCzIgLnVu",
"aXR0ZXN0X2lzc3Vlcy5EZXByZWNhdGVkQ2hpbGRCAhgBEjYKCUVudW1WYWx1",
"ZRgFIAEoDjIfLnVuaXR0ZXN0X2lzc3Vlcy5EZXByZWNhdGVkRW51bUICGAES",
"NgoJRW51bUFycmF5GAYgAygOMh8udW5pdHRlc3RfaXNzdWVzLkRlcHJlY2F0",
"ZWRFbnVtQgIYASIZCglJdGVtRmllbGQSDAoEaXRlbRgBIAEoBSJECg1SZXNl",
"cnZlZE5hbWVzEg0KBXR5cGVzGAEgASgFEhIKCmRlc2NyaXB0b3IYAiABKAUa",
"EAoOU29tZU5lc3RlZFR5cGUioAEKFVRlc3RKc29uRmllbGRPcmRlcmluZxIT",
"CgtwbGFpbl9pbnQzMhgEIAEoBRITCglvMV9zdHJpbmcYAiABKAlIABISCghv",
"MV9pbnQzMhgFIAEoBUgAEhQKDHBsYWluX3N0cmluZxgBIAEoCRISCghvMl9p",
"bnQzMhgGIAEoBUgBEhMKCW8yX3N0cmluZxgDIAEoCUgBQgQKAm8xQgQKAm8y",
"KlUKDE5lZ2F0aXZlRW51bRIWChJORUdBVElWRV9FTlVNX1pFUk8QABIWCglG",
"aXZlQmVsb3cQ+///////////ARIVCghNaW51c09uZRD///////////8BKi4K",
"DkRlcHJlY2F0ZWRFbnVtEhMKD0RFUFJFQ0FURURfWkVSTxAAEgcKA29uZRAB",
"Qh9IAaoCGlVuaXRUZXN0Lklzc3Vlcy5UZXN0UHJvdG9zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307), global::UnitTest.Issues.TestProtos.Issue307.Parser, null, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Parser, null, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice.Parser, null, null, null, null)})}),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.NegativeEnumMessage), global::UnitTest.Issues.TestProtos.NegativeEnumMessage.Parser, new[]{ "Value", "Values", "PackedValues" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedChild), global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser, null, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage), global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage.Parser, new[]{ "PrimitiveValue", "PrimitiveArray", "MessageValue", "MessageArray", "EnumValue", "EnumArray" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), global::UnitTest.Issues.TestProtos.ItemField.Parser, new[]{ "Item" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), global::UnitTest.Issues.TestProtos.ReservedNames.Parser, new[]{ "Types_", "Descriptor_" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType.Parser, null, null, null, null)}),
new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering.Parser, new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null)
}));
}
#endregion
}
#region Enums
public enum NegativeEnum {
NEGATIVE_ENUM_ZERO = 0,
FiveBelow = -5,
MinusOne = -1,
}
public enum DeprecatedEnum {
DEPRECATED_ZERO = 0,
one = 1,
}
#endregion
#region Messages
/// <summary>
/// Issue 307: when generating doubly-nested types, any references
/// should be of the form A.Types.B.Types.C.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Issue307 : pb::IMessage<Issue307> {
private static readonly pb::MessageParser<Issue307> _parser = new pb::MessageParser<Issue307>(() => new Issue307());
public static pb::MessageParser<Issue307> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Issue307() {
OnConstruction();
}
partial void OnConstruction();
public Issue307(Issue307 other) : this() {
}
public Issue307 Clone() {
return new Issue307(this);
}
public override bool Equals(object other) {
return Equals(other as Issue307);
}
public bool Equals(Issue307 other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(Issue307 other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Issue307 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class NestedOnce : pb::IMessage<NestedOnce> {
private static readonly pb::MessageParser<NestedOnce> _parser = new pb::MessageParser<NestedOnce>(() => new NestedOnce());
public static pb::MessageParser<NestedOnce> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.Issue307.Descriptor.NestedTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public NestedOnce() {
OnConstruction();
}
partial void OnConstruction();
public NestedOnce(NestedOnce other) : this() {
}
public NestedOnce Clone() {
return new NestedOnce(this);
}
public override bool Equals(object other) {
return Equals(other as NestedOnce);
}
public bool Equals(NestedOnce other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(NestedOnce other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the NestedOnce message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class NestedTwice : pb::IMessage<NestedTwice> {
private static readonly pb::MessageParser<NestedTwice> _parser = new pb::MessageParser<NestedTwice>(() => new NestedTwice());
public static pb::MessageParser<NestedTwice> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Descriptor.NestedTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public NestedTwice() {
OnConstruction();
}
partial void OnConstruction();
public NestedTwice(NestedTwice other) : this() {
}
public NestedTwice Clone() {
return new NestedTwice(this);
}
public override bool Equals(object other) {
return Equals(other as NestedTwice);
}
public bool Equals(NestedTwice other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(NestedTwice other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
}
#endregion
}
}
#endregion
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class NegativeEnumMessage : pb::IMessage<NegativeEnumMessage> {
private static readonly pb::MessageParser<NegativeEnumMessage> _parser = new pb::MessageParser<NegativeEnumMessage>(() => new NegativeEnumMessage());
public static pb::MessageParser<NegativeEnumMessage> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public NegativeEnumMessage() {
OnConstruction();
}
partial void OnConstruction();
public NegativeEnumMessage(NegativeEnumMessage other) : this() {
value_ = other.value_;
values_ = other.values_.Clone();
packedValues_ = other.packedValues_.Clone();
}
public NegativeEnumMessage Clone() {
return new NegativeEnumMessage(this);
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 1;
private global::UnitTest.Issues.TestProtos.NegativeEnum value_ = global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO;
public global::UnitTest.Issues.TestProtos.NegativeEnum Value {
get { return value_; }
set {
value_ = value;
}
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 2;
private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.NegativeEnum> _repeated_values_codec
= pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x);
private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> values_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum>();
public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> Values {
get { return values_; }
}
/// <summary>Field number for the "packed_values" field.</summary>
public const int PackedValuesFieldNumber = 3;
private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.NegativeEnum> _repeated_packedValues_codec
= pb::FieldCodec.ForEnum(26, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x);
private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> packedValues_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum>();
public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.NegativeEnum> PackedValues {
get { return packedValues_; }
}
public override bool Equals(object other) {
return Equals(other as NegativeEnumMessage);
}
public bool Equals(NegativeEnumMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
if(!values_.Equals(other.values_)) return false;
if(!packedValues_.Equals(other.packedValues_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) hash ^= Value.GetHashCode();
hash ^= values_.GetHashCode();
hash ^= packedValues_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) {
output.WriteRawTag(8);
output.WriteEnum((int) Value);
}
values_.WriteTo(output, _repeated_values_codec);
packedValues_.WriteTo(output, _repeated_packedValues_codec);
}
public int CalculateSize() {
int size = 0;
if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value);
}
size += values_.CalculateSize(_repeated_values_codec);
size += packedValues_.CalculateSize(_repeated_packedValues_codec);
return size;
}
public void MergeFrom(NegativeEnumMessage other) {
if (other == null) {
return;
}
if (other.Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) {
Value = other.Value;
}
values_.Add(other.values_);
packedValues_.Add(other.packedValues_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
value_ = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum();
break;
}
case 18:
case 16: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
case 26:
case 24: {
packedValues_.AddEntriesFrom(input, _repeated_packedValues_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DeprecatedChild : pb::IMessage<DeprecatedChild> {
private static readonly pb::MessageParser<DeprecatedChild> _parser = new pb::MessageParser<DeprecatedChild>(() => new DeprecatedChild());
public static pb::MessageParser<DeprecatedChild> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DeprecatedChild() {
OnConstruction();
}
partial void OnConstruction();
public DeprecatedChild(DeprecatedChild other) : this() {
}
public DeprecatedChild Clone() {
return new DeprecatedChild(this);
}
public override bool Equals(object other) {
return Equals(other as DeprecatedChild);
}
public bool Equals(DeprecatedChild other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(DeprecatedChild other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DeprecatedFieldsMessage : pb::IMessage<DeprecatedFieldsMessage> {
private static readonly pb::MessageParser<DeprecatedFieldsMessage> _parser = new pb::MessageParser<DeprecatedFieldsMessage>(() => new DeprecatedFieldsMessage());
public static pb::MessageParser<DeprecatedFieldsMessage> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DeprecatedFieldsMessage() {
OnConstruction();
}
partial void OnConstruction();
public DeprecatedFieldsMessage(DeprecatedFieldsMessage other) : this() {
primitiveValue_ = other.primitiveValue_;
primitiveArray_ = other.primitiveArray_.Clone();
MessageValue = other.messageValue_ != null ? other.MessageValue.Clone() : null;
messageArray_ = other.messageArray_.Clone();
enumValue_ = other.enumValue_;
enumArray_ = other.enumArray_.Clone();
}
public DeprecatedFieldsMessage Clone() {
return new DeprecatedFieldsMessage(this);
}
/// <summary>Field number for the "PrimitiveValue" field.</summary>
public const int PrimitiveValueFieldNumber = 1;
private int primitiveValue_;
[global::System.ObsoleteAttribute()]
public int PrimitiveValue {
get { return primitiveValue_; }
set {
primitiveValue_ = value;
}
}
/// <summary>Field number for the "PrimitiveArray" field.</summary>
public const int PrimitiveArrayFieldNumber = 2;
private static readonly pb::FieldCodec<int> _repeated_primitiveArray_codec
= pb::FieldCodec.ForInt32(18);
private readonly pbc::RepeatedField<int> primitiveArray_ = new pbc::RepeatedField<int>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<int> PrimitiveArray {
get { return primitiveArray_; }
}
/// <summary>Field number for the "MessageValue" field.</summary>
public const int MessageValueFieldNumber = 3;
private global::UnitTest.Issues.TestProtos.DeprecatedChild messageValue_;
[global::System.ObsoleteAttribute()]
public global::UnitTest.Issues.TestProtos.DeprecatedChild MessageValue {
get { return messageValue_; }
set {
messageValue_ = value;
}
}
/// <summary>Field number for the "MessageArray" field.</summary>
public const int MessageArrayFieldNumber = 4;
private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.DeprecatedChild> _repeated_messageArray_codec
= pb::FieldCodec.ForMessage(34, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser);
private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild> messageArray_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedChild> MessageArray {
get { return messageArray_; }
}
/// <summary>Field number for the "EnumValue" field.</summary>
public const int EnumValueFieldNumber = 5;
private global::UnitTest.Issues.TestProtos.DeprecatedEnum enumValue_ = global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO;
[global::System.ObsoleteAttribute()]
public global::UnitTest.Issues.TestProtos.DeprecatedEnum EnumValue {
get { return enumValue_; }
set {
enumValue_ = value;
}
}
/// <summary>Field number for the "EnumArray" field.</summary>
public const int EnumArrayFieldNumber = 6;
private static readonly pb::FieldCodec<global::UnitTest.Issues.TestProtos.DeprecatedEnum> _repeated_enumArray_codec
= pb::FieldCodec.ForEnum(50, x => (int) x, x => (global::UnitTest.Issues.TestProtos.DeprecatedEnum) x);
private readonly pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum> enumArray_ = new pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<global::UnitTest.Issues.TestProtos.DeprecatedEnum> EnumArray {
get { return enumArray_; }
}
public override bool Equals(object other) {
return Equals(other as DeprecatedFieldsMessage);
}
public bool Equals(DeprecatedFieldsMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PrimitiveValue != other.PrimitiveValue) return false;
if(!primitiveArray_.Equals(other.primitiveArray_)) return false;
if (!object.Equals(MessageValue, other.MessageValue)) return false;
if(!messageArray_.Equals(other.messageArray_)) return false;
if (EnumValue != other.EnumValue) return false;
if(!enumArray_.Equals(other.enumArray_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (PrimitiveValue != 0) hash ^= PrimitiveValue.GetHashCode();
hash ^= primitiveArray_.GetHashCode();
if (messageValue_ != null) hash ^= MessageValue.GetHashCode();
hash ^= messageArray_.GetHashCode();
if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) hash ^= EnumValue.GetHashCode();
hash ^= enumArray_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (PrimitiveValue != 0) {
output.WriteRawTag(8);
output.WriteInt32(PrimitiveValue);
}
primitiveArray_.WriteTo(output, _repeated_primitiveArray_codec);
if (messageValue_ != null) {
output.WriteRawTag(26);
output.WriteMessage(MessageValue);
}
messageArray_.WriteTo(output, _repeated_messageArray_codec);
if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) {
output.WriteRawTag(40);
output.WriteEnum((int) EnumValue);
}
enumArray_.WriteTo(output, _repeated_enumArray_codec);
}
public int CalculateSize() {
int size = 0;
if (PrimitiveValue != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveValue);
}
size += primitiveArray_.CalculateSize(_repeated_primitiveArray_codec);
if (messageValue_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageValue);
}
size += messageArray_.CalculateSize(_repeated_messageArray_codec);
if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumValue);
}
size += enumArray_.CalculateSize(_repeated_enumArray_codec);
return size;
}
public void MergeFrom(DeprecatedFieldsMessage other) {
if (other == null) {
return;
}
if (other.PrimitiveValue != 0) {
PrimitiveValue = other.PrimitiveValue;
}
primitiveArray_.Add(other.primitiveArray_);
if (other.messageValue_ != null) {
if (messageValue_ == null) {
messageValue_ = new global::UnitTest.Issues.TestProtos.DeprecatedChild();
}
MessageValue.MergeFrom(other.MessageValue);
}
messageArray_.Add(other.messageArray_);
if (other.EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) {
EnumValue = other.EnumValue;
}
enumArray_.Add(other.enumArray_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
PrimitiveValue = input.ReadInt32();
break;
}
case 18:
case 16: {
primitiveArray_.AddEntriesFrom(input, _repeated_primitiveArray_codec);
break;
}
case 26: {
if (messageValue_ == null) {
messageValue_ = new global::UnitTest.Issues.TestProtos.DeprecatedChild();
}
input.ReadMessage(messageValue_);
break;
}
case 34: {
messageArray_.AddEntriesFrom(input, _repeated_messageArray_codec);
break;
}
case 40: {
enumValue_ = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) input.ReadEnum();
break;
}
case 50:
case 48: {
enumArray_.AddEntriesFrom(input, _repeated_enumArray_codec);
break;
}
}
}
}
}
/// <summary>
/// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ItemField : pb::IMessage<ItemField> {
private static readonly pb::MessageParser<ItemField> _parser = new pb::MessageParser<ItemField>(() => new ItemField());
public static pb::MessageParser<ItemField> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ItemField() {
OnConstruction();
}
partial void OnConstruction();
public ItemField(ItemField other) : this() {
item_ = other.item_;
}
public ItemField Clone() {
return new ItemField(this);
}
/// <summary>Field number for the "item" field.</summary>
public const int ItemFieldNumber = 1;
private int item_;
public int Item {
get { return item_; }
set {
item_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ItemField);
}
public bool Equals(ItemField other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Item != other.Item) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Item != 0) hash ^= Item.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Item != 0) {
output.WriteRawTag(8);
output.WriteInt32(Item);
}
}
public int CalculateSize() {
int size = 0;
if (Item != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Item);
}
return size;
}
public void MergeFrom(ItemField other) {
if (other == null) {
return;
}
if (other.Item != 0) {
Item = other.Item;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Item = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ReservedNames : pb::IMessage<ReservedNames> {
private static readonly pb::MessageParser<ReservedNames> _parser = new pb::MessageParser<ReservedNames>(() => new ReservedNames());
public static pb::MessageParser<ReservedNames> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[5]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ReservedNames() {
OnConstruction();
}
partial void OnConstruction();
public ReservedNames(ReservedNames other) : this() {
types_ = other.types_;
descriptor_ = other.descriptor_;
}
public ReservedNames Clone() {
return new ReservedNames(this);
}
/// <summary>Field number for the "types" field.</summary>
public const int Types_FieldNumber = 1;
private int types_;
public int Types_ {
get { return types_; }
set {
types_ = value;
}
}
/// <summary>Field number for the "descriptor" field.</summary>
public const int Descriptor_FieldNumber = 2;
private int descriptor_;
public int Descriptor_ {
get { return descriptor_; }
set {
descriptor_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ReservedNames);
}
public bool Equals(ReservedNames other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Types_ != other.Types_) return false;
if (Descriptor_ != other.Descriptor_) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Types_ != 0) hash ^= Types_.GetHashCode();
if (Descriptor_ != 0) hash ^= Descriptor_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Types_ != 0) {
output.WriteRawTag(8);
output.WriteInt32(Types_);
}
if (Descriptor_ != 0) {
output.WriteRawTag(16);
output.WriteInt32(Descriptor_);
}
}
public int CalculateSize() {
int size = 0;
if (Types_ != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Types_);
}
if (Descriptor_ != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Descriptor_);
}
return size;
}
public void MergeFrom(ReservedNames other) {
if (other == null) {
return;
}
if (other.Types_ != 0) {
Types_ = other.Types_;
}
if (other.Descriptor_ != 0) {
Descriptor_ = other.Descriptor_;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Types_ = input.ReadInt32();
break;
}
case 16: {
Descriptor_ = input.ReadInt32();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the ReservedNames message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
/// <summary>
/// Force a nested type called Types
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class SomeNestedType : pb::IMessage<SomeNestedType> {
private static readonly pb::MessageParser<SomeNestedType> _parser = new pb::MessageParser<SomeNestedType>(() => new SomeNestedType());
public static pb::MessageParser<SomeNestedType> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.ReservedNames.Descriptor.NestedTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public SomeNestedType() {
OnConstruction();
}
partial void OnConstruction();
public SomeNestedType(SomeNestedType other) : this() {
}
public SomeNestedType Clone() {
return new SomeNestedType(this);
}
public override bool Equals(object other) {
return Equals(other as SomeNestedType);
}
public bool Equals(SomeNestedType other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(SomeNestedType other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
}
#endregion
}
/// <summary>
/// These fields are deliberately not declared in numeric
/// order, and the oneof fields aren't contiguous either.
/// This allows for reasonably robust tests of JSON output
/// ordering.
/// TestFieldOrderings in unittest_proto3.proto is similar,
/// but doesn't include oneofs.
/// TODO: Consider adding oneofs to TestFieldOrderings, although
/// that will require fixing other tests in multiple platforms.
/// Alternatively, consider just adding this to
/// unittest_proto3.proto if multiple platforms want it.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestJsonFieldOrdering : pb::IMessage<TestJsonFieldOrdering> {
private static readonly pb::MessageParser<TestJsonFieldOrdering> _parser = new pb::MessageParser<TestJsonFieldOrdering>(() => new TestJsonFieldOrdering());
public static pb::MessageParser<TestJsonFieldOrdering> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[6]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestJsonFieldOrdering() {
OnConstruction();
}
partial void OnConstruction();
public TestJsonFieldOrdering(TestJsonFieldOrdering other) : this() {
plainInt32_ = other.plainInt32_;
plainString_ = other.plainString_;
switch (other.O1Case) {
case O1OneofCase.O1String:
O1String = other.O1String;
break;
case O1OneofCase.O1Int32:
O1Int32 = other.O1Int32;
break;
}
switch (other.O2Case) {
case O2OneofCase.O2Int32:
O2Int32 = other.O2Int32;
break;
case O2OneofCase.O2String:
O2String = other.O2String;
break;
}
}
public TestJsonFieldOrdering Clone() {
return new TestJsonFieldOrdering(this);
}
/// <summary>Field number for the "plain_int32" field.</summary>
public const int PlainInt32FieldNumber = 4;
private int plainInt32_;
public int PlainInt32 {
get { return plainInt32_; }
set {
plainInt32_ = value;
}
}
/// <summary>Field number for the "o1_string" field.</summary>
public const int O1StringFieldNumber = 2;
public string O1String {
get { return o1Case_ == O1OneofCase.O1String ? (string) o1_ : ""; }
set {
o1_ = pb::Preconditions.CheckNotNull(value, "value");
o1Case_ = O1OneofCase.O1String;
}
}
/// <summary>Field number for the "o1_int32" field.</summary>
public const int O1Int32FieldNumber = 5;
public int O1Int32 {
get { return o1Case_ == O1OneofCase.O1Int32 ? (int) o1_ : 0; }
set {
o1_ = value;
o1Case_ = O1OneofCase.O1Int32;
}
}
/// <summary>Field number for the "plain_string" field.</summary>
public const int PlainStringFieldNumber = 1;
private string plainString_ = "";
public string PlainString {
get { return plainString_; }
set {
plainString_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "o2_int32" field.</summary>
public const int O2Int32FieldNumber = 6;
public int O2Int32 {
get { return o2Case_ == O2OneofCase.O2Int32 ? (int) o2_ : 0; }
set {
o2_ = value;
o2Case_ = O2OneofCase.O2Int32;
}
}
/// <summary>Field number for the "o2_string" field.</summary>
public const int O2StringFieldNumber = 3;
public string O2String {
get { return o2Case_ == O2OneofCase.O2String ? (string) o2_ : ""; }
set {
o2_ = pb::Preconditions.CheckNotNull(value, "value");
o2Case_ = O2OneofCase.O2String;
}
}
private object o1_;
/// <summary>Enum of possible cases for the "o1" oneof.</summary>
public enum O1OneofCase {
None = 0,
O1String = 2,
O1Int32 = 5,
}
private O1OneofCase o1Case_ = O1OneofCase.None;
public O1OneofCase O1Case {
get { return o1Case_; }
}
public void ClearO1() {
o1Case_ = O1OneofCase.None;
o1_ = null;
}
private object o2_;
/// <summary>Enum of possible cases for the "o2" oneof.</summary>
public enum O2OneofCase {
None = 0,
O2Int32 = 6,
O2String = 3,
}
private O2OneofCase o2Case_ = O2OneofCase.None;
public O2OneofCase O2Case {
get { return o2Case_; }
}
public void ClearO2() {
o2Case_ = O2OneofCase.None;
o2_ = null;
}
public override bool Equals(object other) {
return Equals(other as TestJsonFieldOrdering);
}
public bool Equals(TestJsonFieldOrdering other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PlainInt32 != other.PlainInt32) return false;
if (O1String != other.O1String) return false;
if (O1Int32 != other.O1Int32) return false;
if (PlainString != other.PlainString) return false;
if (O2Int32 != other.O2Int32) return false;
if (O2String != other.O2String) return false;
if (O1Case != other.O1Case) return false;
if (O2Case != other.O2Case) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (PlainInt32 != 0) hash ^= PlainInt32.GetHashCode();
if (o1Case_ == O1OneofCase.O1String) hash ^= O1String.GetHashCode();
if (o1Case_ == O1OneofCase.O1Int32) hash ^= O1Int32.GetHashCode();
if (PlainString.Length != 0) hash ^= PlainString.GetHashCode();
if (o2Case_ == O2OneofCase.O2Int32) hash ^= O2Int32.GetHashCode();
if (o2Case_ == O2OneofCase.O2String) hash ^= O2String.GetHashCode();
hash ^= (int) o1Case_;
hash ^= (int) o2Case_;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (PlainString.Length != 0) {
output.WriteRawTag(10);
output.WriteString(PlainString);
}
if (o1Case_ == O1OneofCase.O1String) {
output.WriteRawTag(18);
output.WriteString(O1String);
}
if (o2Case_ == O2OneofCase.O2String) {
output.WriteRawTag(26);
output.WriteString(O2String);
}
if (PlainInt32 != 0) {
output.WriteRawTag(32);
output.WriteInt32(PlainInt32);
}
if (o1Case_ == O1OneofCase.O1Int32) {
output.WriteRawTag(40);
output.WriteInt32(O1Int32);
}
if (o2Case_ == O2OneofCase.O2Int32) {
output.WriteRawTag(48);
output.WriteInt32(O2Int32);
}
}
public int CalculateSize() {
int size = 0;
if (PlainInt32 != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PlainInt32);
}
if (o1Case_ == O1OneofCase.O1String) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(O1String);
}
if (o1Case_ == O1OneofCase.O1Int32) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(O1Int32);
}
if (PlainString.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PlainString);
}
if (o2Case_ == O2OneofCase.O2Int32) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(O2Int32);
}
if (o2Case_ == O2OneofCase.O2String) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(O2String);
}
return size;
}
public void MergeFrom(TestJsonFieldOrdering other) {
if (other == null) {
return;
}
if (other.PlainInt32 != 0) {
PlainInt32 = other.PlainInt32;
}
if (other.PlainString.Length != 0) {
PlainString = other.PlainString;
}
switch (other.O1Case) {
case O1OneofCase.O1String:
O1String = other.O1String;
break;
case O1OneofCase.O1Int32:
O1Int32 = other.O1Int32;
break;
}
switch (other.O2Case) {
case O2OneofCase.O2Int32:
O2Int32 = other.O2Int32;
break;
case O2OneofCase.O2String:
O2String = other.O2String;
break;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
PlainString = input.ReadString();
break;
}
case 18: {
O1String = input.ReadString();
break;
}
case 26: {
O2String = input.ReadString();
break;
}
case 32: {
PlainInt32 = input.ReadInt32();
break;
}
case 40: {
O1Int32 = input.ReadInt32();
break;
}
case 48: {
O2Int32 = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Threading.Tasks.Sources.Tests
{
public class ManualResetValueTaskSourceTests
{
[Fact]
public async Task ReuseInstanceWithResets_Success()
{
var mrvts = new ManualResetValueTaskSource<int>();
for (short i = 42; i < 48; i++)
{
var ignored = Task.Delay(1).ContinueWith(_ => mrvts.SetResult(i));
Assert.Equal(i, await new ValueTask<int>(mrvts, mrvts.Version));
Assert.Equal(i, await new ValueTask<int>(mrvts, mrvts.Version)); // can use multiple times until it's reset
mrvts.Reset();
}
}
[Fact]
public void AccessAfterReset_Fails()
{
var mrvts = new ManualResetValueTaskSource<int>();
mrvts.Reset();
Assert.Throws<InvalidOperationException>(() => mrvts.GetResult(0));
Assert.Throws<InvalidOperationException>(() => mrvts.GetStatus(0));
Assert.Throws<InvalidOperationException>(() => mrvts.OnCompleted(_ => { }, new object(), 0, ValueTaskSourceOnCompletedFlags.None));
}
[Fact]
public void SetTwice_Fails()
{
var mrvts = new ManualResetValueTaskSource<int>();
mrvts.SetResult(42);
Assert.Throws<InvalidOperationException>(() => mrvts.SetResult(42));
Assert.Throws<InvalidOperationException>(() => mrvts.SetException(new Exception()));
mrvts.Reset();
mrvts.SetException(new Exception());
Assert.Throws<InvalidOperationException>(() => mrvts.SetResult(42));
Assert.Throws<InvalidOperationException>(() => mrvts.SetException(new Exception()));
}
[Fact]
public async Task AsyncEnumerable_Success()
{
// Equivalent to:
// int total = 0;
// foreach async(int i in CountAsync(20))
// {
// total += i;
// }
// Assert.Equal(190, i);
IAsyncEnumerator<int> enumerator = CountAsync(20).GetAsyncEnumerator();
try
{
int total = 0;
while (await enumerator.MoveNextAsync())
{
total += enumerator.Current;
}
Assert.Equal(190, total);
}
finally
{
await enumerator.DisposeAsync();
}
}
// The following is a sketch of an implementation to explore the IAsyncEnumerable feature.
// This should be replaced with the real implementation when available.
// https://github.com/dotnet/csharplang/issues/43
internal interface IAsyncEnumerable<out T>
{
IAsyncEnumerator<T> GetAsyncEnumerator();
}
internal interface IAsyncEnumerator<out T> : IAsyncDisposable
{
// One of two potential shapes for IAsyncEnumerator; another is
// ValueTask<bool> WaitForNextAsync();
// bool TryGetNext(out T current);
// which has several advantages, including that while the next
// result is available synchronously, it incurs only one interface
// call rather than two, and doesn't incur any boilerplate related
// to await.
ValueTask<bool> MoveNextAsync();
T Current { get; }
}
internal interface IAsyncDisposable
{
ValueTask DisposeAsync();
}
// Approximate compiler-generated code for:
// internal static AsyncEnumerable<int> CountAsync(int items)
// {
// for (int i = 0; i < items; i++)
// {
// await Task.Delay(i).ConfigureAwait(false);
// yield return i;
// }
// }
internal static IAsyncEnumerable<int> CountAsync(int items) =>
new CountAsyncEnumerable(items);
private sealed class CountAsyncEnumerable :
IAsyncEnumerable<int>, // used as the enumerable itself
IAsyncEnumerator<int>, // used as the enumerator returned from first call to enumerable's GetAsyncEnumerator
IValueTaskSource<bool>, // used as the backing store behind the ValueTask<bool> returned from each MoveNextAsync
IStrongBox<ManualResetValueTaskSourceLogic<bool>>, // exposes its ValueTaskSource logic implementation
IAsyncStateMachine // uses existing builder's support for ExecutionContext, optimized awaits, etc.
{
// This implementation will generally incur only two allocations of overhead
// for the entire enumeration:
// - The CountAsyncEnumerable object itself.
// - A throw-away task object inside of _builder.
// The task built by the builder isn't necessary, but using the _builder allows
// this implementation to a) avoid needing to be concerned with ExecutionContext
// flowing, and b) enables the implementation to take advantage of optimizations
// such as avoiding Action allocation when all awaited types are known to corelib.
private const int StateStart = -1;
private const int StateDisposed = -2;
private const int StateCtor = -3;
/// <summary>Current state of the state machine.</summary>
private int _state = StateCtor;
/// <summary>All of the logic for managing the IValueTaskSource implementation</summary>
private ManualResetValueTaskSourceLogic<bool> _vts; // mutable struct; do not make this readonly
/// <summary>Builder used for efficiently waiting and appropriately managing ExecutionContext.</summary>
private AsyncTaskMethodBuilder _builder = AsyncTaskMethodBuilder.Create(); // mutable struct; do not make this readonly
private readonly int _param_items;
private int _local_items;
private int _local_i;
private TaskAwaiter _awaiter0;
public CountAsyncEnumerable(int items)
{
_local_items = _param_items = items;
_vts = new ManualResetValueTaskSourceLogic<bool>(this);
}
ref ManualResetValueTaskSourceLogic<bool> IStrongBox<ManualResetValueTaskSourceLogic<bool>>.Value => ref _vts;
public IAsyncEnumerator<int> GetAsyncEnumerator() =>
Interlocked.CompareExchange(ref _state, StateStart, StateCtor) == StateCtor ?
this :
new CountAsyncEnumerable(_param_items) { _state = StateStart };
public ValueTask<bool> MoveNextAsync()
{
_vts.Reset();
CountAsyncEnumerable inst = this;
_builder.Start(ref inst); // invokes MoveNext, protected by ExecutionContext guards
switch (_vts.GetStatus(_vts.Version))
{
case ValueTaskSourceStatus.Succeeded:
return new ValueTask<bool>(_vts.GetResult(_vts.Version));
default:
return new ValueTask<bool>(this, _vts.Version);
}
}
public ValueTask DisposeAsync()
{
_vts.Reset();
_state = StateDisposed;
return default;
}
public int Current { get; private set; }
public void MoveNext()
{
try
{
switch (_state)
{
case StateStart:
_local_i = 0;
goto case 0;
case 0:
if (_local_i < _local_items)
{
_awaiter0 = Task.Delay(_local_i).GetAwaiter();
if (!_awaiter0.IsCompleted)
{
_state = 1;
CountAsyncEnumerable inst = this;
_builder.AwaitUnsafeOnCompleted(ref _awaiter0, ref inst);
return;
}
goto case 1;
}
_state = int.MaxValue;
_vts.SetResult(false);
return;
case 1:
_awaiter0.GetResult();
_awaiter0 = default;
Current = _local_i;
_state = 2;
_vts.SetResult(true);
return;
case 2:
_local_i++;
_state = 0;
goto case 0;
default:
throw new InvalidOperationException();
}
}
catch (Exception e)
{
_state = int.MaxValue;
_vts.SetException(e); // see https://github.com/dotnet/roslyn/issues/26567; we may want to move this out of the catch
return;
}
}
void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { }
bool IValueTaskSource<bool>.GetResult(short token) => _vts.GetResult(token);
ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) => _vts.GetStatus(token);
void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) =>
_vts.OnCompleted(continuation, state, token, flags);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ButtonBase.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms.ButtonInternal {
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
internal abstract class RadioButtonBaseAdapter : CheckableControlBaseAdapter {
internal RadioButtonBaseAdapter(ButtonBase control) : base(control) {}
protected new RadioButton Control {
get {
return ((RadioButton)base.Control);
}
}
#region Drawing helpers
protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, Color checkBorder) {
DrawCheckBackgroundFlat(e, layout.checkBounds, checkBorder, checkBackground, true);
DrawCheckOnly(e, layout, checkColor, checkBackground, true);
}
protected void DrawCheckBackground3DLite(PaintEventArgs e, Rectangle bounds, Color checkColor, Color checkBackground, ColorData colors, bool disabledColors) {
Graphics g = e.Graphics;
Color field = checkBackground;
if (!Control.Enabled && disabledColors) {
field = SystemColors.Control;
}
using (Brush fieldBrush = new SolidBrush(field)) {
using (Pen dark = new Pen(colors.buttonShadow),
light = new Pen(colors.buttonFace),
lightlight = new Pen(colors.highlight)) {
bounds.Width--;
bounds.Height--;
// fall a little short of SW, NW, NE, SE because corners come out nasty
g.DrawPie(dark, bounds, (float)(135 + 1), (float)(90 - 2));
g.DrawPie(dark, bounds, (float)(225 + 1), (float)(90 - 2));
g.DrawPie(lightlight, bounds, (float)(315 + 1), (float)(90 - 2));
g.DrawPie(lightlight, bounds, (float)(45 + 1), (float)(90 - 2));
bounds.Inflate(-1, -1);
g.FillEllipse(fieldBrush, bounds);
g.DrawEllipse(light, bounds);
}
}
}
protected void DrawCheckBackgroundFlat(PaintEventArgs e, Rectangle bounds, Color borderColor, Color checkBackground, bool disabledColors) {
Color field = checkBackground;
Color border = borderColor;
if (!Control.Enabled && disabledColors) {
border = ControlPaint.ContrastControlDark;
field = SystemColors.Control;
}
float scale = GetDpiScaleRatio(e.Graphics);
using( WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics) ) {
using( WindowsPen borderPen = new WindowsPen(wg.DeviceContext, border) ) {
using( WindowsBrush fieldBrush = new WindowsSolidBrush(wg.DeviceContext, field) ) {
// for Dev10 525537, in high DPI mode when we draw ellipse as three rectantles,
// the quality of ellipse is poor. Draw it directly as ellipse
if(scale > 1.1) {
bounds.Width--;
bounds.Height--;
wg.DrawAndFillEllipse(borderPen, fieldBrush, bounds);
bounds.Inflate(-1, -1);
}
else {
DrawAndFillEllipse(wg, borderPen, fieldBrush, bounds);
}
}
}
}
}
// Helper method to overcome the poor GDI ellipse drawing routine
// VSWhidbey #334097
private static void DrawAndFillEllipse(WindowsGraphics wg, WindowsPen borderPen, WindowsBrush fieldBrush, Rectangle bounds)
{
Debug.Assert(wg != null,"Calling DrawAndFillEllipse with null wg");
if (wg == null) {
return;
}
wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 2, bounds.Y + 2, 8, 8));
wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 4, bounds.Y + 1, 4, 10));
wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 1, bounds.Y + 4, 10, 4));
wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 0), new Point(bounds.X + 8, bounds.Y + 0));
wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 11), new Point(bounds.X + 8, bounds.Y + 11));
wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 1), new Point(bounds.X + 4, bounds.Y + 1));
wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 1), new Point(bounds.X + 10, bounds.Y + 1));
wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 10), new Point(bounds.X + 4, bounds.Y + 10));
wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 10), new Point(bounds.X + 10, bounds.Y + 10));
wg.DrawLine(borderPen, new Point(bounds.X + 0, bounds.Y + 4), new Point(bounds.X + 0, bounds.Y + 8));
wg.DrawLine(borderPen, new Point(bounds.X + 11, bounds.Y + 4), new Point(bounds.X + 11, bounds.Y + 8));
wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 2), new Point(bounds.X + 1, bounds.Y + 4));
wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 8), new Point(bounds.X + 1, bounds.Y + 10));
wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 2), new Point(bounds.X + 10, bounds.Y + 4));
wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 8), new Point(bounds.X + 10, bounds.Y + 10));
}
private static int GetScaledNumber(int n, float scale)
{
return (int)(n * scale);
}
protected void DrawCheckOnly(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, bool disabledColors) {
// check
//
if (Control.Checked) {
if (!Control.Enabled && disabledColors) {
checkColor = SystemColors.ControlDark;
}
float scale = GetDpiScaleRatio(e.Graphics);
using( WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics) ) {
using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, checkColor)) {
// circle drawing doesn't work at this size
int offset = 5;
Rectangle vCross = new Rectangle (layout.checkBounds.X + GetScaledNumber(offset, scale), layout.checkBounds.Y + GetScaledNumber(offset - 1, scale), GetScaledNumber(2, scale), GetScaledNumber(4, scale));
wg.FillRectangle(brush, vCross);
Rectangle hCross = new Rectangle (layout.checkBounds.X + GetScaledNumber(offset - 1, scale), layout.checkBounds.Y + GetScaledNumber(offset, scale), GetScaledNumber(4, scale), GetScaledNumber(2, scale));
wg.FillRectangle(brush, hCross);
}
}
}
}
protected ButtonState GetState() {
ButtonState style = (ButtonState)0;
if (Control.Checked) {
style |= ButtonState.Checked;
}
else {
style |= ButtonState.Normal;
}
if (!Control.Enabled) {
style |= ButtonState.Inactive;
}
if (Control.MouseIsDown) {
style |= ButtonState.Pushed;
}
return style;
}
protected void DrawCheckBox(PaintEventArgs e, LayoutData layout) {
Graphics g = e.Graphics;
Rectangle check = layout.checkBounds;
if (!Application.RenderWithVisualStyles) {
check.X--; // compensate for Windows drawing slightly offset to right
}
ButtonState style = GetState();
if (Application.RenderWithVisualStyles) {
RadioButtonRenderer.DrawRadioButton(g, new Point(check.Left, check.Top), RadioButtonRenderer.ConvertFromButtonState(style, Control.MouseIsOver));
}
else {
ControlPaint.DrawRadioButton(g, check, style);
}
}
#endregion
internal override LayoutOptions CommonLayout() {
LayoutOptions layout = base.CommonLayout();
layout.checkAlign = Control.CheckAlign;
return layout;
}
}
}
| |
// 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 Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer
{
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
internal enum SwitchType
{
Flag,
SingletonValue,
ValueList
}
internal class CommandSwitch
{
private readonly string _name;
private readonly string _abbreviation;
private readonly SwitchType _switchType;
internal CommandSwitch(string name, string abbreviation, SwitchType switchType)
{
//ensure name doesn't start with '--' and abbreviation doesn't start with '-'
//also convert to lower-case
if (name.StartsWith("--"))
name = name.Substring(2);
_name = name.ToLower(CultureInfo.InvariantCulture);
if (abbreviation.StartsWith("-"))
abbreviation = abbreviation.Substring(1);
_abbreviation = abbreviation.ToLower(CultureInfo.InvariantCulture);
_switchType = switchType;
}
internal string Name
{
get { return _name; }
}
#if NotUsed
internal string Abbreviation
{
get { return abbreviation; }
}
#endif
internal SwitchType SwitchType
{
get { return _switchType; }
}
internal bool Equals(string other)
{
//ensure that compare doesn't start with '--' or '-'
//also convert to lower-case
if (other.StartsWith("--"))
other = other.Substring(2);
else if (other.StartsWith("-"))
other = other.Substring(1);
//if equal to name, then return the OK
if (_name.Equals(other, StringComparison.InvariantCultureIgnoreCase))
return true;
//now check abbreviation
return _abbreviation.Equals(other, StringComparison.InvariantCultureIgnoreCase);
}
internal static CommandSwitch FindSwitch(string name, CommandSwitch[] switches)
{
foreach (CommandSwitch cs in switches)
if (cs.Equals(name))
return cs;
//if no match found, then return null
return null;
}
}
internal class ArgumentDictionary
{
private Dictionary<string, IList<string>> _contents;
internal ArgumentDictionary(int capacity)
{
_contents = new Dictionary<string, IList<string>>(capacity);
}
internal void Add(string key, string value)
{
IList<string> values;
if (!ContainsArgument(key))
{
values = new List<string>();
Add(key, values);
}
else
values = GetArguments(key);
values.Add(value);
}
internal string GetArgument(string key)
{
IList<string> values;
if (_contents.TryGetValue(key.ToLower(CultureInfo.InvariantCulture), out values))
{
#if SM_TOOL
Tool.Assert((values.Count == 1), "contains more than one argument please call GetArguments");
#endif
return values[0];
}
#if SM_TOOL
Tool.Assert(false, "argument was not specified please call ContainsArgument to check this");
#endif
return null; // unreachable code but the compiler doesn't know this.
}
internal IList<string> GetArguments(string key)
{
IList<string> result;
if (!_contents.TryGetValue(key.ToLower(CultureInfo.InvariantCulture), out result))
result = new List<string>();
return result;
}
internal bool ContainsArgument(string key)
{
return _contents.ContainsKey(key.ToLower(CultureInfo.InvariantCulture));
}
internal void Add(string key, IList<string> values)
{
_contents.Add(key.ToLower(CultureInfo.InvariantCulture), values);
}
internal int Count
{
get { return _contents.Count; }
}
}
internal static class CommandParser
{
internal static ArgumentDictionary ParseCommand(string[] cmd, CommandSwitch[] switches)
{
ArgumentDictionary arguments; //switches/values from cmd line
string arg; //argument to test next
CommandSwitch argSwitch; //switch corresponding to that argument
string argValue; //value corresponding to that argument
int delim; //location of value delimiter (':' or '=')
arguments = new ArgumentDictionary(cmd.Length);
foreach (string s in cmd)
{
arg = s;
bool argIsFlag = true;
//if argument does not start with switch indicator, place into "default" arguments
if (arg[0] != '-')
{
arguments.Add(String.Empty, arg);
continue;
}
//if we have something which begins with '--' or '-', throw if nothing after it
if (arg == "-" || arg == "--")
throw new ArgumentException(SR.Format(SR.ErrSwitchMissing, arg));
//yank switch indicator ('--' or '-') off of command argument
if (arg[1] != '-')
arg = arg.Substring(1);
else
arg = arg.Substring(2);
//check to make sure delimiter does not start off switch
delim = arg.IndexOfAny(new char[] { ':', '=' });
if (delim == 0)
throw new ArgumentException(SR.Format(SR.ErrUnexpectedDelimiter));
//if there is no value, than create a null string
if (delim == (-1))
argValue = String.Empty;
else
{
//assume valid argument now; must remove value attached to it
//must avoid copying delimeter into either arguments
argValue = arg.Substring(delim + 1);
arg = arg.Substring(0, delim);
argIsFlag = false;
}
//check if this switch exists in the list of possible switches
//if no match found, then throw an exception
argSwitch = CommandSwitch.FindSwitch(arg.ToLower(CultureInfo.InvariantCulture), switches);
if (argSwitch == null)
{
// Paths start with "/" on Unix, so the arg could potentially be a path.
// If we didn't find any matched option, check and see if it's a path.
string potentialPath = "/" + arg;
if (File.Exists(potentialPath))
{
arguments.Add(string.Empty, potentialPath);
continue;
}
throw new ArgumentException(SR.Format(SR.ErrUnknownSwitch, arg.ToLower(CultureInfo.InvariantCulture)));
}
//check if switch is allowed to have a value
// if not and a value has been specified, then thrown an exception
if (argSwitch.SwitchType == SwitchType.Flag)
{
if (!argIsFlag)
throw new ArgumentException(SR.Format(SR.ErrUnexpectedValue, arg.ToLower(CultureInfo.InvariantCulture)));
}
else
{
if (argIsFlag)
throw new ArgumentException(SR.Format(SR.ErrExpectedValue, arg.ToLower(CultureInfo.InvariantCulture)));
}
//check if switch is allowed to be specified multiple times
// if not and it has already been specified and a new value has been paresd, throw an exception
if (argSwitch.SwitchType != SwitchType.ValueList && arguments.ContainsArgument(argSwitch.Name))
{
throw new ArgumentException(SR.Format(SR.ErrSingleUseSwitch, arg.ToLower(CultureInfo.InvariantCulture)));
}
else
{
arguments.Add(argSwitch.Name, argValue);
}
}
return arguments;
}
}
}
| |
using System;
using System.Linq;
namespace Veggerby.Algorithm.Calculus.Visitors
{
public class ReduceOperandVisitor : IOperandVisitor<Operand>
{
private Operand Reduce(Operand operand)
{
var visitor = new ReduceOperandVisitor();
var result = operand.Accept(visitor);
if (!operand.Equals(result))
{
return result;
}
return operand;
}
public Operand Visit(Function operand) => Function.Create(operand.Identifier, Reduce(operand.Operand));
public Operand Visit(FunctionReference operand) => FunctionReference.Create(operand.Identifier, operand.Parameters.Select(x => Reduce(x)));
public Operand Visit(ValueConstant operand) => operand;
public Operand Visit(NamedConstant operand) => operand;
public Operand Visit(UnspecifiedConstant operand) => operand;
public Operand Visit(Variable operand) => operand;
public Operand Visit(Addition operand)
{
var operands = operand
.Operands
.Select(x => Reduce(x))
.Where(x => !x.Equals(ValueConstant.Zero))
.GroupBy(x => x)
.Select(x => x.Count() > 1 ? Multiplication.Create(x.Count(), x.Key) : x.Key)
.OrderBy(x => x, new CommutativeOperationComparer())
.ToList();
// combine constants into one operand
if (operands.Count(x => x.IsConstant()) > 1)
{
var constants = operands.Where(x => x.IsConstant()).Cast<ValueConstant>();
var constant = constants.Aggregate((seed, next) => (ValueConstant)(seed + next));
operands = new Operand[] { constant }.Concat(operands.Where(x => !x.IsConstant())).ToList();
}
if (operands.Any(x => x.IsNegative()))
{
return Reduce(Subtraction.Create(
Addition.Create(operands.Where(x => !x.IsNegative())),
Addition.Create(operands.OfType<Negative>().Select(x => x.Inner))
));
}
// consolidate addition and move substraction "out", e.g. c + (c - cos(x)) = (c + c) - cos(x)
if (operands.Any(x => x is Subtraction))
{
var addition = Addition.Create(operands.Select(x => x is Subtraction ? ((Subtraction)x).Left : x));
var substractions = operands.OfType<Subtraction>().Aggregate(addition, (seed, next) => Subtraction.Create(seed, next.Right));
return Reduce(substractions);
}
return Addition.Create(operands);
}
public Operand Visit(Subtraction operand)
{
var left = Reduce(operand.Left);
var right = Reduce(operand.Right);
if (left.Equals(right))
{
return ValueConstant.Zero;
}
if (left.IsConstant() && right.IsConstant())
{
return Reduce((ValueConstant)left - (ValueConstant)right);
}
if (left.Equals(ValueConstant.Zero))
{
return Reduce(Negative.Create(right));
}
if (right is Subtraction) // x-(y-z) = (x+z)-y
{
var rightSubstraction = (Subtraction)right;
return Reduce(Subtraction.Create(
Addition.Create(left, rightSubstraction.Right),
rightSubstraction.Left));
}
if (right.IsNegative())
{
return Reduce(Addition.Create(left, ((Negative)right).Inner));
}
if (right.IsConstant() && ((ValueConstant)right).Value < 0)
{
return Reduce(Addition.Create(left, -((ValueConstant)right).Value));
}
return Subtraction.Create(left, right);
}
public Operand Visit(Multiplication operand)
{
var operands = operand
.Operands
.Select(x => Reduce(x))
.Where(x => !x.Equals(ValueConstant.One))
.GroupBy(x => x)
.Select(x => x.Count() > 1 ? Power.Create(x.Key, x.Count()) : x.Key)
.OrderBy(x => x, new CommutativeOperationComparer())
.ToList();
if (operands.Any(x => x.Equals(ValueConstant.Zero)))
{
return ValueConstant.Zero;
}
// combine constants into one operand
if (operands.Count(x => x.IsConstant()) > 1)
{
var constants = operands.Where(x => x.IsConstant()).Cast<ValueConstant>();
var constant = constants.Aggregate((seed, next) => (ValueConstant)(seed * next));
operands = new Operand[] { constant }.Concat(operands.Where(x => !x.IsConstant())).ToList();
}
var negativeCount = operands.Count(x => x.IsNegative());
if (negativeCount > 0)
{
operands = operands.Select(x => x.IsNegative() ? ((Negative)x).Inner : x).ToList();
}
if (negativeCount % 2 == 1)
{
return Reduce(Negative.Create(Multiplication.Create(operands)));
}
// consolidate addition and move substraction "out", e.g. c + (c - cos(x)) = (c + c) - cos(x)
if (operands.Any(x => x is Division))
{
var multiplication = Multiplication.Create(operands.Select(x => x is Division ? ((Division)x).Left : x));
var divisions = operands.OfType<Division>().Aggregate(multiplication, (seed, next) => Division.Create(seed, next.Right));
return Reduce(divisions);
}
return Multiplication.Create(operands);
}
public Operand Visit(Division operand)
{
var left = Reduce(operand.Left);
var right = Reduce(operand.Right);
if (left.Equals(right))
{
return ValueConstant.One;
}
if (left is Fraction && right is Fraction)
{
return Reduce(((Fraction)left) / ((Fraction)right));
}
if (left.IsConstant() && right.IsConstant())
{
var l = (ValueConstant)left;
var r = (ValueConstant)right;
if (l.IsInteger() && r.IsInteger())
{
return Reduce(Fraction.Create(l, r));
}
return Reduce(l.Value / r.Value);
}
if (left.IsConstant() && right is Fraction)
{
return Reduce(((ValueConstant)left).Value / (Fraction)right);
}
if (left is Fraction && right.IsConstant())
{
return Reduce(((Fraction)left) / ((ValueConstant)right).Value);
}
if (right.Equals(ValueConstant.One))
{
return left;
}
if (left.IsNegative() && right.IsNegative())
{
return Reduce(Division.Create(((Negative)left).Inner, ((Negative)right).Inner));
}
if (left.IsNegative())
{
return Reduce(Negative.Create(Division.Create(((Negative)left).Inner, right)));
}
if (right.IsNegative())
{
return Reduce(Negative.Create(Division.Create(left, ((Negative)right).Inner)));
}
if (left is Division && right is Division)
{
return Reduce(Division.Create(
Multiplication.Create(((Division)left).Left, ((Division)right).Right),
Multiplication.Create(((Division)left).Right, ((Division)right).Left)));
}
if (left is Division)
{
return Reduce(Division.Create(
((Division)left).Left,
Multiplication.Create(((Division)left).Right, right)));
}
if (right is Division)
{
return Reduce(Division.Create(
Multiplication.Create(left, ((Division)right).Right),
((Division)right).Left));
}
return Division.Create(left, right);
}
public Operand Visit(Power operand)
{
var left = Reduce(operand.Left);
var right = Reduce(operand.Right);
if (left.Equals(ValueConstant.One) || right.Equals(ValueConstant.Zero))
{
return ValueConstant.One;
}
if (right.Equals(ValueConstant.One))
{
return left;
}
if (left.IsConstant() && right.IsConstant())
{
return Reduce((ValueConstant)left ^ (ValueConstant)right);
}
return Power.Create(left, right);
}
public Operand Visit(Root operand)
{
var inner = Reduce(operand.Inner);
if (operand.Exponent == 1)
{
return inner;
}
return Root.Create(operand.Exponent, inner);
}
public Operand Visit(Factorial operand) => Factorial.Create(Reduce(operand.Inner));
public Operand Visit(Sine operand) => Sine.Create(Reduce(operand.Inner));
public Operand Visit(Cosine operand) => Cosine.Create(Reduce(operand.Inner));
public Operand Visit(Tangent operand) => Tangent.Create(Reduce(operand.Inner));
public Operand Visit(Exponential operand) => Exponential.Create(Reduce(operand.Inner));
public Operand Visit(Logarithm operand) => Logarithm.Create(Reduce(operand.Inner));
public Operand Visit(LogarithmBase operand) => LogarithmBase.Create(operand.Base, Reduce(operand.Inner));
public Operand Visit(Negative operand)
{
var inner = Reduce(operand.Inner);
if (inner.IsConstant())
{
return ValueConstant.Create(-((ValueConstant)inner).Value);
}
return Negative.Create(inner);
}
public Operand Visit(Fraction operand)
{
var numerator = operand.Numerator;
var denominator = operand.Denominator;
if (denominator < 0)
{
return Reduce(Fraction.Create(-numerator, -denominator)); // flip sign on both 1/-x -> -1/x and -1/-x -> 1/x
}
var gcd = GreatestCommonDivisor.Euclid(Math.Abs(numerator), Math.Abs(denominator));
if (gcd > 1)
{
return Reduce(Fraction.Create(numerator / gcd, denominator / gcd));
}
if (denominator == 1)
{
return numerator;
}
return operand;
}
public Operand Visit(Minimum operand)
{
var reduced = operand
.Operands
.Select(x => Reduce(x))
.GroupBy(x => x)
.Select(x => x.Key)
.ToList();
if (reduced.Count() == 1)
{
return reduced.Single();
}
if (reduced.All(x => x.IsConstant()))
{
return reduced.Aggregate(double.MaxValue, (seed, next) => Math.Min(seed, (ValueConstant)next));
}
return Minimum.Create(reduced);
}
public Operand Visit(Maximum operand)
{
var reduced = operand
.Operands
.Select(x => Reduce(x))
.GroupBy(x => x)
.Select(x => x.Key)
.ToList();
if (reduced.Count() == 1)
{
return reduced.Single();
}
if (reduced.All(x => x.IsConstant()))
{
return reduced.Aggregate(double.MinValue, (seed, next) => Math.Max(seed, (ValueConstant)next));
}
return Maximum.Create(reduced);
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy
{
public class CallHierarchyTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnMethod()
{
var text = @"
namespace N
{
class C
{
void F$$oo()
{
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnProperty()
{
var text = @"
namespace N
{
class C
{
public int F$$oo { get; set;}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InvokeOnEvent()
{
var text = @"
using System;
namespace N
{
class C
{
public event EventHandler Fo$$o;
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_FindCalls()
{
var text = @"
namespace N
{
class C
{
void F$$oo()
{
}
}
class G
{
void Main()
{
var c = new C();
c.Foo();
}
void Main2()
{
var c = new C();
c.Foo();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main()", "N.G.Main2()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_InterfaceImplementation()
{
var text = @"
namespace N
{
interface I
{
void Foo();
}
class C : I
{
public void F$$oo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Foo();
}
void Main2()
{
var c = new C();
c.Foo();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Foo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main2()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Foo()"), new[] { "N.G.Main()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToOverride()
{
var text = @"
namespace N
{
class C
{
protected virtual void F$$oo() { }
}
class D : C
{
protected override void Foo() { }
void Bar()
{
C c;
c.Foo()
}
void Baz()
{
D d;
d.Foo();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.D.Bar()" });
testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" });
}
[WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Method_CallToBase()
{
var text = @"
namespace N
{
class C
{
protected virtual void Foo() { }
}
class D : C
{
protected override void Foo() { }
void Bar()
{
C c;
c.Foo()
}
void Baz()
{
D d;
d.Fo$$o();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.D.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Foo()") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.D.Baz()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Foo()"), new[] { "N.D.Bar()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldInitializers()
{
var text = @"
namespace N
{
class C
{
public int foo = Foo();
protected int Foo$$() { return 0; }
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo") });
testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { EditorFeaturesResources.Initializers });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FieldReferences()
{
var text = @"
namespace N
{
class C
{
public int f$$oo = Foo();
protected int Foo() { foo = 3; }
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.foo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "foo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "foo"), new[] { "N.C.Foo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void PropertyGet()
{
var text = @"
namespace N
{
class C
{
public int val
{
g$$et
{
return 0;
}
}
public int foo()
{
var x = this.val;
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.foo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void Generic()
{
var text = @"
namespace N
{
class C
{
public int gen$$eric<T>(this string generic, ref T stuff)
{
return 0;
}
public int foo()
{
int i;
generic("", ref i);
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.foo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void ExtensionMethods()
{
var text = @"
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var x = ""string"";
x.BarStr$$ing();
}
}
public static class Extensions
{
public static string BarString(this string s)
{
return s;
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void GenericExtensionMethods()
{
var text = @"
using System.Collections.Generic;
using System.Linq;
namespace N
{
class Program
{
static void Main(string[] args)
{
List<int> x = new List<int>();
var z = x.Si$$ngle();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void InterfaceImplementors()
{
var text = @"
namespace N
{
interface I
{
void Fo$$o();
}
class C : I
{
public async Task Foo()
{
}
}
class G
{
void Main()
{
I c = new C();
c.Foo();
}
void Main2()
{
var c = new C();
c.Foo();
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.I.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Implements_0, "Foo") });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main()" });
testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Foo"), new[] { "N.C.Foo()" });
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void NoFindOverridesOnSealedMethod()
{
var text = @"
namespace N
{
class C
{
void F$$oo()
{
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void FindOverrides()
{
var text = @"
namespace N
{
class C
{
public virtual void F$$oo()
{
}
}
class G : C
{
public override void Foo()
{
}
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), EditorFeaturesResources.Overrides_ });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Foo()" });
}
[WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)]
public void AbstractMethodInclusionToOverrides()
{
var text = @"
using System;
abstract class Base
{
public abstract void $$M();
}
class Derived : Base
{
public override void M()
{
throw new NotImplementedException();
}
}";
var testState = CallHierarchyTestState.Create(text);
var root = testState.GetRoot();
testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides });
testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" });
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define TEST_EXCEPTIONS
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.Test;
namespace Microsoft.Zelig.Test
{
public class FieldsTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
public override TestResult Run(string[] args)
{
TestResult result = TestResult.Pass;
string testName = "Fields";
result |= Assert.CheckFailed(Fields1_testMethod(), testName, 1);
result |= Assert.CheckFailed(Fields2_testMethod(), testName, 2);
result |= Assert.CheckFailed(Fields3_testMethod(), testName, 3);
result |= Assert.CheckFailed(Fields4_testMethod(), testName, 4);
result |= Assert.CheckFailed(Fields5_testMethod(), testName, 5);
result |= Assert.CheckFailed(Fields6_testMethod(), testName, 6);
result |= Assert.CheckFailed(Fields7_testMethod(), testName, 7);
result |= Assert.CheckFailed(Fields8_testMethod(), testName, 8);
result |= Assert.CheckFailed(Fields13_testMethod(), testName, 13);
result |= Assert.CheckFailed(Fields14_testMethod(), testName, 14);
result |= Assert.CheckFailed(Fields15_testMethod(), testName, 15);
result |= Assert.CheckFailed(Fields16_testMethod(), testName, 16);
result |= Assert.CheckFailed(Fields17_testMethod(), testName, 17);
result |= Assert.CheckFailed(Fields18_testMethod(), testName, 18);
result |= Assert.CheckFailed(Fields20_testMethod(), testName, 20);
result |= Assert.CheckFailed(Fields22_testMethod(), testName, 22);
result |= Assert.CheckFailed(Fields23_testMethod(), testName, 23);
result |= Assert.CheckFailed(Fields24_testMethod(), testName, 24);
result |= Assert.CheckFailed(Fields41_testMethod(), testName, 41);
//result |= Assert.CheckFailed(Fields42_testMethod(), testName, 42); https://github.com/NETMF/llilum/issues/127
result |= Assert.CheckFailed(Fields43_testMethod(), testName, 43);
result |= Assert.CheckFailed(Fields44_testMethod(), testName, 44);
result |= Assert.CheckFailed(Fields45_testMethod(), testName, 45);
result |= Assert.CheckFailed(Fields46_testMethod(), testName, 46);
result |= Assert.CheckFailed(Fields49_testMethod(), testName, 49);
result |= Assert.CheckFailed(Fields51_testMethod(), testName, 51);
result |= Assert.CheckFailed(Fields52_testMethod(), testName, 52);
result |= Assert.CheckFailed(Fields53_testMethod(), testName, 53);
result |= Assert.CheckFailed(Fields54_testMethod(), testName, 54);
result |= Assert.CheckFailed(Fields55_testMethod(), testName, 55);
result |= Assert.CheckFailed(Fields56_testMethod(), testName, 56);
result |= Assert.CheckFailed(Fields57_testMethod(), testName, 57);
result |= Assert.CheckFailed(Fields58_testMethod(), testName, 58);
return result;
}
//--//
//--//
//--//
//Fields Test methods
//The Fields*_testMethod() functions are ported from Fields\field*.cs files
//The following Fields tests were removed because they were build failure tests:
//9-12,,19,21,25-40,47,48,50,59-62,64
//Fields Test 42 was removed because Microsoft.SPOT.Math does not contain the abs() function which it uses
//It fails in the Baseline document
//Fields Test 63 was removed because the function isVolatile() is not defined
//It was not included in the Baseline document
//The FieldsVolatile*_testMethod() functions would be ported from Fields\Volatile\volatile*.cs files
//but none of them would build because they require
//System.Runtime.CompilerServices.isVolatile() which is not included in the Micro Framework
//Also current Visual Studios docs indicate that all variables are considered volatile
//They are not included in the Baseline document
//22,23,24,42
[TestMethod]
public TestResult Fields1_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass1.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields2_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass2.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields3_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass3.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields4_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass4.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields5_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass5.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields6_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass6.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields7_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass7.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields8_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
if (FieldsTestClass8.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields13_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A field-declaration may include set of attributes,");
Log.Comment(" a new modifier, one of four access modifiers, a");
Log.Comment(" static modifier, and a readonly modifier. The ");
Log.Comment(" attributes and modifiers apply to all of the ");
Log.Comment(" members declared by the field-declaration.");
Log.Comment("");
Log.Comment(" A field declaration that declares multiple fields");
Log.Comment(" is equivalent to multiple declarations of single ");
Log.Comment(" fields with the same attributes, modifiers, and type.");
if (FieldsTestClass13.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields14_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A static field identifies exactly on storage location.");
Log.Comment(" No matter how many instances of a class are created,");
Log.Comment(" there is only ever one copy of a static field.");
if (FieldsTestClass14.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields15_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A static field comes into existence when the ");
Log.Comment(" type in which it is declared is loaded, and ");
Log.Comment(" ceases to exist when the type in which it ");
Log.Comment(" is declared in unloaded.");
if (FieldsTestClass15.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields16_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" Every instance of a class contains a separate copy");
Log.Comment(" of all instance fields of the class. An instance ");
Log.Comment(" field comes into existence when a new instance of ");
Log.Comment(" its class is created, and ceases to exist when there ");
Log.Comment(" are no references to that instance and the destructor");
Log.Comment(" of the instance has executed.");
if (FieldsTestClass16.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields17_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" Every instance of a class contains a separate copy");
Log.Comment(" of all instance fields of the class. An instance ");
Log.Comment(" field comes into existence when a new instance of ");
Log.Comment(" its class is created, and ceases to exist when there ");
Log.Comment(" are no references to that instance and the destructor");
Log.Comment(" of the instance has executed.");
#if TEST_EXCEPTIONS
if (FieldsTestClass17.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
#else
return TestResult.Skip;
#endif
}
[TestMethod]
public TestResult Fields18_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" When a field is referenced in a member-access of");
Log.Comment(" the form E.M, if M is a static field, E must denote");
Log.Comment(" a type, and if M is an instance field, E must ");
Log.Comment(" denote an instance.");
if (FieldsTestClass18.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields20_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" When a field is referenced in a member-access of");
Log.Comment(" the form E.M, if M is a static field, E must denote");
Log.Comment(" a type, and if M is an instance field, E must ");
Log.Comment(" denote an instance.");
if (FieldsTestClass20.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields22_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" When a field-declaration includes a readonly");
Log.Comment(" modifier, assignments to the fields introduced");
Log.Comment(" by the declaration can only occur as part of");
Log.Comment(" the declaration or in a constructor in the");
Log.Comment(" same class.");
if (FieldsTestClass22.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields23_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" When a field-declaration includes a readonly");
Log.Comment(" modifier, assignments to the fields introduced");
Log.Comment(" by the declaration can only occur as part of");
Log.Comment(" the declaration or in a constructor in the");
Log.Comment(" same class.");
if (FieldsTestClass23.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields24_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" When a field-declaration includes a readonly");
Log.Comment(" modifier, assignments to the fields introduced");
Log.Comment(" by the declaration can only occur as part of");
Log.Comment(" the declaration or in a constructor in the");
Log.Comment(" same class.");
if (FieldsTestClass24.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields41_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" A static readonly field is useful when a symbolic");
Log.Comment(" name for a constant value is desired, but when the ");
Log.Comment(" type of the value is not permitted in a const declaration");
Log.Comment(" or when the value cannot be computed at compile-time");
Log.Comment(" by a constant expression.");
if (FieldsTestClass41.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields42_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" Field declarations may include variable-initializers.");
Log.Comment(" For static fields, varaible initializers correspond to");
Log.Comment(" assignment statements that are executed when the class");
Log.Comment(" is loaded. For instance fields, variable initializers");
Log.Comment(" correspond to assignment statements that are executed");
Log.Comment(" when an instance of the class is created.");
Log.Comment("This test has been rewritten to avoid use of the Math.Abs function which the MF does not support");
if (FieldsTestClass42.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields43_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" The static field variable initializers of a class");
Log.Comment(" correspond to a sequence of assignments that are ");
Log.Comment(" executed immediately upon entry to the static");
Log.Comment(" constructor of a class. The variable initializers");
Log.Comment(" are executed in the textual order they appear");
Log.Comment(" in the class declaration.");
if (FieldsTestClass43.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields44_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" The static field variable initializers of a class");
Log.Comment(" correspond to a sequence of assignments that are ");
Log.Comment(" executed immediately upon entry to the static");
Log.Comment(" constructor of a class. The variable initializers");
Log.Comment(" are executed in the textual order they appear");
Log.Comment(" in the class declaration.");
if (FieldsTestClass44.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields45_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" The static field variable initializers of a class");
Log.Comment(" correspond to a sequence of assignments that are ");
Log.Comment(" executed immediately upon entry to the static");
Log.Comment(" constructor of a class. The variable initializers");
Log.Comment(" are executed in the textual order they appear");
Log.Comment(" in the class declaration.");
if (FieldsTestClass45.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields46_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" The instance field variable initializers of a class");
Log.Comment(" correspond to a sequence of assignments that are ");
Log.Comment(" executed immediately upon entry to one of the instance");
Log.Comment(" constructors of the class.");
if (FieldsTestClass46.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields49_testMethod()
{
Log.Comment(" A variable initializer for an instance field");
Log.Comment(" cannot reference the instance being created.");
Log.Comment(" Thus, it is an error to reference this in a ");
Log.Comment(" variable initializer, as it is an error for");
Log.Comment(" a variable initialzer to reference any instance");
Log.Comment(" member through a simple-name.");
if (FieldsTestClass49.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields51_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" Specifically, assignments to a readonly field");
Log.Comment(" are permitted only in the following context.");
Log.Comment(" ...");
Log.Comment(" For an instance field, in the instance constructors");
Log.Comment(" of the class that contains the field declaration, or");
Log.Comment(" for a static field, in the static constructor of the");
Log.Comment(" class the contains the field declaration. These are also");
Log.Comment(" contexts in which it is valid to pass a readonly field");
Log.Comment(" as an out or ref parameter.");
if (FieldsTestClass51.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields52_testMethod()
{
Log.Comment(" Section 10.4");
Log.Comment(" Specifically, assignments to a readonly field");
Log.Comment(" are permitted only in the following context.");
Log.Comment(" ...");
Log.Comment(" For an instance field, in the instance constructors");
Log.Comment(" of the class that contains the field declaration, or");
Log.Comment(" for a static field, in the static constructor of the");
Log.Comment(" class the contains the field declaration. These are also");
Log.Comment(" contexts in which it is valid to pass a readonly field");
Log.Comment(" as an out or ref parameter.");
if (FieldsTestClass52.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields53_testMethod()
{
Log.Comment("Testing bools assigned with (x == y)");
if (FieldsTestClass53.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields54_testMethod()
{
Log.Comment("Testing bools assigned with function calls");
if (FieldsTestClass54.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields55_testMethod()
{
Log.Comment("Testing bools assigned with conditionals");
if (FieldsTestClass55.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields56_testMethod()
{
Log.Comment("Testing ints assigned with function calls");
if (FieldsTestClass56.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields57_testMethod()
{
Log.Comment("Testing strings assigned with \"x\" + \"y\"");
if (FieldsTestClass57.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Fields58_testMethod()
{
Log.Comment("Testing strings assigned with function calls");
if (FieldsTestClass58.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
class FieldsTestClass1
{
int intI = 2;
public static bool testMethod()
{
FieldsTestClass1 test = new FieldsTestClass1();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass2_Base
{
public int intI = 1;
}
class FieldsTestClass2 : FieldsTestClass2_Base
{
new int intI = 2;
public static bool testMethod()
{
FieldsTestClass2 test = new FieldsTestClass2();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass3
{
public int intI = 2;
public static bool testMethod()
{
FieldsTestClass3 test = new FieldsTestClass3();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass4
{
protected int intI = 2;
public static bool testMethod()
{
FieldsTestClass4 test = new FieldsTestClass4();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass5
{
internal int intI = 2;
public static bool testMethod()
{
FieldsTestClass5 test = new FieldsTestClass5();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass6
{
private int intI = 2;
public static bool testMethod()
{
FieldsTestClass6 test = new FieldsTestClass6();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass7
{
static int intI = 2;
public static bool testMethod()
{
if (intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass8
{
readonly int intI = 2;
public static bool testMethod()
{
FieldsTestClass8 test = new FieldsTestClass8();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass13_Base
{
public int intI = 2, intJ = 3;
}
class FieldsTestClass13
{
public static bool testMethod()
{
FieldsTestClass13_Base test = new FieldsTestClass13_Base();
if ((test.intI == 2) && (test.intJ == 3))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass14
{
static int intI = 1;
public void ChangeInt(int intJ)
{
intI = intJ;
}
public static bool testMethod()
{
FieldsTestClass14 c1 = new FieldsTestClass14();
c1.ChangeInt(2);
FieldsTestClass14 c2 = new FieldsTestClass14();
c1.ChangeInt(3);
FieldsTestClass14 c3 = new FieldsTestClass14();
c1.ChangeInt(4);
if (intI == 4)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass15_Base
{
public static int intI = 1;
}
class FieldsTestClass15
{
public static bool testMethod()
{
if (FieldsTestClass15_Base.intI == 1)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass16
{
int intI = 1;
public void ChangeInt(int intJ)
{
intI = intJ;
}
public static bool testMethod()
{
FieldsTestClass16 c1 = new FieldsTestClass16();
c1.ChangeInt(2);
FieldsTestClass16 c2 = new FieldsTestClass16();
c2.ChangeInt(3);
FieldsTestClass16 c3 = new FieldsTestClass16();
c3.ChangeInt(4);
if ((c1.intI == 2) && (c2.intI == 3) && (c3.intI == 4))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass17_Base
{
public int intI = 1;
}
class FieldsTestClass17
{
FieldsTestClass17_Base tc;
public static bool testMethod()
{
try
{
bool RetVal = false;
FieldsTestClass17 test = new FieldsTestClass17();
try
{
int intJ = test.tc.intI; //MyTest hasn't been instantiated
}
catch (System.Exception)
{
RetVal = true;
}
return RetVal;
}
catch { return false; }
}
}
class FieldsTestClass18
{
static int intI = 2;
public static bool testMethod()
{
if (FieldsTestClass18.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass20
{
int intI = 2;
public static bool testMethod()
{
FieldsTestClass20 test = new FieldsTestClass20();
if (test.intI == 2)
{
return true;
}
else
{
return false;
}
}
}
enum FieldsTestClass22_Enum { a = 1, b = 2 }
struct FieldsTestClass22_Struct
{
public FieldsTestClass22_Struct(int intI)
{
Test = intI;
}
public int Test;
}
struct FieldsTestClass22_Sub
{
public FieldsTestClass22_Sub(int intI)
{
Test = intI;
}
public int Test;
}
class FieldsTestClass22
{
readonly int intI = 2;
readonly string strS = "MyString";
readonly FieldsTestClass22_Enum enuE = FieldsTestClass22_Enum.a;
readonly FieldsTestClass22_Struct sctS = new FieldsTestClass22_Struct(3);
readonly FieldsTestClass22_Sub clsC = new FieldsTestClass22_Sub(4);
public static bool testMethod()
{
FieldsTestClass22 MC = new FieldsTestClass22();
if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass22_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4))
{
return true;
}
else
{
return false;
}
}
}
enum FieldsTestClass23_Enum { a = 1, b = 2 }
struct FieldsTestClass23_Struct
{
public FieldsTestClass23_Struct(int intI)
{
Test = intI;
}
public int Test;
}
struct FieldsTestClass23_Sub
{
public FieldsTestClass23_Sub(int intI)
{
Test = intI;
}
public int Test;
}
class FieldsTestClass23
{
public FieldsTestClass23()
{
intI = 2;
strS = "MyString";
enuE = FieldsTestClass23_Enum.a;
sctS = new FieldsTestClass23_Struct(3);
clsC = new FieldsTestClass23_Sub(4);
}
readonly int intI;
readonly string strS;
readonly FieldsTestClass23_Enum enuE;
readonly FieldsTestClass23_Struct sctS;
readonly FieldsTestClass23_Sub clsC;
public static bool testMethod()
{
FieldsTestClass23 MC = new FieldsTestClass23();
if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass23_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4))
{
return true;
}
else
{
return false;
}
}
}
enum FieldsTestClass24_Enum { a = 1, b = 2 }
struct FieldsTestClass24_Struct
{
public FieldsTestClass24_Struct(int intI)
{
Test = intI;
}
public int Test;
}
struct FieldsTestClass24_Sub
{
public FieldsTestClass24_Sub(int intI)
{
Test = intI;
}
public int Test;
}
class FieldsTestClass24
{
public FieldsTestClass24()
{
intI = 2;
strS = "MyString";
enuE = FieldsTestClass24_Enum.a;
sctS = new FieldsTestClass24_Struct(3);
clsC = new FieldsTestClass24_Sub(4);
}
readonly int intI = 3;
readonly string strS = "FooBar";
readonly FieldsTestClass24_Enum enuE = FieldsTestClass24_Enum.b;
readonly FieldsTestClass24_Struct sctS = new FieldsTestClass24_Struct(2);
readonly FieldsTestClass24_Sub clsC = new FieldsTestClass24_Sub(5);
public static bool testMethod()
{
FieldsTestClass24 MC = new FieldsTestClass24();
if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass24_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4))
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass41
{
public static readonly FieldsTestClass41 Black = new FieldsTestClass41(0, 0, 0);
public static readonly FieldsTestClass41 White = new FieldsTestClass41(255, 255, 255);
public static readonly FieldsTestClass41 Red = new FieldsTestClass41(255, 0, 0);
public static readonly FieldsTestClass41 Green = new FieldsTestClass41(0, 255, 0);
public static readonly FieldsTestClass41 Blue = new FieldsTestClass41(0, 0, 255);
private byte red, green, blue;
public FieldsTestClass41(byte r, byte g, byte b)
{
red = r;
green = g;
blue = b;
}
public void getRGB(out byte r1, out byte g1, out byte b1)
{
r1 = red;
g1 = green;
b1 = blue;
}
public static bool testMethod()
{
FieldsTestClass41 wht = FieldsTestClass41.White;
byte r2, g2, b2;
wht.getRGB(out r2, out g2, out b2);
if ((r2 == 255) && (g2 == 255) && (b2 == 255))
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass42
{
static int x = (int)Math.Cos(4 - 2) * 100;
int i = 100;
string s = "Hello";
public static bool testMethod()
{
try
{
FieldsTestClass42 t = new FieldsTestClass42();
if ((x == Math.Cos(2)) && (t.i == 100) && (t.s.Equals("Hello")))
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}
public class FieldsTestClass43
{
static int intI;
static int intJ = 2;
//intJ should be initialized before we enter the static constructor
static FieldsTestClass43()
{
intI = intJ;
}
public static bool testMethod()
{
if (intI == 2)
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass44
{
static int intI = 2;
//intI is initialized before intJ
static int intJ = intI + 3;
public static bool testMethod()
{
if (intJ == 5)
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass45
{
//intI is initialized after intJ
static int intJ = intI + 3;
static int intI = 2;
public static bool testMethod()
{
if (intJ == 3)
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass46
{
int intI = 2;
int intJ;
int intK;
public FieldsTestClass46()
{
//int I should already be initialized
intJ = intI;
}
public FieldsTestClass46(int DummyInt)
{
//int I should already be initialized
intK = intI;
}
public static bool testMethod()
{
FieldsTestClass46 test1 = new FieldsTestClass46();
FieldsTestClass46 test2 = new FieldsTestClass46(0);
if ((test1.intJ == 2) && (test2.intK == 2))
{
return true;
}
else
{
return false;
}
}
}
public class FieldsTestClass49
{
public static int intI = 2;
public int intK = intI;
public static bool testMethod()
{
FieldsTestClass49 test = new FieldsTestClass49();
if (test.intK == 2)
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass51
{
FieldsTestClass51()
{
MyMeth1(ref intI);
MyMeth2(out intJ);
}
public static void MyMeth1(ref int i)
{
i = 2;
}
public static void MyMeth2(out int j)
{
j = 3;
}
public readonly int intI;
public readonly int intJ;
public static bool testMethod()
{
FieldsTestClass51 mc = new FieldsTestClass51();
if ((mc.intI == 2) && (mc.intJ == 3))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass52
{
static FieldsTestClass52()
{
MyMeth1(ref intI);
MyMeth2(out intJ);
}
public static void MyMeth1(ref int i)
{
i = 2;
}
public static void MyMeth2(out int j)
{
j = 3;
}
public static readonly int intI;
public static readonly int intJ;
public static bool testMethod()
{
if ((FieldsTestClass52.intI == 2) && (FieldsTestClass52.intJ == 3))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass53
{
public static bool b1 = (3 == 3);
public static bool b2 = (3 == 4);
public bool b3 = (3 == 3);
public bool b4 = (3 == 4);
public static bool testMethod()
{
FieldsTestClass53 mc = new FieldsTestClass53();
if ((b1 == true) && (b2 == false) && (mc.b3 == true) && (mc.b4 == false))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass54
{
public static bool b1 = RetTrue();
public static bool b2 = RetFalse();
public bool b3 = RetTrue();
public bool b4 = RetFalse();
public static bool RetTrue()
{
return true;
}
public static bool RetFalse()
{
return false;
}
public static bool testMethod()
{
FieldsTestClass54 mc = new FieldsTestClass54();
if ((b1 == true) && (b2 == false) && (mc.b3 == true) && (mc.b4 == false))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass55
{
public static int i1 = (3 & 6);
public static int i2 = (3 | 6);
public int i3 = (3 & 6);
public int i4 = (3 | 6);
public static bool testMethod()
{
FieldsTestClass55 mc = new FieldsTestClass55();
if ((i1 == 2) && (i2 == 7) && (mc.i3 == 2) && (mc.i4 == 7))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass56
{
public static int i1 = Ret2();
public static int i2 = Ret7();
public int i3 = Ret2();
public int i4 = Ret7();
public static int Ret2()
{
return 2;
}
public static int Ret7()
{
return 7;
}
public static bool testMethod()
{
FieldsTestClass56 mc = new FieldsTestClass56();
if ((i1 == 2) && (i2 == 7) && (mc.i3 == 2) && (mc.i4 == 7))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass57
{
public static string s1 = "foo" + "bar";
public static string s2 = "bar" + "foo";
public string s3 = "foo" + "bar";
public string s4 = "bar" + "foo";
public static bool testMethod()
{
FieldsTestClass57 mc = new FieldsTestClass57();
if ((s1 == "foobar") && (s2 == "barfoo") && (mc.s3 == "foobar") && (mc.s4 == "barfoo"))
{
return true;
}
else
{
return false;
}
}
}
class FieldsTestClass58
{
public static string s1 = Ret1();
public static string s2 = Ret2();
public string s3 = Ret1();
public string s4 = Ret2();
public static string Ret1()
{
return "foobar";
}
public static string Ret2()
{
return "barfoo";
}
public static bool testMethod()
{
try
{
FieldsTestClass58 mc = new FieldsTestClass58();
if ((s1 == "foobar") && (s2 == "barfoo") && (mc.s3 == "foobar") && (mc.s4 == "barfoo"))
{
return true;
}
else
{
return false;
}
}
catch { return false; }
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonDictionaryContract : JsonContainerContract
{
/// <summary>
/// Gets or sets the dictionary key resolver.
/// </summary>
/// <value>The dictionary key resolver.</value>
public Func<string, string>? DictionaryKeyResolver { get; set; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary keys.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary keys.</value>
public Type? DictionaryKeyType { get; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary values.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary values.</value>
public Type? DictionaryValueType { get; }
internal JsonContract? KeyContract { get; set; }
private readonly Type? _genericCollectionDefinitionType;
private Type? _genericWrapperType;
private ObjectConstructor<object>? _genericWrapperCreator;
private Func<object>? _genericTemporaryDictionaryCreator;
internal bool ShouldCreateWrapper { get; }
private readonly ConstructorInfo? _parameterizedConstructor;
private ObjectConstructor<object>? _overrideCreator;
private ObjectConstructor<object>? _parameterizedCreator;
internal ObjectConstructor<object>? ParameterizedCreator
{
get
{
if (_parameterizedCreator == null && _parameterizedConstructor != null)
{
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
}
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object>? OverrideCreator
{
get => _overrideCreator;
set => _overrideCreator = value;
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the dictionary values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal => (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null);
/// <summary>
/// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonDictionaryContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Dictionary;
Type? keyType;
Type? valueType;
if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>)))
{
CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
}
else if (NonNullableUnderlyingType.IsGenericType())
{
// ConcurrentDictionary<,> + IDictionary setter + null value = error
// wrap to use generic setter
// https://github.com/JamesNK/Newtonsoft.Json/issues/1582
Type typeDefinition = NonNullableUnderlyingType.GetGenericTypeDefinition();
if (typeDefinition.FullName == JsonTypeReflector.ConcurrentDictionaryTypeName)
{
ShouldCreateWrapper = true;
}
}
#if HAVE_READ_ONLY_COLLECTIONS
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(NonNullableUnderlyingType, typeof(ReadOnlyDictionary<,>));
#endif
}
#if HAVE_READ_ONLY_COLLECTIONS
else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>)))
{
CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType);
}
IsReadOnlyOrFixedSize = true;
}
#endif
else
{
ReflectionUtils.GetDictionaryKeyValueTypes(NonNullableUnderlyingType, out keyType, out valueType);
if (NonNullableUnderlyingType == typeof(IDictionary))
{
CreatedType = typeof(Dictionary<object, object>);
}
}
if (keyType != null && valueType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(
CreatedType,
typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType),
typeof(IDictionary<,>).MakeGenericType(keyType, valueType));
#if HAVE_FSHARP_TYPES
if (!HasParameterizedCreatorInternal && NonNullableUnderlyingType.Name == FSharpUtils.FSharpMapTypeName)
{
FSharpUtils.EnsureInitialized(NonNullableUnderlyingType.Assembly());
_parameterizedCreator = FSharpUtils.Instance.CreateMap(keyType, valueType);
}
#endif
}
if (!typeof(IDictionary).IsAssignableFrom(CreatedType))
{
ShouldCreateWrapper = true;
}
DictionaryKeyType = keyType;
DictionaryValueType = valueType;
#if (NET20 || NET35)
if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType))
{
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _))
{
ShouldCreateWrapper = true;
}
}
#endif
if (DictionaryKeyType != null &&
DictionaryValueType != null &&
ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(
NonNullableUnderlyingType,
DictionaryKeyType,
DictionaryValueType,
out Type? immutableCreatedType,
out ObjectConstructor<object>? immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
}
}
internal IWrappedDictionary CreateWrapper(object dictionary)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType);
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedDictionary)_genericWrapperCreator(dictionary);
}
internal IDictionary CreateTemporaryDictionary()
{
if (_genericTemporaryDictionaryCreator == null)
{
Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object));
_genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType);
}
return (IDictionary)_genericTemporaryDictionaryCreator();
}
}
}
| |
//
// Encog(tm) Core v3.3 - .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.Analyst.CSV.Basic;
using Encog.App.Analyst.Missing;
using Encog.App.Analyst.Script.Normalize;
using Encog.App.Analyst.Util;
using Encog.App.Quant;
using Encog.Util.Arrayutil;
using Encog.Util.CSV;
using Encog.Util.Logging;
namespace Encog.App.Analyst.CSV.Normalize
{
/// <summary>
/// Normalize, or denormalize, a CSV file.
/// </summary>
public class AnalystNormalizeCSV : BasicFile
{
/// <summary>
/// The analyst to use.
/// </summary>
private EncogAnalyst _analyst;
/// <summary>
/// THe headers.
/// </summary>
private CSVHeaders _analystHeaders;
/// <summary>
/// Used to process time series.
/// </summary>
private TimeSeriesUtil _series;
/// <summary>
/// Extract fields from a file into a numeric array for machine learning.
/// </summary>
/// <param name="analyst">The analyst to use.</param>
/// <param name="headers">The headers for the input data.</param>
/// <param name="csv">The CSV that holds the input data.</param>
/// <param name="outputLength">The length of the returned array.</param>
/// <param name="skipOutput">True if the output should be skipped.</param>
/// <returns>The encoded data.</returns>
public static double[] ExtractFields(EncogAnalyst analyst,
CSVHeaders headers, ReadCSV csv,
int outputLength, bool skipOutput)
{
var output = new double[outputLength];
int outputIndex = 0;
foreach (AnalystField stat in analyst.Script.Normalize.NormalizedFields)
{
stat.Init();
if (stat.Action == NormalizationAction.Ignore)
{
continue;
}
if (stat.Output && skipOutput)
{
continue;
}
int index = headers.Find(stat.Name);
String str = csv.Get(index);
// is this an unknown value?
if (str.Equals("?") || str.Length == 0)
{
IHandleMissingValues handler = analyst.Script.Normalize.MissingValues;
double[] d = handler.HandleMissing(analyst, stat);
// should we skip the entire row
if (d == null)
{
return null;
}
// copy the returned values in place of the missing values
for (int i = 0; i < d.Length; i++)
{
output[outputIndex++] = d[i];
}
}
else
{
// known value
if (stat.Action == NormalizationAction.Normalize)
{
double d = csv.Format.Parse(str.Trim());
d = stat.Normalize(d);
output[outputIndex++] = d;
}
else if (stat.Action == NormalizationAction.PassThrough)
{
double d = csv.Format.Parse(str);
output[outputIndex++] = d;
}
else
{
double[] d = stat.Encode(str.Trim());
foreach (double element in d)
{
output[outputIndex++] = element;
}
}
}
}
return output;
}
/// <summary>
/// Analyze the file.
/// </summary>
/// <param name="inputFilename">The input file.</param>
/// <param name="expectInputHeaders">True, if input headers are present.</param>
/// <param name="inputFormat">The format.</param>
/// <param name="theAnalyst">The analyst to use.</param>
public void Analyze(FileInfo inputFilename,
bool expectInputHeaders, CSVFormat inputFormat,
EncogAnalyst theAnalyst)
{
InputFilename = inputFilename;
Format = inputFormat;
ExpectInputHeaders = expectInputHeaders;
_analyst = theAnalyst;
Analyzed = true;
_analystHeaders = new CSVHeaders(inputFilename, expectInputHeaders,
inputFormat);
foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields)
{
field.Init();
}
_series = new TimeSeriesUtil(_analyst, true,
_analystHeaders.Headers);
}
/// <summary>
/// Normalize the input file. Write to the specified file.
/// </summary>
/// <param name="file">The file to write to.</param>
public void Normalize(FileInfo file)
{
if (_analyst == null)
{
throw new EncogError(
"Can't normalize yet, file has not been analyzed.");
}
ReadCSV csv = null;
StreamWriter tw = null;
try
{
csv = new ReadCSV(InputFilename.ToString(),
ExpectInputHeaders, Format);
file.Delete();
tw = new StreamWriter(file.OpenWrite());
// write headers, if needed
if (ProduceOutputHeaders)
{
WriteHeaders(tw);
}
ResetStatus();
int outputLength = _analyst.DetermineTotalColumns();
// write file contents
while (csv.Next() && !ShouldStop())
{
UpdateStatus(false);
double[] output = ExtractFields(
_analyst, _analystHeaders, csv, outputLength,
false);
if (_series.TotalDepth > 1)
{
output = _series.Process(output);
}
if (output != null)
{
var line = new StringBuilder();
NumberList.ToList(Format, line, output);
tw.WriteLine(line);
}
}
}
catch (IOException e)
{
throw new QuantError(e);
}
finally
{
ReportDone(false);
if (csv != null)
{
try
{
csv.Close();
}
catch (Exception ex)
{
EncogLogging.Log(ex);
}
}
if (tw != null)
{
try
{
tw.Close();
}
catch (Exception ex)
{
EncogLogging.Log(ex);
}
}
}
}
/// <summary>
/// Set the source file. This is useful if you want to use pre-existing stats
/// to normalize something and skip the analyze step.
/// </summary>
/// <param name="file">The file to use.</param>
/// <param name="headers">True, if headers are to be expected.</param>
/// <param name="format">The format of the CSV file.</param>
public void SetSourceFile(FileInfo file, bool headers,
CSVFormat format)
{
InputFilename = file;
ExpectInputHeaders = headers;
Format = format;
}
/// <summary>
/// Write the headers.
/// </summary>
/// <param name="tw">The output stream.</param>
private void WriteHeaders(StreamWriter tw)
{
var line = new StringBuilder();
foreach (AnalystField stat in _analyst.Script.Normalize.NormalizedFields)
{
int needed = stat.ColumnsNeeded;
for (int i = 0; i < needed; i++)
{
AppendSeparator(line, Format);
line.Append('\"');
line.Append(CSVHeaders.TagColumn(stat.Name, i,
stat.TimeSlice, needed > 1));
line.Append('\"');
}
}
tw.WriteLine(line.ToString());
}
}
}
| |
// <copyright file="UserSvdTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Factorization
{
/// <summary>
/// Svd factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserSvdTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorSvd = matrixI.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
Assert.AreEqual(matrixI.RowCount, u.RowCount);
Assert.AreEqual(matrixI.RowCount, u.ColumnCount);
Assert.AreEqual(matrixI.ColumnCount, vt.RowCount);
Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount);
Assert.AreEqual(matrixI.RowCount, w.RowCount);
Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount);
for (var i = 0; i < w.RowCount; i++)
{
for (var j = 0; j < w.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, w[i, j]);
}
}
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
// Make sure the U has the right dimensions.
Assert.AreEqual(row, u.RowCount);
Assert.AreEqual(row, u.ColumnCount);
// Make sure the VT has the right dimensions.
Assert.AreEqual(column, vt.RowCount);
Assert.AreEqual(column, vt.ColumnCount);
// Make sure the W has the right dimensions.
Assert.AreEqual(row, w.RowCount);
Assert.AreEqual(column, w.ColumnCount);
// Make sure the U*W*VT is the original matrix.
var matrix = u*w*vt;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
Assert.AreEqual(matrixA[i, j], matrix[i, j], 1.0e-11);
}
}
}
/// <summary>
/// Can check rank of a non-square matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(10, 8)]
[TestCase(48, 52)]
[TestCase(100, 93)]
public void CanCheckRankOfNonSquare(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var mn = Math.Min(row, column);
Assert.AreEqual(factorSvd.Rank, mn);
}
/// <summary>
/// Can check rank of a square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(9)]
[TestCase(50)]
[TestCase(90)]
public void CanCheckRankSquare(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray());
var factorSvd = matrixA.Svd();
if (factorSvd.Determinant != 0)
{
Assert.AreEqual(factorSvd.Rank, order);
}
else
{
Assert.AreEqual(factorSvd.Rank, order - 1);
}
}
/// <summary>
/// Can check rank of a square singular matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanCheckRankOfSquareSingular(int order)
{
var matrixA = new UserDefinedMatrix(order, order);
matrixA[0, 0] = 1;
matrixA[order - 1, order - 1] = 1;
for (var i = 1; i < order - 1; i++)
{
matrixA[i, i - 1] = 1;
matrixA[i, i + 1] = 1;
matrixA[i - 1, i] = 1;
matrixA[i + 1, i] = 1;
}
var factorSvd = matrixA.Svd();
Assert.AreEqual(factorSvd.Determinant, 0);
Assert.AreEqual(factorSvd.Rank, order - 1);
}
/// <summary>
/// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(10, 10, 1).ToArray());
Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException);
}
/// <summary>
/// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(10, 10, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var vectorb = new UserDefinedVector(Vector<double>.Build.Random(10, 1).ToArray());
Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException);
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVector(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<double>.Build.Random(row, 1).ToArray());
var resultx = factorSvd.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixX = factorSvd.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<double>.Build.Random(row, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(column);
factorSvd.Solve(vectorb, resultx);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(column, column);
factorSvd.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
#region Using Statements
using System;
using System.Linq;
using System.IO;
using System.Threading;
using Cake.Core;
using Cake.Testing;
using Microsoft.Web.Administration;
#endregion
namespace Cake.IIS.Tests
{
internal static class CakeHelper
{
#region Methods
//Cake
public static ICakeEnvironment CreateEnvironment()
{
var environment = FakeEnvironment.CreateWindowsEnvironment();
environment.WorkingDirectory = Directory.GetCurrentDirectory();
environment.WorkingDirectory = environment.WorkingDirectory.Combine("../../../");
return environment;
}
//Managers
public static ApplicationPoolManager CreateApplicationPoolManager()
{
ApplicationPoolManager manager = new ApplicationPoolManager(CakeHelper.CreateEnvironment(), new DebugLog());
manager.SetServer();
return manager;
}
public static RewriteManager CreateRewriteManager()
{
RewriteManager manager = new RewriteManager(CakeHelper.CreateEnvironment(), new DebugLog());
manager.SetServer();
return manager;
}
public static FtpsiteManager CreateFtpsiteManager()
{
FtpsiteManager manager = new FtpsiteManager(CakeHelper.CreateEnvironment(), new DebugLog());
manager.SetServer();
return manager;
}
public static WebsiteManager CreateWebsiteManager()
{
WebsiteManager manager = new WebsiteManager(CakeHelper.CreateEnvironment(), new DebugLog());
manager.SetServer();
return manager;
}
public static WebFarmManager CreateWebFarmManager()
{
WebFarmManager manager = new WebFarmManager(CakeHelper.CreateEnvironment(), new DebugLog());
manager.SetServer();
return manager;
}
//Settings
public static ApplicationPoolSettings GetAppPoolSettings(string name = "DC")
{
return new ApplicationPoolSettings
{
Name = name,
IdentityType = IdentityType.NetworkService,
Autostart = true,
MaxProcesses = 1,
Enable32BitAppOnWin64 = false,
IdleTimeout = TimeSpan.FromMinutes(20),
ShutdownTimeLimit = TimeSpan.FromSeconds(90),
StartupTimeLimit = TimeSpan.FromSeconds(90),
PingingEnabled = true,
PingInterval = TimeSpan.FromSeconds(30),
PingResponseTime = TimeSpan.FromSeconds(90),
Overwrite = false
};
}
public static RewriteRuleSettings GetRewriteRuleSettings(string name)
{
return new RewriteRuleSettings
{
Name = name,
Pattern = "*",
PatternSintax = RewritePatternSintax.Wildcard,
IgnoreCase = true,
StopProcessing = true,
Conditions = new[]
{
new RewriteRuleConditionSettings {ConditionInput = "{HTTPS}", Pattern = "off", IgnoreCase = true},
},
Action = new RewriteRuleRedirectAction
{
Url = @"https://{HTTP_HOST}{REQUEST_URI}",
RedirectType = RewriteRuleRedirectType.Found
}
};
}
public static WebsiteSettings GetWebsiteSettings(string name = "Superman")
{
WebsiteSettings settings = new WebsiteSettings
{
Name = name,
PhysicalDirectory = "./Test/" + name,
ApplicationPool = CakeHelper.GetAppPoolSettings(),
ServerAutoStart = true,
Overwrite = false
};
settings.Binding = IISBindings.Http
.SetHostName(name + ".web")
.SetIpAddress("*")
.SetPort(80);
return settings;
}
public static ApplicationSettings GetApplicationSettings(string name)
{
return new ApplicationSettings
{
ApplicationPath = "/Test",
ApplicationPool = CakeHelper.GetAppPoolSettings().Name,
VirtualDirectory = "/",
PhysicalDirectory = "./Test/App/",
SiteName = name,
};
}
public static WebFarmSettings GetWebFarmSettings()
{
return new WebFarmSettings
{
Name = "Batman",
Servers = new string[] { "Gotham", "Metroplis" }
};
}
public static AuthenticationSettings GetAuthenticationSettings(bool? anonymous, bool? basic, bool? windows)
{
return new AuthenticationSettings()
{
EnableAnonymousAuthentication = anonymous,
EnableBasicAuthentication = basic,
EnableWindowsAuthentication = windows
};
}
//Website
public static void CreateWebsite(WebsiteSettings settings)
{
WebsiteManager manager = CakeHelper.CreateWebsiteManager();
manager.Create(settings);
}
public static void DeleteWebsite(string name)
{
using (var server = new ServerManager())
{
var site = server.Sites.FirstOrDefault(x => x.Name == name);
if (site != null)
{
server.Sites.Remove(site);
server.CommitChanges();
}
}
}
public static Site GetWebsite(string name)
{
using (var serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(x => x.Name == name);
// Below is required to fetch ApplicationDefaults before disposing ServerManager.
if (site != null && site.ApplicationDefaults != null)
{
return site;
}
return site;
}
}
public static Application GetApplication(string siteName, string appPath)
{
using (var serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(x => x.Name == siteName);
return site != null ? site.Applications.FirstOrDefault(a => a.Path == appPath) : null;
}
}
public static object GetWebConfigurationValue(string siteName, string appPath, string section, string key)
{
using (var serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(x => x.Name == siteName);
Configuration config;
if (appPath != null)
{
var app = site?.Applications.FirstOrDefault(a => a.Path == appPath);
config = app?.GetWebConfiguration();
}
else
{
config = site?.GetWebConfiguration();
}
var sectionObject = config?.GetSection(section);
return sectionObject?[key];
}
}
public static void StartWebsite(string name)
{
using (var server = new ServerManager())
{
Site site = server.Sites.FirstOrDefault(x => x.Name == name);
if (site != null)
{
try
{
site.Start();
}
catch (System.Runtime.InteropServices.COMException)
{
Thread.Sleep(1000);
}
}
}
}
public static void StopWebsite(string name)
{
using (var server = new ServerManager())
{
Site site = server.Sites.FirstOrDefault(x => x.Name == name);
if (site != null)
{
try
{
site.Stop();
}
catch (System.Runtime.InteropServices.COMException)
{
Thread.Sleep(1000);
}
}
}
}
//Pool
public static void CreatePool(ApplicationPoolSettings settings)
{
ApplicationPoolManager manager = CakeHelper.CreateApplicationPoolManager();
manager.Create(settings);
}
public static void DeletePool(string name)
{
using (var server = new ServerManager())
{
ApplicationPool pool = server.ApplicationPools.FirstOrDefault(x => x.Name == name);
if (pool != null)
{
server.ApplicationPools.Remove(pool);
server.CommitChanges();
}
}
}
public static ApplicationPool GetPool(string name)
{
using (var server = new ServerManager())
{
return server.ApplicationPools.FirstOrDefault(x => x.Name == name);
}
}
public static void StartPool(string name)
{
using (var server = new ServerManager())
{
ApplicationPool pool = server.ApplicationPools.FirstOrDefault(x => x.Name == name);
if (pool != null)
{
try
{
pool.Start();
}
catch (System.Runtime.InteropServices.COMException)
{
Thread.Sleep(1000);
}
}
}
}
public static void StopPool(string name)
{
using (var server = new ServerManager())
{
ApplicationPool pool = server.ApplicationPools.FirstOrDefault(x => x.Name == name);
if (pool != null)
{
try
{
pool.Stop();
}
catch (System.Runtime.InteropServices.COMException)
{
Thread.Sleep(1000);
}
}
}
}
//Config
public static AuthenticationSettings ReadAuthenticationSettings(string siteName = null, string appPath = null)
{
var location = siteName != null ? siteName + (appPath ?? "") : null;
var element = "system.webServer/security/authentication/{0}";
var anon = GetSectionElementValue<bool>(string.Format(element, "anonymousAuthentication"), "enabled", location);
var basic = GetSectionElementValue<bool>(string.Format(element, "basicAuthentication"), "enabled", location);
var windows = GetSectionElementValue<bool>(string.Format(element, "windowsAuthentication"), "enabled", location);
return new AuthenticationSettings()
{
EnableWindowsAuthentication = windows,
EnableBasicAuthentication = basic,
EnableAnonymousAuthentication = anon
};
}
public static T GetSectionElementValue<T>(string elementPath, string attributeName, string location)
{
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var element = location == null ? config.GetSection(elementPath) : config.GetSection(elementPath, location);
var t = typeof(T);
return (T)Convert.ChangeType(element[attributeName], t);
}
}
//WebFarm
public static void CreateWebFarm(WebFarmSettings settings)
{
WebFarmManager manager = CakeHelper.CreateWebFarmManager();
manager.Create(settings);
}
public static void DeleteWebFarm(string name)
{
using (var serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection section = config.GetSection("webFarms");
ConfigurationElementCollection farms = section.GetCollection();
ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);
if (farm != null)
{
farms.Remove(farm);
serverManager.CommitChanges();
}
}
}
public static ConfigurationElement GetWebFarm(string name)
{
using (var serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection section = config.GetSection("webFarms");
ConfigurationElementCollection farms = section.GetCollection();
return farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);
}
}
public static void CreateWebConfig(IDirectorySettings settings)
{
#if NET461
var framework = "net461";
#elif NETCOREAPP3_1
var framework = "netcoreapp3.1";
#elif NET5_0
var framework = "net5.0";
#endif
var folder = Directory.GetCurrentDirectory().Replace("\\", "/").Replace($"/bin/Debug/{framework}", "/") + settings.PhysicalDirectory.FullPath;
// Make sure the directory exists (for configs)
Directory.CreateDirectory(folder);
// Create the web.config
const string webConfig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<configuration>\r\n</configuration>";
File.WriteAllText(Path.Combine(folder, "web.config"), webConfig);
}
//Rewrite
public static void CreateRewriteRule(RewriteRuleSettings settings)
{
var rewriteRule = CreateRewriteManager();
rewriteRule.CreateRule(settings);
}
public static bool ExistsRewriteRule(string name)
{
var rewriteRule = CreateRewriteManager();
return rewriteRule.Exists(name);
}
public static bool DeleteRewriteRule(string name)
{
var rewriteRule = CreateRewriteManager();
return rewriteRule.DeleteRule(name);
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Utils;
using System.Diagnostics;
namespace DotVVM.Framework.Binding
{
/// <summary>
/// Represents a property of DotVVM controls.
/// </summary>
[DebuggerDisplay("{FullName}")]
public class DotvvmProperty
{
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the default value of the property.
/// </summary>
public object DefaultValue { get; private set; }
/// <summary>
/// Gets the type of the property.
/// </summary>
public Type PropertyType { get; private set; }
/// <summary>
/// Gets the type of the class where the property is registered.
/// </summary>
public Type DeclaringType { get; private set; }
/// <summary>
/// Gets whether the value can be inherited from the parent controls.
/// </summary>
public bool IsValueInherited { get; private set; }
/// <summary>
/// Gets or sets the Reflection property information.
/// </summary>
public PropertyInfo PropertyInfo { get; set; }
/// <summary>
/// Gets or sets the markup options.
/// </summary>
public MarkupOptionsAttribute MarkupOptions { get; set; }
/// <summary>
/// Gets the full name of the descriptor.
/// </summary>
public string DescriptorFullName
{
get { return DeclaringType.FullName + "." + Name + "Property"; }
}
/// <summary>
/// Gets the full name of the property.
/// </summary>
public string FullName
{
get { return DeclaringType.Name + "." + Name; }
}
/// <summary>
/// Prevents a default instance of the <see cref="DotvvmProperty"/> class from being created.
/// </summary>
internal DotvvmProperty()
{
}
/// <summary>
/// Gets the value of the property.
/// </summary>
public virtual object GetValue(DotvvmControl dotvvcmontrol, bool inherit = true)
{
object value;
if (dotvvcmontrol.properties != null && dotvvcmontrol.properties.TryGetValue(this, out value))
{
return value;
}
if (IsValueInherited && inherit && dotvvcmontrol.Parent != null)
{
return GetValue(dotvvcmontrol.Parent);
}
return DefaultValue;
}
/// <summary>
/// Sets the value of the property.
/// </summary>
public virtual void SetValue(DotvvmControl dotvvmControl, object value)
{
dotvvmControl.Properties[this] = value;
}
/// <summary>
/// Registers the specified DotVVM property.
/// </summary>
public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<TDeclaringType, object>> propertyName, object defaultValue = null, bool isValueInherited = false)
{
return Register<TPropertyType, TDeclaringType>(ReflectionUtils.GetPropertyNameFromExpression(propertyName), defaultValue, isValueInherited);
}
/// <summary>
/// Registers the specified DotVVM property.
/// </summary>
public static DotvvmProperty Register<TPropertyType, TDeclaringType>(string propertyName, object defaultValue = null, bool isValueInherited = false, DotvvmProperty property = null)
{
var fullName = typeof(TDeclaringType).FullName + "." + propertyName;
return registeredProperties.GetOrAdd(fullName, _ =>
{
var propertyInfo = typeof(TDeclaringType).GetProperty(propertyName);
var markupOptions = (propertyInfo != null ? propertyInfo.GetCustomAttribute<MarkupOptionsAttribute>() : null) ?? new MarkupOptionsAttribute()
{
AllowBinding = true,
AllowHardCodedValue = true,
MappingMode = MappingMode.Attribute,
Name = propertyName
};
if (string.IsNullOrEmpty(markupOptions.Name))
{
markupOptions.Name = propertyName;
}
if (property == null) property = new DotvvmProperty();
property.Name = propertyName;
property.DefaultValue = defaultValue ?? default(TPropertyType);
property.DeclaringType = typeof(TDeclaringType);
property.PropertyType = typeof(TPropertyType);
property.IsValueInherited = isValueInherited;
property.PropertyInfo = propertyInfo;
property.MarkupOptions = markupOptions;
return property;
});
}
private static ConcurrentDictionary<string, DotvvmProperty> registeredProperties = new ConcurrentDictionary<string, DotvvmProperty>();
/// <summary>
/// Resolves the <see cref="DotvvmProperty"/> by the declaring type and name.
/// </summary>
public static DotvvmProperty ResolveProperty(Type type, string name)
{
var fullName = type.FullName + "." + name;
DotvvmProperty property;
while (!registeredProperties.TryGetValue(fullName, out property) && type.BaseType != null)
{
type = type.BaseType;
fullName = type.FullName + "." + name;
}
return property;
}
/// <summary>
/// Resolves the <see cref="DotvvmProperty"/> from the full name (DeclaringTypeName.PropertyName).
/// </summary>
public static DotvvmProperty ResolveProperty(string fullName)
{
return registeredProperties.Values.LastOrDefault(p => p.FullName == fullName);
}
/// <summary>
/// Resolves all properties of specified type.
/// </summary>
public static IReadOnlyList<DotvvmProperty> ResolveProperties(Type type)
{
var types = new HashSet<Type>();
while (type.BaseType != null)
{
types.Add(type);
type = type.BaseType;
}
return registeredProperties.Values.Where(p => types.Contains(p.DeclaringType)).ToList();
}
/// <summary>
/// Called when a control of the property type is created and initialized.
/// </summary>
protected internal virtual void OnControlInitialized(DotvvmControl dotvvmControl)
{
}
/// <summary>
/// Called right before the page is rendered.
/// </summary>
public void OnControlRendering(DotvvmControl dotvvmControl)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Baseline;
using Marten.Exceptions;
using Marten.Linq;
using Marten.Services;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Weasel.Postgresql;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Linq
{
[ControlledQueryStoryteller]
public class query_against_child_collections_integrated_Tests : IntegrationContext
{
private readonly ITestOutputHelper _output;
public query_against_child_collections_integrated_Tests(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
{
_output = output;
StoreOptions(_ => _.UseDefaultSerialization(EnumStorage.AsString));
}
private Target[] targets;
private void buildUpTargetData()
{
targets = Target.GenerateRandomData(20).ToArray();
targets.SelectMany(x => x.Children).Each(x => x.Number = 5);
targets[5].Children[0].Number = 6;
targets[9].Children[0].Number = 6;
targets[12].Children[0].Number = 6;
targets[5].Children[0].Double = -1;
targets[9].Children[0].Double = -1;
targets[12].Children[0].Double = 10;
targets[10].Color = Colors.Green;
var child = targets[10].Children[0];
child.Color = Colors.Blue;
child.Inner = new Target
{
Number = -2,
Color = Colors.Blue
};
theSession.Store(targets);
theSession.SaveChanges();
}
[Fact]
public void can_query_with_containment_operator()
{
buildUpTargetData();
var expected = new[] { targets[5].Id, targets[9].Id, targets[12].Id }.OrderBy(x => x);
theSession.Query<Target>("where data @> '{\"Children\": [{\"Number\": 6}]}'")
.ToArray()
.Select(x => x.Id).OrderBy(x => x)
.ShouldHaveTheSameElementsAs(expected);
}
[Fact]
public void can_query_with_an_any_operator()
{
buildUpTargetData();
#region sample_any-query-through-child-collections
var results = theSession.Query<Target>()
.Where(x => x.Children.Any(_ => _.Number == 6))
.ToArray();
#endregion
results
.Select(x => x.Id)
.OrderBy(x => x)
.ShouldHaveTheSameElementsAs(new[] { targets[5].Id, targets[9].Id, targets[12].Id }.OrderBy(x => x));
}
[Fact]
public void can_query_with_an_any_operator_that_does_a_multiple_search_within_the_collection()
{
buildUpTargetData();
#region sample_any-query-through-child-collection-with-and
var results = theSession
.Query<Target>()
.Where(x => x.Children.Any(_ => _.Number == 6 && _.Double == -1))
.ToArray();
#endregion
results
.Select(x => x.Id)
.OrderBy(x => x)
.ShouldHaveTheSameElementsAs(new[] { targets[5].Id, targets[9].Id }.OrderBy(x => x));
}
[Fact]
public void can_query_on_deep_properties()
{
buildUpTargetData();
theSession.Query<Target>()
.Single(x => Enumerable.Any<Target>(x.Children, _ => _.Inner.Number == -2))
.Id.ShouldBe(targets[10].Id);
}
[Theory]
[InlineData(EnumStorage.AsInteger)]
[InlineData(EnumStorage.AsString)]
public void can_query_on_enum_properties(EnumStorage enumStorage)
{
StoreOptions(_ => _.UseDefaultSerialization(enumStorage));
buildUpTargetData();
theSession.Query<Target>()
.Count(x => Enumerable.Any<Target>(x.Children, _ => _.Color == Colors.Green))
.ShouldBeGreaterThanOrEqualTo(1);
}
[Theory]
[InlineData(EnumStorage.AsInteger)]
[InlineData(EnumStorage.AsString)]
public void can_query_on_deep_enum_properties(EnumStorage enumStorage)
{
StoreOptions(_ => _.UseDefaultSerialization(enumStorage));
buildUpTargetData();
theSession.Query<Target>()
.Count(x => x.Children.Any<Target>(_ => _.Inner.Color == Colors.Blue))
.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public void Bug_503_child_collection_query_in_compiled_query()
{
using (var session = theStore.OpenSession())
{
var outer = new Outer();
outer.Inners.Add(new Inner { Type = "T1", Value = "V11" });
outer.Inners.Add(new Inner { Type = "T1", Value = "V12" });
outer.Inners.Add(new Inner { Type = "T2", Value = "V21" });
session.Store(outer);
session.SaveChanges();
}
using (var session2 = theStore.OpenSession())
{
// This works
var o1 = session2.Query<Outer>().First(o => o.Inners.Any(i => i.Type == "T1" && i.Value == "V12"));
o1.ShouldNotBeNull();
var o2 = session2.Query(new FindOuterByInner("T1", "V12"));
o2.ShouldNotBeNull();
o2.Id.ShouldBe(o1.Id);
}
}
public class Outer
{
public Guid Id { get; set; }
public IList<Inner> Inners { get; } = new List<Inner>();
}
public class Inner
{
public string Type { get; set; }
public string Value { get; set; }
}
public class FindOuterByInner : ICompiledQuery<Outer, Outer>
{
public string Type { get; private set; }
public string Value { get; private set; }
public FindOuterByInner(string type, string value)
{
this.Type = type;
this.Value = value;
}
public Expression<Func<IMartenQueryable<Outer>, Outer>> QueryIs()
{
return q => q.FirstOrDefault(o => o.Inners.Any(i => i.Type == Type && i.Value == Value));
}
}
[Fact]
public void Bug_415_can_query_when_matched_value_has_quotes()
{
using (var session = theStore.QuerySession())
{
session.Query<Course>().Any(x => x.ExtIds.Contains("some'thing")).ShouldBeFalse();
}
}
[Fact]
public void Bug_415_can_query_inside_of_non_primitive_collection()
{
using (var session = theStore.QuerySession())
{
session.Query<Course>().Any(x => x.Sources.Any(_ => _.Case == "some'thing"));
}
}
public class Course
{
public Guid Id { get; set; }
public string[] ExtIds { get; set; }
public IList<Source> Sources { get; set; }
}
public class Source
{
public string Case { get; set; }
}
private Guid[] favAuthors = new Guid[] { Guid.NewGuid(), Guid.NewGuid() };
private void buildAuthorData()
{
// test fixtures
theSession.Store(new Article
{
Long = 1,
CategoryArray = new [] { "sports", "finance", "health" },
CategoryList = new List<string> { "sports", "finance", "health" },
AuthorArray = favAuthors,
Published = true,
});
theSession.Store(new Article
{
Long = 2,
CategoryArray = new [] { "sports", "astrology" },
AuthorArray = favAuthors.Take(1).ToArray(),
});
theSession.Store(new Article
{
Long = 3,
CategoryArray = new [] { "health", "finance" },
CategoryList = new List<string> { "sports", "health" },
AuthorArray = favAuthors.Skip(1).ToArray(),
});
theSession.Store(new Article
{
Long = 4,
CategoryArray = new [] { "health", "astrology" },
AuthorList = new List<Guid> { Guid.NewGuid() },
Published = true,
});
theSession.Store(new Article
{
Long = 5,
CategoryArray = new [] { "sports", "nested" },
AuthorList = new List<Guid> { Guid.NewGuid(), favAuthors[1] },
});
theSession.Store(new Article
{
Long = 6,
AuthorArray = new Guid[] { favAuthors[0], Guid.NewGuid() },
ReferencedArticle = new Article
{
CategoryArray = new [] { "nested" },
}
});
theSession.SaveChanges();
}
[Fact]
public void query_string_array_intersects_array()
{
buildAuthorData();
var interests = new [] { "finance", "astrology" };
var res = theSession.Query<Article>()
.Where(x => x.CategoryArray.Any(s => interests.Contains(s)))
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(4);
res[0].Long.ShouldBe(1);
res[1].Long.ShouldBe(2);
res[2].Long.ShouldBe(3);
res[3].Long.ShouldBe(4);
}
[Fact]
public void query_string_list_intersects_array()
{
buildAuthorData();
var interests = new [] { "health", "astrology" };
var res = theSession.Query<Article>()
.Where(x => x.CategoryList.Any(s => interests.Contains(s)))
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(2);
res[0].Long.ShouldBe(1);
res[1].Long.ShouldBe(3);
}
[Fact]
public void query_nested_string_array_intersects_array()
{
buildAuthorData();
var interests = new [] { "nested" };
var res = theSession.Query<Article>()
.Where(x => x.ReferencedArticle.CategoryArray.Any(s => interests.Contains(s)))
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(1);
res[0].Long.ShouldBe(6);
}
[Fact]
public void query_string_array_intersects_array_with_boolean_and()
{
buildAuthorData();
var interests = new [] { "finance", "astrology" };
var res = theSession.Query<Article>()
.Where(x => x.CategoryArray.Any(s => interests.Contains(s)) && x.Published)
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(2);
res[0].Long.ShouldBe(1);
res[1].Long.ShouldBe(4);
}
[Fact]
public void query_guid_array_intersects_array()
{
buildAuthorData();
var res = theSession.Query<Article>()
.Where(x => x.AuthorArray.Any(s => favAuthors.Contains(s)))
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(4);
res[0].Long.ShouldBe(1);
res[1].Long.ShouldBe(2);
res[2].Long.ShouldBe(3);
res[3].Long.ShouldBe(6);
}
[Fact]
public void query_array_with_Intersect_should_blow_up()
{
buildAuthorData();
Exception<BadLinqExpressionException>.ShouldBeThrownBy(() =>
{
var res = theSession.Query<Article>()
.Where(x => x.AuthorArray.Any(s => favAuthors.Intersect(new Guid[] { Guid.NewGuid() }).Any()))
.OrderBy(x => x.Long)
.ToList();
});
}
[Fact]
public void query_guid_list_intersects_array()
{
buildAuthorData();
var res = theSession.Query<Article>()
.Where(x => x.AuthorList.Any(s => favAuthors.Contains(s)))
.OrderBy(x => x.Long)
.ToList();
res.Count.ShouldBe(1);
res[0].Long.ShouldBe(5);
}
[Fact]
public void query_against_number_array()
{
var doc1 = new DocWithArrays { Numbers = new [] { 1, 2, 3 } };
var doc2 = new DocWithArrays { Numbers = new [] { 3, 4, 5 } };
var doc3 = new DocWithArrays { Numbers = new [] { 5, 6, 7 } };
theSession.Store(doc1, doc2, doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Numbers.Contains(3)).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
[Fact]
#region sample_query_against_string_array
public void query_against_string_array()
{
var doc1 = new DocWithArrays { Strings = new [] { "a", "b", "c" } };
var doc2 = new DocWithArrays { Strings = new [] { "c", "d", "e" } };
var doc3 = new DocWithArrays { Strings = new [] { "d", "e", "f" } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Strings.Contains("c")).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
#endregion
[Fact]
public void query_against_string_array_with_Any()
{
var doc1 = new DocWithArrays { Strings = new [] { "a", "b", "c" } };
var doc2 = new DocWithArrays { Strings = new [] { "c", "d", "e" } };
var doc3 = new DocWithArrays { Strings = new [] { "d", "e", "f" } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Strings.Any(_ => _ == "c")).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
[Fact]
public void query_against_string_array_with_Length()
{
var doc1 = new DocWithArrays { Strings = new [] { "a", "b", "c" } };
var doc2 = new DocWithArrays { Strings = new [] { "c", "d", "e" } };
var doc3 = new DocWithArrays { Strings = new [] { "d", "e", "f", "g" } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Strings.Length == 4).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc3.Id);
}
[Fact]
public void query_against_string_array_with_Count_method()
{
var doc1 = new DocWithArrays { Strings = new [] { "a", "b", "c" } };
var doc2 = new DocWithArrays { Strings = new [] { "c", "d", "e" } };
var doc3 = new DocWithArrays { Strings = new [] { "d", "e", "f", "g" } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Strings.Count() == 4).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc3.Id);
}
[Fact]
public void query_against_date_array()
{
var doc1 = new DocWithArrays { Dates = new[] { DateTime.Today, DateTime.Today.AddDays(1), DateTime.Today.AddDays(2) } };
var doc2 = new DocWithArrays { Dates = new[] { DateTime.Today.AddDays(2), DateTime.Today.AddDays(3), DateTime.Today.AddDays(4) } };
var doc3 = new DocWithArrays { Dates = new[] { DateTime.Today.AddDays(4), DateTime.Today.AddDays(5), DateTime.Today.AddDays(6) } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithArrays>().Where(x => x.Dates.Contains(DateTime.Today.AddDays(2))).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
[Fact]
public void query_against_number_list()
{
var doc1 = new DocWithLists { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists { Numbers = new List<int> { 5, 6, 7 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists>().Where(x => x.Numbers.Contains(3)).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
#region sample_query_any_string_array
[Fact]
public void query_against_number_list_with_any()
{
var doc1 = new DocWithLists { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists { Numbers = new List<int> { 5, 6, 7 } };
var doc4 = new DocWithLists { Numbers = new List<int> { } };
theSession.Store(doc1, doc2, doc3, doc4);
theSession.SaveChanges();
theSession.Query<DocWithLists>().Where(x => x.Numbers.Any(_ => _ == 3)).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
// Or without any predicate
theSession.Query<DocWithLists>()
.Count(x => x.Numbers.Any()).ShouldBe(3);
}
#endregion
#region sample_query_against_number_list_with_count_method
[Fact]
public void query_against_number_list_with_count_method()
{
var doc1 = new DocWithLists { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists { Numbers = new List<int> { 5, 6, 7, 8 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists>()
.Single(x => x.Numbers.Count() == 4).Id.ShouldBe(doc3.Id);
}
#endregion
[Fact]
public void query_against_number_list_with_count_property()
{
var doc1 = new DocWithLists { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists { Numbers = new List<int> { 5, 6, 7, 8 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists>()
.Single(x => x.Numbers.Count == 4).Id.ShouldBe(doc3.Id);
}
[Fact]
public void query_against_number_list_with_count_property_and_other_operators()
{
var doc1 = new DocWithLists { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists { Numbers = new List<int> { 5, 6, 7, 8 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists>()
.Single(x => x.Numbers.Count > 3).Id.ShouldBe(doc3.Id);
}
[Fact]
public void query_against_number_IList()
{
var doc1 = new DocWithLists2 { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists2 { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists2 { Numbers = new List<int> { 5, 6, 7 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists2>().Where(x => x.Numbers.Contains(3)).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
[Fact]
public void query_against_number_IEnumerable()
{
var doc1 = new DocWithLists3 { Numbers = new List<int> { 1, 2, 3 } };
var doc2 = new DocWithLists3 { Numbers = new List<int> { 3, 4, 5 } };
var doc3 = new DocWithLists3 { Numbers = new List<int> { 5, 6, 7 } };
theSession.Store(doc1);
theSession.Store(doc2);
theSession.Store(doc3);
theSession.SaveChanges();
theSession.Query<DocWithLists3>().Where(x => x.Numbers.Contains(3)).ToArray()
.Select(x => x.Id).ShouldHaveTheSameElementsAs(doc1.Id, doc2.Id);
}
[Fact]
public void naked_any_hit_without_predicate()
{
var targetithchildren = new Target { Number = 1 };
targetithchildren.Children = new[] { new Target(), };
var nochildrennullarray = new Target { Number = 2 };
var nochildrenemptyarray = new Target { Number = 3 };
nochildrenemptyarray.Children = new Target[] { };
theSession.Store(nochildrennullarray);
theSession.Store(nochildrenemptyarray);
theSession.Store(targetithchildren);
theSession.SaveChanges();
var items = theSession.Query<Target>().Where(x => x.Children.Any()).ToList();
items.Count.ShouldBe(1);
}
}
public class Article
{
public Guid Id { get; set; }
public long Long { get; set; }
public string[] CategoryArray { get; set; }
public List<string> CategoryList { get; set; }
public Guid[] AuthorArray { get; set; }
public List<Guid> AuthorList { get; set; }
public Article ReferencedArticle { get; set; }
public bool Published { get; set; }
}
public class DocWithLists
{
public Guid Id { get; set; }
public List<int> Numbers { get; set; }
}
public class DocWithLists2
{
public Guid Id { get; set; }
public IList<int> Numbers { get; set; }
}
public class DocWithLists3
{
public Guid Id { get; set; }
public IEnumerable<int> Numbers { get; set; }
}
public class DocWithArrays
{
public Guid Id { get; set; }
public int[] Numbers { get; set; }
public string[] Strings { get; set; }
public DateTime[] Dates { get; set; }
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using Microsoft.JScript.Vsa;
using System;
using System.Reflection;
using System.Reflection.Emit;
public class StrictEquality : BinaryOp{
internal StrictEquality(Context context, AST operand1, AST operand2, JSToken operatorTok)
: base(context, operand1, operand2, operatorTok) {
}
internal override Object Evaluate(){
bool result = JScriptStrictEquals(this.operand1.Evaluate(), this.operand2.Evaluate(), VsaEngine.executeForJSEE);
if (this.operatorTok == JSToken.StrictEqual)
return result;
else
return !result;
}
public static bool JScriptStrictEquals(Object v1, Object v2){
return StrictEquality.JScriptStrictEquals(v1, v2, false);
}
internal static bool JScriptStrictEquals(Object v1, Object v2, bool checkForDebuggerObjects){
IConvertible ic1 = Convert.GetIConvertible(v1);
IConvertible ic2 = Convert.GetIConvertible(v2);
TypeCode t1 = Convert.GetTypeCode(v1, ic1);
TypeCode t2 = Convert.GetTypeCode(v2, ic2);
return StrictEquality.JScriptStrictEquals(v1, v2, ic1, ic2, t1, t2, checkForDebuggerObjects);
}
internal static bool JScriptStrictEquals(Object v1, Object v2, IConvertible ic1, IConvertible ic2, TypeCode t1, TypeCode t2, bool checkForDebuggerObjects){
switch (t1){
case TypeCode.Empty: return t2 == TypeCode.Empty;
case TypeCode.Object:
if (v1 == v2) return true;
if (v1 is Missing || v1 is System.Reflection.Missing) v1 = null;
if (v1 == v2) return true;
if (v2 is Missing || v2 is System.Reflection.Missing) v2 = null;
return v1 == v2;
case TypeCode.DBNull: return t2 == TypeCode.DBNull;
case TypeCode.Boolean: return t2 == TypeCode.Boolean && ic1.ToBoolean(null) == ic2.ToBoolean(null);
case TypeCode.Char:
Char ch = ic1.ToChar(null);
switch(t2){
case TypeCode.Char: return ch == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return ch == ic2.ToInt64(null);
case TypeCode.UInt64: return ch == ic2.ToUInt64(null);
case TypeCode.Single:
case TypeCode.Double: return ch == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)(int)ch) == ic2.ToDecimal(null);
case TypeCode.String:
String str = ic2.ToString(null);
return str.Length == 1 && ch == str[0];
}
return false;
case TypeCode.SByte:
SByte sb1 = ic1.ToSByte(null);
switch (t2){
case TypeCode.Char: return sb1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return sb1 == ic2.ToInt64(null);
case TypeCode.UInt64: return sb1 >= 0 && ((UInt64)sb1) == ic2.ToUInt64(null);
case TypeCode.Single: return sb1 == ic2.ToSingle(null);
case TypeCode.Double: return sb1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)sb1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Byte:
Byte b1 = ic1.ToByte(null);
switch (t2){
case TypeCode.Char: return b1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return b1 == ic2.ToInt64(null);
case TypeCode.UInt64: return b1 == ic2.ToUInt64(null);
case TypeCode.Single: return b1 == ic2.ToSingle(null);
case TypeCode.Double: return b1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)b1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Int16:
Int16 s1 = ic1.ToInt16(null);
switch (t2){
case TypeCode.Char: return s1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return s1 == ic2.ToInt64(null);
case TypeCode.UInt64: return s1 >= 0 && ((UInt64)s1) == ic2.ToUInt64(null);
case TypeCode.Single: return s1 == ic2.ToSingle(null);
case TypeCode.Double: return s1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)s1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.UInt16:
UInt16 us1 = ic1.ToUInt16(null);
switch (t2){
case TypeCode.Char: return us1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return us1 == ic2.ToInt64(null);
case TypeCode.UInt64: return us1 == ic2.ToUInt64(null);
case TypeCode.Single: return us1 == ic2.ToSingle(null);
case TypeCode.Double: return us1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)us1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Int32:
Int32 i1 = ic1.ToInt32(null);
switch (t2){
case TypeCode.Char: return i1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return i1 == ic2.ToInt64(null);
case TypeCode.UInt64: return i1 >= 0 && ((UInt64)i1) == ic2.ToUInt64(null);
case TypeCode.Single: return i1 == ic2.ToSingle(null);
case TypeCode.Double: return i1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)i1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.UInt32:
UInt32 ui1 = ic1.ToUInt32(null);
switch (t2){
case TypeCode.Char: return ui1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return ui1 == ic2.ToInt64(null);
case TypeCode.UInt64: return ui1 == ic2.ToUInt64(null);
case TypeCode.Single: return ui1 == ic2.ToSingle(null);
case TypeCode.Double: return ui1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)ui1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Int64:
Int64 l1 = ic1.ToInt64(null);
switch (t2){
case TypeCode.Char: return l1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return l1 == ic2.ToInt64(null);
case TypeCode.UInt64: return l1 >= 0 && ((UInt64)l1) == ic2.ToUInt64(null);
case TypeCode.Single: return l1 == ic2.ToSingle(null);
case TypeCode.Double: return l1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)l1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.UInt64:
UInt64 ul1 = ic1.ToUInt64(null);
switch (t2){
case TypeCode.Char: return ul1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
l1 = ic2.ToInt64(null);
return l1 >= 0 && ul1 == (UInt64)l1;
case TypeCode.UInt64: return ul1 == ic2.ToUInt64(null);
case TypeCode.Single: return ul1 == ic2.ToSingle(null);
case TypeCode.Double: return ul1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)ul1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Single:
Single f1 = ic1.ToSingle(null);
switch (t2){
case TypeCode.Char: return f1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return f1 == ic2.ToInt64(null);
case TypeCode.UInt64: return f1 == ic2.ToUInt64(null);
case TypeCode.Single: return f1 == ic2.ToSingle(null);
case TypeCode.Double: return f1 == ic2.ToSingle(null);
case TypeCode.Decimal: return ((Decimal)f1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Double:
Double d1 = ic1.ToDouble(null);
switch (t2){
case TypeCode.Char: return d1 == ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return d1 == ic2.ToInt64(null);
case TypeCode.UInt64: return d1 == ic2.ToUInt64(null);
case TypeCode.Single: return ((float)d1) == ic2.ToSingle(null);
case TypeCode.Double: return d1 == ic2.ToDouble(null);
case TypeCode.Decimal: return ((Decimal)d1) == ic2.ToDecimal(null);
}
return false;
case TypeCode.Decimal:
Decimal de1 = ic1.ToDecimal(null);
switch (t2){
case TypeCode.Char: return de1 == (Decimal)(int)ic2.ToChar(null);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64: return de1 == ic2.ToInt64(null);
case TypeCode.UInt64: return de1 == ic2.ToUInt64(null);
case TypeCode.Single: return de1 == (Decimal)ic2.ToSingle(null);
case TypeCode.Double: return de1 == (Decimal)ic2.ToDouble(null);
case TypeCode.Decimal: return de1 == ic2.ToDecimal(null);
}
return false;
case TypeCode.DateTime: return t2 == TypeCode.DateTime && ic1.ToDateTime(null) == ic2.ToDateTime(null);
case TypeCode.String:
if (t2 == TypeCode.Char){
String str = ic1.ToString(null);
return str.Length == 1 && str[0] == ic2.ToChar(null);
}
return t2 == TypeCode.String && (v1 == v2 || ic1.ToString(null).Equals(ic2.ToString(null)));
}
return false; //should never get here
}
internal override IReflect InferType(JSField inference_target){
return Typeob.Boolean;
}
internal override void TranslateToConditionalBranch(ILGenerator il, bool branchIfTrue, Label label, bool shortForm){
Type t1 = Convert.ToType(this.operand1.InferType(null));
Type t2 = Convert.ToType(this.operand2.InferType(null));
if (this.operand1 is ConstantWrapper)
if (this.operand1.Evaluate() == null) t1 = Typeob.Empty;
if (this.operand2 is ConstantWrapper)
if (this.operand2.Evaluate() == null) t2 = Typeob.Empty;
if (t1 != t2 && t1.IsPrimitive && t2.IsPrimitive){
if (t1 == Typeob.Single)
t2 = t1;
else if (t2 == Typeob.Single)
t1 = t2;
else if (Convert.IsPromotableTo(t2, t1))
t2 = t1;
else if (Convert.IsPromotableTo(t1, t2))
t1 = t2;
}
bool nonPrimitive = true;
if (t1 == t2 && t1 != Typeob.Object){
// Operand types are equal and not Object - need to compare values only. Primitive
// values get compared with IL instructions; other values including value types
// get compared with Object.Equals. String is special cased for perf.
Type t = t1;
if (!t1.IsPrimitive)
t = Typeob.Object;
this.operand1.TranslateToIL(il, t);
this.operand2.TranslateToIL(il, t);
if (t1 == Typeob.String)
il.Emit(OpCodes.Call, CompilerGlobals.stringEqualsMethod);
else if (!t1.IsPrimitive)
il.Emit(OpCodes.Callvirt, CompilerGlobals.equalsMethod);
else
nonPrimitive = false;
}else if (t1 == Typeob.Empty){
this.operand2.TranslateToIL(il, Typeob.Object);
branchIfTrue = !branchIfTrue;
}else if (t2 == Typeob.Empty){
this.operand1.TranslateToIL(il, Typeob.Object);
branchIfTrue = !branchIfTrue;
}else{
this.operand1.TranslateToIL(il, Typeob.Object);
this.operand2.TranslateToIL(il, Typeob.Object);
il.Emit(OpCodes.Call, CompilerGlobals.jScriptStrictEqualsMethod);
}
if (branchIfTrue){
if (this.operatorTok == JSToken.StrictEqual)
if (nonPrimitive)
il.Emit(shortForm ? OpCodes.Brtrue_S : OpCodes.Brtrue, label);
else
il.Emit(shortForm ? OpCodes.Beq_S : OpCodes.Beq, label);
else
if (nonPrimitive)
il.Emit(shortForm ? OpCodes.Brfalse_S : OpCodes.Brfalse, label);
else
il.Emit(shortForm ? OpCodes.Bne_Un_S : OpCodes.Bne_Un, label);
}else{
if (this.operatorTok == JSToken.StrictEqual)
if (nonPrimitive)
il.Emit(shortForm ? OpCodes.Brfalse_S : OpCodes.Brfalse, label);
else
il.Emit(shortForm ? OpCodes.Bne_Un_S : OpCodes.Bne_Un, label);
else
if (nonPrimitive)
il.Emit(shortForm ? OpCodes.Brtrue_S : OpCodes.Brtrue, label);
else
il.Emit(shortForm ? OpCodes.Beq_S : OpCodes.Beq, label);
}
return;
}
internal override void TranslateToIL(ILGenerator il, Type rtype){
Label true_label = il.DefineLabel();
Label done_label = il.DefineLabel();
this.TranslateToConditionalBranch(il, true, true_label, true);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Br_S, done_label);
il.MarkLabel(true_label);
il.Emit(OpCodes.Ldc_I4_1);
il.MarkLabel(done_label);
Convert.Emit(this, il, Typeob.Boolean, rtype);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Linq.Expressions.Compiler;
using System.Reflection;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Linq.Expressions;
namespace System.Linq.Expressions
{
/// <summary>
/// Creates a <see cref="LambdaExpression"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
[DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))]
public abstract class LambdaExpression : Expression
{
private readonly string _name;
private readonly Expression _body;
private readonly ReadOnlyCollection<ParameterExpression> _parameters;
private readonly Type _delegateType;
private readonly bool _tailCall;
internal LambdaExpression(
Type delegateType,
string name,
Expression body,
bool tailCall,
ReadOnlyCollection<ParameterExpression> parameters
)
{
Debug.Assert(delegateType != null);
_name = name;
_body = body;
_parameters = parameters;
_delegateType = delegateType;
_tailCall = tailCall;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _delegateType; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Lambda; }
}
/// <summary>
/// Gets the parameters of the lambda expression.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Parameters
{
get { return _parameters; }
}
/// <summary>
/// Gets the name of the lambda expression.
/// </summary>
/// <remarks>Used for debugging purposes.</remarks>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the body of the lambda expression.
/// </summary>
public Expression Body
{
get { return _body; }
}
/// <summary>
/// Gets the return type of the lambda expression.
/// </summary>
public Type ReturnType
{
get { return Type.GetMethod("Invoke").ReturnType; }
}
/// <summary>
/// Gets the value that indicates if the lambda expression will be compiled with
/// tail call optimization.
/// </summary>
public bool TailCall
{
get { return _tailCall; }
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile()
{
return Compile(preferInterpretation: false);
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="Boolean"/> that indicates if the expression should be compiled to an interpreted form, if available. </param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE
#if FEATURE_INTERPRET
if (preferInterpretation)
{
return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return Compiler.LambdaCompiler.Compile(this);
#else
return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
#if FEATURE_COMPILE
internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller);
#endif
}
/// <summary>
/// Defines a <see cref="Expression{TDelegate}"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <typeparam name="TDelegate">The type of the delegate.</typeparam>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
public sealed class Expression<TDelegate> : LambdaExpression
{
public Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
: base(typeof(TDelegate), name, body, tailCall, parameters)
{
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile()
{
return Compile(preferInterpretation: false);
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="Boolean"/> that indicates if the expression should be compiled to an interpreted form, if available. </param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE
#if FEATURE_INTERPRET
if (preferInterpretation)
{
return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this);
#else
return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param>
/// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters)
{
if (body == Body && parameters == Parameters)
{
return this;
}
return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters);
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitLambda(this);
}
#if FEATURE_COMPILE
internal override LambdaExpression Accept(Compiler.StackSpiller spiller)
{
return spiller.Rewrite(this);
}
internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
return new Expression<TDelegate>(body, name, tailCall, parameters);
}
#endif
}
#if !FEATURE_COMPILE
// Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T>
public class ExpressionCreator<TDelegate>
{
public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
return new Expression<TDelegate>(body, name, tailCall, parameters);
}
}
#endif
public partial class Expression
{
/// <summary>
/// Creates an Expression{T} given the delegate type. Caches the
/// factory method to speed up repeated creations for the same T.
/// </summary>
internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
// Get or create a delegate to the public Expression.Lambda<T>
// method and call that will be used for creating instances of this
// delegate type
Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath;
var factories = s_lambdaFactories;
if (factories == null)
{
s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
}
MethodInfo create = null;
if (!factories.TryGetValue(delegateType, out fastPath))
{
#if FEATURE_COMPILE
create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
#else
create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public);
#endif
if (TypeUtils.CanCache(delegateType))
{
factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>));
}
}
if (fastPath != null)
{
return fastPath(body, name, tailCall, parameters);
}
Debug.Assert(create != null);
return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters });
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, tailCall, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, name, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
var parameterList = parameters.ToReadOnly();
ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList, nameof(TDelegate));
return new Expression<TDelegate>(body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters)
{
return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, name, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
ContractUtils.RequiresNotNull(body, nameof(body));
var parameterList = parameters.ToReadOnly();
int paramCount = parameterList.Count;
Type[] typeArgs = new Type[paramCount + 1];
if (paramCount > 0)
{
var set = new HashSet<ParameterExpression>();
for (int i = 0; i < paramCount; i++)
{
var param = parameterList[i];
ContractUtils.RequiresNotNull(param, "parameter");
typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type;
if (!set.Add(param))
{
throw Error.DuplicateVariable(param, $"parameters[{i}]");
}
}
}
typeArgs[paramCount] = body.Type;
Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
return CreateLambda(delegateType, body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
var paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType));
return CreateLambda(delegateType, body, name, false, paramList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
var paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType));
return CreateLambda(delegateType, body, name, tailCall, paramList);
}
private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters, string paramName)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
RequiresCanRead(body, nameof(body));
if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate))
{
throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(paramName);
}
MethodInfo mi;
var ldc = s_lambdaDelegateCache;
if (!ldc.TryGetValue(delegateType, out mi))
{
mi = delegateType.GetMethod("Invoke");
if (TypeUtils.CanCache(delegateType))
{
ldc[delegateType] = mi;
}
}
ParameterInfo[] pis = mi.GetParametersCached();
if (pis.Length > 0)
{
if (pis.Length != parameters.Count)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
var set = new HashSet<ParameterExpression>();
for (int i = 0, n = pis.Length; i < n; i++)
{
ParameterExpression pex = parameters[i];
ParameterInfo pi = pis[i];
RequiresCanRead(pex, nameof(parameters));
Type pType = pi.ParameterType;
if (pex.IsByRef)
{
if (!pType.IsByRef)
{
//We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type.
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType);
}
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pex.Type, pType))
{
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType);
}
if (!set.Add(pex))
{
throw Error.DuplicateVariable(pex, $"{nameof(parameters)}[{i}]");
}
}
}
else if (parameters.Count > 0)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type))
{
if (!TryQuote(mi.ReturnType, ref body))
{
throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType);
}
}
}
private enum TryGetFuncActionArgsResult
{
Valid,
ArgumentNull,
ByRef,
PointerOrVoid
}
private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[] typeArgs)
{
if (typeArgs == null)
{
return TryGetFuncActionArgsResult.ArgumentNull;
}
for (int i = 0; i < typeArgs.Length; i++)
{
var a = typeArgs[i];
if (a == null)
{
return TryGetFuncActionArgsResult.ArgumentNull;
}
if (a.IsByRef)
{
return TryGetFuncActionArgsResult.ByRef;
}
if (a == typeof(void) || a.IsPointer)
{
return TryGetFuncActionArgsResult.PointerOrVoid;
}
}
return TryGetFuncActionArgsResult.Valid;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
/// <returns>The type of a System.Func delegate that has the specified type arguments.</returns>
public static Type GetFuncType(params Type[] typeArgs)
{
switch (ValidateTryGetFuncActionArgs(typeArgs))
{
case TryGetFuncActionArgsResult.ArgumentNull:
throw new ArgumentNullException(nameof(typeArgs));
case TryGetFuncActionArgsResult.ByRef:
throw Error.TypeMustNotBeByRef(nameof(typeArgs));
default:
// This includes pointers or void. We allow the exception that comes
// from trying to use them as generic arguments to pass through.
Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs));
}
return result;
}
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
/// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetFuncType(Type[] typeArgs, out Type funcType)
{
if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid)
{
return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null;
}
funcType = null;
return false;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
/// <returns>The type of a System.Action delegate that has the specified type arguments.</returns>
public static Type GetActionType(params Type[] typeArgs)
{
switch (ValidateTryGetFuncActionArgs(typeArgs))
{
case TryGetFuncActionArgsResult.ArgumentNull:
throw new ArgumentNullException(nameof(typeArgs));
case TryGetFuncActionArgsResult.ByRef:
throw Error.TypeMustNotBeByRef(nameof(typeArgs));
default:
// This includes pointers or void. We allow the exception that comes
// from trying to use them as generic arguments to pass through.
Type result = Compiler.DelegateHelpers.GetActionType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs));
}
return result;
}
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
/// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetActionType(Type[] typeArgs, out Type actionType)
{
if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid)
{
return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null;
}
actionType = null;
return false;
}
/// <summary>
/// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments.
/// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom
/// delegate type.
/// </summary>
/// <param name="typeArgs">The type arguments of the delegate.</param>
/// <returns>The delegate type.</returns>
/// <remarks>
/// As with Func, the last argument is the return type. It can be set
/// to System.Void to produce an Action.</remarks>
public static Type GetDelegateType(params Type[] typeArgs)
{
ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs));
ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs));
return Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
}
}
}
| |
// https://github.com/dotnet/runtime/blob/527f9ae88a0ee216b44d556f9bdc84037fe0ebda/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs
#pragma warning disable
#define INTERNAL_NULLABLE_ATTRIBUTES
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Diagnostics.CodeAnalysis
{
#if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class AllowNullAttribute : Attribute
{ }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DisallowNullAttribute : Attribute
{ }
/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MaybeNullAttribute : Attribute
{ }
/// <summary>Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullAttribute : Attribute
{ }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;
/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}
/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DoesNotReturnAttribute : Attribute
{ }
/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;
/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
#endif
#if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NETCOREAPP3_0 || NETCOREAPP3_1 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MemberNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with a field or property member.</summary>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };
/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullAttribute(params string[] members) => Members = members;
/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}
/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class MemberNotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition and a field or property member.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
}
/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
{
ReturnValue = returnValue;
Members = members;
}
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}
#endif
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 374175 $
* $LastChangedDate: 2006-04-30 18:01:40 +0200 (dim., 30 avr. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using IBatisNet.Common.Exceptions;
namespace IBatisNet.Common.Utilities.Objects.Members
{
/// <summary>
/// A factory to build <see cref="IGetAccessorFactory"/> for a type.
/// </summary>
public class GetAccessorFactory : IGetAccessorFactory
{
private delegate IGetAccessor CreatePropertyGetAccessor(Type targetType, string propertyName);
private delegate IGetAccessor CreateFieldGetAccessor(Type targetType, string fieldName);
private CreatePropertyGetAccessor _createPropertyGetAccessor = null;
private CreateFieldGetAccessor _createFieldGetAccessor = null;
private IDictionary _cachedIGetAccessor = new HybridDictionary();
private AssemblyBuilder _assemblyBuilder = null;
private ModuleBuilder _moduleBuilder = null;
private object _syncObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref="GetAccessorFactory"/> class.
/// </summary>
/// <param name="allowCodeGeneration">if set to <c>true</c> [allow code generation].</param>
public GetAccessorFactory(bool allowCodeGeneration)
{
if (allowCodeGeneration)
{
// Detect runtime environment and create the appropriate factory
if (Environment.Version.Major >= 2)
{
//#if dotnet2
_createPropertyGetAccessor = new CreatePropertyGetAccessor(CreateDynamicPropertyGetAccessor);
_createFieldGetAccessor = new CreateFieldGetAccessor(CreateDynamicFieldGetAccessor);
//#endif
}
else
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "iBATIS.FastGetAccessor" + HashCodeProvider.GetIdentityHashCode(this).ToString();
// Create a new assembly with one module
_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
_moduleBuilder = _assemblyBuilder.DefineDynamicModule(assemblyName.Name + ".dll");
_createPropertyGetAccessor = new CreatePropertyGetAccessor(CreatePropertyAccessor);
_createFieldGetAccessor = new CreateFieldGetAccessor(CreateFieldAccessor);
}
}
else
{
_createPropertyGetAccessor = new CreatePropertyGetAccessor(CreateReflectionPropertyGetAccessor);
_createFieldGetAccessor = new CreateFieldGetAccessor(CreateReflectionFieldGetAccessor);
}
}
//#if dotnet2
/// <summary>
/// Create a Dynamic IGetAccessor instance for a property
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreateDynamicPropertyGetAccessor(Type targetType, string propertyName)
{
ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
PropertyInfo propertyInfo = (PropertyInfo)reflectionCache.GetGetter(propertyName);
if (propertyInfo.CanRead)
{
MethodInfo methodInfo = null;
//#if dotnet2
methodInfo = propertyInfo.GetGetMethod();
//#else
// methodInfo = targetType.GetMethod("get_" + propertyName);
//#endif
if (methodInfo != null)// == visibilty public
{
return new DelegatePropertyGetAccessor(targetType, propertyName);
}
else
{
return new ReflectionPropertyGetAccessor(targetType, propertyName);
}
}
else
{
throw new NotSupportedException(
string.Format("Property \"{0}\" on type "
+ "{1} cannot be get.", propertyInfo.Name, targetType));
}
}
/// <summary>
/// Create a Dynamic IGetAccessor instance for a field
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="fieldName">Property name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreateDynamicFieldGetAccessor(Type targetType, string fieldName)
{
ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
FieldInfo fieldInfo = (FieldInfo)reflectionCache.GetGetter(fieldName);
if (fieldInfo.IsPublic)
{
return new DelegateFieldGetAccessor(targetType, fieldName);
}
else
{
return new ReflectionFieldGetAccessor(targetType, fieldName);
}
}
//#endif
/// <summary>
/// Create a IGetAccessor instance for a property
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreatePropertyAccessor(Type targetType, string propertyName)
{
ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
PropertyInfo propertyInfo = (PropertyInfo)reflectionCache.GetGetter(propertyName);
if (propertyInfo.CanRead)
{
MethodInfo methodInfo = null;
//#if dotnet2
methodInfo = propertyInfo.GetGetMethod();
//#else
// methodInfo = targetType.GetMethod("get_" + propertyName,BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
// if (methodInfo == null)
// {
// methodInfo = targetType.GetMethod("get_" + propertyName);
// }
//#endif
if (methodInfo != null)// == visibilty public
{
return new EmitPropertyGetAccessor(targetType, propertyName, _assemblyBuilder, _moduleBuilder);
}
else
{
return new ReflectionPropertyGetAccessor(targetType, propertyName);
}
}
else
{
throw new NotSupportedException(
string.Format("Property \"{0}\" on type "
+ "{1} cannot be get.", propertyInfo.Name, targetType));
}
}
/// <summary>
/// Create a IGetAccessor instance for a field
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="fieldName">Field name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreateFieldAccessor(Type targetType, string fieldName)
{
ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
FieldInfo fieldInfo = (FieldInfo)reflectionCache.GetGetter(fieldName);
if (fieldInfo.IsPublic)
{
return new EmitFieldGetAccessor(targetType, fieldName, _assemblyBuilder, _moduleBuilder);
}
else
{
return new ReflectionFieldGetAccessor(targetType, fieldName);
}
}
/// <summary>
/// Create a Reflection IGetAccessor instance for a property
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="propertyName">Property name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreateReflectionPropertyGetAccessor(Type targetType, string propertyName)
{
return new ReflectionPropertyGetAccessor(targetType, propertyName);
}
/// <summary>
/// Create Reflection IGetAccessor instance for a field
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="fieldName">field name.</param>
/// <returns>null if the generation fail</returns>
private IGetAccessor CreateReflectionFieldGetAccessor(Type targetType, string fieldName)
{
return new ReflectionFieldGetAccessor(targetType, fieldName);
}
#region IGetAccessorFactory Members
/// <summary>
/// Generate an <see cref="IGetAccessor"/> instance.
/// </summary>
/// <param name="targetType">Target object type.</param>
/// <param name="name">Field or Property name.</param>
/// <returns>null if the generation fail</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public IGetAccessor CreateGetAccessor(Type targetType, string name)
{
string key = new StringBuilder(targetType.FullName).Append(".").Append(name).ToString();
if (_cachedIGetAccessor.Contains(key))
{
return (IGetAccessor)_cachedIGetAccessor[key];
}
else
{
IGetAccessor getAccessor = null;
lock (_syncObject)
{
if (!_cachedIGetAccessor.Contains(key))
{
// Property
ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
MemberInfo memberInfo = reflectionCache.GetGetter(name);
if (memberInfo != null)
{
if (memberInfo is PropertyInfo)
{
getAccessor = _createPropertyGetAccessor(targetType, name);
_cachedIGetAccessor[key] = getAccessor;
}
else
{
getAccessor = _createFieldGetAccessor(targetType, name);
_cachedIGetAccessor[key] = getAccessor;
}
}
else
{
throw new ProbeException(
string.Format("No property or field named \"{0}\" exists for type "
+ "{1}.", name, targetType));
}
}
else
{
getAccessor = (IGetAccessor)_cachedIGetAccessor[key];
}
}
return getAccessor;
}
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Represents a grouping of data emitted at a certain time.
/// </summary>
public class TimeSlice
{
/// <summary>
/// Gets the count of data points in this <see cref="TimeSlice"/>
/// </summary>
public int DataPointCount { get; private set; }
/// <summary>
/// Gets the time this data was emitted
/// </summary>
public DateTime Time { get; private set; }
/// <summary>
/// Gets the data in the time slice
/// </summary>
public List<DataFeedPacket> Data { get; private set; }
/// <summary>
/// Gets the <see cref="Slice"/> that will be used as input for the algorithm
/// </summary>
public Slice Slice { get; private set; }
/// <summary>
/// Gets the data used to update the cash book
/// </summary>
public List<UpdateData<Cash>> CashBookUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update securities
/// </summary>
public List<UpdateData<Security>> SecuritiesUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update the consolidators
/// </summary>
public List<UpdateData<SubscriptionDataConfig>> ConsolidatorUpdateData { get; private set; }
/// <summary>
/// Gets all the custom data in this <see cref="TimeSlice"/>
/// </summary>
public List<UpdateData<Security>> CustomData { get; private set; }
/// <summary>
/// Gets the changes to the data subscriptions as a result of universe selection
/// </summary>
public SecurityChanges SecurityChanges { get; set; }
/// <summary>
/// Initializes a new <see cref="TimeSlice"/> containing the specified data
/// </summary>
public TimeSlice(DateTime time,
int dataPointCount,
Slice slice,
List<DataFeedPacket> data,
List<UpdateData<Cash>> cashBookUpdateData,
List<UpdateData<Security>> securitiesUpdateData,
List<UpdateData<SubscriptionDataConfig>> consolidatorUpdateData,
List<UpdateData<Security>> customData,
SecurityChanges securityChanges)
{
Time = time;
Data = data;
Slice = slice;
CustomData = customData;
DataPointCount = dataPointCount;
CashBookUpdateData = cashBookUpdateData;
SecuritiesUpdateData = securitiesUpdateData;
ConsolidatorUpdateData = consolidatorUpdateData;
SecurityChanges = securityChanges;
}
/// <summary>
/// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data
/// </summary>
/// <param name="utcDateTime">The UTC frontier date time</param>
/// <param name="algorithmTimeZone">The algorithm's time zone, required for computing algorithm and slice time</param>
/// <param name="cashBook">The algorithm's cash book, required for generating cash update pairs</param>
/// <param name="data">The data in this <see cref="TimeSlice"/></param>
/// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param>
/// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns>
public static TimeSlice Create(DateTime utcDateTime, DateTimeZone algorithmTimeZone, CashBook cashBook, List<DataFeedPacket> data, SecurityChanges changes)
{
int count = 0;
var security = new List<UpdateData<Security>>();
var custom = new List<UpdateData<Security>>();
var consolidator = new List<UpdateData<SubscriptionDataConfig>>();
var allDataForAlgorithm = new List<BaseData>(data.Count);
var cash = new List<UpdateData<Cash>>(cashBook.Count);
var cashSecurities = new HashSet<Symbol>();
foreach (var cashItem in cashBook.Values)
{
cashSecurities.Add(cashItem.SecuritySymbol);
}
Split split;
Dividend dividend;
Delisting delisting;
SymbolChangedEvent symbolChange;
// we need to be able to reference the slice being created in order to define the
// evaluation of option price models, so we define a 'future' that can be referenced
// in the option price model evaluation delegates for each contract
Slice slice = null;
var sliceFuture = new Lazy<Slice>(() => slice);
var algorithmTime = utcDateTime.ConvertFromUtc(algorithmTimeZone);
var tradeBars = new TradeBars(algorithmTime);
var quoteBars = new QuoteBars(algorithmTime);
var ticks = new Ticks(algorithmTime);
var splits = new Splits(algorithmTime);
var dividends = new Dividends(algorithmTime);
var delistings = new Delistings(algorithmTime);
var optionChains = new OptionChains(algorithmTime);
var futuresChains = new FuturesChains(algorithmTime);
var symbolChanges = new SymbolChangedEvents(algorithmTime);
foreach (var packet in data)
{
var list = packet.Data;
var symbol = packet.Security.Symbol;
if (list.Count == 0) continue;
// keep count of all data points
if (list.Count == 1 && list[0] is BaseDataCollection)
{
var baseDataCollectionCount = ((BaseDataCollection)list[0]).Data.Count;
if (baseDataCollectionCount == 0)
{
continue;
}
count += baseDataCollectionCount;
}
else
{
count += list.Count;
}
if (!packet.Configuration.IsInternalFeed && packet.Configuration.IsCustomData)
{
// This is all the custom data
custom.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, list));
}
var securityUpdate = new List<BaseData>(list.Count);
var consolidatorUpdate = new List<BaseData>(list.Count);
for (int i = 0; i < list.Count; i++)
{
var baseData = list[i];
if (!packet.Configuration.IsInternalFeed)
{
// this is all the data that goes into the algorithm
allDataForAlgorithm.Add(baseData);
}
// don't add internal feed data to ticks/bars objects
if (baseData.DataType != MarketDataType.Auxiliary)
{
if (!packet.Configuration.IsInternalFeed)
{
PopulateDataDictionaries(baseData, ticks, tradeBars, quoteBars, optionChains, futuresChains);
// special handling of options data to build the option chain
if (packet.Security.Type == SecurityType.Option)
{
if (baseData.DataType == MarketDataType.OptionChain)
{
optionChains[baseData.Symbol] = (OptionChain) baseData;
}
else if (!HandleOptionData(algorithmTime, baseData, optionChains, packet.Security, sliceFuture))
{
continue;
}
}
// special handling of futures data to build the futures chain
if (packet.Security.Type == SecurityType.Future)
{
if (baseData.DataType == MarketDataType.FuturesChain)
{
futuresChains[baseData.Symbol] = (FuturesChain)baseData;
}
else if (!HandleFuturesData(algorithmTime, baseData, futuresChains, packet.Security))
{
continue;
}
}
// this is data used to update consolidators
consolidatorUpdate.Add(baseData);
}
// this is the data used set market prices
securityUpdate.Add(baseData);
}
// include checks for various aux types so we don't have to construct the dictionaries in Slice
else if ((delisting = baseData as Delisting) != null)
{
delistings[symbol] = delisting;
}
else if ((dividend = baseData as Dividend) != null)
{
dividends[symbol] = dividend;
}
else if ((split = baseData as Split) != null)
{
splits[symbol] = split;
}
else if ((symbolChange = baseData as SymbolChangedEvent) != null)
{
// symbol changes is keyed by the requested symbol
symbolChanges[packet.Configuration.Symbol] = symbolChange;
}
}
if (securityUpdate.Count > 0)
{
// check for 'cash securities' if we found valid update data for this symbol
// and we need this data to update cash conversion rates, long term we should
// have Cash hold onto it's security, then he can update himself, or rather, just
// patch through calls to conversion rate to compue it on the fly using Security.Price
if (cashSecurities.Contains(packet.Security.Symbol))
{
foreach (var cashKvp in cashBook)
{
if (cashKvp.Value.SecuritySymbol == packet.Security.Symbol)
{
var cashUpdates = new List<BaseData> {securityUpdate[securityUpdate.Count - 1]};
cash.Add(new UpdateData<Cash>(cashKvp.Value, packet.Configuration.Type, cashUpdates));
}
}
}
security.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, securityUpdate));
}
if (consolidatorUpdate.Count > 0)
{
consolidator.Add(new UpdateData<SubscriptionDataConfig>(packet.Configuration, packet.Configuration.Type, consolidatorUpdate));
}
}
slice = new Slice(algorithmTime, allDataForAlgorithm, tradeBars, quoteBars, ticks, optionChains, futuresChains, splits, dividends, delistings, symbolChanges, allDataForAlgorithm.Count > 0);
return new TimeSlice(utcDateTime, count, slice, data, cash, security, consolidator, custom, changes);
}
/// <summary>
/// Adds the specified <see cref="BaseData"/> instance to the appropriate <see cref="DataDictionary{T}"/>
/// </summary>
private static void PopulateDataDictionaries(BaseData baseData, Ticks ticks, TradeBars tradeBars, QuoteBars quoteBars, OptionChains optionChains, FuturesChains futuresChains)
{
var symbol = baseData.Symbol;
// populate data dictionaries
switch (baseData.DataType)
{
case MarketDataType.Tick:
ticks.Add(symbol, (Tick)baseData);
break;
case MarketDataType.TradeBar:
tradeBars[symbol] = (TradeBar) baseData;
break;
case MarketDataType.QuoteBar:
quoteBars[symbol] = (QuoteBar) baseData;
break;
case MarketDataType.OptionChain:
optionChains[symbol] = (OptionChain) baseData;
break;
case MarketDataType.FuturesChain:
futuresChains[symbol] = (FuturesChain)baseData;
break;
}
}
private static bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, Security security, Lazy<Slice> sliceFuture)
{
var symbol = baseData.Symbol;
OptionChain chain;
var canonical = Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, default(OptionStyle), default(OptionRight), 0, SecurityIdentifier.DefaultDate);
if (!optionChains.TryGetValue(canonical, out chain))
{
chain = new OptionChain(canonical, algorithmTime);
optionChains[canonical] = chain;
}
var universeData = baseData as OptionChainUniverseDataCollection;
if (universeData != null)
{
if (universeData.Underlying != null)
{
chain.Underlying = universeData.Underlying;
foreach(var addedContract in chain.Contracts)
{
addedContract.Value.UnderlyingLastPrice = chain.Underlying.Price;
}
}
foreach (var contractSymbol in universeData.FilteredContracts)
{
chain.FilteredContracts.Add(contractSymbol);
}
return false;
}
OptionContract contract;
if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
{
var underlyingSymbol = baseData.Symbol.Underlying;
contract = new OptionContract(baseData.Symbol, underlyingSymbol)
{
Time = baseData.EndTime,
LastPrice = security.Close,
BidPrice = security.BidPrice,
BidSize = security.BidSize,
AskPrice = security.AskPrice,
AskSize = security.AskSize,
OpenInterest = security.OpenInterest,
UnderlyingLastPrice = chain.Underlying.Price
};
chain.Contracts[baseData.Symbol] = contract;
var option = security as Option;
if (option != null)
{
contract.SetOptionPriceModel(() => option.PriceModel.Evaluate(option, sliceFuture.Value, contract));
}
}
// populate ticks and tradebars dictionaries with no aux data
switch (baseData.DataType)
{
case MarketDataType.Tick:
var tick = (Tick)baseData;
chain.Ticks.Add(tick.Symbol, tick);
UpdateContract(contract, tick);
break;
case MarketDataType.TradeBar:
var tradeBar = (TradeBar)baseData;
chain.TradeBars[symbol] = tradeBar;
contract.LastPrice = tradeBar.Close;
break;
case MarketDataType.QuoteBar:
var quote = (QuoteBar)baseData;
chain.QuoteBars[symbol] = quote;
UpdateContract(contract, quote);
break;
case MarketDataType.Base:
chain.AddAuxData(baseData);
break;
}
return true;
}
private static bool HandleFuturesData(DateTime algorithmTime, BaseData baseData, FuturesChains futuresChains, Security security)
{
var symbol = baseData.Symbol;
FuturesChain chain;
var canonical = Symbol.Create(symbol.Underlying.Value, SecurityType.Future, symbol.ID.Market);
if (!futuresChains.TryGetValue(canonical, out chain))
{
chain = new FuturesChain(canonical, algorithmTime);
futuresChains[canonical] = chain;
}
var universeData = baseData as FuturesChainUniverseDataCollection;
if (universeData != null)
{
foreach (var contractSymbol in universeData.FilteredContracts)
{
chain.FilteredContracts.Add(contractSymbol);
}
return false;
}
FuturesContract contract;
if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
{
var underlyingSymbol = baseData.Symbol.Underlying;
contract = new FuturesContract(baseData.Symbol, underlyingSymbol)
{
Time = baseData.EndTime,
LastPrice = security.Close,
BidPrice = security.BidPrice,
BidSize = security.BidSize,
AskPrice = security.AskPrice,
AskSize = security.AskSize,
OpenInterest = security.OpenInterest
};
chain.Contracts[baseData.Symbol] = contract;
}
// populate ticks and tradebars dictionaries with no aux data
switch (baseData.DataType)
{
case MarketDataType.Tick:
var tick = (Tick)baseData;
chain.Ticks.Add(tick.Symbol, tick);
UpdateContract(contract, tick);
break;
case MarketDataType.TradeBar:
var tradeBar = (TradeBar)baseData;
chain.TradeBars[symbol] = tradeBar;
contract.LastPrice = tradeBar.Close;
break;
case MarketDataType.QuoteBar:
var quote = (QuoteBar)baseData;
chain.QuoteBars[symbol] = quote;
UpdateContract(contract, quote);
break;
case MarketDataType.Base:
chain.AddAuxData(baseData);
break;
}
return true;
}
private static void UpdateContract(OptionContract contract, QuoteBar quote)
{
if (quote.Ask != null && quote.Ask.Close != 0m)
{
contract.AskPrice = quote.Ask.Close;
contract.AskSize = quote.LastAskSize;
}
if (quote.Bid != null && quote.Bid.Close != 0m)
{
contract.BidPrice = quote.Bid.Close;
contract.BidSize = quote.LastBidSize;
}
}
private static void UpdateContract(OptionContract contract, Tick tick)
{
if (tick.TickType == TickType.Trade)
{
contract.LastPrice = tick.Price;
}
else if (tick.TickType == TickType.Quote)
{
if (tick.AskPrice != 0m)
{
contract.AskPrice = tick.AskPrice;
contract.AskSize = tick.AskSize;
}
if (tick.BidPrice != 0m)
{
contract.BidPrice = tick.BidPrice;
contract.BidSize = tick.BidSize;
}
}
else if (tick.TickType == TickType.OpenInterest)
{
if (tick.Value != 0m)
{
contract.OpenInterest = tick.Value;
}
}
}
private static void UpdateContract(FuturesContract contract, QuoteBar quote)
{
if (quote.Ask != null && quote.Ask.Close != 0m)
{
contract.AskPrice = quote.Ask.Close;
contract.AskSize = quote.LastAskSize;
}
if (quote.Bid != null && quote.Bid.Close != 0m)
{
contract.BidPrice = quote.Bid.Close;
contract.BidSize = quote.LastBidSize;
}
}
private static void UpdateContract(FuturesContract contract, Tick tick)
{
if (tick.TickType == TickType.Trade)
{
contract.LastPrice = tick.Price;
}
else if (tick.TickType == TickType.Quote)
{
if (tick.AskPrice != 0m)
{
contract.AskPrice = tick.AskPrice;
contract.AskSize = tick.AskSize;
}
if (tick.BidPrice != 0m)
{
contract.BidPrice = tick.BidPrice;
contract.BidSize = tick.BidSize;
}
}
else if (tick.TickType == TickType.OpenInterest)
{
if (tick.Value != 0m)
{
contract.OpenInterest = tick.Value;
}
}
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtoBuf;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace InWorldz.Region.Data.Thoosa.Serialization
{
/// <summary>
/// A snapshot in time of the current state of a SceneObjectPart that is
/// also protobuf serializable
/// </summary>
[ProtoContract]
public class SceneObjectPartSnapshot
{
[ProtoMember(1)]
public Guid Id;
[ProtoMember(2)]
public string Name;
[ProtoMember(3)]
public string Description;
[ProtoMember(4)]
public int[] PayPrice;
[ProtoMember(5)]
public Guid Sound;
[ProtoMember(6)]
public byte SoundFlags;
[ProtoMember(7)]
public float SoundGain;
[ProtoMember(8)]
public float SoundRadius;
[ProtoMember(9)]
public byte[] SerializedPhysicsData;
[ProtoMember(10)]
public Guid CreatorId;
[ProtoMember(11)]
public TaskInventorySnapshot Inventory;
[ProtoMember(12)]
public OpenMetaverse.PrimFlags ObjectFlags;
[ProtoMember(13)]
public uint LocalId;
[ProtoMember(14)]
public OpenMetaverse.Material Material;
[ProtoMember(15)]
public bool PassTouches;
[ProtoMember(16)]
public ulong RegionHandle;
[ProtoMember(17)]
public int ScriptAccessPin;
[ProtoMember(18)]
public byte[] TextureAnimation;
[ProtoMember(19)]
public OpenMetaverse.Vector3 GroupPosition;
[ProtoMember(20)]
public OpenMetaverse.Vector3 OffsetPosition;
[ProtoMember(21)]
public OpenMetaverse.Quaternion RotationOffset;
[ProtoMember(22)]
public OpenMetaverse.Vector3 Velocity;
/// <summary>
/// This maps to the old angular velocity property on the prim which
/// now is used only to store omegas
/// </summary>
[ProtoMember(23)]
public OpenMetaverse.Vector3 AngularVelocityTarget;
/// <summary>
/// This is the new physical angular velocity
/// </summary>
[ProtoMember(24)]
public OpenMetaverse.Vector3 AngularVelocity;
public System.Drawing.Color TextColor {get; set;}
[ProtoMember(25, DataFormat=DataFormat.FixedSize)]
private int SerializedTextColor
{
get { return TextColor.ToArgb(); }
set { TextColor = System.Drawing.Color.FromArgb(value); }
}
[ProtoMember(26)]
public string HoverText;
[ProtoMember(27)]
public string SitName;
[ProtoMember(28)]
public string TouchName;
[ProtoMember(29)]
public int LinkNumber;
[ProtoMember(30)]
public byte ClickAction;
[ProtoMember(31)]
public PrimShapeSnapshot Shape;
[ProtoMember(32)]
public OpenMetaverse.Vector3 Scale;
[ProtoMember(33)]
public OpenMetaverse.Quaternion SitTargetOrientation;
[ProtoMember(34)]
public OpenMetaverse.Vector3 SitTargetPosition;
[ProtoMember(35)]
public uint ParentId;
[ProtoMember(36)]
public int CreationDate;
[ProtoMember(37)]
public uint Category;
[ProtoMember(38)]
public int SalePrice;
[ProtoMember(39)]
public byte ObjectSaleType;
[ProtoMember(40)]
public int OwnershipCost;
[ProtoMember(41)]
public Guid GroupId;
[ProtoMember(42)]
public Guid OwnerId;
[ProtoMember(43)]
public Guid LastOwnerId;
[ProtoMember(44)]
public uint BaseMask;
[ProtoMember(45)]
public uint OwnerMask;
[ProtoMember(46)]
public uint GroupMask;
[ProtoMember(47)]
public uint EveryoneMask;
[ProtoMember(48)]
public uint NextOwnerMask;
[ProtoMember(49)]
public byte SavedAttachmentPoint;
[ProtoMember(50)]
public OpenMetaverse.Vector3 SavedAttachmentPos;
[ProtoMember(51)]
public OpenMetaverse.Quaternion SavedAttachmentRot;
[ProtoMember(52)]
public OpenMetaverse.PrimFlags Flags;
[ProtoMember(53)]
public Guid CollisionSound;
[ProtoMember(54)]
public float CollisionSoundVolume;
/// <summary>
/// Script states by [Item Id, Data]
/// </summary>
[ProtoMember(55)]
public Dictionary<Guid, byte[]> SerializedScriptStates;
[ProtoMember(56)]
public string MediaUrl;
[ProtoMember(57)]
public byte[] ParticleSystem;
/// <summary>
/// Contains a collection of serialized script bytecode that go with this prim/part
/// May be null if these are not required
/// </summary>
[ProtoMember(58)]
public Dictionary<Guid, byte[]> SeralizedScriptBytecode;
/// <summary>
/// Contains a collection of physx serialized convex meshes that go with this prim/part
/// May be null if these are not requested
/// </summary>
[ProtoMember(59)]
public byte[] SerializedPhysicsShapes;
/// <summary>
/// Stores the item ID that is associated with a worn attachment
/// </summary>
[ProtoMember(60)]
public Guid FromItemId;
[ProtoMember(61)]
public float ServerWeight;
[ProtoMember(62)]
public float StreamingCost;
[ProtoMember(63)]
public KeyframeAnimationSnapshot KeyframeAnimation;
[ProtoMember(64)]
public ServerPrimFlags ServerFlags;
static SceneObjectPartSnapshot()
{
ProtoBuf.Serializer.PrepareSerializer<SceneObjectPartSnapshot>();
}
static public SceneObjectPartSnapshot FromSceneObjectPart(SceneObjectPart part, SerializationFlags flags)
{
bool serializePhysicsShapes = (flags & SerializationFlags.SerializePhysicsShapes) != 0;
bool serializeScriptBytecode = (flags & SerializationFlags.SerializeScriptBytecode) != 0;
StopScriptReason stopScriptReason;
if ((flags & SerializationFlags.StopScripts) == 0)
{
stopScriptReason = StopScriptReason.None;
}
else
{
if ((flags & SerializationFlags.FromCrossing) != 0)
stopScriptReason = StopScriptReason.Crossing;
else
stopScriptReason = StopScriptReason.Derez;
}
SitTargetInfo sitInfo = part.ParentGroup.SitTargetForPart(part.UUID);
SceneObjectPartSnapshot partSnap = new SceneObjectPartSnapshot
{
AngularVelocity = part.PhysicalAngularVelocity,
AngularVelocityTarget = part.AngularVelocity,
BaseMask = part.BaseMask,
Category = part.Category,
ClickAction = part.ClickAction,
CollisionSound = part.CollisionSound.Guid,
CollisionSoundVolume = part.CollisionSoundVolume,
CreationDate = part.CreationDate,
CreatorId = part.CreatorID.Guid,
Description = part.Description,
EveryoneMask = part.EveryoneMask,
Flags = part.Flags,
GroupId = part.GroupID.Guid,
GroupMask = part.GroupMask,
//if this is an attachment, dont fill out the group position. This prevents an issue where
//a user is crossing to a new region and the vehicle has already been sent. Since the attachment's
//group position is actually the wearer's position and the wearer's position is the vehicle position,
//trying to get the attachment grp pos triggers an error and a ton of log spam.
GroupPosition = part.ParentGroup.IsAttachment ? OpenMetaverse.Vector3.Zero : part.GroupPosition,
HoverText = part.Text,
Id = part.UUID.Guid,
Inventory = TaskInventorySnapshot.FromTaskInventory(part),
KeyframeAnimation = KeyframeAnimationSnapshot.FromKeyframeAnimation(part.KeyframeAnimation),
LastOwnerId = part.LastOwnerID.Guid,
LinkNumber = part.LinkNum,
LocalId = part.LocalId,
Material = (OpenMetaverse.Material)part.Material,
MediaUrl = part.MediaUrl,
Name = part.Name,
NextOwnerMask = part.NextOwnerMask,
ObjectFlags = (OpenMetaverse.PrimFlags)part.ObjectFlags,
ObjectSaleType = part.ObjectSaleType,
OffsetPosition = part.OffsetPosition,
OwnerId = part.OwnerID.Guid,
OwnerMask = part.OwnerMask,
OwnershipCost = part.OwnershipCost,
ParentId = part.ParentID,
ParticleSystem = part.ParticleSystem,
PassTouches = part.PassTouches,
PayPrice = part.PayPrice,
RegionHandle = part.RegionHandle,
RotationOffset = part.RotationOffset,
SalePrice = part.SalePrice,
SavedAttachmentPoint = part.SavedAttachmentPoint,
SavedAttachmentPos = part.SavedAttachmentPos,
SavedAttachmentRot = part.SavedAttachmentRot,
Scale = part.Scale,
ScriptAccessPin = part.ScriptAccessPin,
SerializedPhysicsData = part.SerializedPhysicsData,
ServerWeight = part.ServerWeight,
ServerFlags = (ServerPrimFlags)part.ServerFlags,
Shape = PrimShapeSnapshot.FromShape(part.Shape),
SitName = part.SitName,
SitTargetOrientation = sitInfo.Rotation,
SitTargetPosition = sitInfo.Offset,
Sound = part.Sound.Guid,
SoundFlags = part.SoundOptions,
SoundGain = part.SoundGain,
SoundRadius = part.SoundRadius,
StreamingCost = part.StreamingCost,
TextColor = part.TextColor,
TextureAnimation = part.TextureAnimation,
TouchName = part.TouchName,
Velocity = part.Velocity,
FromItemId = part.FromItemID.Guid
};
Dictionary<OpenMetaverse.UUID, byte[]> states;
Dictionary<OpenMetaverse.UUID, byte[]> byteCode;
if (serializeScriptBytecode)
{
Tuple<Dictionary<OpenMetaverse.UUID, byte[]>, Dictionary<OpenMetaverse.UUID, byte[]>>
statesAndBytecode = part.Inventory.GetBinaryScriptStatesAndCompiledScripts(stopScriptReason);
states = statesAndBytecode.Item1;
byteCode = statesAndBytecode.Item2;
}
else
{
states = part.Inventory.GetBinaryScriptStates(stopScriptReason);
byteCode = null;
}
partSnap.SerializedScriptStates = new Dictionary<Guid, byte[]>(states.Count);
foreach (var kvp in states)
{
//map from UUID to Guid
partSnap.SerializedScriptStates[kvp.Key.Guid] = kvp.Value;
}
if (byteCode != null)
{
partSnap.SeralizedScriptBytecode = new Dictionary<Guid, byte[]>();
foreach (var kvp in byteCode)
{
//map from UUID to Guid
partSnap.SeralizedScriptBytecode[kvp.Key.Guid] = kvp.Value;
}
}
if (serializePhysicsShapes)
{
partSnap.SerializedPhysicsShapes = part.SerializedPhysicsShapes;
}
return partSnap;
}
internal SceneObjectPart ToSceneObjectPart()
{
SceneObjectPart sop = new SceneObjectPart
{
AngularVelocity = this.AngularVelocityTarget,
PhysicalAngularVelocity = this.AngularVelocity,
BaseMask = this.BaseMask,
Category = this.Category,
ClickAction = this.ClickAction,
CollisionSound = new OpenMetaverse.UUID(this.CollisionSound),
CollisionSoundVolume = this.CollisionSoundVolume,
CreationDate = this.CreationDate,
CreatorID = new OpenMetaverse.UUID(this.CreatorId),
Description = this.Description,
EveryoneMask = this.EveryoneMask,
Flags = this.Flags,
GroupID = new OpenMetaverse.UUID(this.GroupId),
GroupMask = this.GroupMask,
GroupPosition = this.GroupPosition,
Text = this.HoverText,
UUID = new OpenMetaverse.UUID(this.Id),
TaskInventory = this.Inventory.ToTaskInventory(),
LastOwnerID = new OpenMetaverse.UUID(this.LastOwnerId),
LinkNum = this.LinkNumber,
LocalId = this.LocalId,
Material = (byte)this.Material,
MediaUrl = this.MediaUrl,
Name = this.Name,
NextOwnerMask = this.NextOwnerMask,
ObjectFlags = (uint)this.ObjectFlags,
ObjectSaleType = this.ObjectSaleType,
OffsetPosition = this.OffsetPosition,
OwnerID = new OpenMetaverse.UUID(this.OwnerId),
OwnerMask = this.OwnerMask,
OwnershipCost = this.OwnershipCost,
ParentID = this.ParentId,
ParticleSystem = this.ParticleSystem,
PassTouches = this.PassTouches,
PayPrice = this.PayPrice,
RegionHandle = this.RegionHandle,
RotationOffset = this.RotationOffset,
SalePrice = this.SalePrice,
SavedAttachmentPoint = this.SavedAttachmentPoint,
SavedAttachmentPos = this.SavedAttachmentPos,
SavedAttachmentRot = this.SavedAttachmentRot,
Scale = this.Scale,
ScriptAccessPin = this.ScriptAccessPin,
SerializedPhysicsData = this.SerializedPhysicsData,
ServerFlags = (uint)this.ServerFlags,
ServerWeight = this.ServerWeight,
Shape = this.Shape.ToPrimitiveBaseShape(),
SitName = this.SitName,
SitTargetOrientation = this.SitTargetOrientation,
SitTargetPosition = this.SitTargetPosition,
Sound = new OpenMetaverse.UUID(this.Sound),
SoundOptions = this.SoundFlags,
SoundGain = this.SoundGain,
SoundRadius = this.SoundRadius,
StreamingCost = this.StreamingCost,
TextColor = this.TextColor,
TextureAnimation = this.TextureAnimation,
TouchName = this.TouchName,
Velocity = this.Velocity,
SerializedPhysicsShapes = this.SerializedPhysicsShapes,
FromItemID = new OpenMetaverse.UUID(this.FromItemId),
KeyframeAnimation = this.KeyframeAnimation == null ? null : this.KeyframeAnimation.ToKeyframeAnimation()
};
// Do legacy to current update for sop.ServerFlags.
sop.PrepSitTargetFromStorage(sop.SitTargetPosition, sop.SitTargetOrientation);
if (SerializedScriptStates != null)
{
var states = new Dictionary<OpenMetaverse.UUID, byte[]>(SerializedScriptStates.Count);
foreach (var kvp in SerializedScriptStates)
{
//map from Guid to UUID
states.Add(new OpenMetaverse.UUID(kvp.Key), kvp.Value);
}
sop.SetSavedScriptStates(states);
}
if (SeralizedScriptBytecode != null)
{
var byteCode = new Dictionary<OpenMetaverse.UUID, byte[]>(SeralizedScriptBytecode.Count);
foreach (var kvp in SeralizedScriptBytecode)
{
//map from Guid to UUID
byteCode.Add(new OpenMetaverse.UUID(kvp.Key), kvp.Value);
}
sop.SerializedScriptByteCode = byteCode;
}
return sop;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace ExportImportPromotion.StoreMarketingWebService
{
#if MS
[GeneratedCode("System.Xml", "4.0.30319.1"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "http://schemas.microsoft.com/CommerceServer/2006/06/MarketingWebService")]
#else
[GeneratedCode("System.Xml", "4.0.30319.1"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "http://schemas.commerceserver.net/2013/01/Marketing/MarketingWebService")]
#endif
[Serializable]
public class CampaignData
{
private int idField;
private string nameField;
private string descriptionField;
private bool activeField;
private DateTime startDateField;
private DateTime endDateField;
private int customerIdField;
private string eventTypeNameField;
private bool campaignLevelGoalingField;
private int numberOfEventsOrderedField;
private string customerNameField;
private DateTime createdDateField;
private DateTime lastModifiedDateField;
private string lastModifiedByField;
private DateTime deletedDateField;
public int Id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
[XmlElement(IsNullable = true)]
public string Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
[XmlElement(IsNullable = true)]
public string Description
{
get
{
return this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
public bool Active
{
get
{
return this.activeField;
}
set
{
this.activeField = value;
}
}
public DateTime StartDate
{
get
{
return this.startDateField;
}
set
{
this.startDateField = value;
}
}
public DateTime EndDate
{
get
{
return this.endDateField;
}
set
{
this.endDateField = value;
}
}
public int CustomerId
{
get
{
return this.customerIdField;
}
set
{
this.customerIdField = value;
}
}
public string EventTypeName
{
get
{
return this.eventTypeNameField;
}
set
{
this.eventTypeNameField = value;
}
}
public bool CampaignLevelGoaling
{
get
{
return this.campaignLevelGoalingField;
}
set
{
this.campaignLevelGoalingField = value;
}
}
public int NumberOfEventsOrdered
{
get
{
return this.numberOfEventsOrderedField;
}
set
{
this.numberOfEventsOrderedField = value;
}
}
[XmlElement(IsNullable = true)]
public string CustomerName
{
get
{
return this.customerNameField;
}
set
{
this.customerNameField = value;
}
}
public DateTime CreatedDate
{
get
{
return this.createdDateField;
}
set
{
this.createdDateField = value;
}
}
public DateTime LastModifiedDate
{
get
{
return this.lastModifiedDateField;
}
set
{
this.lastModifiedDateField = value;
}
}
[XmlElement(IsNullable = true)]
public string LastModifiedBy
{
get
{
return this.lastModifiedByField;
}
set
{
this.lastModifiedByField = value;
}
}
public DateTime DeletedDate
{
get
{
return this.deletedDateField;
}
set
{
this.deletedDateField = value;
}
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.WebApi;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Listener
{
[ServiceLocator(Default = typeof(Agent))]
public interface IAgent : IAgentService
{
Task<int> ExecuteCommand(CommandSettings command);
}
public sealed class Agent : AgentService, IAgent
{
private IMessageListener _listener;
private ITerminal _term;
private bool _inConfigStage;
private ManualResetEvent _completedCommand = new ManualResetEvent(false);
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_term = HostContext.GetService<ITerminal>();
}
public async Task<int> ExecuteCommand(CommandSettings command)
{
try
{
var agentWebProxy = HostContext.GetService<IVstsAgentWebProxy>();
var agentCertManager = HostContext.GetService<IAgentCertificateManager>();
VssUtil.InitializeVssClientSettings(HostContext.UserAgent, agentWebProxy.WebProxy, agentCertManager.VssClientCertificateManager);
_inConfigStage = true;
_completedCommand.Reset();
_term.CancelKeyPress += CtrlCHandler;
//register a SIGTERM handler
HostContext.Unloading += Agent_Unloading;
// TODO Unit test to cover this logic
Trace.Info(nameof(ExecuteCommand));
var configManager = HostContext.GetService<IConfigurationManager>();
// command is not required, if no command it just starts if configured
// TODO: Invalid config prints usage
if (command.Help)
{
PrintUsage(command);
return Constants.Agent.ReturnCode.Success;
}
if (command.Version)
{
_term.WriteLine(Constants.Agent.Version);
return Constants.Agent.ReturnCode.Success;
}
if (command.Commit)
{
_term.WriteLine(BuildConstants.Source.CommitHash);
return Constants.Agent.ReturnCode.Success;
}
// Configure agent prompt for args if not supplied
// Unattend configure mode will not prompt for args if not supplied and error on any missing or invalid value.
if (command.Configure)
{
try
{
await configManager.ConfigureAsync(command);
return Constants.Agent.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Agent.ReturnCode.TerminatedError;
}
}
// remove config files, remove service, and exit
if (command.Remove)
{
try
{
await configManager.UnconfigureAsync(command);
return Constants.Agent.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Agent.ReturnCode.TerminatedError;
}
}
_inConfigStage = false;
AgentSettings settings = configManager.LoadSettings();
var store = HostContext.GetService<IConfigurationStore>();
bool configuredAsService = store.IsServiceConfigured();
// Run agent
//if (command.Run) // this line is current break machine provisioner.
//{
// Error if agent not configured.
if (!configManager.IsConfigured())
{
_term.WriteError(StringUtil.Loc("AgentIsNotConfigured"));
PrintUsage(command);
return Constants.Agent.ReturnCode.TerminatedError;
}
Trace.Verbose($"Configured as service: '{configuredAsService}'");
//Get the startup type of the agent i.e., autostartup, service, manual
StartupType startType;
var startupTypeAsString = command.GetStartupType();
if (string.IsNullOrEmpty(startupTypeAsString) && configuredAsService)
{
// We need try our best to make the startup type accurate
// The problem is coming from agent autoupgrade, which result an old version service host binary but a newer version agent binary
// At that time the servicehost won't pass --startuptype to agent.listener while the agent is actually running as service.
// We will guess the startup type only when the agent is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
Trace.Info($"Try determine agent startup type base on console redirects.");
startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
}
else
{
if (!Enum.TryParse(startupTypeAsString, true, out startType))
{
Trace.Info($"Could not parse the argument value '{startupTypeAsString}' for StartupType. Defaulting to {StartupType.Manual}");
startType = StartupType.Manual;
}
}
Trace.Info($"Set agent startup type - {startType}");
HostContext.StartupType = startType;
#if OS_WINDOWS
if (store.IsAutoLogonConfigured())
{
if (HostContext.StartupType != StartupType.Service)
{
Trace.Info($"Autologon is configured on the machine, dumping all the autologon related registry settings");
var autoLogonRegManager = HostContext.GetService<IAutoLogonRegistryManager>();
autoLogonRegManager.DumpAutoLogonRegistrySettings();
}
else
{
Trace.Info($"Autologon is configured on the machine but current Agent.Listner.exe is launched from the windows service");
}
}
#endif
// Run the agent interactively or as service
return await RunAsync(settings);
}
finally
{
_term.CancelKeyPress -= CtrlCHandler;
HostContext.Unloading -= Agent_Unloading;
_completedCommand.Set();
}
}
private void Agent_Unloading(object sender, EventArgs e)
{
if ((!_inConfigStage) && (!HostContext.AgentShutdownToken.IsCancellationRequested))
{
HostContext.ShutdownAgent(ShutdownReason.UserCancelled);
_completedCommand.WaitOne(Constants.Agent.ExitOnUnloadTimeout);
}
}
private void CtrlCHandler(object sender, EventArgs e)
{
_term.WriteLine("Exiting...");
if (_inConfigStage)
{
HostContext.Dispose();
Environment.Exit(Constants.Agent.ReturnCode.TerminatedError);
}
else
{
ConsoleCancelEventArgs cancelEvent = e as ConsoleCancelEventArgs;
if (cancelEvent != null && HostContext.GetService<IConfigurationStore>().IsServiceConfigured())
{
ShutdownReason reason;
if (cancelEvent.SpecialKey == ConsoleSpecialKey.ControlBreak)
{
Trace.Info("Received Ctrl-Break signal from agent service host, this indicate the operating system is shutting down.");
reason = ShutdownReason.OperatingSystemShutdown;
}
else
{
Trace.Info("Received Ctrl-C signal, stop agent.listener and agent.worker.");
reason = ShutdownReason.UserCancelled;
}
HostContext.ShutdownAgent(reason);
}
else
{
HostContext.ShutdownAgent(ShutdownReason.UserCancelled);
}
}
}
//create worker manager, create message listener and start listening to the queue
private async Task<int> RunAsync(AgentSettings settings)
{
Trace.Info(nameof(RunAsync));
_listener = HostContext.GetService<IMessageListener>();
if (!await _listener.CreateSessionAsync(HostContext.AgentShutdownToken))
{
return Constants.Agent.ReturnCode.TerminatedError;
}
HostContext.WritePerfCounter("SessionCreated");
_term.WriteLine(StringUtil.Loc("ListenForJobs", DateTime.UtcNow));
IJobDispatcher jobDispatcher = null;
CancellationTokenSource messageQueueLoopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(HostContext.AgentShutdownToken);
try
{
var notification = HostContext.GetService<IJobNotification>();
if (!String.IsNullOrEmpty(settings.NotificationSocketAddress))
{
notification.StartClient(settings.NotificationSocketAddress);
}
else
{
notification.StartClient(settings.NotificationPipeName, HostContext.AgentShutdownToken);
}
// this is not a reliable way to disable auto update.
// we need server side work to really enable the feature
// https://github.com/Microsoft/vsts-agent/issues/446 (Feature: Allow agent / pool to opt out of automatic updates)
bool disableAutoUpdate = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("agent.disableupdate"));
bool autoUpdateInProgress = false;
Task<bool> selfUpdateTask = null;
jobDispatcher = HostContext.CreateService<IJobDispatcher>();
while (!HostContext.AgentShutdownToken.IsCancellationRequested)
{
TaskAgentMessage message = null;
bool skipMessageDeletion = false;
try
{
Task<TaskAgentMessage> getNextMessage = _listener.GetNextMessageAsync(messageQueueLoopTokenSource.Token);
if (autoUpdateInProgress)
{
Trace.Verbose("Auto update task running at backend, waiting for getNextMessage or selfUpdateTask to finish.");
Task completeTask = await Task.WhenAny(getNextMessage, selfUpdateTask);
if (completeTask == selfUpdateTask)
{
autoUpdateInProgress = false;
if (await selfUpdateTask)
{
Trace.Info("Auto update task finished at backend, an agent update is ready to apply exit the current agent instance.");
Trace.Info("Stop message queue looping.");
messageQueueLoopTokenSource.Cancel();
try
{
await getNextMessage;
}
catch (Exception ex)
{
Trace.Info($"Ignore any exception after cancel message loop. {ex}");
}
return Constants.Agent.ReturnCode.AgentUpdating;
}
else
{
Trace.Info("Auto update task finished at backend, there is no available agent update needs to apply, continue message queue looping.");
}
}
}
message = await getNextMessage; //get next message
HostContext.WritePerfCounter($"MessageReceived_{message.MessageType}");
if (string.Equals(message.MessageType, AgentRefreshMessage.MessageType, StringComparison.OrdinalIgnoreCase))
{
if (disableAutoUpdate)
{
Trace.Info("Refresh message received, skip autoupdate since environment variable agent.disableupdate is set.");
}
else
{
if (autoUpdateInProgress == false)
{
autoUpdateInProgress = true;
var agentUpdateMessage = JsonUtility.FromString<AgentRefreshMessage>(message.Body);
var selfUpdater = HostContext.GetService<ISelfUpdater>();
selfUpdateTask = selfUpdater.SelfUpdate(agentUpdateMessage, jobDispatcher, HostContext.StartupType != StartupType.Service, HostContext.AgentShutdownToken);
Trace.Info("Refresh message received, kick-off selfupdate background process.");
}
else
{
Trace.Info("Refresh message received, skip autoupdate since a previous autoupdate is already running.");
}
}
}
else if (string.Equals(message.MessageType, JobRequestMessageTypes.AgentJobRequest, StringComparison.OrdinalIgnoreCase) ||
string.Equals(message.MessageType, JobRequestMessageTypes.PipelineAgentJobRequest, StringComparison.OrdinalIgnoreCase))
{
if (autoUpdateInProgress)
{
skipMessageDeletion = true;
}
else
{
Pipelines.AgentJobRequestMessage pipelineJobMessage = null;
switch (message.MessageType)
{
case JobRequestMessageTypes.AgentJobRequest:
var legacyJobMessage = JsonUtility.FromString<AgentJobRequestMessage>(message.Body);
pipelineJobMessage = Pipelines.AgentJobRequestMessageUtil.Convert(legacyJobMessage);
break;
case JobRequestMessageTypes.PipelineAgentJobRequest:
pipelineJobMessage = JsonUtility.FromString<Pipelines.AgentJobRequestMessage>(message.Body);
break;
}
jobDispatcher.Run(pipelineJobMessage);
}
}
else if (string.Equals(message.MessageType, JobCancelMessage.MessageType, StringComparison.OrdinalIgnoreCase))
{
var cancelJobMessage = JsonUtility.FromString<JobCancelMessage>(message.Body);
bool jobCancelled = jobDispatcher.Cancel(cancelJobMessage);
skipMessageDeletion = autoUpdateInProgress && !jobCancelled;
}
else
{
Trace.Error($"Received message {message.MessageId} with unsupported message type {message.MessageType}.");
}
}
finally
{
if (!skipMessageDeletion && message != null)
{
try
{
await _listener.DeleteMessageAsync(message);
}
catch (Exception ex)
{
Trace.Error($"Catch exception during delete message from message queue. message id: {message.MessageId}");
Trace.Error(ex);
}
finally
{
message = null;
}
}
}
}
}
finally
{
if (jobDispatcher != null)
{
await jobDispatcher.ShutdownAsync();
}
//TODO: make sure we don't mask more important exception
await _listener.DeleteSessionAsync();
messageQueueLoopTokenSource.Dispose();
}
return Constants.Agent.ReturnCode.Success;
}
private void PrintUsage(CommandSettings command)
{
string separator;
string ext;
#if OS_WINDOWS
separator = "\\";
ext = "cmd";
#else
separator = "/";
ext = "sh";
#endif
string commonHelp = StringUtil.Loc("CommandLineHelp_Common");
string envHelp = StringUtil.Loc("CommandLineHelp_Env");
if (command.Configure)
{
_term.WriteLine(StringUtil.Loc("CommandLineHelp_Configure", separator, ext, commonHelp, envHelp));
}
else if (command.Remove)
{
_term.WriteLine(StringUtil.Loc("CommandLineHelp_Remove", separator, ext, commonHelp, envHelp));
}
else
{
_term.WriteLine(StringUtil.Loc("CommandLineHelp", separator, ext));
}
}
}
}
| |
// 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\Arm\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LoadVector128_Single()
{
var test = new LoadUnaryOpTest__LoadVector128_Single();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class LoadUnaryOpTest__LoadVector128_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private DataTable _dataTable;
public LoadUnaryOpTest__LoadVector128_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LoadVector128(
(Single*)(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(Single*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Single*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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 BenchmarkDotNet.Attributes;
using Benchmarks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
namespace System.Text.JsonLab.Benchmarks
{
// Since there are 90 tests here (6 * 15), setting low values for the warmupCount, targetCount, and invocationCount
[SimpleJob(-1, 3, 5)]
[MemoryDiagnoser]
public class JsonReaderPerf
{
// Keep the JsonStrings resource names in sync with TestCaseType enum values.
public enum TestCaseType
{
HelloWorld,
BasicJson,
BasicLargeNum,
SpecialNumForm,
ProjectLockJson,
FullSchema1,
FullSchema2,
DeepTree,
BroadTree,
LotsOfNumbers,
LotsOfStrings,
Json400B,
Json4KB,
Json40KB,
Json400KB
}
private string _jsonString;
private byte[] _dataUtf8;
private ReadOnlySequence<byte> _sequence;
private ReadOnlySequence<byte> _sequenceSingle;
private MemoryStream _stream;
private StreamReader _reader;
[ParamsSource(nameof(TestCaseValues))]
public TestCaseType TestCase;
[Params(true, false)]
public bool IsDataCompact;
public static IEnumerable<TestCaseType> TestCaseValues() => (IEnumerable<TestCaseType>)Enum.GetValues(typeof(TestCaseType));
[GlobalSetup]
public void Setup()
{
_jsonString = JsonStrings.ResourceManager.GetString(TestCase.ToString());
// Remove all formatting/indendation
if (IsDataCompact)
{
using (var jsonReader = new JsonTextReader(new StringReader(_jsonString)))
{
JToken obj = JToken.ReadFrom(jsonReader);
var stringWriter = new StringWriter();
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
obj.WriteTo(jsonWriter);
_jsonString = stringWriter.ToString();
}
}
}
_dataUtf8 = Encoding.UTF8.GetBytes(_jsonString);
ReadOnlyMemory<byte> dataMemory = _dataUtf8;
_sequenceSingle = new ReadOnlySequence<byte>(dataMemory);
var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, _dataUtf8.Length / 2));
ReadOnlyMemory<byte> secondMem = dataMemory.Slice(_dataUtf8.Length / 2);
BufferSegment<byte> secondSegment = firstSegment.Append(secondMem);
_sequence = new ReadOnlySequence<byte>(firstSegment, 0, secondSegment, secondMem.Length);
_stream = new MemoryStream(_dataUtf8);
_reader = new StreamReader(_stream, Encoding.UTF8, false, 1024, true);
}
[Benchmark(Baseline = true)]
public void ReaderNewtonsoftReaderEmptyLoop()
{
_stream.Seek(0, SeekOrigin.Begin);
TextReader reader = _reader;
var json = new JsonTextReader(reader);
while (json.Read()) ;
}
[Benchmark]
public string ReaderNewtonsoftReaderReturnString()
{
_stream.Seek(0, SeekOrigin.Begin);
TextReader reader = _reader;
var sb = new StringBuilder();
var json = new JsonTextReader(reader);
while (json.Read())
{
if (json.Value != null)
{
sb.Append(json.Value).Append(", ");
}
}
return sb.ToString();
}
[Benchmark]
public void ReaderSystemTextJsonLabSpanEmptyLoop()
{
var json = new Utf8JsonReader(_dataUtf8);
while (json.Read()) ;
}
[Benchmark]
public void ReaderSystemTextJsonLabSingleSpanSequenceEmptyLoop()
{
var json = new Utf8JsonReader(_sequenceSingle);
while (json.Read()) ;
}
[Benchmark]
public void ReaderSystemTextJsonLabMultiSpanSequenceEmptyLoop()
{
var json = new Utf8JsonReader(_sequence);
while (json.Read()) ;
}
[Benchmark]
public byte[] ReaderSystemTextJsonLabReturnBytes()
{
var outputArray = new byte[_dataUtf8.Length * 2];
Span<byte> destination = outputArray;
var json = new Utf8JsonReader(_dataUtf8);
while (json.Read())
{
JsonTokenType tokenType = json.TokenType;
ReadOnlySpan<byte> valueSpan = json.Value;
switch (tokenType)
{
case JsonTokenType.PropertyName:
valueSpan.CopyTo(destination);
destination[valueSpan.Length] = (byte)',';
destination[valueSpan.Length + 1] = (byte)' ';
destination = destination.Slice(valueSpan.Length + 2);
break;
case JsonTokenType.Value:
var valueType = json.ValueType;
switch (valueType)
{
case JsonValueType.True:
destination[0] = (byte)'T';
destination[1] = (byte)'r';
destination[2] = (byte)'u';
destination[3] = (byte)'e';
destination[valueSpan.Length] = (byte)',';
destination[valueSpan.Length + 1] = (byte)' ';
destination = destination.Slice(valueSpan.Length + 2);
break;
case JsonValueType.False:
destination[0] = (byte)'F';
destination[1] = (byte)'a';
destination[2] = (byte)'l';
destination[3] = (byte)'s';
destination[4] = (byte)'e';
destination[valueSpan.Length] = (byte)',';
destination[valueSpan.Length + 1] = (byte)' ';
destination = destination.Slice(valueSpan.Length + 2);
break;
case JsonValueType.Number:
case JsonValueType.String:
valueSpan.CopyTo(destination);
destination[valueSpan.Length] = (byte)',';
destination[valueSpan.Length + 1] = (byte)' ';
destination = destination.Slice(valueSpan.Length + 2);
break;
case JsonValueType.Null:
// Special casing Null so that it matches what JSON.NET does
break;
}
break;
default:
break;
}
}
return outputArray;
}
[Benchmark]
public void ReaderUtf8JsonEmptyLoop()
{
var json = new Utf8Json.JsonReader(_dataUtf8);
while (json.GetCurrentJsonToken() != Utf8Json.JsonToken.None)
{
json.ReadNext();
}
}
[Benchmark]
public byte[] ReaderUtf8JsonReturnBytes()
{
var json = new Utf8Json.JsonReader(_dataUtf8);
var outputArray = new byte[_dataUtf8.Length * 2];
Span<byte> destination = outputArray;
Utf8Json.JsonToken token = json.GetCurrentJsonToken();
while (token != Utf8Json.JsonToken.None)
{
json.ReadNext();
token = json.GetCurrentJsonToken();
switch (token)
{
case Utf8Json.JsonToken.String:
case Utf8Json.JsonToken.Number:
case Utf8Json.JsonToken.True:
case Utf8Json.JsonToken.False:
case Utf8Json.JsonToken.Null:
ReadOnlySpan<byte> valueSpan = json.ReadNextBlockSegment();
valueSpan.CopyTo(destination);
destination[valueSpan.Length] = (byte)',';
destination[valueSpan.Length + 1] = (byte)' ';
destination = destination.Slice(valueSpan.Length + 2);
break;
default:
break;
}
}
return outputArray;
}
}
internal class BufferSegment<T> : ReadOnlySequenceSegment<T>
{
public BufferSegment(ReadOnlyMemory<T> memory)
{
Memory = memory;
}
public BufferSegment<T> Append(ReadOnlyMemory<T> memory)
{
var segment = new BufferSegment<T>(memory)
{
RunningIndex = RunningIndex + Memory.Length
};
Next = segment;
return segment;
}
}
}
| |
#region Using Statements
using System;
using System.Linq;
using System.Threading;
using Microsoft.Web.Administration;
using Cake.Core;
using Cake.Core.Diagnostics;
#endregion
namespace Cake.IIS
{
public class WebFarmManager : BaseManager
{
#region Constructor (1)
public WebFarmManager(ICakeEnvironment environment, ICakeLog log)
: base(environment, log)
{
}
#endregion
#region Functions (14)
public static WebFarmManager Using(ICakeEnvironment environment, ICakeLog log, ServerManager server)
{
WebFarmManager manager = new WebFarmManager(environment, log);
manager.SetServer(server);
return manager;
}
//Farms
public void Create(WebFarmSettings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (string.IsNullOrWhiteSpace(settings.Name))
{
throw new ArgumentException("WebFarm name cannot be null!");
}
//Get Farm
ConfigurationElementCollection farms = this.GetFarms();
ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == settings.Name);
if (farm != null)
{
_Log.Information("WebFarm '{0}' already exists.", settings.Name);
if (settings.Overwrite)
{
_Log.Information("WebFarm '{0}' will be overriden by request.", settings.Name);
this.Delete(settings.Name);
}
else
{
return;
}
}
//Create Farm
farm = farms.CreateElement("webFarm");
farm["name"] = settings.Name;
//Add Server
ConfigurationElementCollection servers = farm.GetCollection();
foreach (string server in settings.Servers)
{
ConfigurationElement serverElement = servers.CreateElement("server");
serverElement["address"] = server;
servers.Add(serverElement);
_Log.Information("Adding server '{0}'.", server);
}
farms.Add(farm);
_Server.CommitChanges();
_Log.Information("WebFarm created.");
}
public bool Delete(string name)
{
ConfigurationElementCollection farms = this.GetFarms();
ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);
if (farm != null)
{
farms.Remove(farm);
_Server.CommitChanges();
_Log.Information("WebFarm deleted.");
return true;
}
else
{
_Log.Information("The webfarm '{0}' does not exists.", name);
return false;
}
}
public bool Exists(string name)
{
ConfigurationElementCollection farms = this.GetFarms();
ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);
if (farm != null)
{
_Log.Information("The webfarm '{0}' exists.", name);
return true;
}
else
{
_Log.Information("The webfarm '{0}' does not exists.", name);
return false;
}
}
//Servers
public bool AddServer(string farm, string address)
{
ConfigurationElement farmElement = this.GetFarm(farm);
if (farmElement != null)
{
ConfigurationElementCollection servers = farmElement.GetCollection();
ConfigurationElement server = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address);
if (server == null)
{
ConfigurationElement serverElement = servers.CreateElement("server");
serverElement["address"] = server;
servers.Add(serverElement);
_Server.CommitChanges();
_Log.Information("Adding server '{0}'.", address);
return true;
}
else
{
_Log.Information("The server '{0}' already exists.", address);
return false;
}
}
return false;
}
public bool RemoveServer(string farm, string address)
{
ConfigurationElement farmElement = this.GetFarm(farm);
if (farmElement != null)
{
ConfigurationElementCollection servers = farmElement.GetCollection();
ConfigurationElement server = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address);
if (server != null)
{
servers.Remove(server);
_Server.CommitChanges();
_Log.Information("Removed server '{0}'.", address);
return true;
}
else
{
_Log.Information("The server '{0}' does not exists.", address);
return false;
}
}
return false;
}
public bool ServerExists(string farm, string address)
{
ConfigurationElement farmElement = this.GetFarm(farm);
if (farmElement != null)
{
ConfigurationElementCollection servers = farmElement.GetCollection();
ConfigurationElement server = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address);
if (server != null)
{
_Log.Information("The server '{0}' exists.", address);
return true;
}
else
{
_Log.Information("The server '{0}' does not exists.", address);
return false;
}
}
else
{
return false;
}
}
//Health
public void SetServerHealthy(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationMethod method = arrElement.Methods["SetHealthy"];
ConfigurationMethodInstance instance = method.CreateInstance();
instance.Execute();
_Log.Information("Marking the server '{0}' as healthy.", address);
}
}
public void SetServerUnhealthy(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationMethod method = arrElement.Methods["SetUnhealthy"];
ConfigurationMethodInstance instance = method.CreateInstance();
instance.Execute();
_Log.Information("Marking the server '{0}' as unhealthy.", address);
}
}
//Available
public void SetServerAvailable(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationMethod method = arrElement.Methods["SetState"];
ConfigurationMethodInstance instance = method.CreateInstance();
instance.Input.Attributes[0].Value = 0;
instance.Execute();
_Log.Information("Marking the server '{0}' as available.", address);
}
}
public void SetServerUnavailable(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationMethod method = arrElement.Methods["SetState"];
ConfigurationMethodInstance instance = method.CreateInstance();
instance.Input.Attributes[0].Value = 3;
instance.Execute();
_Log.Information("Marking the server '{0}' as unavailable.", address);
}
}
//State
public bool GetServerIsHealthy(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationElement countersElement = arrElement.GetChildElement("counters");
string value = countersElement.GetAttributeValue("isHealthy").ToString().ToLower();
return (value == "true");
}
else
{
return false;
}
}
public string GetServerState(string farm, string address)
{
ConfigurationElement arrElement = this.GetServerArr(farm, address);
if (arrElement != null)
{
ConfigurationElement countersElement = arrElement.GetChildElement("counters");
return countersElement.GetAttributeValue("isHealthy").ToString();
}
else
{
return "";
}
}
//Helpers
private ConfigurationElementCollection GetFarms()
{
Configuration config = _Server.GetApplicationHostConfiguration();
ConfigurationSection section = config.GetSection("webFarms");
return section.GetCollection();
}
private ConfigurationElement GetFarm(string name)
{
ConfigurationElementCollection farms = this.GetFarms();
ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);
if (farm == null)
{
_Log.Information("The webfarm '{0}' does not exists.", name);
}
return farm;
}
private ConfigurationElement GetServer(ConfigurationElement farm, string address)
{
ConfigurationElementCollection servers = farm.GetCollection();
ConfigurationElement server = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address);
if (server == null)
{
_Log.Information("The server '{0}' does not exists.", address);
}
return server;
}
private ConfigurationElement GetServerArr(string farm, string address)
{
ConfigurationElement farmElement = this.GetFarm(farm);
if (farmElement != null)
{
ConfigurationElement serverElement = this.GetServer(farmElement, address);
if (serverElement != null)
{
return serverElement.GetChildElement("applicationRequestRouting");
}
}
return null;
}
#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.Config
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Xml;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.Time;
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
/// </summary>
public class XmlLoggingConfiguration : LoggingConfiguration
{
private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default;
private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string originalFileName;
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration(string fileName)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName)
{
this.Initialize(reader, fileName, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors)
{
this.Initialize(reader, fileName, ignoreErrors);
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, ignoreErrors);
}
}
#endif
#if !SILVERLIGHT
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet.
/// </summary>
public bool? InitializeSucceeded { get; private set; }
/// <summary>
/// Gets the variables defined in the configuration.
/// </summary>
public override Dictionary<string, string> Variables
{
get
{
return variables;
}
}
/// <summary>
/// Gets or sets a value indicating whether the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload { get; set; }
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
if (this.AutoReload)
{
return this.visitedFile.Keys;
}
return new string[0];
}
}
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
return new XmlLoggingConfiguration(this.originalFileName);
}
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
private static string CleanWhitespace(string s)
{
s = s.Replace(" ", string.Empty); // get rid of the whitespace
return s;
}
private static string StripOptionalNamespacePrefix(string attributeValue)
{
if (attributeValue == null)
{
return null;
}
int p = attributeValue.IndexOf(':');
if (p < 0)
{
return attributeValue;
}
return attributeValue.Substring(p + 1);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
{
try
{
InitializeSucceeded = null;
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (fileName != null)
{
#if SILVERLIGHT
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
this.visitedFile[key] = true;
this.originalFileName = fileName;
this.ParseTopLevel(content, Path.GetDirectoryName(fileName));
InternalLogger.Info("Configured from an XML element in {0}...", fileName);
}
else
{
this.ParseTopLevel(content, null);
}
InitializeSucceeded = true;
}
catch (Exception exception)
{
InitializeSucceeded = false;
if (exception.MustBeRethrown())
{
throw;
}
NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
if (!ignoreErrors)
{
if (LogManager.ThrowExceptions)
{
throw ConfigException;
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
}
private void ConfigureFromFile(string fileName)
{
#if SILVERLIGHT
// file names are relative to XAP
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
if (this.visitedFile.ContainsKey(key))
{
return;
}
this.visitedFile[key] = true;
this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName));
}
private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "CONFIGURATION":
this.ParseConfigurationElement(content, baseDirectory);
break;
case "NLOG":
this.ParseNLogElement(content, baseDirectory);
break;
}
}
private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
foreach (var el in configurationElement.Elements("nlog"))
{
this.ParseNLogElement(el, baseDirectory);
}
}
private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
{
this.DefaultCultureInfo = CultureInfo.InvariantCulture;
}
this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));
foreach (var el in nlogElement.Children)
{
switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "EXTENSIONS":
this.ParseExtensionsElement(el, baseDirectory);
break;
case "INCLUDE":
this.ParseIncludeElement(el, baseDirectory);
break;
case "APPENDERS":
case "TARGETS":
this.ParseTargetsElement(el);
break;
case "VARIABLE":
this.ParseVariableElement(el);
break;
case "RULES":
this.ParseRulesElement(el, this.LoggingRules);
break;
case "TIME":
this.ParseTimeElement(el);
break;
default:
InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName);
break;
}
}
}
private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var loggerElement in rulesElement.Elements("logger"))
{
this.ParseLoggerElement(loggerElement, rulesCollection);
}
}
private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
{
loggerElement.AssertName("logger");
var namePattern = loggerElement.GetOptionalAttribute("name", "*");
var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true);
if (!enabled)
{
InternalLogger.Debug("The logger named '{0}' are disabled");
return;
}
var rule = new LoggingRule();
string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
if (appendTo == null)
{
appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
}
rule.LoggerNamePattern = namePattern;
if (appendTo != null)
{
foreach (string t in appendTo.Split(','))
{
string targetName = t.Trim();
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
throw new NLogConfigurationException("Target " + targetName + " not found.");
}
}
}
rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);
string levelString;
if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
{
LogLevel level = LogLevel.FromString(levelString);
rule.EnableLoggingForLevel(level);
}
else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
{
levelString = CleanWhitespace(levelString);
string[] tokens = levelString.Split(',');
foreach (string s in tokens)
{
if (!string.IsNullOrEmpty(s))
{
LogLevel level = LogLevel.FromString(s);
rule.EnableLoggingForLevel(level);
}
}
}
else
{
int minLevel = 0;
int maxLevel = LogLevel.MaxLevel.Ordinal;
string minLevelString;
string maxLevelString;
if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
{
minLevel = LogLevel.FromString(minLevelString).Ordinal;
}
if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
{
maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
}
for (int i = minLevel; i <= maxLevel; ++i)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
foreach (var child in loggerElement.Children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "FILTERS":
this.ParseFilters(rule, child);
break;
case "LOGGER":
this.ParseLoggerElement(child, rule.ChildRules);
break;
}
}
rulesCollection.Add(rule);
}
private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
{
filtersElement.AssertName("filters");
foreach (var filterElement in filtersElement.Children)
{
string name = filterElement.LocalName;
Filter filter = this.configurationItemFactory.Filters.CreateInstance(name);
this.ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseVariableElement(NLogXmlElement variableElement)
{
variableElement.AssertName("variable");
string name = variableElement.GetRequiredAttribute("name");
string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value"));
this.variables[name] = value;
}
private void ParseTargetsElement(NLogXmlElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
NLogXmlElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();
foreach (var targetElement in targetsElement.Children)
{
string name = targetElement.LocalName;
string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));
switch (name.ToUpper(CultureInfo.InvariantCulture))
{
case "DEFAULT-WRAPPER":
defaultWrapperElement = targetElement;
break;
case "DEFAULT-TARGET-PARAMETERS":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
typeNameToDefaultTargetParameters[type] = targetElement;
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
NLogXmlElement defaults;
if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults))
{
this.ParseTargetElement(newTarget, defaults);
}
this.ParseTargetElement(newTarget, targetElement);
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}", newTarget);
AddTarget(newTarget.Name, newTarget);
break;
}
}
}
private void ParseTargetElement(Target target, NLogXmlElement targetElement)
{
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
this.ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.LocalName;
if (compound != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
continue;
}
}
if (wrapper != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
wrapper.WrappedTarget = newTarget;
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
throw new NLogConfigurationException("Wrapped target already defined.");
}
wrapper.WrappedTarget = newTarget;
}
continue;
}
}
this.SetPropertyFromElement(target, childElement);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var addElement in extensionsElement.Elements("add"))
{
string prefix = addElement.GetOptionalAttribute("prefix", null);
if (prefix != null)
{
prefix = prefix + ".";
}
string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
if (type != null)
{
this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
}
string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
if (assemblyFile != null)
{
try
{
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
string fullFileName = Path.Combine(baseDirectory, assemblyFile);
InternalLogger.Info("Loading assembly file: {0}", fullFileName);
Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
}
}
continue;
}
string assemblyName = addElement.GetOptionalAttribute("assembly", null);
if (assemblyName != null)
{
try
{
InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
Assembly asm = Assembly.Load(assemblyName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
}
}
continue;
}
}
}
private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredAttribute("file");
try
{
newFileName = this.ExpandVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
if (baseDirectory != null)
{
newFileName = Path.Combine(baseDirectory, newFileName);
}
#if SILVERLIGHT
newFileName = newFileName.Replace("\\", "/");
if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
if (File.Exists(newFileName))
#endif
{
InternalLogger.Debug("Including file '{0}'", newFileName);
this.ConfigureFromFile(newFileName);
}
else
{
throw new FileNotFoundException("Included file not found: " + newFileName);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception);
if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
{
return;
}
throw new NLogConfigurationException("Error when including: " + newFileName, exception);
}
}
private void ParseTimeElement(NLogXmlElement timeElement)
{
timeElement.AssertName("time");
string type = timeElement.GetRequiredAttribute("type");
TimeSource newTimeSource = this.configurationItemFactory.TimeSources.CreateInstance(type);
this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
private void SetPropertyFromElement(object o, NLogXmlElement element)
{
if (this.AddArrayItemFromElement(o, element))
{
return;
}
if (this.SetLayoutFromElement(o, element))
{
return;
}
PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory);
}
private bool AddArrayItemFromElement(object o, NLogXmlElement element)
{
string name = element.LocalName;
PropertyInfo propInfo;
if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
{
return false;
}
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
object arrayItem = FactoryHelper.CreateInstance(elementType);
this.ConfigureObjectFromAttributes(arrayItem, element, true);
this.ConfigureObjectFromElement(arrayItem, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
{
foreach (var kvp in element.AttributeValues)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
{
continue;
}
PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory);
}
}
private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
{
PropertyInfo targetPropertyInfo;
string name = layoutElement.LocalName;
// if property exists
if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
{
// and is a Layout
if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
{
string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));
// and 'type' attribute has been specified
if (layoutTypeName != null)
{
// configure it from current element
Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName));
this.ConfigureObjectFromAttributes(layout, layoutElement, true);
this.ConfigureObjectFromElement(layout, layoutElement);
targetPropertyInfo.SetValue(o, layout, null);
return true;
}
}
}
return false;
}
private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
{
foreach (var child in element.Children)
{
this.SetPropertyFromElement(targetObject, child);
}
}
private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
{
string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));
Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
wtb.WrappedTarget = t;
wrapperTargetInstance.Name = t.Name;
t.Name = t.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
return wrapperTargetInstance;
}
private string ExpandVariables(string input)
{
string output = input;
// TODO - make this case-insensitive, will probably require a different approach
foreach (var kvp in this.variables)
{
output = output.Replace("${" + kvp.Key + "}", kvp.Value);
}
return output;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.DurableInstancing
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime;
using System.Runtime.DurableInstancing;
using System.Threading;
class SqlWorkflowInstanceStoreLock
{
TimeSpan hostLockRenewalPulseInterval = TimeSpan.Zero;
bool isBeingModified;
Guid lockOwnerId;
SqlWorkflowInstanceStore sqlWorkflowInstanceStore;
WeakReference lockOwnerInstanceHandle;
object thisLock;
public SqlWorkflowInstanceStoreLock(SqlWorkflowInstanceStore sqlWorkflowInstanceStore)
{
this.sqlWorkflowInstanceStore = sqlWorkflowInstanceStore;
this.thisLock = new object();
this.SurrogateLockOwnerId = -1;
}
public PersistenceTask InstanceDetectionTask
{
get;
set;
}
public bool IsValid
{
get
{
return IsLockOwnerValid(this.SurrogateLockOwnerId);
}
}
public bool IsLockOwnerValid(long surrogateLockOwnerId)
{
return (this.SurrogateLockOwnerId != -1)
&& (surrogateLockOwnerId == this.SurrogateLockOwnerId)
&& (this.sqlWorkflowInstanceStore.InstanceOwnersExist);
}
public Guid LockOwnerId
{
get
{
return this.lockOwnerId;
}
}
public PersistenceTask LockRecoveryTask
{
get;
set;
}
public PersistenceTask LockRenewalTask
{
get;
set;
}
public long SurrogateLockOwnerId
{
get;
private set;
}
object ThisLock
{
get
{
return this.thisLock;
}
}
TimeSpan HostLockRenewalPulseInterval
{
get
{
if (this.hostLockRenewalPulseInterval == TimeSpan.Zero)
{
// if user configured HostLockRenewalPeriod is less than constant MaxHostLockRenewalPulseInterval,
// then HostLockRenewalPeriod is how frequently SWIS will connect to SQL store to renew lock expiration.
// Otherwise, SWIS will connect to SQL store to renew lock expiration every MaxHostLockRenewalPulseInterval timespan.
if (SqlWorkflowInstanceStoreConstants.MaxHostLockRenewalPulseInterval < this.sqlWorkflowInstanceStore.HostLockRenewalPeriod)
{
this.hostLockRenewalPulseInterval = SqlWorkflowInstanceStoreConstants.MaxHostLockRenewalPulseInterval;
}
else
{
this.hostLockRenewalPulseInterval = this.sqlWorkflowInstanceStore.HostLockRenewalPeriod;
}
}
return this.hostLockRenewalPulseInterval;
}
}
public void MarkInstanceOwnerCreated(Guid lockOwnerId, long surrogateLockOwnerId, InstanceHandle lockOwnerInstanceHandle, bool detectRunnableInstances, bool detectActivatableInstances)
{
Fx.Assert(this.isBeingModified, "Must have modification lock to mark owner as created");
this.lockOwnerId = lockOwnerId;
this.SurrogateLockOwnerId = surrogateLockOwnerId;
this.lockOwnerInstanceHandle = new WeakReference(lockOwnerInstanceHandle);
TimeSpan runnableInstancesDetectionPeriod = this.sqlWorkflowInstanceStore.RunnableInstancesDetectionPeriod;
if (detectActivatableInstances)
{
this.InstanceDetectionTask = new DetectActivatableWorkflowsTask(this.sqlWorkflowInstanceStore, this, runnableInstancesDetectionPeriod);
}
else if (detectRunnableInstances)
{
this.InstanceDetectionTask = new DetectRunnableInstancesTask(this.sqlWorkflowInstanceStore, this, runnableInstancesDetectionPeriod);
}
// By setting taskTimeout value with BufferedHostLockRenewalPeriod,
// BufferedHostLockRenewalPeriod becomes max sql retry duration for ExtendLock command and RecoveryIntanceLock command.
this.LockRenewalTask = new LockRenewalTask(this.sqlWorkflowInstanceStore, this, this.HostLockRenewalPulseInterval, this.sqlWorkflowInstanceStore.BufferedHostLockRenewalPeriod);
this.LockRecoveryTask = new LockRecoveryTask(this.sqlWorkflowInstanceStore, this, this.HostLockRenewalPulseInterval, this.sqlWorkflowInstanceStore.BufferedHostLockRenewalPeriod);
if (this.InstanceDetectionTask != null)
{
this.InstanceDetectionTask.ResetTimer(true);
}
this.LockRenewalTask.ResetTimer(true);
this.LockRecoveryTask.ResetTimer(true);
}
public void MarkInstanceOwnerLost(long surrogateLockOwnerId, bool hasModificationLock)
{
if (hasModificationLock)
{
this.MarkInstanceOwnerLost(surrogateLockOwnerId);
}
else
{
this.TakeModificationLock();
this.MarkInstanceOwnerLost(surrogateLockOwnerId);
this.ReturnModificationLock();
}
}
public void ReturnModificationLock()
{
Fx.Assert(this.isBeingModified, "Must have modification lock to release it!");
bool lockTaken = false;
while (true)
{
Monitor.Enter(ThisLock, ref lockTaken);
if (lockTaken)
{
this.isBeingModified = false;
Monitor.Pulse(ThisLock);
Monitor.Exit(ThisLock);
return;
}
}
}
public void TakeModificationLock()
{
bool lockTaken = false;
while (true)
{
Monitor.Enter(ThisLock, ref lockTaken);
if (lockTaken)
{
while (this.isBeingModified)
{
Monitor.Wait(ThisLock);
}
this.isBeingModified = true;
Monitor.Exit(ThisLock);
return;
}
}
}
void MarkInstanceOwnerLost(long surrogateLockOwnerId)
{
Fx.Assert(this.isBeingModified, "Must have modification lock to mark owner as lost");
if (this.SurrogateLockOwnerId == surrogateLockOwnerId)
{
this.SurrogateLockOwnerId = -1;
InstanceHandle instanceHandle = this.lockOwnerInstanceHandle.Target as InstanceHandle;
if (instanceHandle != null)
{
instanceHandle.Free();
}
if (this.sqlWorkflowInstanceStore.IsLockRetryEnabled())
{
this.sqlWorkflowInstanceStore.LoadRetryHandler.AbortPendingRetries();
}
if (this.LockRenewalTask != null)
{
this.LockRenewalTask.CancelTimer();
}
if (this.LockRecoveryTask != null)
{
this.LockRecoveryTask.CancelTimer();
}
if (this.InstanceDetectionTask != null)
{
this.InstanceDetectionTask.CancelTimer();
}
}
}
}
}
| |
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
// Ben Motmans <ben.motmans@gmail.com>
// Nicholas Terry <nick.i.terry@gmail.com>
//
// Copyright (C) 2006 Alan McGovern
// Copyright (C) 2007 Ben Motmans
// Copyright (C) 2014 Nicholas Terry
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Mono.Nat.Logging;
namespace Mono.Nat.Upnp
{
class UpnpSearcher : Searcher
{
static Logger Log { get; } = Logger.Create ();
static readonly IList<string> SupportedServices = new List<string> {
"urn:schemas-upnp-org:service:WANIPConnection:1",
"urn:schemas-upnp-org:service:WANIPConnection:2",
"urn:schemas-upnp-org:service:WANPPPConnection:1",
"urn:schemas-upnp-org:service:WANPPPConnection:2",
/* Some routers don't correctly implement the version ID on the URN, so we search for the
* unversioned type too.
*/
"urn:schemas-upnp-org:service:WANIPConnection:",
"urn:schemas-upnp-org:service:WANPPPConnection:",
}.AsReadOnly ();
internal static UpnpSearcher Create ()
{
var clients = new Dictionary<UdpClient, List<IPAddress>> ();
var gateways = new List<IPAddress> { IPAddress.Parse ("239.255.255.250") };
try {
foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces ()) {
foreach (UnicastIPAddressInformation address in n.GetIPProperties ().UnicastAddresses) {
if (address.Address.AddressFamily == AddressFamily.InterNetwork) {
try {
var client = new UdpClient (new IPEndPoint (address.Address, 0));
clients.Add (client, gateways);
client = new UdpClient ();
client.Client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
client.Client.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption (gateways[0], IPAddress.Any));
client.Client.Bind (new IPEndPoint (address.Address, 1900));
clients.Add (client, gateways);
} catch (Exception ex) {
Log.Error (ex.Message);
continue; // Move on to the next address.
}
}
}
}
} catch (Exception) {
clients.Add (new UdpClient (0), gateways);
}
return new UpnpSearcher (new SocketGroup (clients, 1900));
}
public override NatProtocol Protocol => NatProtocol.Upnp;
Dictionary<Uri, DateTime> LastFetched { get; }
SemaphoreSlim Locker { get; }
UpnpSearcher (SocketGroup sockets)
: base (sockets)
{
LastFetched = new Dictionary<Uri, DateTime> ();
Locker = new SemaphoreSlim (1, 1);
}
protected override async void SearchAsync (IPAddress gatewayAddress, TimeSpan? repeatInterval, CancellationToken token)
{
var messages = gatewayAddress == null ? DiscoverDeviceMessage.EncodeSSDP () : DiscoverDeviceMessage.EncodeUnicast (gatewayAddress);
while (!token.IsCancellationRequested) {
try {
foreach (var message in messages)
await Clients.SendAsync (message, gatewayAddress, token).ConfigureAwait (false);
if (!repeatInterval.HasValue)
break;
await Task.Delay (repeatInterval.Value, token).ConfigureAwait (false);
} catch (OperationCanceledException) {
break;
} catch (Exception ex) {
Log.Exception (ex, "Unhandled exception searching for a upnp device");
}
}
}
protected override async Task HandleMessageReceived (IPAddress localAddress, byte[] response, IPEndPoint remoteEndPoint, bool externalEvent, CancellationToken token)
{
string dataString = null;
// No matter what, this method should never throw an exception. If something goes wrong
// we should still be in a position to handle the next reply correctly.
try {
dataString = Encoding.UTF8.GetString (response);
Log.InfoFormatted ("uPnP Search Response: {0}", dataString);
/* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection.
Any other device type is no good to us for this purpose. See the IGP overview paper
page 5 for an overview of device types and their hierarchy.
http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */
/* TODO: Currently we are assuming version 1 of the protocol. We should figure out which
version it is and apply the correct URN. */
string foundService = null;
foreach (var type in SupportedServices.Concat (DiscoverDeviceMessage.SupportedServiceTypes)) {
if (dataString.IndexOf (type, StringComparison.OrdinalIgnoreCase) != -1) {
foundService = type;
break;
}
}
if (foundService == null && !externalEvent) {
RaiseDeviceUnknown (localAddress, remoteEndPoint, dataString, NatProtocol.Upnp);
return;
}
Log.InfoFormatted ("uPnP Search Response: Router advertised a '{0}' service", foundService);
var location = dataString.Split (new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select (t => t.Trim ())
.FirstOrDefault (t => t.StartsWith ("LOCATION", StringComparison.OrdinalIgnoreCase));
if (location == null)
return;
var deviceLocation = location.Split (new[] { ':' }, 2).Skip (1).FirstOrDefault ();
var deviceServiceUri = new Uri (deviceLocation);
using (await Locker.EnterAsync (token).ConfigureAwait (false)) {
// If we send 3 requests at a time, ensure we only fetch the services list once
// even if three responses are received
if (LastFetched.TryGetValue (deviceServiceUri, out DateTime last))
if ((DateTime.Now - last) < TimeSpan.FromSeconds (20))
return;
LastFetched[deviceServiceUri] = DateTime.Now;
}
// Once we've parsed the information we need, we tell the device to retrieve it's service list
// Once we successfully receive the service list, the callback provided will be invoked.
Log.InfoFormatted ("Fetching service list: {0}", deviceServiceUri);
var d = await GetServicesList (localAddress, deviceServiceUri, token).ConfigureAwait (false);
if (d != null)
RaiseDeviceFound (d);
} catch (OperationCanceledException) {
// Do nothing
} catch (Exception ex) {
Log.ExceptionFormated (ex, "Unhandled exception when trying to decode a device's response. Please file a bug with the following data: {0}", dataString);
}
}
async Task<UpnpNatDevice> GetServicesList (IPAddress localAddress, Uri deviceServiceUri, CancellationToken token)
{
// Create a HTTPWebRequest to download the list of services the device offers
var request = new GetServicesMessage (deviceServiceUri).Encode (out byte[] body);
if (body.Length > 0)
Log.Error ("Services Message unexpectedly contained a message body");
using (token.Register (() => request.Abort ()))
using (var response = (HttpWebResponse) await request.GetResponseAsync ().ConfigureAwait (false))
return await ServicesReceived (localAddress, deviceServiceUri, response, token).ConfigureAwait (false);
}
async Task<UpnpNatDevice> ServicesReceived (IPAddress localAddress, Uri deviceServiceUri, HttpWebResponse response, CancellationToken token)
{
Stream s = response.GetResponseStream ();
if (response.StatusCode != HttpStatusCode.OK) {
Log.ErrorFormatted ("Couldn't get services list from: {0}. Return code was: {1}", response.ResponseUri, response.StatusCode);
return null; // FIXME: This the best thing to do??
}
int abortCount = 0;
StringBuilder servicesXml = new StringBuilder ();
XmlDocument xmldoc = new XmlDocument ();
byte[] buffer = BufferHelpers.Rent ();
try {
while (true) {
var bytesRead = await s.ReadAsync (buffer, 0, buffer.Length, token).ConfigureAwait (false);
servicesXml.Append (Encoding.UTF8.GetString (buffer, 0, bytesRead));
try {
xmldoc.LoadXml (servicesXml.ToString ());
break;
} catch (XmlException) {
// If we can't receive the entire XML within 5 seconds, then drop the connection
// Unfortunately not all routers supply a valid ContentLength (mine doesn't)
// so this hack is needed to keep testing our recieved data until it gets successfully
// parsed by the xmldoc. Without this, the code will never pick up my router.
if (abortCount++ > 5000) {
return null;
}
Log.InfoFormatted ("Couldn't parse services list from {0}", response.ResponseUri);
await Task.Delay (10, token).ConfigureAwait (false);
}
}
} finally {
BufferHelpers.Release (buffer);
}
Log.InfoFormatted ("Parsed services list {0}", response.ResponseUri);
XmlNamespaceManager ns = new XmlNamespaceManager (xmldoc.NameTable);
ns.AddNamespace ("ns", "urn:schemas-upnp-org:device-1-0");
XmlNodeList nodes = xmldoc.SelectNodes ("//*/ns:serviceList", ns);
foreach (XmlNode node in nodes) {
//Go through each service there
foreach (XmlNode service in node.ChildNodes) {
string serviceType = service["serviceType"].InnerText;
Log.InfoFormatted ("Found service {1} from service list {0}", response.ResponseUri, serviceType);
// TODO: Add support for version 2 of UPnP.
if (SupportedServices.Contains (serviceType, StringComparer.OrdinalIgnoreCase)) {
var controlUrl = new Uri (service["controlURL"].InnerText, UriKind.RelativeOrAbsolute);
IPEndPoint deviceEndpoint = new IPEndPoint (IPAddress.Parse (response.ResponseUri.Host), response.ResponseUri.Port);
Log.InfoFormatted ("Found upnp control uri at {1} from service url {0}", response.ResponseUri, controlUrl.OriginalString);
try {
if (controlUrl.IsAbsoluteUri) {
deviceEndpoint = new IPEndPoint (IPAddress.Parse (controlUrl.Host), controlUrl.Port);
Log.InfoFormatted ("New control url {1} for device endpoint {0}", deviceEndpoint, controlUrl);
} else {
controlUrl = new Uri (deviceServiceUri, controlUrl.OriginalString);
}
} catch {
controlUrl = new Uri (deviceServiceUri, controlUrl.OriginalString);
Log.InfoFormatted ("{0}: Assuming control Uri is relative: {1}", deviceEndpoint, controlUrl);
}
Log.InfoFormatted ("Handshake Complete for {0}", deviceEndpoint);
return new UpnpNatDevice (localAddress, deviceEndpoint, controlUrl, serviceType);
}
}
}
//If we get here, it means that we didn't get WANIPConnection/WANPPPConnection service, which means no uPnP forwarding
//So we don't invoke the callback, so this device is never added to our lists
return null;
}
}
}
| |
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using hw.DebugFormatter;
using hw.Helper;
using hw.Parser;
using hw.Scanner;
using JetBrains.Annotations;
using Reni.Helper;
using Reni.Parser;
using Reni.SyntaxTree;
using Reni.TokenClasses.Whitespace;
using Reni.Validation;
using static Reni.Validation.IssueId;
namespace Reni.TokenClasses;
public sealed class BinaryTree : DumpableObject, ISyntax, ValueCache.IContainer, ITree<BinaryTree>
{
internal interface IFormatter
{
void SetupPositions(IPositionTarget target);
bool HasComplexDeclaration(BinaryTree target);
}
internal interface IPositionTarget { }
internal sealed class BracketNodes
{
internal BinaryTree Center;
internal BinaryTree Left;
internal BinaryTree Right;
[DisableDump]
internal Anchor ToAnchor => Anchor.Create(Left, Right);
}
static int NextObjectId;
[EnableDump(Order = 1)]
[EnableDumpExcept(null)]
internal BinaryTree Left { get; }
[EnableDump(Order = 3)]
[EnableDumpExcept(null)]
internal BinaryTree Right { get; }
[DisableDump]
internal readonly SourcePart Token;
[DisableDump]
internal readonly WhiteSpaceItem WhiteSpaces;
[DisableDump]
internal Syntax Syntax;
[DisableDump]
internal BinaryTree Parent;
[PublicAPI]
internal IFormatter Formatter;
[DisableDump]
readonly ITokenClass InnerTokenClass;
readonly FunctionCache<bool, string> FlatFormatCache;
readonly FunctionCache<int, BinaryTree> FindItemCache;
[DisableDump]
BinaryTree LeftNeighbor;
[DisableDump]
[UsedImplicitly]
BinaryTree RightNeighbor;
int Depth;
BinaryTree
(
BinaryTree left
, ITokenClass tokenClass
, IToken token
, BinaryTree right
)
: base(NextObjectId++)
{
Token = token.Characters;
WhiteSpaces = new(token.GetPrefixSourcePart());
Left = left;
InnerTokenClass = tokenClass;
Right = right;
FlatFormatCache = new(GetFlatStringValue);
FindItemCache = new(position => FindItemForCache(Token.Source + position));
SetLinks();
StopByObjectIds();
}
ValueCache ValueCache.IContainer.Cache { get; } = new();
SourcePart ISyntax.All => SourcePart;
SourcePart ISyntax.Main => Token;
int ITree<BinaryTree>.DirectChildCount => 2;
BinaryTree ITree<BinaryTree>.GetDirectChild(int index)
=> index switch
{
0 => Left, 1 => Right, _ => null
};
int ITree<BinaryTree>.LeftDirectChildCount => 1;
protected override string GetNodeDump() => base.GetNodeDump() + $"({TokenClass.Id}{InnerTokenClassPart})";
internal SourcePart FullToken => WhiteSpaces.SourcePart.Start.Span(Token.End);
string InnerTokenClassPart => InnerTokenClass == TokenClass? "" : $"/{InnerTokenClass.Id}";
[DisableDump]
internal ITokenClass TokenClass => this.CachedValue(GetTokenClass);
[DisableDump]
internal SourcePart SourcePart
=> LeftMost
.WhiteSpaces
.SourcePart
.Start
.Span(RightMost.Token.End);
[DisableDump]
internal BinaryTree LeftMost => Left?.LeftMost ?? this;
[DisableDump]
BinaryTree RightMost => Right?.RightMost ?? this;
[DisableDump]
internal IEnumerable<Issue> AllIssues
=> T(Left?.AllIssues, T(Issue), Right?.AllIssues)
.ConcatMany()
.Where(node => node != null);
[DisableDump]
internal Issue Issue => this.CachedValue(GetIssue);
[DisableDump]
internal BracketNodes BracketKernel
{
get
{
if(TokenClass is not IIssueTokenClass errorToken)
return TokenClass is IRightBracket
? new BracketNodes { Left = Left, Center = Left.Right, Right = this }
: null;
if(errorToken.IssueId == MissingRightBracket)
return new() { Left = this, Center = Right, Right = RightMost };
if(errorToken.IssueId == MissingLeftBracket)
return new() { Left = Left.LeftMost, Center = Left, Right = this };
if(errorToken.IssueId == MissingMatchingRightBracket)
return new() { Left = Left, Center = Left.Right, Right = this };
throw new InvalidEnumArgumentException($"Unexpected Bracket issue: {errorToken.IssueId}");
}
}
[DisableDump]
public BinaryTree[] ParserLevelGroup
=> this.CachedValue(() => GetParserLevelGroup()?.ToArray() ?? new BinaryTree[0]);
[DisableDump]
IssueId BracketIssueId
{
get
{
var left = Left;
var right = Right;
var tokenClass = InnerTokenClass;
var leftBracket = tokenClass as ILeftBracket;
var rightBracket = tokenClass as IRightBracket;
if(rightBracket == null && leftBracket == null)
return null;
if(leftBracket != null)
{
if(Parent is { IsBracketLevel: true })
return null;
left.AssertIsNull();
rightBracket.AssertIsNull();
return MissingRightBracket;
}
rightBracket.AssertIsNotNull();
var level = rightBracket.Level;
right.AssertIsNull();
var innerLeftBracket = left.InnerTokenClass as ILeftBracket;
if(innerLeftBracket == null)
return MissingLeftBracket;
left.Left.AssertIsNull();
return innerLeftBracket.Level > level? MissingMatchingRightBracket : null;
}
}
bool IsBracketLevel => InnerTokenClass is IRightBracket;
[DisableDump]
internal SeparatorRequests SeparatorRequests
{
get
{
StopByObjectIds();
var flat = SeparatorExtension.Get(LeftNeighbor?.InnerTokenClass, InnerTokenClass as ISeparatorClass);
return new()
{
Head = SeparatorExtension.Get(LeftNeighbor?.InnerTokenClass, WhiteSpaces) //
, Inner = true
, Tail = SeparatorExtension.Get(WhiteSpaces, InnerTokenClass as ISeparatorClass) //
, Flat = flat //
};
}
}
internal bool HasComplexDeclaration => Formatter?.HasComplexDeclaration(this) ?? false;
Issue GetIssue()
{
if(TokenClass is not IIssueTokenClass errorToken)
return null;
if(errorToken.IssueId == MissingRightBracket)
return errorToken.IssueId.Issue(Right?.SourcePart ?? Token.End.Span(0));
if(errorToken.IssueId == MissingLeftBracket)
return errorToken.IssueId.Issue(Left.SourcePart);
if(errorToken.IssueId == MissingMatchingRightBracket)
return errorToken.IssueId.Issue(Left.Right.SourcePart);
if(errorToken.IssueId == EOFInComment || errorToken.IssueId == EOLInString)
return errorToken.IssueId.Issue(Token);
throw new InvalidEnumArgumentException($"Unexpected issue: {errorToken.IssueId}");
}
ITokenClass GetTokenClass()
{
var issueId = BracketIssueId;
return issueId == null? InnerTokenClass : IssueTokenClass.From[issueId];
}
BinaryTree FindItemForCache(SourcePosition position)
{
if(position < WhiteSpaces.SourcePart.Start)
return Left?.FindItemCache[position.Position];
if(position < Token.End || position == Token.End && TokenClass is EndOfText)
return this;
return Right?.FindItemCache[position.Position];
}
void SetLinks()
{
if(Left != null)
{
Left.Parent = this;
Left.Depth = Depth + 1;
var binaryTree = Left.Chain(node => node.Right).Last();
binaryTree.RightNeighbor = this;
LeftNeighbor = binaryTree;
}
if(Right != null)
{
Right.Parent = this;
Right.Depth = Depth + 1;
var binaryTree = Right.Chain(node => node.Left).Last();
binaryTree.LeftNeighbor = this;
RightNeighbor = binaryTree;
}
}
IEnumerable<BinaryTree> GetParserLevelGroup()
{
var tokenClass = InnerTokenClass;
if(tokenClass is not IBelongingsMatcher)
return new BinaryTree[0];
if(tokenClass is List)
return this
.Chain(node => tokenClass.IsBelongingTo(node.Right?.InnerTokenClass)? node.Right : null);
if(tokenClass is IRightBracket)
return BracketKernel == null? null : T(BracketKernel.Left, BracketKernel.Right);
if(tokenClass is ILeftBracket)
return Parent?.BracketKernel == null? null : T(Parent.BracketKernel.Left, Parent.BracketKernel.Right);
if(tokenClass is ThenToken)
{
var elseItem = Parent is { TokenClass: ElseToken }? Parent : null;
return elseItem == null? default : T(this, elseItem);
}
if(tokenClass is ElseToken)
{
var thenItem = Right.TokenClass is ThenToken? Right : null;
return thenItem == null? default : T(thenItem, this);
}
NotImplementedMethod();
return default;
}
internal static BinaryTree Create
(
BinaryTree left
, ITokenClass tokenClass
, IToken token
, BinaryTree right
)
{
var linked = token as ILinked<BinaryTree>;
linked.AssertIsNotNull();
linked.Container.AssertIsNull();
return new(left, tokenClass, token, right);
}
internal int? GetBracketLevel()
{
if(InnerTokenClass is not IRightBracket rightParenthesis)
return null;
var leftParenthesis = Left?.InnerTokenClass as ILeftBracket;
return T(leftParenthesis?.Level ?? 0, rightParenthesis.Level).Max();
}
string GetFlatStringValue(bool areEmptyLinesPossible)
{
var separatorRequests = SeparatorRequests;
var tokenString = Left == null? "" : WhiteSpaces.FlatFormat(areEmptyLinesPossible, separatorRequests);
if(tokenString == null)
return null;
var leftResult = Left == null
? ""
: Left.FlatFormatCache[areEmptyLinesPossible];
if(leftResult == null)
return null;
var rightResult = Right == null
? ""
: Right.FlatFormatCache[areEmptyLinesPossible];
if(rightResult == null)
return null;
var gapSeparatorRequests = GetGapSeparatorRequests();
var gapString =
Right == null
? ""
: Right.LeftMost.WhiteSpaces.FlatFormat(areEmptyLinesPossible, gapSeparatorRequests);
if(gapString == null)
return null;
return leftResult + tokenString + Token.Id + gapString + rightResult;
}
SeparatorRequests GetGapSeparatorRequests() => new()
{
Head = Token.Length > 0 //
, Inner = true
, Tail = Right != null && Right.LeftMost.Token.Length > 0
, Flat = SeparatorExtension.Get(InnerTokenClass, Right?.LeftMost.InnerTokenClass) //
};
internal bool HasAsParent(BinaryTree parent)
=> Parent
.Chain(node => node.Depth >= parent.Depth? node.Parent : null)
.Any(node => node == parent);
/// <summary>
/// Try to format target into one line.
/// </summary>
/// <param name="areEmptyLinesPossible"></param>
/// <returns>The formatted line or null if target contains line breaks.</returns>
internal string GetFlatString(bool areEmptyLinesPossible) => FlatFormatCache[areEmptyLinesPossible];
/// <summary>
/// Get the line length of target when formatted as one line.
/// </summary>
/// <param name="areEmptyLinesPossible"></param>
/// <returns>The line length calculated or null if target contains line breaks.</returns>
internal int? GetFlatLength(bool areEmptyLinesPossible) => FlatFormatCache[areEmptyLinesPossible]?.Length;
internal void SetSyntax(Syntax syntax)
{
if(Token.Source.Identifier == Compiler.PredefinedSource)
return;
(Syntax == null || Syntax == syntax).Assert(() => @$"
this: {Dump()}
Current: {Syntax.Dump()}
New: {syntax.Dump()}");
Syntax = syntax;
}
internal BinaryTree FindItem(SourcePosition offset)
{
(Token.Source == offset.Source).Assert();
return FindItemCache[offset.Position];
}
internal BinaryTree CommonRoot(BinaryTree end)
{
var startParents = this.Chain(node => node.Parent).Reverse().ToArray();
var endParents = end.Chain(node => node.Parent).Reverse().ToArray();
var result = startParents[0];
for(var index = 1; index < startParents.Length && index < endParents.Length; index++)
{
var parent = startParents[index];
if(parent != endParents[index])
return result;
result = parent;
}
return result;
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Impersonates another user for the duration of the write.
/// </summary>
/// <remarks>
/// <a href="https://github.com/nlog/nlog/wiki/ImpersonatingWrapper-target">See NLog Wiki</a>
/// </remarks>
/// <seealso href="https://github.com/nlog/nlog/wiki/ImpersonatingWrapper-target">Documentation on NLog Wiki</seealso>
[SecuritySafeCritical]
[Target("ImpersonatingWrapper", IsWrapper = true)]
public class ImpersonatingTargetWrapper : WrapperTargetBase
{
private NewIdentityHandle _newIdentity;
/// <summary>
/// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class.
/// </summary>
public ImpersonatingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public ImpersonatingTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImpersonatingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public ImpersonatingTargetWrapper(Target wrappedTarget)
{
WrappedTarget = wrappedTarget;
}
/// <summary>
/// Gets or sets username to change context to.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public string UserName { get; set; }
/// <summary>
/// Gets or sets the user account password.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public string Password { get; set; }
/// <summary>
/// Gets or sets Windows domain name to change context to.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public string Domain { get; set; } = ".";
/// <summary>
/// Gets or sets the Logon Type.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public SecurityLogOnType LogOnType { get; set; } = SecurityLogOnType.Interactive;
/// <summary>
/// Gets or sets the type of the logon provider.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public LogOnProviderType LogOnProvider { get; set; } = LogOnProviderType.Default;
/// <summary>
/// Gets or sets the required impersonation level.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public SecurityImpersonationLevel ImpersonationLevel { get; set; } = SecurityImpersonationLevel.Impersonation;
/// <summary>
/// Gets or sets a value indicating whether to revert to the credentials of the process instead of impersonating another user.
/// </summary>
/// <docgen category='Impersonation Options' order='10' />
public bool RevertToSelf { get; set; }
/// <summary>
/// Initializes the impersonation context.
/// </summary>
protected override void InitializeTarget()
{
if (!RevertToSelf)
{
_newIdentity = new NewIdentityHandle(UserName, Domain, Password, LogOnType, LogOnProvider, ImpersonationLevel);
}
base.InitializeTarget();
}
/// <summary>
/// Closes the impersonation context.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
_newIdentity?.Close();
_newIdentity = null;
}
/// <summary>
/// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and switches the context back to original.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
if (_writeLogEvent is null)
_writeLogEvent = (l) => WrappedTarget.WriteAsyncLogEvent(l);
RunImpersonated(_newIdentity, _writeLogEvent, logEvent);
}
private Action<AsyncLogEventInfo> _writeLogEvent;
/// <summary>
/// Changes the security context, forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and switches the context back to original.
/// </summary>
/// <param name="logEvents">Log events.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
if (_writeLogEvents is null)
_writeLogEvents = (l) => WrappedTarget.WriteAsyncLogEvents(l);
RunImpersonated(_newIdentity, _writeLogEvents, logEvents);
}
private Action<IList<AsyncLogEventInfo>> _writeLogEvents;
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
RunImpersonated(_newIdentity, (s) => WrappedTarget.Flush(s), asyncContinuation);
}
private void RunImpersonated<T>(NewIdentityHandle newIdentity, Action<T> executeOperation, T state)
{
NewIdentityHandle.RunImpersonated(RevertToSelf ? null : newIdentity, executeOperation, state);
}
internal sealed class NewIdentityHandle : IDisposable
{
#if NETSTANDARD
public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle Handle { get; }
#else
public WindowsIdentity Handle { get; }
private readonly IntPtr _handle = IntPtr.Zero;
#endif
public NewIdentityHandle(string userName, string domain, string password, SecurityLogOnType logOnType, LogOnProviderType logOnProvider, SecurityImpersonationLevel impersonationLevel)
{
if (!NativeMethods.LogonUser(
userName,
domain,
password,
(int)logOnType,
(int)logOnProvider,
out var logonHandle))
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
#if NETSTANDARD
Handle = logonHandle;
#else
// adapted from:
// https://www.codeproject.com/csharp/cpimpersonation1.asp
if (!NativeMethods.DuplicateToken(logonHandle, (int)impersonationLevel, out _handle))
{
NativeMethods.CloseHandle(logonHandle);
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
NativeMethods.CloseHandle(logonHandle);
// create new identity using new primary token)
Handle = new WindowsIdentity(_handle);
#endif
}
public void Close()
{
Handle.Dispose();
#if !NETSTANDARD
if (_handle != IntPtr.Zero)
NativeMethods.CloseHandle(_handle);
#endif
}
public void Dispose()
{
Close();
}
internal static void RunImpersonated<T>(NewIdentityHandle newIdentity, Action<T> executeOperation, T state)
{
#if NETSTANDARD
WindowsIdentity.RunImpersonated(newIdentity?.Handle ?? Microsoft.Win32.SafeHandles.SafeAccessTokenHandle.InvalidHandle, () => executeOperation.Invoke(state));
#else
WindowsImpersonationContext context = null;
try
{
context = newIdentity?.Handle.Impersonate() ?? WindowsIdentity.Impersonate(IntPtr.Zero);
executeOperation.Invoke(state);
}
finally
{
context?.Undo();
}
#endif
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_CAIRO
namespace Avalonia.Cairo.RenderTests.Controls
#elif AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class BorderTests : TestBase
{
public BorderTests()
: base(@"Controls\Border")
{
}
[Fact]
public async Task Border_1px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 1,
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_2px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Fill()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Red,
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Brush_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Padding_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Padding = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Margin_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new Border
{
Background = Brushes.Red,
Margin = new Thickness(2),
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Centers_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Centers_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Stretches_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Stretches_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Left_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Left,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Right_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Right,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Top_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Top,
}
}
};
await RenderToFile(target);
CompareImages();
}
#if AVALONIA_CAIRO
[Fact(Skip = "Font scaling currently broken on cairo")]
#else
[Fact]
#endif
public async Task Border_Bottom_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = 2,
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Bottom,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Nested_Rotate()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Coral,
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Child = new Border
{
Margin = new Thickness(25),
Background = Brushes.Chocolate,
},
RenderTransform = new RotateTransform(45),
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| |
/*
* Copyright (c) 2009, Stefan Simek
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace TriAxis.RunSharp
{
interface IDelayedDefinition
{
void EndDefinition();
}
interface IDelayedCompletion
{
void Complete();
}
public class TypeGen : ITypeInfoProvider
{
class InterfaceImplEntry
{
IMemberInfo interfaceMethod;
MethodGen implementation;
public InterfaceImplEntry(IMemberInfo interfaceMethod)
{
this.interfaceMethod = interfaceMethod;
}
public bool Match(MethodGen candidate)
{
return candidate.Name == interfaceMethod.Name &&
candidate.ReturnType == interfaceMethod.ReturnType &&
ArrayUtils.Equals(candidate.ParameterTypes, interfaceMethod.ParameterTypes);
}
public IMemberInfo InterfaceMethod { get { return interfaceMethod; } }
public Type InterfaceType { get { return interfaceMethod.Member.DeclaringType; } }
public MethodGen BoundMethod { get { return implementation; } }
public bool IsBound { get { return implementation != null; } }
public void Bind(MethodGen implementation)
{
this.implementation = implementation;
}
}
AssemblyGen owner;
string name;
Type baseType;
Type[] interfaces;
TypeBuilder tb;
Type type;
MethodGen commonCtor = null;
ConstructorGen staticCtor = null;
List<IDelayedDefinition> definitionQueue = new List<IDelayedDefinition>();
List<IDelayedCompletion> completionQueue = new List<IDelayedCompletion>();
List<TypeGen> nestedTypes = new List<TypeGen>();
List<InterfaceImplEntry> implementations = new List<InterfaceImplEntry>();
List<IMemberInfo> constructors = new List<IMemberInfo>();
List<IMemberInfo> fields = new List<IMemberInfo>();
List<IMemberInfo> properties = new List<IMemberInfo>();
List<IMemberInfo> events = new List<IMemberInfo>();
List<IMemberInfo> methods = new List<IMemberInfo>();
List<AttributeGen> customAttributes = new List<AttributeGen>();
string indexerName;
internal TypeBuilder TypeBuilder { get { return tb; } }
internal Type BaseType { get { return baseType; } }
public string Name { get { return name; } }
internal TypeGen(AssemblyGen owner, string name, TypeAttributes attrs, Type baseType, Type[] interfaces)
{
this.owner = owner;
this.name = name;
this.baseType = baseType;
this.interfaces = interfaces;
tb = owner.ModuleBuilder.DefineType(name, attrs, baseType, interfaces);
owner.AddType(this);
ScanMethodsToImplement(interfaces);
TypeInfo.RegisterProvider(tb, this);
ResetAttrs();
}
internal TypeGen(TypeGen owner, string name, TypeAttributes attrs, Type baseType, Type[] interfaces)
{
this.owner = owner.owner;
this.name = name;
this.baseType = baseType;
this.interfaces = interfaces;
tb = owner.TypeBuilder.DefineNestedType(name, attrs, baseType, interfaces);
owner.nestedTypes.Add(this);
ScanMethodsToImplement(interfaces);
TypeInfo.RegisterProvider(tb, this);
}
void ScanMethodsToImplement(Type[] interfaces)
{
if (interfaces == null)
return;
foreach (Type t in interfaces)
{
foreach (IMemberInfo mi in TypeInfo.GetMethods(t))
implementations.Add(new InterfaceImplEntry(mi));
}
}
internal MethodAttributes PreprocessAttributes(MethodGen mg, MethodAttributes attrs)
{
bool requireVirtual = false;
foreach (InterfaceImplEntry implEntry in implementations)
{
if (!implEntry.IsBound && implEntry.Match(mg))
{
implEntry.Bind(mg);
requireVirtual = true;
}
}
if (requireVirtual && ((attrs & MethodAttributes.Virtual) == 0))
// create an exclusive VTable entry for the method
attrs |= MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final;
return attrs;
}
internal void RegisterForCompletion(ICodeGenContext routine)
{
definitionQueue.Add(routine);
completionQueue.Add(routine);
}
internal void RegisterForCompletion(IDelayedCompletion completion)
{
completionQueue.Add(completion);
}
#region Modifiers
MethodAttributes mthVis, mthFlags, mthVirt;
FieldAttributes fldVis, fldFlags;
TypeAttributes typeVis, typeFlags, typeVirt;
MethodImplAttributes implFlags;
void SetVisibility(MethodAttributes mthVis, FieldAttributes fldVis, TypeAttributes typeVis)
{
if (this.mthVis != 0)
throw new InvalidOperationException(Properties.Messages.ErrMultiVisibility);
this.mthVis = mthVis;
this.fldVis = fldVis;
this.typeVis = typeVis;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Public { get { SetVisibility(MethodAttributes.Public, FieldAttributes.Public, TypeAttributes.NestedPublic); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Private { get { SetVisibility(MethodAttributes.Private, FieldAttributes.Private, TypeAttributes.NestedPrivate); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Protected { get { SetVisibility(MethodAttributes.Family, FieldAttributes.Family, TypeAttributes.NestedFamily); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Internal { get { SetVisibility(MethodAttributes.Assembly, FieldAttributes.Assembly, TypeAttributes.NestedAssembly); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ProtectedOrInternal { get { SetVisibility(MethodAttributes.FamORAssem, FieldAttributes.FamORAssem, TypeAttributes.NestedFamORAssem); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ProtectedAndInternal { get { SetVisibility(MethodAttributes.FamANDAssem, FieldAttributes.FamANDAssem, TypeAttributes.NestedFamANDAssem); return this; } }
void SetVirtual(MethodAttributes mthVirt, TypeAttributes typeVirt)
{
if (this.mthVirt != 0)
throw new InvalidOperationException(Properties.Messages.ErrMultiVTable);
this.mthVirt = mthVirt;
this.typeVirt = typeVirt;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Sealed { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.Final, TypeAttributes.Sealed); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Virtual { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.NewSlot, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Override { get { SetVirtual(MethodAttributes.Virtual, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Abstract { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.Abstract, TypeAttributes.Abstract); return this; } }
void SetFlag(MethodAttributes mthFlag, FieldAttributes fldFlag, TypeAttributes typeFlag)
{
if ((this.mthFlags & mthFlag) != 0 ||
(this.fldFlags & fldFlag) != 0 ||
(this.typeFlags & typeFlag) != 0)
throw new InvalidOperationException(string.Format(null, Properties.Messages.ErrMultiAttribute, mthFlag));
this.mthFlags |= mthFlag;
this.fldFlags |= fldFlag;
this.typeFlags |= typeFlag;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Static { get { SetFlag(MethodAttributes.Static, FieldAttributes.Static, TypeAttributes.Sealed | TypeAttributes.Abstract); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ReadOnly { get { SetFlag(0, FieldAttributes.InitOnly, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen NoBeforeFieldInit { get { SetFlag(0, 0, TypeAttributes.BeforeFieldInit); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal TypeGen RuntimeImpl { get { implFlags |= MethodImplAttributes.Runtime | MethodImplAttributes.Managed; return this; } }
void ResetAttrs()
{
if (tb.IsInterface)
{
mthVis = MethodAttributes.Public;
mthVirt = MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract;
mthFlags = 0;
}
else
mthVis = mthVirt = mthFlags = 0;
fldVis = fldFlags = 0;
typeVis = typeVirt = typeFlags = 0;
implFlags = 0;
}
#endregion
#region Custom Attributes
public TypeGen Attribute<AT>() where AT : Attribute
{
return Attribute(typeof(AT));
}
public TypeGen Attribute(AttributeType type)
{
BeginAttribute(type);
return this;
}
public TypeGen Attribute<AT>(params object[] args) where AT : Attribute
{
return Attribute(typeof(AT), args);
}
public TypeGen Attribute(AttributeType type, params object[] args)
{
BeginAttribute(type, args);
return this;
}
public AttributeGen<TypeGen> BeginAttribute<AT>() where AT : Attribute
{
return BeginAttribute(typeof(AT));
}
public AttributeGen<TypeGen> BeginAttribute(AttributeType type)
{
return BeginAttribute(type, EmptyArray<object>.Instance);
}
public AttributeGen<TypeGen> BeginAttribute<AT>(params object[] args) where AT : Attribute
{
return BeginAttribute(typeof(AT), args);
}
public AttributeGen<TypeGen> BeginAttribute(AttributeType type, params object[] args)
{
AttributeTargets target = AttributeTargets.Class;
if (baseType == null)
target = AttributeTargets.Interface;
else if (baseType == typeof(ValueType))
target = AttributeTargets.Struct;
else
target = AttributeTargets.Class;
return AttributeGen<TypeGen>.CreateAndAdd(this, ref customAttributes, target, type, args);
}
#endregion
#region Members
public MethodGen CommonConstructor()
{
if (tb.IsValueType)
throw new InvalidOperationException(Properties.Messages.ErrStructNoDefaultCtor);
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
if (commonCtor == null)
{
commonCtor = new MethodGen(this, "$$ctor", 0, typeof(void), 0).LockSignature();
}
return commonCtor;
}
public ConstructorGen Constructor()
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
ConstructorGen cg = new ConstructorGen(this, mthVis, implFlags);
ResetAttrs();
return cg;
}
public ConstructorGen StaticConstructor()
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
if (staticCtor == null)
{
staticCtor = new ConstructorGen(this, MethodAttributes.Static, 0).LockSignature();
}
return staticCtor;
}
public FieldGen Field<T>(string name)
{
return Field(typeof(T), name);
}
public FieldGen Field(Type type, string name)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoField);
if (fldVis == 0)
fldVis |= FieldAttributes.Private;
FieldGen fld = new FieldGen(this, name, type, fldVis | fldFlags);
fields.Add(fld);
ResetAttrs();
return fld;
}
public FieldGen Field<T>(string name, Operand initialValue)
{
return Field(typeof(T), name, initialValue);
}
public FieldGen Field(Type type, string name, Operand initialValue)
{
FieldGen fld = Field(type, name);
CodeGen initCode = fld.IsStatic ? StaticConstructor().GetCode(): CommonConstructor().GetCode();
initCode.Assign(fld, initialValue);
return fld;
}
public PropertyGen Property<T>(string name)
{
return Property(typeof(T), name);
}
public PropertyGen Property(Type type, string name)
{
if (mthVis == 0)
mthVis |= MethodAttributes.Private;
if (tb.IsInterface)
mthVirt |= MethodAttributes.Virtual | MethodAttributes.Abstract;
PropertyGen pg = new PropertyGen(this, mthVis | mthVirt | mthFlags, type, name);
properties.Add(pg);
ResetAttrs();
return pg;
}
public PropertyGen Indexer<T>()
{
return Indexer(typeof(T));
}
public PropertyGen Indexer(Type type)
{
return Indexer(type, "Item");
}
public PropertyGen Indexer<T>(string name)
{
return Indexer(typeof(T), name);
}
public PropertyGen Indexer(Type type, string name)
{
if (indexerName != null && indexerName != name)
throw new InvalidOperationException(Properties.Messages.ErrAmbiguousIndexerName);
PropertyGen pg = Property(type, name);
indexerName = name;
return pg;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "It is invalid to use anything else than a Field as a base for SimpleProperty")]
public PropertyGen SimpleProperty(FieldGen field, string name)
{
if ((object)field == null)
throw new ArgumentNullException("field");
PropertyGen pg = Property(field.Type, name);
pg.Getter().GetCode().Return(field);
pg.Setter().GetCode().Assign(field, pg.Setter().GetCode().PropertyValue());
return pg;
}
public EventGen Event(Type handlerType, string name)
{
return CustomEvent(handlerType, name).WithStandardImplementation();
}
public EventGen CustomEvent(Type handlerType, string name)
{
EventGen eg = new EventGen(this, name, handlerType, mthVis | mthVirt | mthFlags);
events.Add(eg);
ResetAttrs();
return eg;
}
public MethodGen Void(string name)
{
return Method(typeof(void), name);
}
public MethodGen Method<T>(string name)
{
return Method(typeof(T), name);
}
public MethodGen Method(Type returnType, string name)
{
if (mthVis == 0)
mthVis |= MethodAttributes.Private;
if (tb.IsInterface)
mthVirt |= MethodAttributes.Virtual | MethodAttributes.Abstract;
MethodGen mg = new MethodGen(this, name, mthVis | mthVirt | mthFlags, returnType, implFlags);
ResetAttrs();
return mg;
}
public MethodGen ImplicitConversionFrom<T>()
{
return ImplicitConversionFrom(typeof(T));
}
public MethodGen ImplicitConversionFrom(Type fromType)
{
return ImplicitConversionFrom(fromType, "value");
}
public MethodGen ImplicitConversionFrom<T>(string parameterName)
{
return ImplicitConversionFrom(typeof(T), parameterName);
}
public MethodGen ImplicitConversionFrom(Type fromType, string parameterName)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(tb, "op_Implicit").Parameter(fromType, parameterName);
}
public MethodGen ImplicitConversionTo<T>()
{
return ImplicitConversionTo(typeof(T));
}
public MethodGen ImplicitConversionTo(Type toType)
{
return ImplicitConversionTo(toType, "value");
}
public MethodGen ImplicitConversionTo<T>(string parameterName)
{
return ImplicitConversionTo(typeof(T), parameterName);
}
public MethodGen ImplicitConversionTo(Type toType, string parameterName)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(toType, "op_Implicit").Parameter(tb, parameterName);
}
public MethodGen ExplicitConversionFrom<T>()
{
return ExplicitConversionFrom(typeof(T));
}
public MethodGen ExplicitConversionFrom(Type fromType)
{
return ExplicitConversionFrom(fromType, "value");
}
public MethodGen ExplicitConversionFrom<T>(string parameterName)
{
return ExplicitConversionFrom(typeof(T), parameterName);
}
public MethodGen ExplicitConversionFrom(Type fromType, string parameterName)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(tb, "op_Explicit").Parameter(fromType, parameterName);
}
public MethodGen ExplicitConversionTo<T>()
{
return ExplicitConversionTo(typeof(T));
}
public MethodGen ExplicitConversionTo(Type toType)
{
return ExplicitConversionTo(toType, "value");
}
public MethodGen ExplicitConversionTo<T>(string parameterName)
{
return ExplicitConversionTo(typeof(T), parameterName);
}
public MethodGen ExplicitConversionTo(Type toType, string parameterName)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(toType, "op_Explicit").Parameter(tb, parameterName);
}
public MethodGen Operator(Operator op, Type returnType, Type operandType)
{
return Operator(op, returnType, operandType, "operand");
}
public MethodGen Operator(Operator op, Type returnType, Type operandType, string operandName)
{
if (op == null)
throw new ArgumentNullException("op");
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(returnType, "op_" + op.methodName).Parameter(operandType, operandName);
}
public MethodGen Operator(Operator op, Type returnType, Type leftType, Type rightType)
{
return Operator(op, returnType, leftType, "left", rightType, "right");
}
public MethodGen Operator(Operator op, Type returnType, Type leftType, string leftName, Type rightType, string rightName)
{
if (op == null)
throw new ArgumentNullException("op");
ResetAttrs();
mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
mthVis = MethodAttributes.Public;
return Method(returnType, "op_" + op.methodName)
.Parameter(leftType, leftName)
.Parameter(rightType, rightName)
;
}
public TypeGen Class(string name)
{
return Class(name, typeof(object), Type.EmptyTypes);
}
public TypeGen Class(string name, Type baseType)
{
return Class(name, baseType, Type.EmptyTypes);
}
public TypeGen Class(string name, Type baseType, params Type[] interfaces)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoNested);
if (typeVis == 0)
typeVis |= TypeAttributes.NestedPrivate;
TypeGen tg = new TypeGen(this, name, (typeVis | typeVirt | typeFlags | TypeAttributes.Class) ^ TypeAttributes.BeforeFieldInit, baseType, interfaces);
ResetAttrs();
return tg;
}
public TypeGen Struct(string name)
{
return Struct(name, Type.EmptyTypes);
}
public TypeGen Struct(string name, params Type[] interfaces)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoNested);
if (typeVis == 0)
typeVis |= TypeAttributes.NestedPrivate;
TypeGen tg = new TypeGen(this, name, (typeVis | typeVirt | typeFlags | TypeAttributes.Sealed | TypeAttributes.SequentialLayout) ^ TypeAttributes.BeforeFieldInit, typeof(ValueType), interfaces);
ResetAttrs();
return tg;
}
#endregion
#region Interface implementations
void DefineMethodOverride(MethodGen methodBody, MethodInfo methodDeclaration)
{
foreach (InterfaceImplEntry iie in implementations)
{
if (iie.InterfaceMethod.Member == methodDeclaration)
{
iie.Bind(methodBody);
return;
}
}
}
public MethodGen MethodImplementation<TInterface>(Type returnType, string name)
{
return MethodImplementation(typeof(TInterface), returnType, name);
}
public MethodGen MethodImplementation<TInterface, TReturnType>(string name)
{
return MethodImplementation(typeof(TInterface), typeof(TReturnType), name);
}
public MethodGen MethodImplementation(Type interfaceType, Type returnType, string name)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoExplicitImpl);
MethodGen mg = new MethodGen(this, name,
MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
returnType, 0);
mg.ImplementedInterface = interfaceType;
return mg;
}
public PropertyGen PropertyImplementation<TInterface>(Type type, string name)
{
return PropertyImplementation(typeof(TInterface), type, name);
}
public PropertyGen PropertyImplementation<TInterface, TType>(string name)
{
return PropertyImplementation(typeof(TInterface), typeof(TType), name);
}
public PropertyGen PropertyImplementation(Type interfaceType, Type type, string name)
{
if (tb.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoExplicitImpl);
PropertyGen pg = new PropertyGen(this,
MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
type, name);
pg.ImplementedInterface = interfaceType;
return pg;
}
#endregion
public Type GetCompletedType()
{
return GetCompletedType(false);
}
public Type GetCompletedType(bool completeIfNeeded)
{
if (type != null)
return type;
if (completeIfNeeded)
{
Complete();
return type;
}
throw new InvalidOperationException(Properties.Messages.ErrTypeNotCompleted);
}
public bool IsCompleted
{
get { return type != null; }
}
void FlushDefinitionQueue()
{
// cannot use foreach, because it is possible that new objects
// will be appended while completing the existing ones
for (int i = 0; i < definitionQueue.Count; i++)
{
definitionQueue[i].EndDefinition();
}
definitionQueue.Clear();
}
void FlushCompletionQueue()
{
// cannot use foreach, because it is possible that new objects
// will be appended while completing the existing ones
for (int i = 0; i < completionQueue.Count; i++)
{
completionQueue[i].Complete();
}
completionQueue.Clear();
}
public void Complete()
{
if (type != null)
return;
foreach (TypeGen nested in nestedTypes)
nested.Complete();
// ensure creation of default constructor
EnsureDefaultConstructor();
FlushDefinitionQueue();
FlushCompletionQueue();
// implement all interfaces
foreach (InterfaceImplEntry iie in implementations)
{
if (!iie.IsBound)
throw new NotImplementedException(string.Format(null, Properties.Messages.ErrInterfaceNotImplemented,
iie.InterfaceType, iie.InterfaceMethod.Member));
tb.DefineMethodOverride(iie.BoundMethod.GetMethodBuilder(), (MethodInfo) iie.InterfaceMethod.Member);
}
// set indexer name
if (indexerName != null)
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
typeof(DefaultMemberAttribute).GetConstructor(new Type[] { typeof(string) }),
new object[] { indexerName });
tb.SetCustomAttribute(cab);
}
AttributeGen.ApplyList(ref customAttributes, tb.SetCustomAttribute);
type = tb.CreateType();
TypeInfo.UnregisterProvider(tb);
}
public static implicit operator Type(TypeGen tg)
{
if (tg == null)
return null;
if (tg.type != null)
return tg.type;
return tg.tb;
}
public override string ToString()
{
return tb.FullName;
}
void EnsureDefaultConstructor()
{
if (constructors.Count == 0 && tb.IsClass)
{
// create default constructor
ResetAttrs();
Public.Constructor().LockSignature();
}
}
#region Member registration
internal void Register(ConstructorGen constructor)
{
if (constructor.IsStatic)
return;
if (constructor.ParameterCount == 0 && tb.IsValueType)
throw new InvalidOperationException(Properties.Messages.ErrStructNoDefaultCtor);
constructors.Add(constructor);
}
internal void Register(MethodGen method)
{
if (owner.AssemblyBuilder.EntryPoint == null && method.Name == "Main" && method.IsStatic && (
method.ParameterCount == 0 ||
(method.ParameterCount == 1 && method.ParameterTypes[0] == typeof(string[]))))
owner.AssemblyBuilder.SetEntryPoint(method.GetMethodBuilder());
// match explicit interface implementations
if (method.ImplementedInterface != null)
{
foreach (IMemberInfo mi in TypeInfo.Filter(TypeInfo.GetMethods(method.ImplementedInterface), method.Name, false, false, true))
{
if (ArrayUtils.Equals(mi.ParameterTypes, method.ParameterTypes))
{
DefineMethodOverride(method, (MethodInfo)mi.Member);
return;
}
}
throw new MissingMethodException(Properties.Messages.ErrMissingMethod);
}
methods.Add(method);
}
#endregion
#region ITypeInfoProvider implementation
IEnumerable<IMemberInfo> ITypeInfoProvider.GetConstructors()
{
EnsureDefaultConstructor();
FlushDefinitionQueue();
return constructors;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetFields()
{
FlushDefinitionQueue();
return fields;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetProperties()
{
FlushDefinitionQueue();
return properties;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetEvents()
{
FlushDefinitionQueue();
return events;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetMethods()
{
FlushDefinitionQueue();
return methods;
}
string ITypeInfoProvider.DefaultMember
{
get { return indexerName; }
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using RestCake.Metadata;
using RestCake.Util;
namespace RestCake.Clients
{
public class JsClientWriter
{
private readonly TextWriter m_textWriter;
public JsClientWriter(TextWriter textWriter)
{
m_textWriter = textWriter;
}
public void WriteJsClientBase()
{
// Write out the WcfClient.js contents
m_textWriter.WriteLine("// WcfClient.js");
m_textWriter.WriteLine(ReflectionHelper.GetTemplateContents("Js.WcfClient.js"));
}
public void WriteServiceClient(ServiceMetadata service, string baseUrl, string clientVarName)
{
// Get the service client template, and setup the namespace, and the name of the js class
string clientTemplate = ReflectionHelper.GetTemplateContents("Js.ServiceClient.js");
clientTemplate = clientTemplate
.Replace("<#= Namespace #>", service.ServiceNamespace)
.Replace("<#= JsClassName #>", service.ServiceName + "Client");
// Go through each method in the service class, creating the js body for each one.
StringBuilder sbServiceMethods = new StringBuilder();
foreach (MethodMetadata method in service.Methods)
sbServiceMethods.AppendLine(getMethodBody(method));
// Now create special versions that can be called using just a form ID, where the form will be jquery serialized, and the args taken automatically
foreach (MethodMetadata method in service.Methods)
sbServiceMethods.AppendLine(getMethodBody_jqueryFormSerialize(method));
// Add the service method bodies (js) that we just created to the client template
clientTemplate = clientTemplate.Replace("<#= ServiceMethods #>", sbServiceMethods.ToString());
// Create the js client instances
string jsClientDeclaration;
if (clientVarName == null)
jsClientDeclaration = "// If you want an auto created js client var, put a \"&clientVarName=x\" in your query string when including this script.";
else
jsClientDeclaration = "window." + clientVarName + " = new " + service.ServiceNamespace + "." + service.ServiceName + "Client(\"" + baseUrl + "\");";
clientTemplate = clientTemplate.Replace("<#= JsClientDeclaration #>", jsClientDeclaration);
// Write out the client template
m_textWriter.WriteLine("// ServiceClient.js template");
m_textWriter.WriteLine(clientTemplate);
}
private static string getMethodBody_jqueryFormSerialize(MethodMetadata method)
{
string serviceMethodTemplate = ReflectionHelper.GetTemplateContents("Js.ServiceMethod-jqueryFormSerialize.txt");
string[] paramNames = method.GetParamNames();
string strParamNames = "";
if (paramNames.Length > 0)
strParamNames = "\"" + String.Join("\",\"", paramNames) + "\"";
IList<ParameterInfo> intParams = method.GetIntParams();
string strIntParams = "";
if (intParams.Count > 0)
strIntParams = "\"" + String.Join("\",\"", intParams.Select(p => p.Name)) + "\"";
IList<object> intParamDefaults = intParams.Select(prm => Activator.CreateInstance(prm.ParameterType) ?? "null").ToList();
string strIntParamDefaults = String.Join(",", intParamDefaults);
IList<ParameterInfo> floatParams = method.GetFloatParams();
string strFloatParams = "";
if (floatParams.Count > 0)
strFloatParams = "\"" + String.Join("\",\"", floatParams.Select(p => p.Name)) + "\"";
IList<object> floatParamDefaults = floatParams.Select(prm => Activator.CreateInstance(prm.ParameterType) ?? "null").ToList();
string strFloatParamDefaults = String.Join(",", floatParamDefaults);
string methodBody = serviceMethodTemplate
.Replace("<#= MethodName #>", method.Name)
.Replace("<#= jsonp #>", "")
.Replace("<#= ParamNames #>", strParamNames)
.Replace("<#= IntParams #>", strIntParams)
.Replace("<#= IntParamDefaults #>", strIntParamDefaults)
.Replace("<#= FloatParams #>", strFloatParams)
.Replace("<#= FloatParamDefaults #>", strFloatParamDefaults);
// If it's GET, add an additional "_jsonp" method that can be called
if (method.Verb == HttpVerb.Get)
{
string jsonpMethodBody = serviceMethodTemplate
.Replace("<#= MethodName #>", method.Name)
.Replace("<#= jsonp #>", "_jsonp")
.Replace("<#= ParamNames #>", strParamNames)
.Replace("<#= IntParams #>", strIntParams)
.Replace("<#= IntParamDefaults #>", strIntParamDefaults)
.Replace("<#= FloatParams #>", strFloatParams)
.Replace("<#= FloatParamDefaults #>", strFloatParamDefaults);
methodBody += Environment.NewLine + jsonpMethodBody;
}
return methodBody;
}
private static string getMethodBody(MethodMetadata method)
{
string serviceMethodTemplate = ReflectionHelper.GetTemplateContents("Js.ServiceMethod.txt");
string dataArg = "null";
// The template works "as-is" with HTTP GET. For the other verbs (PUT, POST, DELETE), we have to modify the dataArg value.
if (method.Verb != HttpVerb.Get)
{
string[] dataParams = method.GetDataParamNames();
// Set up the dataArg variable
StringBuilder sbDataArg = new StringBuilder();
if (method.IsWrappedRequest)
{
// Start the wrapped json object
sbDataArg.Append("{");
foreach (string param in dataParams)
{
sbDataArg.Append("\"").Append(param).Append("\": ");
if (param.EndsWith("Json"))
sbDataArg.Append("JSON.stringify(").Append(param.Substring(0, param.Length - "Json".Length)).Append("), ");
else
sbDataArg.Append(param).Append(", ");
}
// Get rid of the trailing ", "
if (sbDataArg.Length > 1)
sbDataArg.Remove(sbDataArg.Length - 2, 2);
// End the json wrapped object
sbDataArg.Append("}");
}
else // Not wrapped
{
if (dataParams.Length > 1)
throw new NotSupportedException("Error with service method " + method.Name + " in the " + method.Service.ServiceName
+ " service. Passing in multiple data arguments requires that the service have a wrapped request "
+ "(WebMessageBodyStyle.Wrapped or WebMessageBodyStyle.WrappedRequest)");
if (dataParams.Length == 0)
{
sbDataArg.Append("null");
}
else
{
if (dataParams[0].EndsWith("Json"))
sbDataArg.Append("JSON.stringify(").Append(dataParams[0].Substring(0, dataParams[0].Length - "Json".Length)).
Append(")");
else
sbDataArg.Append(dataParams[0]);
}
}
dataArg = sbDataArg.ToString();
}
string methodBody = serviceMethodTemplate
.Replace("<#= MethodName #>", method.Name)
.Replace("<#= jsonp #>", "")
.Replace("<#= isJsonp #>", "false")
.Replace("<#= MethodArgs #>", getArgsListAsString(method))
.Replace("<#= DefaultErrorMessage #>", "Error calling " + method.Service.ServiceNamespace + "." + method.Name)
.Replace("<#= MethodUrl #>", getMethodUrl(method))
.Replace("<#= HttpVerb #>", method.Verb.ToString("g").ToUpper())
.Replace("<#= DataArg #>", dataArg)
.Replace("<#= IsWrappedResponse #>", method.IsWrappedResponse.ToString().ToLower());
if (method.Verb == HttpVerb.Get)
{
string jsonpMethodBody = serviceMethodTemplate
.Replace("<#= MethodName #>", method.Name)
.Replace("<#= jsonp #>", "_jsonp")
.Replace("<#= isJsonp #>", "true")
.Replace("<#= MethodArgs #>", getArgsListAsString(method))
.Replace("<#= DefaultErrorMessage #>", "Error calling " + method.Service.ServiceNamespace + "." + method.Name)
.Replace("<#= MethodUrl #>", getMethodUrl(method))
.Replace("<#= HttpVerb #>", method.Verb.ToString("g").ToUpper())
.Replace("<#= DataArg #>", dataArg)
.Replace("<#= IsWrappedResponse #>", method.IsWrappedResponse.ToString().ToLower());
methodBody += Environment.NewLine + jsonpMethodBody;
}
return methodBody;
}
/// <summary>
/// Returns a string like "arg1, arg2, arg3", etc (joins all params with a comma)
/// TODO: Currently, any arg that ends with the string "Json" (such as personJson), the "Json" will be chopped off.
/// This was for a specific feature (need to look into it and see if it's still used)
/// </summary>
/// <returns></returns>
internal static string getArgsListAsString(MethodMetadata method)
{
// For args that end with "Json", we want to strip that off the arg name.
// WCF doesn't seem to let us pass raw json in as a param. They want to use their own deserialization, which fails for many things.
// We are using Json.NET, and so we pass in doubly quoted json strings, so the arg going into the service method is not an object, but a string.
// But, we want our params named sanely.
Regex rxNoJson = new Regex(@"Json$");
string argsList = String.Join(", ", method.GetParamNames().Select(p => rxNoJson.Replace(p, "")).ToArray());
if (argsList.Length > 0)
argsList += ", ";
return argsList;
}
private static string getMethodUrl(MethodMetadata method)
{
string methodUrl = "'" + method.UriTemplate + "'";
ParameterInfo[] urlParams = method.GetUrlParams();
// Query string params
foreach (ParameterInfo param in urlParams)
{
string search = String.Format("{0}={{{0}}}", param.Name);
string replace = String.Format("{0}=' + (({0} == null || {0} === 'undefined') ? '' : {1}) + '",
param.Name,
getParamUrlString(param));
methodUrl = methodUrl.Replace(search, replace);
}
// Get rid of useless empty string concats
methodUrl = methodUrl.Replace(" + ''", "");
// Uri segment params
foreach (var param in urlParams)
methodUrl = methodUrl.Replace("{" + param.Name + "}", "' + " + getParamUrlString(param) + " + '");
// Get rid of weird [ + ''] and ['' + ] instances at the end or beginning (respecitvely) of the string
Regex rxBeg = new Regex(@"^'' \+ ");
Regex rxEnd = new Regex(@" \+ ''$");
methodUrl = rxBeg.Replace(methodUrl, "");
methodUrl = rxEnd.Replace(methodUrl, "");
return methodUrl;
}
private static string getParamUrlString(ParameterInfo param)
{
string value = param.Name;
// Do we need to JSON.stringify() the arg?
if ((!typeof(IEnumerable).IsAssignableFrom(param.ParameterType) || typeof(IDictionary).IsAssignableFrom(param.ParameterType)) // Not an IEnumerable or IS a Dictionary.
&& !typeof(string).IsAssignableFrom(param.ParameterType)
&& !param.ParameterType.IsPrimitive
&& !param.ParameterType.IsEnum)
{
value = "JSON.stringify(" + param.Name + ")";
}
// True, RestCake on the server handles it when it's NOT that way, but it won't handle commas in the strings, so it's an easy point of failure.
else if (param.ParameterType == typeof(string[]) || typeof(IList<string>).IsAssignableFrom(param.ParameterType))
{
// For arrays or lists of strings (in a GET url, remember), use an empty string for null, [] for an empty array, and JSON.stringify() for a populated array.
value = "(" + param.Name + " == null ? '' : (" + param.Name + ".length == 0 ? '[]' : JSON.stringify(" + param.Name + ")))";
}
return value;
}
}
}
| |
/*****************************************************************************
* Skeleton Utility created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using Spine;
/// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary>
[ExecuteInEditMode]
[AddComponentMenu("Spine/SkeletonUtilityBone")]
public class SkeletonUtilityBone : MonoBehaviour {
public enum Mode {
Follow,
Override
}
[System.NonSerialized]
public bool valid;
[System.NonSerialized]
public SkeletonUtility skeletonUtility;
[System.NonSerialized]
public Bone bone;
public Mode mode;
public bool zPosition = true;
public bool position;
public bool rotation;
public bool scale;
public bool flip;
public bool flipX;
[Range(0f, 1f)]
public float overrideAlpha = 1;
/// <summary>If a bone isn't set, boneName is used to find the bone.</summary>
public String boneName;
public Transform parentReference;
[HideInInspector]
public bool transformLerpComplete;
protected Transform cachedTransform;
protected Transform skeletonTransform;
public bool NonUniformScaleWarning {
get {
return nonUniformScaleWarning;
}
}
private bool nonUniformScaleWarning;
public void Reset () {
bone = null;
cachedTransform = transform;
valid = skeletonUtility != null && skeletonUtility.skeletonRenderer != null && skeletonUtility.skeletonRenderer.valid;
if (!valid)
return;
skeletonTransform = skeletonUtility.transform;
skeletonUtility.OnReset -= HandleOnReset;
skeletonUtility.OnReset += HandleOnReset;
DoUpdate();
}
void OnEnable () {
skeletonUtility = SkeletonUtility.GetInParent<SkeletonUtility>(transform);
if (skeletonUtility == null)
return;
skeletonUtility.RegisterBone(this);
skeletonUtility.OnReset += HandleOnReset;
}
void HandleOnReset () {
Reset();
}
void OnDisable () {
if (skeletonUtility != null) {
skeletonUtility.OnReset -= HandleOnReset;
skeletonUtility.UnregisterBone(this);
}
}
public void DoUpdate () {
if (!valid) {
Reset();
return;
}
Spine.Skeleton skeleton = skeletonUtility.skeletonRenderer.skeleton;
if (bone == null) {
if (boneName == null || boneName.Length == 0)
return;
bone = skeleton.FindBone(boneName);
if (bone == null) {
Debug.LogError("Bone not found: " + boneName, this);
return;
}
}
float skeletonFlipRotation = (skeleton.flipX ^ skeleton.flipY) ? -1f : 1f;
float flipCompensation = 0;
// MITCH
//if (flip && (flipX || (flipX != bone.flipX)) && bone.parent != null) {
// flipCompensation = bone.parent.WorldRotation * -2;
//}
if (mode == Mode.Follow) {
if (flip) {
// MITCH
//flipX = bone.flipX;
}
if (position) {
cachedTransform.localPosition = new Vector3(bone.x, bone.y, 0);
}
if (rotation) {
if (bone.Data.InheritRotation) {
// MITCH
//if (bone.FlipX) {
// cachedTransform.localRotation = Quaternion.Euler(0, 180, bone.rotationIK - flipCompensation);
//} else {
cachedTransform.localRotation = Quaternion.Euler(0, 0, bone.AppliedRotation);
//}
} else {
Vector3 euler = skeletonTransform.rotation.eulerAngles;
cachedTransform.rotation = Quaternion.Euler(euler.x, euler.y, skeletonTransform.rotation.eulerAngles.z + (bone.WorldRotationX * skeletonFlipRotation));
}
}
if (scale) {
cachedTransform.localScale = new Vector3(bone.scaleX, bone.scaleY, bone.WorldSignX);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
} else if (mode == Mode.Override) {
if (transformLerpComplete)
return;
if (parentReference == null) {
if (position) {
bone.x = Mathf.Lerp(bone.x, cachedTransform.localPosition.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, cachedTransform.localPosition.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, cachedTransform.localRotation.eulerAngles.z, overrideAlpha) + flipCompensation;
if (flip) {
// MITCH
//if ((!flipX && bone.flipX)) {
// angle -= flipCompensation;
//}
//TODO fix this...
if (angle >= 360)
angle -= 360;
else if (angle <= -360)
angle += 360;
}
bone.Rotation = angle;
bone.AppliedRotation = angle;
}
if (scale) {
bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
// MITCH
//if (flip) {
// bone.flipX = flipX;
//}
} else {
if (transformLerpComplete)
return;
if (position) {
Vector3 pos = parentReference.InverseTransformPoint(cachedTransform.position);
bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha);
bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha);
}
if (rotation) {
float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(flipX ? Vector3.forward * -1 : Vector3.forward, parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles.z, overrideAlpha) + flipCompensation;
if (flip) {
// MITCH
//if ((!flipX && bone.flipX)) {
// angle -= flipCompensation;
//}
//TODO fix this...
if (angle >= 360)
angle -= 360;
else if (angle <= -360)
angle += 360;
}
bone.Rotation = angle;
bone.AppliedRotation = angle;
}
//TODO: Something about this
if (scale) {
bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha);
bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha);
nonUniformScaleWarning = (bone.scaleX != bone.scaleY);
}
// MITCH
//if (flip) {
// bone.flipX = flipX;
//}
}
transformLerpComplete = true;
}
}
public void FlipX (bool state) {
if (state != flipX) {
flipX = state;
if (flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) > 90) {
skeletonUtility.skeletonAnimation.LateUpdate();
return;
} else if (!flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) < 90) {
skeletonUtility.skeletonAnimation.LateUpdate();
return;
}
}
// MITCH
//bone.FlipX = state;
transform.RotateAround(transform.position, skeletonUtility.transform.up, 180);
Vector3 euler = transform.localRotation.eulerAngles;
euler.x = 0;
// MITCH
//euler.y = bone.FlipX ? 180 : 0;
euler.y = 0;
transform.localRotation = Quaternion.Euler(euler);
}
public void AddBoundingBox (string skinName, string slotName, string attachmentName) {
SkeletonUtility.AddBoundingBox(bone.skeleton, skinName, slotName, attachmentName, transform);
}
void OnDrawGizmos () {
if (NonUniformScaleWarning) {
Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning");
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Security.Principal;
using EventStore.Common.Log;
using EventStore.Common.Utils;
using EventStore.Core.Authentication;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services.TimerService;
using EventStore.Core.Services.UserManagement;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Services.Processing;
using EventStore.Projections.Core.Utils;
using ReadStreamResult = EventStore.Core.Data.ReadStreamResult;
namespace EventStore.Projections.Core.Services.Management
{
/// <summary>
/// managed projection controls start/stop/create/update/delete lifecycle of the projection.
/// </summary>
public class ManagedProjection : IDisposable
{
public class PersistedState
{
public string HandlerType { get; set; }
public string Query { get; set; }
public ProjectionMode Mode { get; set; }
public bool Enabled { get; set; }
public bool Deleted { get; set; }
[Obsolete]
public ProjectionSourceDefinition SourceDefintion
{
set { SourceDefinition = value; }
}
public ProjectionSourceDefinition SourceDefinition { get; set; }
public bool? EmitEnabled { get; set; }
public bool? CreateTempStreams { get; set; }
public bool? CheckpointsDisabled { get; set; }
public int? Epoch { get; set; }
public int? Version { get; set; }
public SerializedRunAs RunAs { get; set; }
}
private readonly IPublisher _inputQueue;
private readonly IPublisher _output;
private readonly RequestResponseDispatcher<ClientMessage.WriteEvents, ClientMessage.WriteEventsCompleted>
_writeDispatcher;
private readonly
RequestResponseDispatcher
<ClientMessage.ReadStreamEventsBackward, ClientMessage.ReadStreamEventsBackwardCompleted>
_readDispatcher;
private readonly
RequestResponseDispatcher
<CoreProjectionManagementMessage.GetState, CoreProjectionManagementMessage.StateReport>
_getStateDispatcher;
private readonly
RequestResponseDispatcher
<CoreProjectionManagementMessage.GetResult, CoreProjectionManagementMessage.ResultReport>
_getResultDispatcher;
private readonly ILogger _logger;
private readonly ProjectionStateHandlerFactory _projectionStateHandlerFactory;
private readonly ITimeProvider _timeProvider;
private readonly ISingletonTimeoutScheduler _timeoutScheduler;
private readonly IPublisher _coreQueue;
private readonly Guid _id;
private readonly int _projectionId;
private readonly string _name;
private readonly bool _enabledToRun;
private ManagedProjectionState _state;
private PersistedState _persistedState = new PersistedState();
//private int _version;
private string _faultedReason;
private Action _onStopped;
//private List<IEnvelope> _debugStateRequests;
private ProjectionStatistics _lastReceivedStatistics;
private Action _onPrepared;
private Action _onStarted;
private DateTime _lastAccessed;
private int _lastWrittenVersion = -1;
private IPrincipal _runAs;
//TODO: slave (extract into derived class)
private readonly bool _isSlave;
private readonly IPublisher _slaveResultsPublisher;
private readonly Guid _slaveMasterCorrelationId;
private Guid _slaveProjectionSubscriptionId;
public ManagedProjection(
IPublisher coreQueue, Guid id, int projectionId, string name, bool enabledToRun, ILogger logger,
RequestResponseDispatcher<ClientMessage.WriteEvents, ClientMessage.WriteEventsCompleted> writeDispatcher,
RequestResponseDispatcher
<ClientMessage.ReadStreamEventsBackward, ClientMessage.ReadStreamEventsBackwardCompleted> readDispatcher,
IPublisher inputQueue, IPublisher output, ProjectionStateHandlerFactory projectionStateHandlerFactory,
ITimeProvider timeProvider, ISingletonTimeoutScheduler timeoutScheduler = null, bool isSlave = false,
IPublisher slaveResultsPublisher = null, Guid slaveMasterCorrelationId = default(Guid))
{
if (coreQueue == null) throw new ArgumentNullException("coreQueue");
if (id == Guid.Empty) throw new ArgumentException("id");
if (name == null) throw new ArgumentNullException("name");
if (output == null) throw new ArgumentNullException("output");
if (name == "") throw new ArgumentException("name");
_coreQueue = coreQueue;
_id = id;
_projectionId = projectionId;
_name = name;
_enabledToRun = enabledToRun;
_logger = logger;
_writeDispatcher = writeDispatcher;
_readDispatcher = readDispatcher;
_inputQueue = inputQueue;
_output = output;
_projectionStateHandlerFactory = projectionStateHandlerFactory;
_timeProvider = timeProvider;
_timeoutScheduler = timeoutScheduler;
_isSlave = isSlave;
_slaveResultsPublisher = slaveResultsPublisher;
_slaveMasterCorrelationId = slaveMasterCorrelationId;
_getStateDispatcher =
new RequestResponseDispatcher
<CoreProjectionManagementMessage.GetState, CoreProjectionManagementMessage.StateReport>(
coreQueue, v => v.CorrelationId, v => v.CorrelationId, new PublishEnvelope(_inputQueue));
_getResultDispatcher =
new RequestResponseDispatcher
<CoreProjectionManagementMessage.GetResult, CoreProjectionManagementMessage.ResultReport>(
coreQueue, v => v.CorrelationId, v => v.CorrelationId, new PublishEnvelope(_inputQueue));
_lastAccessed = _timeProvider.Now;
}
private string HandlerType
{
get { return _persistedState.HandlerType; }
}
private string Query
{
get { return _persistedState.Query; }
}
private ProjectionMode Mode
{
get { return _persistedState.Mode; }
}
private bool Enabled
{
get { return _persistedState.Enabled; }
set { _persistedState.Enabled = value; }
}
public bool Deleted
{
get { return _persistedState.Deleted; }
private set { _persistedState.Deleted = value; }
}
//TODO: remove property. pass value back to completion routine
public Guid SlaveProjectionSubscriptionId
{
get { return _slaveProjectionSubscriptionId; }
}
public Guid Id
{
get { return _id; }
}
public void Dispose()
{
DisposeCoreProjection();
}
public ProjectionMode GetMode()
{
return Mode;
}
public ProjectionStatistics GetStatistics()
{
_coreQueue.Publish(new CoreProjectionManagementMessage.UpdateStatistics(Id));
ProjectionStatistics status;
if (_lastReceivedStatistics == null)
{
status = new ProjectionStatistics
{
Name = _name,
Epoch = -1,
Version = -1,
Mode = GetMode(),
Status = _state.EnumValueName(),
MasterStatus = _state
};
}
else
{
status = _lastReceivedStatistics.Clone();
status.Mode = GetMode();
status.Name = _name;
var enabledSuffix = ((_state == ManagedProjectionState.Stopped || _state == ManagedProjectionState.Faulted) && Enabled ? " (Enabled)" : "");
status.Status = (status.Status == "Stopped" && _state == ManagedProjectionState.Completed
? _state.EnumValueName()
: (!status.Status.StartsWith(_state.EnumValueName())
? _state.EnumValueName() + "/" + status.Status
: status.Status)) + enabledSuffix;
status.MasterStatus = _state;
}
if (_state == ManagedProjectionState.Faulted)
status.StateReason = _faultedReason;
status.Enabled = Enabled;
return status;
}
public void Handle(ProjectionManagementMessage.GetQuery message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Read, _runAs, message)) return;
var emitEnabled = _persistedState.EmitEnabled ?? false;
message.Envelope.ReplyWith(
new ProjectionManagementMessage.ProjectionQuery(_name, Query, emitEnabled, _persistedState.SourceDefinition));
}
public void Handle(ProjectionManagementMessage.UpdateQuery message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
Stop(() => DoUpdateQuery(message));
}
public void Handle(ProjectionManagementMessage.GetResult message)
{
_lastAccessed = _timeProvider.Now;
if (_state >= ManagedProjectionState.Stopped)
{
_getResultDispatcher.Publish(
new CoreProjectionManagementMessage.GetResult(
new PublishEnvelope(_inputQueue), Guid.NewGuid(), Id, message.Partition),
m =>
message.Envelope.ReplyWith(
new ProjectionManagementMessage.ProjectionResult(_name, m.Partition, m.Result, m.Position)));
}
else
{
message.Envelope.ReplyWith(
new ProjectionManagementMessage.ProjectionResult(
message.Name, message.Partition, "*** UNKNOWN ***", position: null));
}
}
public void Handle(ProjectionManagementMessage.Disable message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
Stop(() => DoDisable(message.Envelope, message.Name));
}
public void Handle(ProjectionManagementMessage.Abort message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
Abort(() => DoDisable(message.Envelope, message.Name));
}
public void Handle(ProjectionManagementMessage.Enable message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
if (Enabled
&& !(_state == ManagedProjectionState.Completed || _state == ManagedProjectionState.Faulted
|| _state == ManagedProjectionState.Loaded || _state == ManagedProjectionState.Prepared
|| _state == ManagedProjectionState.Stopped))
{
message.Envelope.ReplyWith(
new ProjectionManagementMessage.OperationFailed("Invalid state"));
return;
}
if (!Enabled)
Enable();
Action completed = () =>
{
if (_state == ManagedProjectionState.Prepared)
StartOrLoadStopped(() => message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name)));
else
message.Envelope.ReplyWith(
new ProjectionManagementMessage.Updated(message.Name));
};
UpdateProjectionVersion();
Prepare(() => BeginWrite(completed));
}
public void Handle(ProjectionManagementMessage.SetRunAs message)
{
_lastAccessed = _timeProvider.Now;
if (
!ProjectionManagementMessage.RunAs.ValidateRunAs(
Mode, ReadWrite.Write, _runAs, message,
message.Action == ProjectionManagementMessage.SetRunAs.SetRemove.Set)) return;
Stop(
() =>
{
UpdateProjectionVersion();
_persistedState.RunAs = message.Action == ProjectionManagementMessage.SetRunAs.SetRemove.Set
? SerializePrincipal(message.RunAs)
: null;
_runAs = DeserializePrincipal(_persistedState.RunAs);
Prepare(
() => BeginWrite(
() =>
{
StartOrLoadStopped(() => { });
message.Envelope.ReplyWith(
new ProjectionManagementMessage.Updated(message.Name));
}));
});
}
public void Handle(ProjectionManagementMessage.Reset message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
Stop(
() =>
{
ResetProjection();
Prepare(
() =>
BeginWrite(
() =>
StartOrLoadStopped(
() =>
message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name)))));
});
}
private void ResetProjection()
{
UpdateProjectionVersion(force: true);
_persistedState.Epoch = _persistedState.Version;
}
public void Handle(ProjectionManagementMessage.Delete message)
{
_lastAccessed = _timeProvider.Now;
if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return;
Stop(() => DoDelete(message));
}
public void Handle(CoreProjectionManagementMessage.Started message)
{
_state = ManagedProjectionState.Running;
if (_onStarted != null)
{
var action = _onStarted;
_onStarted = null;
action();
}
}
public void Handle(CoreProjectionManagementMessage.Stopped message)
{
_state = message.Completed ? ManagedProjectionState.Completed : ManagedProjectionState.Stopped;
OnStoppedOrFaulted();
}
private void OnStoppedOrFaulted()
{
FireStoppedOrFaulted();
}
private void FireStoppedOrFaulted()
{
var stopCompleted = _onStopped;
_onStopped = null;
if (stopCompleted != null) stopCompleted();
}
public void Handle(CoreProjectionManagementMessage.Faulted message)
{
SetFaulted(message.FaultedReason);
if (_state == ManagedProjectionState.Preparing)
{
// cannot prepare - thus we don't know source defintion
_persistedState.SourceDefinition = null;
OnPrepared();
}
OnStoppedOrFaulted();
}
public void Handle(CoreProjectionManagementMessage.Prepared message)
{
_persistedState.SourceDefinition = message.SourceDefinition;
if (_state == ManagedProjectionState.Preparing)
{
_state = ManagedProjectionState.Prepared;
OnPrepared();
}
else
{
_logger.Trace("Received prepared without being prepared");
}
}
public void Handle(CoreProjectionManagementMessage.StateReport message)
{
_getStateDispatcher.Handle(message);
}
public void Handle(CoreProjectionManagementMessage.ResultReport message)
{
_getResultDispatcher.Handle(message);
}
public void Handle(CoreProjectionManagementMessage.StatisticsReport message)
{
_lastReceivedStatistics = message.Statistics;
}
public void Handle(ProjectionManagementMessage.Internal.CleanupExpired message)
{
//TODO: configurable expiration
if (IsExpiredProjection())
{
if (_state == ManagedProjectionState.Creating)
{
// NOTE: workaround for stop not working on creating state (just ignore them)
return;
}
Stop(
() =>
Handle(
new ProjectionManagementMessage.Delete(
new NoopEnvelope(), _name, ProjectionManagementMessage.RunAs.System, false, false)));
}
}
private bool IsExpiredProjection()
{
return Mode == ProjectionMode.Transient && !_isSlave && _lastAccessed.AddMinutes(5) < _timeProvider.Now;
}
public void InitializeNew(Action completed, PersistedState persistedState)
{
LoadPersistedState(persistedState);
UpdateProjectionVersion();
Prepare(() => BeginWrite(() => StartOrLoadStopped(completed)));
}
public static SerializedRunAs SerializePrincipal(ProjectionManagementMessage.RunAs runAs)
{
if (runAs.Principal == null)
return null; // anonymous
if (runAs.Principal == SystemAccount.Principal)
return new SerializedRunAs {Name = "$system"};
var genericPrincipal = runAs.Principal as OpenGenericPrincipal;
if (genericPrincipal == null)
throw new ArgumentException(
"OpenGenericPrincipal is the only supported principal type in projections", "runAs");
return new SerializedRunAs {Name = runAs.Principal.Identity.Name, Roles = genericPrincipal.Roles};
}
public void InitializeExisting(string name)
{
_state = ManagedProjectionState.Loading;
BeginLoad(name);
}
private void BeginLoad(string name)
{
var corrId = Guid.NewGuid();
_readDispatcher.Publish(
new ClientMessage.ReadStreamEventsBackward(
corrId, corrId, _readDispatcher.Envelope, "$projections-" + name, -1, 1,
resolveLinkTos: false, requireMaster: false, validationStreamVersion: null, user: SystemAccount.Principal),
LoadCompleted);
}
private void LoadCompleted(ClientMessage.ReadStreamEventsBackwardCompleted completed)
{
if (completed.Result == ReadStreamResult.Success && completed.Events.Length == 1)
{
byte[] state = completed.Events[0].Event.Data;
var persistedState = state.ParseJson<PersistedState>();
_lastWrittenVersion = completed.Events[0].Event.EventNumber;
FixUpOldFormat(completed, persistedState);
FixupOldProjectionModes(persistedState);
FixUpOldProjectionRunAs(persistedState);
LoadPersistedState(persistedState);
//TODO: encapsulate this into managed projection
_state = ManagedProjectionState.Loaded;
if (Enabled && _enabledToRun)
{
if (Mode >= ProjectionMode.Continuous)
Prepare(() => Start(() => { }));
}
else
CreatePrepared(() => LoadStopped(() => { }));
return;
}
_state = ManagedProjectionState.Creating;
_logger.Trace(
"Projection manager did not find any projection configuration records in the {0} stream. Projection stays in CREATING state",
completed.EventStreamId);
}
private void FixUpOldProjectionRunAs(PersistedState persistedState)
{
if (persistedState.RunAs == null || string.IsNullOrEmpty(persistedState.RunAs.Name))
{
_runAs = SystemAccount.Principal;
persistedState.RunAs = SerializePrincipal(ProjectionManagementMessage.RunAs.System);
}
}
private void FixUpOldFormat(ClientMessage.ReadStreamEventsBackwardCompleted completed, PersistedState persistedState)
{
if (persistedState.Version == null)
{
persistedState.Version = completed.Events[0].Event.EventNumber;
persistedState.Epoch = -1;
}
if (_lastWrittenVersion > persistedState.Version)
persistedState.Version = _lastWrittenVersion;
}
private void FixupOldProjectionModes(PersistedState persistedState)
{
switch ((int) persistedState.Mode)
{
case 2: // old continuous
persistedState.Mode = ProjectionMode.Continuous;
break;
case 3: // old persistent
persistedState.Mode = ProjectionMode.Continuous;
persistedState.EmitEnabled = persistedState.EmitEnabled ?? true;
break;
}
}
private void LoadPersistedState(PersistedState persistedState)
{
var handlerType = persistedState.HandlerType;
var query = persistedState.Query;
if (handlerType == null) throw new ArgumentNullException("persistedState", "HandlerType");
if (query == null) throw new ArgumentNullException("persistedState", "Query");
if (handlerType == "") throw new ArgumentException("HandlerType", "persistedState");
if (_state != ManagedProjectionState.Creating && _state != ManagedProjectionState.Loading)
throw new InvalidOperationException("LoadPersistedState is now allowed in this state");
_persistedState = persistedState;
_runAs = DeserializePrincipal(persistedState.RunAs);
}
private IPrincipal DeserializePrincipal(SerializedRunAs runAs)
{
if (runAs == null)
return null;
if (runAs.Name == null)
return null;
if (runAs.Name == "$system") //TODO: make sure nobody else uses it
return SystemAccount.Principal;
return new OpenGenericPrincipal(new GenericIdentity(runAs.Name), runAs.Roles);
}
private void OnPrepared()
{
if (_onPrepared != null)
{
var action = _onPrepared;
_onPrepared = null;
action();
}
}
private void BeginWrite(Action completed)
{
if (Mode == ProjectionMode.Transient)
{
//TODO: move to common completion procedure
_lastWrittenVersion = _persistedState.Version ?? -1;
completed();
return;
}
var oldState = _state;
_state = ManagedProjectionState.Writing;
var managedProjectionSerializedState = _persistedState.ToJsonBytes();
var eventStreamId = "$projections-" + _name;
var corrId = Guid.NewGuid();
_writeDispatcher.Publish(
new ClientMessage.WriteEvents(
corrId, corrId, _writeDispatcher.Envelope, true, eventStreamId, ExpectedVersion.Any,
new Event(Guid.NewGuid(), "$ProjectionUpdated", true, managedProjectionSerializedState, Empty.ByteArray),
SystemAccount.Principal),
m => WriteCompleted(m, oldState, completed, eventStreamId));
}
private void WriteCompleted(
ClientMessage.WriteEventsCompleted message, ManagedProjectionState completedState, Action completed,
string eventStreamId)
{
if (_state != ManagedProjectionState.Writing)
{
_logger.Error("Projection definition write completed in non writing state. ({0})", _name);
}
if (message.Result == OperationResult.Success)
{
_logger.Info("'{0}' projection source has been written", _name);
var writtenEventNumber = message.FirstEventNumber;
if (writtenEventNumber != (_persistedState.Version ?? writtenEventNumber))
throw new Exception("Projection version and event number mismatch");
_lastWrittenVersion = (_persistedState.Version ?? writtenEventNumber);
_state = completedState;
if (completed != null) completed();
return;
}
_logger.Info(
"Projection '{0}' source has not been written to {1}. Error: {2}", _name, eventStreamId,
Enum.GetName(typeof (OperationResult), message.Result));
if (message.Result == OperationResult.CommitTimeout || message.Result == OperationResult.ForwardTimeout
|| message.Result == OperationResult.PrepareTimeout
|| message.Result == OperationResult.WrongExpectedVersion)
{
_logger.Info("Retrying write projection source for {0}", _name);
BeginWrite(completed);
}
else
throw new NotSupportedException("Unsupported error code received");
}
private void Prepare(Action onPrepared)
{
var config = CreateDefaultProjectionConfiguration();
DisposeCoreProjection();
BeginCreateAndPrepare(_projectionStateHandlerFactory, config, onPrepared);
}
private void CreatePrepared(Action onPrepared)
{
var config = CreateDefaultProjectionConfiguration();
DisposeCoreProjection();
BeginCreatePrepared(config, onPrepared);
}
private void Start(Action completed)
{
if (!Enabled)
throw new InvalidOperationException("Projection is disabled");
_onStopped = _onStarted = () =>
{
_onStopped = null;
_onStarted = null;
if (completed != null)
completed();
};
_state = ManagedProjectionState.Starting;
_coreQueue.Publish(new CoreProjectionManagementMessage.Start(Id));
}
private void LoadStopped(Action onLoaded)
{
_onStopped = onLoaded;
_state = ManagedProjectionState.LoadingState;
_coreQueue.Publish(new CoreProjectionManagementMessage.LoadStopped(Id));
}
private void DisposeCoreProjection()
{
_coreQueue.Publish(new CoreProjectionManagementMessage.Dispose(Id));
}
/// <summary>
/// Enables managed projection, but does not automatically start it
/// </summary>
private void Enable()
{
if (Enabled)
throw new InvalidOperationException("Projection is not disabled");
Enabled = true;
}
/// <summary>
/// Disables managed projection, but does not automatically stop it
/// </summary>
private void Disable()
{
if (!Enabled)
throw new InvalidOperationException("Projection is not enabled");
Enabled = false;
}
private void Delete()
{
Deleted = true;
}
private void BeginCreateAndPrepare(
ProjectionStateHandlerFactory handlerFactory, ProjectionConfig config, Action onPrepared)
{
_onPrepared = _onStopped = () =>
{
_onStopped = null;
_onPrepared = null;
if (onPrepared != null)
onPrepared();
};
if (handlerFactory == null) throw new ArgumentNullException("handlerFactory");
if (config == null) throw new ArgumentNullException("config");
//TODO: which states are allowed here?
if (_state >= ManagedProjectionState.Preparing)
{
DisposeCoreProjection();
_state = ManagedProjectionState.Loaded;
}
//TODO: load configuration from the definition
Func<IProjectionStateHandler> stateHandlerFactory = delegate
{
// this delegate runs in the context of a projection core thread
// TODO: move this code to the projection core service as we may be in different processes in the future
IProjectionStateHandler stateHandler = null;
try
{
stateHandler = handlerFactory.Create(
HandlerType, Query, logger: s => _logger.Trace(s),
cancelCallbackFactory:
_timeoutScheduler == null
? (Action<int, Action>) null
: _timeoutScheduler.Schedule);
return stateHandler;
}
catch (Exception ex)
{
SetFaulted(
string.Format(
"Cannot create a projection state handler.\r\n\r\nHandler type: {0}\r\nQuery:\r\n\r\n{1}\r\n\r\nMessage:\r\n\r\n{2}",
HandlerType, Query, ex.Message), ex);
if (stateHandler != null)
stateHandler.Dispose();
throw;
}
};
var createProjectionMessage = _isSlave ?
(Message) new CoreProjectionManagementMessage.CreateAndPrepareSlave(
new PublishEnvelope(_inputQueue), Id, _name,
new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 0),
config, _slaveResultsPublisher, _slaveMasterCorrelationId, stateHandlerFactory) :
new CoreProjectionManagementMessage.CreateAndPrepare(
new PublishEnvelope(_inputQueue), Id, _name,
new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 0),
config, HandlerType, Query, stateHandlerFactory);
//note: set runnign before start as coreProjection.start() can respond with faulted
_state = ManagedProjectionState.Preparing;
_coreQueue.Publish(createProjectionMessage);
}
private void BeginCreatePrepared(ProjectionConfig config, Action onPrepared)
{
_onPrepared = onPrepared;
if (config == null) throw new ArgumentNullException("config");
//TODO: which states are allowed here?
if (_state >= ManagedProjectionState.Preparing)
{
DisposeCoreProjection();
_state = ManagedProjectionState.Loaded;
}
//TODO: load configuration from the definition
if (_persistedState.SourceDefinition == null)
throw new Exception(
"The projection cannot be loaded as stopped as it was stored in the old format. Update the projection query text to force prepare");
var createProjectionMessage =
new CoreProjectionManagementMessage.CreatePrepared(
new PublishEnvelope(_inputQueue), Id, _name,
new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 1),
config, _persistedState.SourceDefinition, HandlerType, Query);
//note: set running before start as coreProjection.start() can respond with faulted
_state = ManagedProjectionState.Preparing;
_coreQueue.Publish(createProjectionMessage);
}
private void Stop(Action completed)
{
switch (_state)
{
case ManagedProjectionState.Stopped:
case ManagedProjectionState.Completed:
case ManagedProjectionState.Faulted:
case ManagedProjectionState.Loaded:
if (completed != null) completed();
return;
case ManagedProjectionState.Loading:
case ManagedProjectionState.Creating:
throw new InvalidOperationException(
string.Format(
"Cannot stop a projection in the '{0}' state",
Enum.GetName(typeof (ManagedProjectionState), _state)));
case ManagedProjectionState.Stopping:
_onStopped += completed;
return;
case ManagedProjectionState.Running:
case ManagedProjectionState.Starting:
_state = ManagedProjectionState.Stopping;
_onStopped = completed;
_coreQueue.Publish(new CoreProjectionManagementMessage.Stop(Id));
break;
default:
throw new NotSupportedException();
}
}
private void Abort(Action completed)
{
switch (_state)
{
case ManagedProjectionState.Stopped:
case ManagedProjectionState.Completed:
case ManagedProjectionState.Faulted:
case ManagedProjectionState.Loaded:
if (completed != null) completed();
return;
case ManagedProjectionState.Loading:
case ManagedProjectionState.Creating:
throw new InvalidOperationException(
string.Format(
"Cannot stop a projection in the '{0}' state",
Enum.GetName(typeof (ManagedProjectionState), _state)));
case ManagedProjectionState.Stopping:
_onStopped = completed;
_coreQueue.Publish(new CoreProjectionManagementMessage.Kill(Id));
return;
case ManagedProjectionState.Running:
case ManagedProjectionState.Starting:
_state = ManagedProjectionState.Stopping;
_onStopped = completed;
_coreQueue.Publish(new CoreProjectionManagementMessage.Kill(Id));
break;
default:
throw new NotSupportedException();
}
}
private void SetFaulted(string reason, Exception ex = null)
{
if (ex != null)
_logger.ErrorException(ex, "The '{0}' projection faulted due to '{1}'", _name, reason);
else
_logger.Error("The '{0}' projection faulted due to '{1}'", _name, reason);
_state = ManagedProjectionState.Faulted;
_faultedReason = reason;
}
private ProjectionConfig CreateDefaultProjectionConfiguration()
{
var checkpointsEnabled = _persistedState.CheckpointsDisabled != true;
var checkpointHandledThreshold = checkpointsEnabled ? 4000 : 0;
var checkpointUnhandledBytesThreshold = checkpointsEnabled ? 10*1000*1000 : 0;
var pendingEventsThreshold = 5000;
var maxWriteBatchLength = 500;
var emitEventEnabled = _persistedState.EmitEnabled == true;
var createTempStreams = _persistedState.CreateTempStreams == true;
var stopOnEof = _persistedState.Mode <= ProjectionMode.OneTime;
var projectionConfig = new ProjectionConfig(
_runAs, checkpointHandledThreshold, checkpointUnhandledBytesThreshold, pendingEventsThreshold,
maxWriteBatchLength, emitEventEnabled, checkpointsEnabled, createTempStreams, stopOnEof,
isSlaveProjection: false);
return projectionConfig;
}
private void StartOrLoadStopped(Action completed)
{
if (_state == ManagedProjectionState.Prepared || _state == ManagedProjectionState.Writing)
{
if (Enabled && _enabledToRun)
Start(completed);
else
LoadStopped(completed);
}
else if (completed != null)
completed();
}
private void DoUpdateQuery(ProjectionManagementMessage.UpdateQuery message)
{
_persistedState.HandlerType = message.HandlerType ?? HandlerType;
_persistedState.Query = message.Query;
_persistedState.EmitEnabled = message.EmitEnabled ?? _persistedState.EmitEnabled;
if (_state == ManagedProjectionState.Completed)
{
ResetProjection();
}
Action completed = () =>
{
StartOrLoadStopped(() => { });
message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name));
};
UpdateProjectionVersion();
Prepare(() => BeginWrite(completed));
}
private void DoDisable(IEnvelope envelope, string name)
{
if (!Enabled)
{
envelope.ReplyWith(new ProjectionManagementMessage.OperationFailed("Not enabled"));
return;
}
Disable();
Action completed = () => envelope.ReplyWith(new ProjectionManagementMessage.Updated(name));
UpdateProjectionVersion();
if (Enabled)
Prepare(() => BeginWrite(completed));
else
BeginWrite(completed);
}
private void DoDelete(ProjectionManagementMessage.Delete message)
{
if (Enabled)
Disable();
Delete();
Action completed = () =>
{
message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(_name));
DisposeCoreProjection();
_output.Publish(new ProjectionManagementMessage.Internal.Deleted(_name, Id));
};
UpdateProjectionVersion();
if (Enabled)
Prepare(() => BeginWrite(completed));
else
BeginWrite(completed);
}
private void UpdateProjectionVersion(bool force = false)
{
if (_lastWrittenVersion == _persistedState.Version)
_persistedState.Version++;
else if (force)
throw new ApplicationException("Internal error: projection definition must be saved before forced updating version");
}
public void Handle(ProjectionManagementMessage.GetState message)
{
_lastAccessed = _timeProvider.Now;
if (_state >= ManagedProjectionState.Stopped)
{
_getStateDispatcher.Publish(
new CoreProjectionManagementMessage.GetState(
new PublishEnvelope(_inputQueue), Guid.NewGuid(), Id, message.Partition),
m =>
message.Envelope.ReplyWith(
new ProjectionManagementMessage.ProjectionState(_name, m.Partition, m.State, m.Position)));
}
else
{
message.Envelope.ReplyWith(
new ProjectionManagementMessage.ProjectionState(
message.Name, message.Partition, "*** UNKNOWN ***", position: null));
}
}
public void Handle(CoreProjectionManagementMessage.SlaveProjectionReaderAssigned message)
{
_slaveProjectionSubscriptionId = message.SubscriptionId;
}
}
public class SerializedRunAs
{
public string Name { get; set; }
public string[] Roles { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
#if INSIDE_CLR
internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
#endif
// The minimum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using System.Text.RegularExpressions;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Settings.Configuration.Assemblies;
namespace Serilog.Settings.Configuration
{
class ConfigurationReader : IConfigurationReader
{
const string LevelSwitchNameRegex = @"^\$[A-Za-z]+[A-Za-z0-9]*$";
readonly IConfigurationSection _section;
readonly IReadOnlyCollection<Assembly> _configurationAssemblies;
readonly ResolutionContext _resolutionContext;
public ConfigurationReader(IConfigurationSection configSection, AssemblyFinder assemblyFinder, IConfiguration configuration = null)
{
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_configurationAssemblies = LoadConfigurationAssemblies(_section, assemblyFinder);
_resolutionContext = new ResolutionContext(configuration);
}
// Used internally for processing nested configuration sections -- see GetMethodCalls below.
internal ConfigurationReader(IConfigurationSection configSection, IReadOnlyCollection<Assembly> configurationAssemblies, ResolutionContext resolutionContext)
{
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_configurationAssemblies = configurationAssemblies ?? throw new ArgumentNullException(nameof(configurationAssemblies));
_resolutionContext = resolutionContext ?? throw new ArgumentNullException(nameof(resolutionContext));
}
public void Configure(LoggerConfiguration loggerConfiguration)
{
ProcessLevelSwitchDeclarations();
ApplyMinimumLevel(loggerConfiguration);
ApplyEnrichment(loggerConfiguration);
ApplyFilters(loggerConfiguration);
ApplyDestructuring(loggerConfiguration);
ApplySinks(loggerConfiguration);
ApplyAuditSinks(loggerConfiguration);
}
void ProcessLevelSwitchDeclarations()
{
var levelSwitchesDirective = _section.GetSection("LevelSwitches");
foreach (var levelSwitchDeclaration in levelSwitchesDirective.GetChildren())
{
var switchName = levelSwitchDeclaration.Key;
var switchInitialLevel = levelSwitchDeclaration.Value;
// switchName must be something like $switch to avoid ambiguities
if (!IsValidSwitchName(switchName))
{
throw new FormatException($"\"{switchName}\" is not a valid name for a Level Switch declaration. Level switch must be declared with a '$' sign, like \"LevelSwitches\" : {{\"$switchName\" : \"InitialLevel\"}}");
}
LoggingLevelSwitch newSwitch;
if (string.IsNullOrEmpty(switchInitialLevel))
{
newSwitch = new LoggingLevelSwitch();
}
else
{
var initialLevel = ParseLogEventLevel(switchInitialLevel);
newSwitch = new LoggingLevelSwitch(initialLevel);
}
SubscribeToLoggingLevelChanges(levelSwitchDeclaration, newSwitch);
// make them available later on when resolving argument values
_resolutionContext.AddLevelSwitch(switchName, newSwitch);
}
}
void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration)
{
var minimumLevelDirective = _section.GetSection("MinimumLevel");
var defaultMinLevelDirective = minimumLevelDirective.Value != null ? minimumLevelDirective : minimumLevelDirective.GetSection("Default");
if (defaultMinLevelDirective.Value != null)
{
ApplyMinimumLevel(defaultMinLevelDirective, (configuration, levelSwitch) => configuration.ControlledBy(levelSwitch));
}
var minLevelControlledByDirective = minimumLevelDirective.GetSection("ControlledBy");
if (minLevelControlledByDirective.Value != null)
{
var globalMinimumLevelSwitch = _resolutionContext.LookUpSwitchByName(minLevelControlledByDirective.Value);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
loggerConfiguration.MinimumLevel.ControlledBy(globalMinimumLevelSwitch);
}
foreach (var overrideDirective in minimumLevelDirective.GetSection("Override").GetChildren())
{
var overridePrefix = overrideDirective.Key;
var overridenLevelOrSwitch = overrideDirective.Value;
if (Enum.TryParse(overridenLevelOrSwitch, out LogEventLevel _))
{
ApplyMinimumLevel(overrideDirective, (configuration, levelSwitch) => configuration.Override(overridePrefix, levelSwitch));
}
else
{
var overrideSwitch = _resolutionContext.LookUpSwitchByName(overridenLevelOrSwitch);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
loggerConfiguration.MinimumLevel.Override(overridePrefix, overrideSwitch);
}
}
void ApplyMinimumLevel(IConfigurationSection directive, Action<LoggerMinimumLevelConfiguration, LoggingLevelSwitch> applyConfigAction)
{
var minimumLevel = ParseLogEventLevel(directive.Value);
var levelSwitch = new LoggingLevelSwitch(minimumLevel);
applyConfigAction(loggerConfiguration.MinimumLevel, levelSwitch);
SubscribeToLoggingLevelChanges(directive, levelSwitch);
}
}
void SubscribeToLoggingLevelChanges(IConfigurationSection levelSection, LoggingLevelSwitch levelSwitch)
{
ChangeToken.OnChange(
levelSection.GetReloadToken,
() =>
{
if (Enum.TryParse(levelSection.Value, out LogEventLevel minimumLevel))
levelSwitch.MinimumLevel = minimumLevel;
else
SelfLog.WriteLine($"The value {levelSection.Value} is not a valid Serilog level.");
});
}
void ApplyFilters(LoggerConfiguration loggerConfiguration)
{
var filterDirective = _section.GetSection("Filter");
if (filterDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(filterDirective);
CallConfigurationMethods(methodCalls, FindFilterConfigurationMethods(_configurationAssemblies), loggerConfiguration.Filter);
}
}
void ApplyDestructuring(LoggerConfiguration loggerConfiguration)
{
var destructureDirective = _section.GetSection("Destructure");
if (destructureDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(destructureDirective);
CallConfigurationMethods(methodCalls, FindDestructureConfigurationMethods(_configurationAssemblies), loggerConfiguration.Destructure);
}
}
void ApplySinks(LoggerConfiguration loggerConfiguration)
{
var writeToDirective = _section.GetSection("WriteTo");
if (writeToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(writeToDirective);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.WriteTo);
}
}
void ApplyAuditSinks(LoggerConfiguration loggerConfiguration)
{
var auditToDirective = _section.GetSection("AuditTo");
if (auditToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(auditToDirective);
CallConfigurationMethods(methodCalls, FindAuditSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.AuditTo);
}
}
void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration)
{
var methodCalls = GetMethodCalls(_section);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerSinkConfiguration);
}
void ApplyEnrichment(LoggerConfiguration loggerConfiguration)
{
var enrichDirective = _section.GetSection("Enrich");
if (enrichDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(enrichDirective);
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerConfiguration.Enrich);
}
var propertiesDirective = _section.GetSection("Properties");
if (propertiesDirective.GetChildren().Any())
{
foreach (var enrichProperyDirective in propertiesDirective.GetChildren())
{
loggerConfiguration.Enrich.WithProperty(enrichProperyDirective.Key, enrichProperyDirective.Value);
}
}
}
internal ILookup<string, Dictionary<string, IConfigurationArgumentValue>> GetMethodCalls(IConfigurationSection directive)
{
var children = directive.GetChildren().ToList();
var result =
(from child in children
where child.Value != null // Plain string
select new { Name = child.Value, Args = new Dictionary<string, IConfigurationArgumentValue>() })
.Concat(
(from child in children
where child.Value == null
let name = GetSectionName(child)
let callArgs = (from argument in child.GetSection("Args").GetChildren()
select new
{
Name = argument.Key,
Value = GetArgumentValue(argument)
}).ToDictionary(p => p.Name, p => p.Value)
select new { Name = name, Args = callArgs }))
.ToLookup(p => p.Name, p => p.Args);
return result;
IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection)
{
IConfigurationArgumentValue argumentValue;
// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");
if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, _configurationAssemblies);
}
return argumentValue;
}
string GetSectionName(IConfigurationSection s)
{
var name = s.GetSection("Name");
if (name.Value == null)
throw new InvalidOperationException($"The configuration value in {name.Path} has no 'Name' element.");
return name.Value;
}
}
static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfigurationSection section, AssemblyFinder assemblyFinder)
{
var assemblies = new Dictionary<string, Assembly>();
var usingSection = section.GetSection("Using");
if (usingSection.GetChildren().Any())
{
foreach (var simpleName in usingSection.GetChildren().Select(c => c.Value))
{
if (string.IsNullOrWhiteSpace(simpleName))
throw new InvalidOperationException(
"A zero-length or whitespace assembly name was supplied to a Serilog.Using configuration statement.");
var assembly = Assembly.Load(new AssemblyName(simpleName));
if (!assemblies.ContainsKey(assembly.FullName))
assemblies.Add(assembly.FullName, assembly);
}
}
foreach (var assemblyName in assemblyFinder.FindAssembliesContainingName("serilog"))
{
var assumed = Assembly.Load(assemblyName);
if (assumed != null && !assemblies.ContainsKey(assumed.FullName))
assemblies.Add(assumed.FullName, assumed);
}
return assemblies.Values.ToList().AsReadOnly();
}
void CallConfigurationMethods(ILookup<string, Dictionary<string, IConfigurationArgumentValue>> methods, IList<MethodInfo> configurationMethods, object receiver)
{
foreach (var method in methods.SelectMany(g => g.Select(x => new { g.Key, Value = x })))
{
var methodInfo = SelectConfigurationMethod(configurationMethods, method.Key, method.Value.Keys);
if (methodInfo != null)
{
var call = (from p in methodInfo.GetParameters().Skip(1)
let directive = method.Value.FirstOrDefault(s => ParameterNameMatches(p.Name, s.Key))
select directive.Key == null
? GetImplicitValueForNotSpecifiedKey(p, methodInfo)
: directive.Value.ConvertTo(p.ParameterType, _resolutionContext)).ToList();
call.Insert(0, receiver);
methodInfo.Invoke(null, call.ToArray());
}
}
}
static bool HasImplicitValueWhenNotSpecified(ParameterInfo paramInfo)
{
return paramInfo.HasDefaultValue
// parameters of type IConfiguration are implicitly populated with provided Configuration
|| paramInfo.ParameterType == typeof(IConfiguration);
}
object GetImplicitValueForNotSpecifiedKey(ParameterInfo parameter, MethodInfo methodToInvoke)
{
if (!HasImplicitValueWhenNotSpecified(parameter))
{
throw new InvalidOperationException("GetImplicitValueForNotSpecifiedKey() should only be called for parameters for which HasImplicitValueWhenNotSpecified() is true. " +
"This means something is wrong in the Serilog.Settings.Configuration code.");
}
if (parameter.ParameterType == typeof(IConfiguration))
{
if (_resolutionContext.HasAppConfiguration)
{
return _resolutionContext.AppConfiguration;
}
if (parameter.HasDefaultValue)
{
return parameter.DefaultValue;
}
throw new InvalidOperationException("Trying to invoke a configuration method accepting a `IConfiguration` argument. " +
$"This is not supported when only a `IConfigSection` has been provided. (method '{methodToInvoke}')");
}
return parameter.DefaultValue;
}
internal static MethodInfo SelectConfigurationMethod(IEnumerable<MethodInfo> candidateMethods, string name, IEnumerable<string> suppliedArgumentNames)
{
// Per issue #111, it is safe to use case-insensitive matching on argument names. The CLR doesn't permit this type
// of overloading, and the Microsoft.Extensions.Configuration keys are case-insensitive (case is preserved with some
// config sources, but key-matching is case-insensitive and case-preservation does not appear to be guaranteed).
var selectedMethod = candidateMethods
.Where(m => m.Name == name)
.Where(m => m.GetParameters()
.Skip(1)
.All(p => HasImplicitValueWhenNotSpecified(p) ||
ParameterNameMatches(p.Name, suppliedArgumentNames)))
.OrderByDescending(m =>
{
var matchingArgs = m.GetParameters().Where(p => ParameterNameMatches(p.Name, suppliedArgumentNames)).ToList();
// Prefer the configuration method with most number of matching arguments and of those the ones with
// the most string type parameters to predict best match with least type casting
return new Tuple<int, int>(
matchingArgs.Count,
matchingArgs.Count(p => p.ParameterType == typeof(string)));
})
.FirstOrDefault();
if (selectedMethod == null)
{
var methodsByName = candidateMethods
.Where(m => m.Name == name)
.Select(m => $"{m.Name}({string.Join(", ", m.GetParameters().Skip(1).Select(p => p.Name))})")
.ToList();
if (!methodsByName.Any())
SelfLog.WriteLine($"Unable to find a method called {name}. Candidate methods are:{Environment.NewLine}{string.Join(Environment.NewLine, candidateMethods)}");
else
SelfLog.WriteLine($"Unable to find a method called {name} "
+ (suppliedArgumentNames.Any()
? "for supplied arguments: " + string.Join(", ", suppliedArgumentNames)
: "with no supplied arguments")
+ ". Candidate methods are:"
+ Environment.NewLine
+ string.Join(Environment.NewLine, methodsByName));
}
return selectedMethod;
}
static bool ParameterNameMatches(string actualParameterName, string suppliedName)
{
return suppliedName.Equals(actualParameterName, StringComparison.OrdinalIgnoreCase);
}
static bool ParameterNameMatches(string actualParameterName, IEnumerable<string> suppliedNames)
{
return suppliedNames.Any(s => ParameterNameMatches(actualParameterName, s));
}
static IList<MethodInfo> FindSinkConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerSinkConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerSinkConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.WriteTo);
return found;
}
static IList<MethodInfo> FindAuditSinkConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerAuditSinkConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerAuditSinkConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.AuditTo);
return found;
}
static IList<MethodInfo> FindFilterConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerFilterConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerFilterConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Filter);
return found;
}
static IList<MethodInfo> FindDestructureConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerDestructuringConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerDestructuringConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Destructure);
return found;
}
static IList<MethodInfo> FindEventEnricherConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerEnrichmentConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerEnrichmentConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Enrich);
return found;
}
static List<MethodInfo> FindConfigurationExtensionMethods(IReadOnlyCollection<Assembly> configurationAssemblies, Type configType)
{
return configurationAssemblies
.SelectMany(a => a.ExportedTypes
.Select(t => t.GetTypeInfo())
.Where(t => t.IsSealed && t.IsAbstract && !t.IsNested))
.SelectMany(t => t.DeclaredMethods)
.Where(m => m.IsStatic && m.IsPublic && m.IsDefined(typeof(ExtensionAttribute), false))
.Where(m => m.GetParameters()[0].ParameterType == configType)
.ToList();
}
internal static bool IsValidSwitchName(string input)
{
return Regex.IsMatch(input, LevelSwitchNameRegex);
}
static LogEventLevel ParseLogEventLevel(string value)
{
if (!Enum.TryParse(value, out LogEventLevel parsedLevel))
throw new InvalidOperationException($"The value {value} is not a valid Serilog level.");
return parsedLevel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public class TestManager
{
[SerializeField]
private static bool reloadTestList = true;
private static DateTime nextIvalidateTime = DateTime.Now;
[SerializeField]
private List<TestResult> testList = new List<TestResult>();
public IList<TestResult> GetAllTestsResults ()
{
TryToReload ();
return testList.ToList();
}
private void TryToReload ()
{
if (reloadTestList && nextIvalidateTime <= DateTime.Now)
{
var foundTestList = GetAllTestGameObjects ();
var newTestList = new List<TestResult> ();
foreach (var gameObject in foundTestList)
{
var result = testList.Find (t => t.go == gameObject);
if (result != null)
{
result.name = result.go.name;
newTestList.Add (result);
}
else
newTestList.Add (new TestResult (gameObject));
}
testList = newTestList;
SortTestList ();
reloadTestList = false;
nextIvalidateTime = DateTime.Now.AddSeconds (1);
}
}
public TestResult AddTest ()
{
var go = new GameObject ();
go.name = "New Test";
go.AddComponent<TestComponent>();
ShowTestInHierarchy (go, true);
var testResult = new TestResult (go);
testList.Add(testResult);
SortTestList ();
return testResult;
}
private void SortTestList ()
{
testList.Sort((t1, t2) =>
{
var result = t1.go.name.CompareTo (t2.go.name);
if(result == 0)
result = t1.go.GetInstanceID ().CompareTo(t2.go.GetInstanceID ());
return result;
});
}
public void ClearTestList ()
{
testList.Clear ();
InvalidateTestList ();
}
public void DeleteTest(List<TestResult> tests)
{
foreach (var test in tests)
{
GameObject.DestroyImmediate(test.go);
testList.Remove (test);
}
}
public static void InvalidateTestList ()
{
nextIvalidateTime = DateTime.Now;
reloadTestList = true;
}
public TestResult GetResultFor (GameObject testInfo)
{
if(reloadTestList) TryToReload ();
try{
return testList.Single (result => result.go == testInfo);
}catch(Exception)
{
InvalidateTestList();
TryToReload();
return testList.SingleOrDefault(result => result.go == testInfo);
}
}
public void UpdateResults (List<TestResult> tests)
{
foreach (var testResult in tests)
{
var idx = testList.FindIndex (result => result.id == testResult.id);
testList[idx] = testResult;
}
}
#region Static methods
public static void ShowOrHideTestInHierarchy (bool hideTestsInHierarchy)
{
foreach (var t in GetAllTestGameObjects ())
{
var a = t.activeInHierarchy;
t.SetActive (true);
ShowTestInHierarchy(t.gameObject, !hideTestsInHierarchy);
t.SetActive (a);
}
}
public static GameObject FindTopGameObject (GameObject go)
{
while (go.transform.parent != null)
go = go.transform.parent.gameObject;
return go;
}
public static bool AnyTestsOnScene ()
{
return GetAllTestGameObjects ().Any ();
}
public static void SelectInHierarchy (GameObject test, bool hideTestsInHierarchy)
{
foreach (var t in GetAllTestGameObjects ())
{
t.gameObject.SetActive(t == test);
if (hideTestsInHierarchy)
ShowTestInHierarchy(t.gameObject, t == test);
}
}
public static void DisableAllTests ()
{
foreach (var t in GetAllTestGameObjects ())
{
t.gameObject.SetActive (true);
ShowTestInHierarchy (t.gameObject, true);
t.gameObject.SetActive (false);
}
}
public static void ShowTestInHierarchy (GameObject gameObject, bool show)
{
if (show)
gameObject.hideFlags &= ~HideFlags.HideInHierarchy;
else
gameObject.hideFlags |= HideFlags.HideInHierarchy;
gameObject.hideFlags |= HideFlags.NotEditable;
gameObject.transform.hideFlags |= HideFlags.HideInInspector;
var c = gameObject.GetComponent<TestComponent>();
if(c!=null) c.hideFlags = 0;
EditorUtility.SetDirty(gameObject);
}
public static List<GameObject> GetAllTestGameObjects ()
{
var resultArray = Resources.FindObjectsOfTypeAll (typeof (TestComponent)) as TestComponent[];
var foundTestList = new List<GameObject> (resultArray.Select (component => component.gameObject));
return foundTestList;
}
#endregion
public IEnumerable<TestResult> GetTestsToSelect (List<TestResult> selectedTests, TestResult testToSelect)
{
TestResult start = null;
TestResult end = null;
for (int i = testList.Count-1; i >=0 ; i--)
{
var testResult = testList[i];
if (start==null)
{
if (testResult == testToSelect)
start = testToSelect;
else if (selectedTests.Contains (testResult))
start = testResult;
}else if(testResult == testToSelect)
{
end = testToSelect;
break;
}
if(start!=null)
{
if (testResult == testToSelect)
end = testToSelect;
else if (selectedTests.Contains(testResult))
end = testResult;
}
}
var startIdx = testList.IndexOf (start);
var endIdx = testList.IndexOf (end);
return testList.GetRange(endIdx, startIdx-endIdx+1);
}
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace APproject {
public class Token {
public int kind; // token kind
public int pos; // token position in bytes in the source text (starting at 0)
public int charPos; // token position in characters in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
public class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
stream.Close();
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
// beg .. begin, zero-based, inclusive, in byte
// end .. end, zero-based, exclusive, in byte
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
public class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 40;
const int noSym = 40;
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int charPos; // position by unicode characters starting with 0
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Hashtable start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Hashtable(128);
for (int i = 65; i <= 90; ++i) start[i] = 1;
for (int i = 97; i <= 122; ++i) start[i] = 1;
for (int i = 39; i <= 39; ++i) start[i] = 2;
for (int i = 48; i <= 57; ++i) start[i] = 10;
start[34] = 11;
start[40] = 16;
start[44] = 17;
start[41] = 18;
start[123] = 19;
start[125] = 20;
start[61] = 35;
start[59] = 21;
start[45] = 22;
start[43] = 23;
start[60] = 36;
start[62] = 37;
start[33] = 25;
start[38] = 29;
start[124] = 31;
start[42] = 33;
start[47] = 34;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0; charPos = -1;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0; charPos = -1;
NextCh();
}
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
// buffer reads unicode chars, if UTF8 has been detected
ch = buffer.Read(); col++; charPos++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = (char) ch;
NextCh();
}
}
bool Comment0() {
int level = 1, pos0 = pos, line0 = line, col0 = col, charPos0 = charPos;
NextCh();
if (ch == '/') {
NextCh();
for(;;) {
if (ch == 10) {
level--;
if (level == 0) { oldEols = line - line0; NextCh(); return true; }
NextCh();
} else if (ch == Buffer.EOF) return false;
else NextCh();
}
} else {
buffer.Pos = pos0; NextCh(); line = line0; col = col0; charPos = charPos0;
}
return false;
}
bool Comment1() {
int level = 1, pos0 = pos, line0 = line, col0 = col, charPos0 = charPos;
NextCh();
if (ch == '*') {
NextCh();
for(;;) {
if (ch == '*') {
NextCh();
if (ch == '/') {
level--;
if (level == 0) { oldEols = line - line0; NextCh(); return true; }
NextCh();
}
} else if (ch == '/') {
NextCh();
if (ch == '*') {
level++; NextCh();
}
} else if (ch == Buffer.EOF) return false;
else NextCh();
}
} else {
buffer.Pos = pos0; NextCh(); line = line0; col = col0; charPos = charPos0;
}
return false;
}
void CheckLiteral() {
switch (t.val) {
case "fun": t.kind = 5; break;
case "main": t.kind = 11; break;
case "async": t.kind = 13; break;
case "return": t.kind = 14; break;
case "dasync": t.kind = 16; break;
case "readln": t.kind = 17; break;
case "if": t.kind = 18; break;
case "else": t.kind = 19; break;
case "while": t.kind = 20; break;
case "println": t.kind = 21; break;
case "var": t.kind = 22; break;
case "true": t.kind = 24; break;
case "false": t.kind = 25; break;
case "int": t.kind = 26; break;
case "bool": t.kind = 27; break;
case "url": t.kind = 28; break;
default: break;
}
}
Token NextToken() {
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
if (ch == '/' && Comment0() ||ch == '/' && Comment1()) return NextToken();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line; t.charPos = charPos;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
recEnd = pos; recKind = 1;
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 1;}
else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;}
case 2:
if (ch == 'h') {AddCh(); goto case 3;}
else {goto case 0;}
case 3:
if (ch == 't') {AddCh(); goto case 4;}
else {goto case 0;}
case 4:
if (ch == 't') {AddCh(); goto case 5;}
else {goto case 0;}
case 5:
if (ch == 'p') {AddCh(); goto case 6;}
else {goto case 0;}
case 6:
if (ch == ':') {AddCh(); goto case 7;}
else {goto case 0;}
case 7:
if (ch == '/') {AddCh(); goto case 8;}
else {goto case 0;}
case 8:
if (ch == '/') {AddCh(); goto case 9;}
else {goto case 0;}
case 9:
if (ch == 39) {AddCh(); goto case 13;}
else if (ch <= 8 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '&' || ch >= '(' && ch <= 65535) {AddCh(); goto case 9;}
else {goto case 0;}
case 10:
recEnd = pos; recKind = 3;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 10;}
else {t.kind = 3; break;}
case 11:
if (ch <= 9 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '!' || ch >= '#' && ch <= '[' || ch >= ']' && ch <= 65535) {AddCh(); goto case 11;}
else if (ch == '"') {AddCh(); goto case 12;}
else if (ch == 92) {AddCh(); goto case 14;}
else {goto case 0;}
case 12:
{t.kind = 4; break;}
case 13:
recEnd = pos; recKind = 2;
if (ch == 39) {AddCh(); goto case 13;}
else if (ch <= 8 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '&' || ch >= '(' && ch <= 65535) {AddCh(); goto case 9;}
else {t.kind = 2; break;}
case 14:
if (ch <= 9 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '!' || ch >= '#' && ch <= '[' || ch >= ']' && ch <= 65535) {AddCh(); goto case 11;}
else if (ch == '"') {AddCh(); goto case 15;}
else if (ch == 92) {AddCh(); goto case 14;}
else {goto case 0;}
case 15:
recEnd = pos; recKind = 4;
if (ch <= 9 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '!' || ch >= '#' && ch <= '[' || ch >= ']' && ch <= 65535) {AddCh(); goto case 11;}
else if (ch == '"') {AddCh(); goto case 12;}
else if (ch == 92) {AddCh(); goto case 14;}
else {t.kind = 4; break;}
case 16:
{t.kind = 6; break;}
case 17:
{t.kind = 7; break;}
case 18:
{t.kind = 8; break;}
case 19:
{t.kind = 9; break;}
case 20:
{t.kind = 10; break;}
case 21:
{t.kind = 15; break;}
case 22:
{t.kind = 23; break;}
case 23:
{t.kind = 29; break;}
case 24:
{t.kind = 32; break;}
case 25:
if (ch == '=') {AddCh(); goto case 26;}
else {goto case 0;}
case 26:
{t.kind = 33; break;}
case 27:
{t.kind = 34; break;}
case 28:
{t.kind = 35; break;}
case 29:
if (ch == '&') {AddCh(); goto case 30;}
else {goto case 0;}
case 30:
{t.kind = 36; break;}
case 31:
if (ch == '|') {AddCh(); goto case 32;}
else {goto case 0;}
case 32:
{t.kind = 37; break;}
case 33:
{t.kind = 38; break;}
case 34:
{t.kind = 39; break;}
case 35:
recEnd = pos; recKind = 12;
if (ch == '=') {AddCh(); goto case 24;}
else {t.kind = 12; break;}
case 36:
recEnd = pos; recKind = 30;
if (ch == '=') {AddCh(); goto case 27;}
else {t.kind = 30; break;}
case 37:
recEnd = pos; recKind = 31;
if (ch == '=') {AddCh(); goto case 28;}
else {t.kind = 31; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col; charPos = t.charPos;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cluster
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Collections;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Cluster node implementation.
/// </summary>
internal class ClusterNodeImpl : IClusterNode
{
/** Node ID. */
private readonly Guid _id;
/** Attributes. */
private readonly IDictionary<string, object> _attrs;
/** Addresses. */
private readonly ICollection<string> _addrs;
/** Hosts. */
private readonly ICollection<string> _hosts;
/** Order. */
private readonly long _order;
/** Local flag. */
private readonly bool _isLocal;
/** Daemon flag. */
private readonly bool _isDaemon;
/** Client flag. */
private readonly bool _isClient;
/** Consistent id. */
private readonly object _consistentId;
/** Ignite version. */
private readonly IgniteProductVersion _version;
/** Metrics. */
private volatile ClusterMetricsImpl _metrics;
/** Ignite reference. */
private WeakReference _igniteRef;
/// <summary>
/// Initializes a new instance of the <see cref="ClusterNodeImpl"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
public ClusterNodeImpl(IBinaryRawReader reader)
{
var id = reader.ReadGuid();
Debug.Assert(id.HasValue);
_id = id.Value;
_attrs = ReadAttributes(reader);
_addrs = reader.ReadCollectionAsList<string>().AsReadOnly();
_hosts = reader.ReadCollectionAsList<string>().AsReadOnly();
_order = reader.ReadLong();
_isLocal = reader.ReadBoolean();
_isDaemon = reader.ReadBoolean();
_isClient = reader.ReadBoolean();
_consistentId = reader.ReadObject<object>();
_version = new IgniteProductVersion(reader);
_metrics = reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null;
}
/** <inheritDoc /> */
public Guid Id
{
get { return _id; }
}
/** <inheritDoc /> */
public T GetAttribute<T>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return (T)_attrs[name];
}
/** <inheritDoc /> */
public bool TryGetAttribute<T>(string name, out T attr)
{
IgniteArgumentCheck.NotNull(name, "name");
object val;
if (_attrs.TryGetValue(name, out val))
{
attr = (T)val;
return true;
}
attr = default(T);
return false;
}
/** <inheritDoc /> */
public IDictionary<string, object> GetAttributes()
{
return _attrs;
}
/** <inheritDoc /> */
public ICollection<string> Addresses
{
get { return _addrs; }
}
/** <inheritDoc /> */
public ICollection<string> HostNames
{
get { return _hosts; }
}
/** <inheritDoc /> */
public long Order
{
get { return _order; }
}
/** <inheritDoc /> */
public bool IsLocal
{
get { return _isLocal; }
}
/** <inheritDoc /> */
public bool IsDaemon
{
get { return _isDaemon; }
}
/** <inheritDoc /> */
public IgniteProductVersion Version
{
get { return _version; }
}
public IClusterMetrics GetMetrics()
{
var ignite = (Ignite)_igniteRef.Target;
if (ignite == null)
return _metrics;
ClusterMetricsImpl oldMetrics = _metrics;
long lastUpdateTime = oldMetrics.LastUpdateTimeRaw;
ClusterMetricsImpl newMetrics = ignite.ClusterGroup.RefreshClusterNodeMetrics(_id, lastUpdateTime);
if (newMetrics != null)
{
lock (this)
{
if (_metrics.LastUpdateTime < newMetrics.LastUpdateTime)
_metrics = newMetrics;
}
return newMetrics;
}
return oldMetrics;
}
/** <inheritDoc /> */
public object ConsistentId
{
get { return _consistentId; }
}
/** <inheritDoc /> */
public IDictionary<string, object> Attributes
{
get { return _attrs; }
}
/** <inheritDoc /> */
public bool IsClient
{
get { return _isClient; }
}
/** <inheritDoc /> */
public override string ToString()
{
return "GridNode [id=" + Id + ']';
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
ClusterNodeImpl node = obj as ClusterNodeImpl;
if (node != null)
return _id.Equals(node._id);
return false;
}
/** <inheritDoc /> */
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return _id.GetHashCode();
}
/// <summary>
/// Initializes this instance with a grid.
/// </summary>
/// <param name="grid">The grid.</param>
internal void Init(Ignite grid)
{
_igniteRef = new WeakReference(grid);
}
/// <summary>
/// Reads the attributes.
/// </summary>
internal static IDictionary<string, object> ReadAttributes(IBinaryRawReader reader)
{
Debug.Assert(reader != null);
var count = reader.ReadInt();
var res = new Dictionary<string, object>(count);
for (var i = 0; i < count; i++)
{
res[reader.ReadString()] = reader.ReadObject<object>();
}
return res.AsReadOnly();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using IRTaktiks.Components.Playable;
using IRTaktiks.Components.Manager;
using System.Threading;
namespace IRTaktiks.Components.Menu
{
/// <summary>
/// Representation of one action from the unit.
/// </summary>
public class ActionMenu
{
#region ActionMenuType
/// <summary>
/// Representation of the types of the ActionMenu.
/// </summary>
public enum ActionMenuType
{
/// <summary>
/// Move action menu.
/// </summary>
Move,
/// <summary>
/// Attack action menu.
/// </summary>
Attack,
/// <summary>
/// Skills action menu.
/// </summary>
Skills,
/// <summary>
/// Items action menu.
/// </summary>
Items
}
#endregion
#region Properties
/// <summary>
/// The unit owner of the action.
/// </summary>
private Unit UnitField;
/// <summary>
/// The unit owner of the action.
/// </summary>
public Unit Unit
{
get { return UnitField; }
}
/// <summary>
/// The type of the action.
/// </summary>
private ActionMenuType TypeField;
/// <summary>
/// The type of the action.
/// </summary>
public ActionMenuType Type
{
get { return TypeField; }
}
/// <summary>
/// The commands of this action.
/// </summary>
private List<CommandMenu> CommandsField;
/// <summary>
/// The commands of this action.
/// </summary>
public List<CommandMenu> Commands
{
get { return CommandsField; }
}
/// <summary>
/// The text of the action.
/// </summary>
private string TextField;
/// <summary>
/// The text of the action.
/// </summary>
public string Text
{
get { return TextField; }
}
/// <summary>
/// The actual position of the item.
/// </summary>
private Vector2 PositionField;
/// <summary>
/// The actual position of the item.
/// </summary>
public Vector2 Position
{
get { return PositionField; }
set { PositionField = value; }
}
/// <summary>
/// For actions who have commands, indicates its selection.
/// </summary>
private bool SelectedField;
/// <summary>
/// For actions who have commands, indicates its selection.
/// </summary>
public bool Selected
{
get { return SelectedField; }
set { SelectedField = value; }
}
#endregion
#region Event
/// <summary>
/// The method template who will used to handle the Execute event.
/// </summary>
/// <param name="actionMenu">The menu that dispacted the event.</param>
public delegate void ExecuteEventHandler(ActionMenu actionMenu);
/// <summary>
/// The Execute event.
/// </summary>
public virtual event ExecuteEventHandler Execute;
#endregion
#region Textures and SpriteFonts
/// <summary>
/// The texture of the item, when its not selected.
/// </summary>
protected Texture2D ItemTexture;
/// <summary>
/// The texture of the item, when its selected.
/// </summary>
protected Texture2D SelectedItemTexture;
/// <summary>
/// The sprite font that will be used to write the command.
/// </summary>
protected SpriteFont TextSpriteFont;
#endregion
#region Constructor
/// <summary>
/// Constructor of the class.
/// </summary>
/// <param name="unit">The unit owner of the action.</param>
/// <param name="text">The text of the action.</param>
/// <param name="type">The type of the action.</param>
public ActionMenu(Unit unit, string text, ActionMenuType type)
{
// Set the properties.
this.UnitField = unit;
this.TextField = text;
this.TypeField = type;
if (this.Unit.Player.PlayerIndex == PlayerIndex.One)
{
this.ItemTexture = TextureManager.Instance.Sprites.Menu.ItemPlayerOne;
}
else
{
this.ItemTexture = TextureManager.Instance.Sprites.Menu.ItemPlayerTwo;
}
this.SelectedItemTexture = TextureManager.Instance.Sprites.Menu.SelectedItem;
// Set the font to draw the text.
this.TextSpriteFont = FontManager.Instance.Chilopod16;
// Create the commands.
this.CommandsField = new List<CommandMenu>();
}
#endregion
#region Event Dispatcher
/// <summary>
/// Queue the Execute event for dispatch.
/// </summary>
public void RaiseExecute()
{
ThreadPool.QueueUserWorkItem(ExecuteNow, null);
}
/// <summary>
/// Dispatch the Execute event.
/// </summary>
/// <param name="data">Event data.</param>
public void ExecuteNow(object data)
{
if (this.Execute != null)
this.Execute(this);
}
#endregion
#region Methods
/// <summary>
/// Draws the item.
/// </summary>
/// <param name="spriteBatchManager">SpriteBatchManager used to draw.</param>
public virtual void Draw(SpriteManager spriteBatchManager)
{
// Draws the item of the menu.
spriteBatchManager.Draw(this.Selected ? this.SelectedItemTexture : this.ItemTexture, this.Position, Color.White, 50);
// Measure the text size.
Vector2 textSize = this.TextSpriteFont.MeasureString(this.Text);
// Calculate the position of the text.
Vector2 textPosition = new Vector2(this.Position.X + this.ItemTexture.Width / 2 - textSize.X / 2, this.Position.Y + this.ItemTexture.Height / 2 - textSize.Y / 2);
// Draws the text.
spriteBatchManager.DrawString(this.TextSpriteFont, this.Text, textPosition, Color.White, 51);
}
#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.
*/
//#define SPAM
using System;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Compression;
using PrimMesher;
using log4net;
using Nini.Config;
using System.Reflection;
using System.IO;
using ComponentAce.Compression.Libs.zlib;
namespace OpenSim.Region.Physics.Meshing
{
public class MeshmerizerPlugin : IMeshingPlugin
{
public MeshmerizerPlugin()
{
}
public string GetName()
{
return "Meshmerizer";
}
public IMesher GetMesher(IConfigSource config)
{
return new Meshmerizer(config);
}
}
public class Meshmerizer : IMesher
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Setting baseDir to a path will enable the dumping of raw files
// raw files can be imported by blender so a visual inspection of the results can be done
#if SPAM
const string baseDir = "rawFiles";
#else
private const string baseDir = null; //"rawFiles";
#endif
private bool cacheSculptMaps = true;
private string decodedSculptMapPath = null;
private bool useMeshiesPhysicsMesh = false;
private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
public Meshmerizer(IConfigSource config)
{
IConfig start_config = config.Configs["Startup"];
IConfig mesh_config = config.Configs["Mesh"];
decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath","j2kDecodeCache");
cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
if(mesh_config != null)
useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
try
{
if (!Directory.Exists(decodedSculptMapPath))
Directory.CreateDirectory(decodedSculptMapPath);
}
catch (Exception e)
{
m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message);
}
}
/// <summary>
/// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
/// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
/// for some reason
/// </summary>
/// <param name="minX"></param>
/// <param name="maxX"></param>
/// <param name="minY"></param>
/// <param name="maxY"></param>
/// <param name="minZ"></param>
/// <param name="maxZ"></param>
/// <returns></returns>
private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
{
Mesh box = new Mesh();
List<Vertex> vertices = new List<Vertex>();
// bottom
vertices.Add(new Vertex(minX, maxY, minZ));
vertices.Add(new Vertex(maxX, maxY, minZ));
vertices.Add(new Vertex(maxX, minY, minZ));
vertices.Add(new Vertex(minX, minY, minZ));
box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
// top
vertices.Add(new Vertex(maxX, maxY, maxZ));
vertices.Add(new Vertex(minX, maxY, maxZ));
vertices.Add(new Vertex(minX, minY, maxZ));
vertices.Add(new Vertex(maxX, minY, maxZ));
box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
// sides
box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
return box;
}
/// <summary>
/// Creates a simple bounding box mesh for a complex input mesh
/// </summary>
/// <param name="meshIn"></param>
/// <returns></returns>
private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
{
float minX = float.MaxValue;
float maxX = float.MinValue;
float minY = float.MaxValue;
float maxY = float.MinValue;
float minZ = float.MaxValue;
float maxZ = float.MinValue;
foreach (Vector3 v in meshIn.getVertexList())
{
if (v != null)
{
if (v.X < minX) minX = v.X;
if (v.Y < minY) minY = v.Y;
if (v.Z < minZ) minZ = v.Z;
if (v.X > maxX) maxX = v.X;
if (v.Y > maxY) maxY = v.Y;
if (v.Z > maxZ) maxZ = v.Z;
}
}
return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
}
private void ReportPrimError(string message, string primName, PrimMesh primMesh)
{
m_log.Error(message);
m_log.Error("\nPrim Name: " + primName);
m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
}
private ulong GetMeshKey(PrimitiveBaseShape pbs, Vector3 size, float lod)
{
ulong hash = 5381;
hash = djb2(hash, pbs.PathCurve);
hash = djb2(hash, (byte)((byte)pbs.HollowShape | (byte)pbs.ProfileShape));
hash = djb2(hash, pbs.PathBegin);
hash = djb2(hash, pbs.PathEnd);
hash = djb2(hash, pbs.PathScaleX);
hash = djb2(hash, pbs.PathScaleY);
hash = djb2(hash, pbs.PathShearX);
hash = djb2(hash, pbs.PathShearY);
hash = djb2(hash, (byte)pbs.PathTwist);
hash = djb2(hash, (byte)pbs.PathTwistBegin);
hash = djb2(hash, (byte)pbs.PathRadiusOffset);
hash = djb2(hash, (byte)pbs.PathTaperX);
hash = djb2(hash, (byte)pbs.PathTaperY);
hash = djb2(hash, pbs.PathRevolutions);
hash = djb2(hash, (byte)pbs.PathSkew);
hash = djb2(hash, pbs.ProfileBegin);
hash = djb2(hash, pbs.ProfileEnd);
hash = djb2(hash, pbs.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (pbs.SculptEntry)
{
scaleBytes = pbs.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
{
PrimMesh primMesh;
PrimMesher.SculptMesh sculptMesh;
List<Coord> coords = new List<Coord>();
List<Face> faces = new List<Face>();
Image idata = null;
string decodedSculptFileName = "";
if (primShape.SculptEntry)
{
if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
{
if (!useMeshiesPhysicsMesh)
return null;
m_log.Debug("[MESH]: experimental mesh proxy generation");
OSD meshOsd = null;
if (primShape.SculptData.Length <= 0)
{
m_log.Error("[MESH]: asset data is zero length");
return null;
}
long start = 0;
using (MemoryStream data = new MemoryStream(primShape.SculptData))
{
try
{
meshOsd = (OSDMap)OSDParser.DeserializeLLSDBinary(data);
}
catch (Exception e)
{
m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
}
start = data.Position;
}
if (meshOsd is OSDMap)
{
OSDMap map = (OSDMap)meshOsd;
OSDMap physicsParms = (OSDMap)map["physics_shape"];
int physOffset = physicsParms["offset"].AsInteger() + (int)start;
int physSize = physicsParms["size"].AsInteger();
if (physOffset < 0 || physSize == 0)
return null; // no mesh data in asset
OSD decodedMeshOsd = new OSD();
byte[] meshBytes = new byte[physSize];
System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
// byte[] decompressed = new byte[physSize * 5];
try
{
using (MemoryStream inMs = new MemoryStream(meshBytes))
{
using (MemoryStream outMs = new MemoryStream())
{
using (ZOutputStream zOut = new ZOutputStream(outMs))
{
byte[] readBuffer = new byte[2048];
int readLen = 0;
while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
zOut.Write(readBuffer, 0, readLen);
}
zOut.Flush();
outMs.Seek(0, SeekOrigin.Begin);
byte[] decompressedBuf = outMs.GetBuffer();
decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
}
}
}
}
catch (Exception e)
{
m_log.Error("[MESH]: exception decoding physical mesh: " + e.ToString());
return null;
}
OSDArray decodedMeshOsdArray = null;
// physics_shape is an array of OSDMaps, one for each submesh
if (decodedMeshOsd is OSDArray)
{
decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
foreach (OSD subMeshOsd in decodedMeshOsdArray)
{
if (subMeshOsd is OSDMap)
{
OSDMap subMeshMap = (OSDMap)subMeshOsd;
OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshMap["PositionDomain"])["Max"].AsVector3();
OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshMap["PositionDomain"])["Min"].AsVector3();
ushort faceIndexOffset = (ushort)coords.Count;
byte[] posBytes = subMeshMap["Position"].AsBinary();
for (int i = 0; i < posBytes.Length; i += 6)
{
ushort uX = Utils.BytesToUInt16(posBytes, i);
ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
Coord c = new Coord(
Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);
coords.Add(c);
}
byte[] triangleBytes = subMeshMap["TriangleList"].AsBinary();
for (int i = 0; i < triangleBytes.Length; i += 6)
{
ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
Face f = new Face(v1, v2, v3);
faces.Add(f);
}
}
}
}
}
}
else
{
if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
{
decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
try
{
if (File.Exists(decodedSculptFileName))
{
idata = Image.FromFile(decodedSculptFileName);
}
}
catch (Exception e)
{
m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
}
//if (idata != null)
// m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
}
if (idata == null)
{
if (primShape.SculptData == null || primShape.SculptData.Length == 0)
return null;
try
{
OpenMetaverse.Imaging.ManagedImage unusedData;
OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
unusedData = null;
//idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);
if (cacheSculptMaps && idata != null)
{
try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
}
}
catch (DllNotFoundException)
{
m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
return null;
}
catch (IndexOutOfRangeException)
{
m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
return null;
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
return null;
}
}
PrimMesher.SculptMesh.SculptType sculptType;
switch ((OpenMetaverse.SculptType)primShape.SculptType)
{
case OpenMetaverse.SculptType.Cylinder:
sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
break;
case OpenMetaverse.SculptType.Plane:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
case OpenMetaverse.SculptType.Torus:
sculptType = PrimMesher.SculptMesh.SculptType.torus;
break;
case OpenMetaverse.SculptType.Sphere:
sculptType = PrimMesher.SculptMesh.SculptType.sphere;
break;
default:
sculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
}
bool mirror = ((primShape.SculptType & 128) != 0);
bool invert = ((primShape.SculptType & 64) != 0);
sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
idata.Dispose();
sculptMesh.DumpRaw(baseDir, primName, "primMesh");
sculptMesh.Scale(size.X, size.Y, size.Z);
coords = sculptMesh.coords;
faces = sculptMesh.faces;
}
}
else
{
float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
if (profileHollow > 0.95f)
profileHollow = 0.95f;
int sides = 4;
if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
sides = 3;
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
sides = 24;
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
{ // half circle, prim is a sphere
sides = 24;
profileBegin = 0.5f * profileBegin + 0.5f;
profileEnd = 0.5f * profileEnd + 0.5f;
}
int hollowSides = sides;
if (primShape.HollowShape == HollowShape.Circle)
hollowSides = 24;
else if (primShape.HollowShape == HollowShape.Square)
hollowSides = 4;
else if (primShape.HollowShape == HollowShape.Triangle)
hollowSides = 3;
primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
if (primMesh.errorMessage != null)
if (primMesh.errorMessage.Length > 0)
m_log.Error("[ERROR] " + primMesh.errorMessage);
primMesh.topShearX = pathShearX;
primMesh.topShearY = pathShearY;
primMesh.pathCutBegin = pathBegin;
primMesh.pathCutEnd = pathEnd;
if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
{
primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
primMesh.twistEnd = primShape.PathTwist * 18 / 10;
primMesh.taperX = pathScaleX;
primMesh.taperY = pathScaleY;
if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
{
ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
if (profileBegin < 0.0f) profileBegin = 0.0f;
if (profileEnd > 1.0f) profileEnd = 1.0f;
}
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeLinear();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return null;
}
}
else
{
primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
primMesh.radius = 0.01f * primShape.PathRadiusOffset;
primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
primMesh.skew = 0.01f * primShape.PathSkew;
primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
primMesh.twistEnd = primShape.PathTwist * 36 / 10;
primMesh.taperX = primShape.PathTaperX * 0.01f;
primMesh.taperY = primShape.PathTaperY * 0.01f;
if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
{
ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
if (profileBegin < 0.0f) profileBegin = 0.0f;
if (profileEnd > 1.0f) profileEnd = 1.0f;
}
#if SPAM
m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
#endif
try
{
primMesh.ExtrudeCircular();
}
catch (Exception ex)
{
ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
return null;
}
}
primMesh.DumpRaw(baseDir, primName, "primMesh");
primMesh.Scale(size.X, size.Y, size.Z);
coords = primMesh.coords;
faces = primMesh.faces;
}
// Remove the reference to any JPEG2000 sculpt data so it can be GCed
primShape.SculptData = Utils.EmptyBytes;
int numCoords = coords.Count;
int numFaces = faces.Count;
// Create the list of vertices
List<Vertex> vertices = new List<Vertex>();
for (int i = 0; i < numCoords; i++)
{
Coord c = coords[i];
vertices.Add(new Vertex(c.X, c.Y, c.Z));
}
Mesh mesh = new Mesh();
// Add the corresponding triangles to the mesh
for (int i = 0; i < numFaces; i++)
{
Face f = faces[i];
mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
}
return mesh;
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
{
return CreateMesh(primName, primShape, size, lod, false);
}
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
{
Mesh mesh = null;
ulong key = 0;
// If this mesh has been created already, return it instead of creating another copy
// For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
key = GetMeshKey(primShape, size, lod);
if (m_uniqueMeshes.TryGetValue(key, out mesh))
return mesh;
if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f;
if (size.Z < 0.01f) size.Z = 0.01f;
mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
if (mesh != null)
{
if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
{
#if SPAM
m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
minSizeForComplexMesh.ToString() + " - creating simple bounding box");
#endif
mesh = CreateBoundingBoxMesh(mesh);
mesh.DumpRaw(baseDir, primName, "Z extruded");
}
// trim the vertex and triangle lists to free up memory
mesh.TrimExcess();
m_uniqueMeshes.Add(key, mesh);
}
return mesh;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WorkerMenu.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using UnityEngine;
using Random = UnityEngine.Random;
public class WorkerMenu : MonoBehaviour
{
public GUISkin Skin;
public Vector2 WidthAndHeight = new Vector2(600, 400);
private string roomName = "myRoom";
private Vector2 scrollPos = Vector2.zero;
private bool connectFailed = false;
public static readonly string SceneNameMenu = "DemoWorker-Scene";
public static readonly string SceneNameGame = "DemoWorkerGame-Scene";
private string errorDialog;
private double timeToClearDialog;
public string ErrorDialog
{
get { return this.errorDialog; }
private set
{
this.errorDialog = value;
if (!string.IsNullOrEmpty(value))
{
this.timeToClearDialog = Time.time + 4.0f;
}
}
}
public void Awake()
{
// this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
PhotonNetwork.automaticallySyncScene = true;
// the following line checks if this client was just created (and not yet online). if so, we connect
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
{
// Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project)
PhotonNetwork.ConnectUsingSettings("0.9");
}
// generate a name for this player, if none is assigned yet
if (String.IsNullOrEmpty(PhotonNetwork.playerName))
{
PhotonNetwork.playerName = "Guest" + Random.Range(1, 9999);
}
// if you wanted more debug out, turn this on:
// PhotonNetwork.logLevel = NetworkLogLevel.Full;
}
public void OnGUI()
{
if (this.Skin != null)
{
GUI.skin = this.Skin;
}
if (!PhotonNetwork.connected)
{
if (PhotonNetwork.connecting)
{
GUILayout.Label("Connecting to: " + PhotonNetwork.ServerAddress);
}
else
{
GUILayout.Label("Not connected. Check console output. Detailed connection state: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.ServerAddress);
}
if (this.connectFailed)
{
GUILayout.Label("Connection failed. Check setup and use Setup Wizard to fix configuration.");
GUILayout.Label(String.Format("Server: {0}", new object[] {PhotonNetwork.ServerAddress}));
GUILayout.Label("AppId: " + PhotonNetwork.PhotonServerSettings.AppID.Substring(0, 8) + "****"); // only show/log first 8 characters. never log the full AppId.
if (GUILayout.Button("Try Again", GUILayout.Width(100)))
{
this.connectFailed = false;
PhotonNetwork.ConnectUsingSettings("0.9");
}
}
return;
}
Rect content = new Rect((Screen.width - this.WidthAndHeight.x)/2, (Screen.height - this.WidthAndHeight.y)/2, this.WidthAndHeight.x, this.WidthAndHeight.y);
GUI.Box(content, "Join or Create Room");
GUILayout.BeginArea(content);
GUILayout.Space(40);
// Player name
GUILayout.BeginHorizontal();
GUILayout.Label("Player name:", GUILayout.Width(150));
PhotonNetwork.playerName = GUILayout.TextField(PhotonNetwork.playerName);
GUILayout.Space(158);
if (GUI.changed)
{
// Save name
PlayerPrefs.SetString("playerName", PhotonNetwork.playerName);
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
// Join room by title
GUILayout.BeginHorizontal();
GUILayout.Label("Roomname:", GUILayout.Width(150));
this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Create Room", GUILayout.Width(150)))
{
PhotonNetwork.CreateRoom(this.roomName, new RoomOptions() {maxPlayers = 10}, null);
}
GUILayout.EndHorizontal();
// Create a room (fails if exist!)
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
//this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Join Room", GUILayout.Width(150)))
{
PhotonNetwork.JoinRoom(this.roomName);
}
GUILayout.EndHorizontal();
if (!string.IsNullOrEmpty(ErrorDialog))
{
GUILayout.Label(ErrorDialog);
if (this.timeToClearDialog < Time.time)
{
this.timeToClearDialog = 0;
ErrorDialog = "";
}
}
GUILayout.Space(15);
// Join random room
GUILayout.BeginHorizontal();
GUILayout.Label(PhotonNetwork.countOfPlayers + " users are online in " + PhotonNetwork.countOfRooms + " rooms.");
GUILayout.FlexibleSpace();
if (GUILayout.Button("Join Random", GUILayout.Width(150)))
{
PhotonNetwork.JoinRandomRoom();
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
if (PhotonNetwork.GetRoomList().Length == 0)
{
GUILayout.Label("Currently no games are available.");
GUILayout.Label("Rooms will be listed here, when they become available.");
}
else
{
GUILayout.Label(PhotonNetwork.GetRoomList().Length + " rooms available:");
// Room listing: simply call GetRoomList: no need to fetch/poll whatever!
this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
{
GUILayout.BeginHorizontal();
GUILayout.Label(roomInfo.name + " " + roomInfo.playerCount + "/" + roomInfo.maxPlayers);
if (GUILayout.Button("Join", GUILayout.Width(150)))
{
PhotonNetwork.JoinRoom(roomInfo.name);
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
GUILayout.EndArea();
}
// We have two options here: we either joined(by title, list or random) or created a room.
public void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom");
}
public void OnPhotonCreateRoomFailed()
{
ErrorDialog = "Error: Can't create room (room name maybe already used).";
Debug.Log("OnPhotonCreateRoomFailed got called. This can happen if the room exists (even if not visible). Try another room name.");
}
public void OnPhotonJoinRoomFailed(object[] cause)
{
ErrorDialog = "Error: Can't join room (full or unknown room name). " + cause[1];
Debug.Log("OnPhotonJoinRoomFailed got called. This can happen if the room is not existing or full or closed.");
}
public void OnPhotonRandomJoinFailed()
{
ErrorDialog = "Error: Can't join random room (none found).";
Debug.Log("OnPhotonRandomJoinFailed got called. Happens if no room is available (or all full or invisible or closed). JoinrRandom filter-options can limit available rooms.");
}
public void OnCreatedRoom()
{
Debug.Log("OnCreatedRoom");
PhotonNetwork.LoadLevel(SceneNameGame);
}
public void OnDisconnectedFromPhoton()
{
Debug.Log("Disconnected from Photon.");
}
public void OnFailedToConnectToPhoton(object parameters)
{
this.connectFailed = true;
Debug.Log("OnFailedToConnectToPhoton. StatusCode: " + parameters + " ServerAddress: " + PhotonNetwork.networkingPeer.ServerAddress);
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq.Test
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class GroupAdjacentTest
{
[Test]
public void GroupAdjacentIsLazy()
{
var bs = new BreakingSequence<object>();
var bf = BreakingFunc.Of<object, int>();
var bfo = BreakingFunc.Of<object, object>();
var bfg = BreakingFunc.Of<int, IEnumerable<object>, IEnumerable<object>>();
bs.GroupAdjacent(bf);
bs.GroupAdjacent(bf, bfo);
bs.GroupAdjacent(bf, bfo, EqualityComparer<int>.Default);
bs.GroupAdjacent(bf, EqualityComparer<int>.Default);
bs.GroupAdjacent(bf, bfg);
bs.GroupAdjacent(bf, bfg, EqualityComparer<int>.Default);
}
[Test]
public void GroupAdjacentSourceSequence()
{
const string one = "one";
const string two = "two";
const string three = "three";
const string four = "four";
const string five = "five";
const string six = "six";
const string seven = "seven";
const string eight = "eight";
const string nine = "nine";
const string ten = "ten";
var source = new[] { one, two, three, four, five, six, seven, eight, nine, ten };
var groupings = source.GroupAdjacent(s => s.Length);
using (var reader = groupings.Read())
{
AssertGrouping(reader, 3, one, two);
AssertGrouping(reader, 5, three);
AssertGrouping(reader, 4, four, five);
AssertGrouping(reader, 3, six);
AssertGrouping(reader, 5, seven, eight);
AssertGrouping(reader, 4, nine);
AssertGrouping(reader, 3, ten);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceComparer()
{
var source = new[] { "foo", "FOO", "Foo", "bar", "BAR", "Bar" };
var groupings = source.GroupAdjacent(s => s, StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read())
{
AssertGrouping(reader, "foo", "foo", "FOO", "Foo");
AssertGrouping(reader, "bar", "bar", "BAR", "Bar");
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceElementSelector()
{
var source = new[]
{
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 789 },
new { Month = 2, Value = 987 },
new { Month = 2, Value = 654 },
new { Month = 2, Value = 321 },
new { Month = 3, Value = 789 },
new { Month = 3, Value = 456 },
new { Month = 3, Value = 123 },
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, e => e.Value * 2);
using (var reader = groupings.Read())
{
AssertGrouping(reader, 1, 123 * 2, 456 * 2, 789 * 2);
AssertGrouping(reader, 2, 987 * 2, 654 * 2, 321 * 2);
AssertGrouping(reader, 3, 789 * 2, 456 * 2, 123 * 2);
AssertGrouping(reader, 1, 123 * 2, 456 * 2, 781 * 2);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceElementSelectorComparer()
{
var source = new[]
{
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 789 },
new { Month = "feb", Value = 987 },
new { Month = "Feb", Value = 654 },
new { Month = "FEB", Value = 321 },
new { Month = "mar", Value = 789 },
new { Month = "Mar", Value = 456 },
new { Month = "MAR", Value = 123 },
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, e => e.Value * 2, StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read())
{
AssertGrouping(reader, "jan", 123 * 2, 456 * 2, 789 * 2);
AssertGrouping(reader, "feb", 987 * 2, 654 * 2, 321 * 2);
AssertGrouping(reader, "mar", 789 * 2, 456 * 2, 123 * 2);
AssertGrouping(reader, "jan", 123 * 2, 456 * 2, 781 * 2);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceResultSelector()
{
var source = new[]
{
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 789 },
new { Month = 2, Value = 987 },
new { Month = 2, Value = 654 },
new { Month = 2, Value = 321 },
new { Month = 3, Value = 789 },
new { Month = 3, Value = 456 },
new { Month = 3, Value = 123 },
new { Month = 1, Value = 123 },
new { Month = 1, Value = 456 },
new { Month = 1, Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, (key, group) => group.Sum(v => v.Value));
using (var reader = groupings.Read()) {
AssertResult(reader, 123 + 456 + 789);
AssertResult(reader, 987 + 654 + 321);
AssertResult(reader, 789 + 456 + 123);
AssertResult(reader, 123 + 456 + 781);
reader.ReadEnd();
}
}
[Test]
public void GroupAdjacentSourceSequenceResultSelectorComparer()
{
var source = new[]
{
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 789 },
new { Month = "feb", Value = 987 },
new { Month = "Feb", Value = 654 },
new { Month = "FEB", Value = 321 },
new { Month = "mar", Value = 789 },
new { Month = "Mar", Value = 456 },
new { Month = "MAR", Value = 123 },
new { Month = "jan", Value = 123 },
new { Month = "Jan", Value = 456 },
new { Month = "JAN", Value = 781 },
};
var groupings = source.GroupAdjacent(e => e.Month, (key, group) => group.Sum(v => v.Value), StringComparer.OrdinalIgnoreCase);
using (var reader = groupings.Read()) {
AssertResult(reader, 123 + 456 + 789);
AssertResult(reader, 987 + 654 + 321);
AssertResult(reader, 789 + 456 + 123);
AssertResult(reader, 123 + 456 + 781);
reader.ReadEnd();
}
}
static void AssertGrouping<TKey, TElement>(SequenceReader<System.Linq.IGrouping<TKey, TElement>> reader,
TKey key, params TElement[] elements)
{
var grouping = reader.Read();
Assert.That(grouping, Is.Not.Null);
Assert.That(grouping.Key, Is.EqualTo(key));
grouping.AssertSequenceEqual(elements);
}
static void AssertResult<TElement>(SequenceReader<TElement> reader, TElement element)
{
var result = reader.Read();
Assert.That(result, Is.Not.Null);
Assert.AreEqual(element, result);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="GridErrorDlg.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms.PropertyGridInternal {
using System.Runtime.Serialization.Formatters;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System;
using System.Collections;
using System.Windows.Forms;
using System.Windows.Forms.ComponentModel;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.IO;
using System.Drawing;
using Microsoft.Win32;
using Message = System.Windows.Forms.Message;
using System.Drawing.Drawing2D;
/// <include file='doc\GridErrorDlg.uex' path='docs/doc[@for="GridErrorDlg"]/*' />
/// <devdoc>
/// Implements a dialog that is displayed when an unhandled exception occurs in
/// a thread. This dialog's width is defined by the summary message
/// in the top pane. We don't restrict dialog width in any way.
/// Use caution and check at all DPI scaling factors if adding a new message
/// to be displayed in the top pane.
/// </devdoc>
internal class GridErrorDlg : Form {
private TableLayoutPanel overarchingTableLayoutPanel;
private TableLayoutPanel buttonTableLayoutPanel;
private PictureBox pictureBox;
private Label lblMessage;
private Button detailsBtn;
private Button cancelBtn;
private Button okBtn;
private TableLayoutPanel pictureLabelTableLayoutPanel;
private TextBox details;
private Bitmap expandImage = null;
private Bitmap collapseImage = null;
private PropertyGrid ownerGrid;
public string Details {
set {
this.details.Text = value;
}
}
public string Message {
set {
this.lblMessage.Text = value;
}
}
[
SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // We use " " for the text so we leave a small amount of test.
// So we don't have to localize it.
]
public GridErrorDlg(PropertyGrid owner) {
ownerGrid = owner;
expandImage = new Bitmap(typeof(ThreadExceptionDialog), "down.bmp");
expandImage.MakeTransparent();
if (DpiHelper.IsScalingRequired) {
DpiHelper.ScaleBitmapLogicalToDevice(ref expandImage);
}
collapseImage = new Bitmap(typeof(ThreadExceptionDialog), "up.bmp");
collapseImage.MakeTransparent();
if (DpiHelper.IsScalingRequired) {
DpiHelper.ScaleBitmapLogicalToDevice(ref collapseImage);
}
InitializeComponent();
foreach( Control c in this.Controls ){
if( c.SupportsUseCompatibleTextRendering ){
c.UseCompatibleTextRenderingInt = ownerGrid.UseCompatibleTextRendering;
}
}
pictureBox.Image = SystemIcons.Warning.ToBitmap();
detailsBtn.Text = " " + SR.GetString(SR.ExDlgShowDetails);
details.AccessibleName = SR.GetString(SR.ExDlgDetailsText);
okBtn.Text = SR.GetString(SR.ExDlgOk);
cancelBtn.Text = SR.GetString(SR.ExDlgCancel);
detailsBtn.Image = expandImage;
}
/// <include file='doc\GridErrorDlg.uex' path='docs/doc[@for="GridErrorDlg.DetailsClick"]/*' />
/// <devdoc>
/// Called when the details button is clicked.
/// </devdoc>
private void DetailsClick(object sender, EventArgs devent) {
int delta = details.Height + 8;
if (details.Visible) {
detailsBtn.Image = expandImage;
Height -= delta;
}
else {
detailsBtn.Image = collapseImage;
details.Width = overarchingTableLayoutPanel.Width - details.Margin.Horizontal;
Height += delta;
}
details.Visible = !details.Visible;
}
/// <devdoc>
/// Tells whether the current resources for this dll have been
/// localized for a RTL language.
/// </devdoc>
private static bool IsRTLResources {
get {
return SR.GetString(SR.RTL) != "RTL_False";
}
}
private void InitializeComponent() {
if (IsRTLResources) {
this.RightToLeft = RightToLeft.Yes;
}
this.detailsBtn = new System.Windows.Forms.Button();
this.overarchingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.buttonTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.okBtn = new System.Windows.Forms.Button();
this.cancelBtn = new System.Windows.Forms.Button();
this.pictureLabelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.lblMessage = new System.Windows.Forms.Label();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.details = new System.Windows.Forms.TextBox();
this.overarchingTableLayoutPanel.SuspendLayout();
this.buttonTableLayoutPanel.SuspendLayout();
this.pictureLabelTableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// lblMessage
//
this.lblMessage.AutoSize = true;
this.lblMessage.Location = new System.Drawing.Point(73, 30);
this.lblMessage.Margin = new System.Windows.Forms.Padding(3, 30, 3, 0);
this.lblMessage.Name = "lblMessage";
this.lblMessage.Size = new System.Drawing.Size(208, 43);
this.lblMessage.TabIndex = 0;
//
// pictureBox
//
this.pictureBox.Location = new System.Drawing.Point(3, 3);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(64, 64);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBox.TabIndex = 5;
this.pictureBox.TabStop = false;
this.pictureBox.AutoSize = true;
//
// detailsBtn
//
this.detailsBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.detailsBtn.Location = new System.Drawing.Point(3, 3);
this.detailsBtn.Margin = new System.Windows.Forms.Padding(12, 3, 29, 3);
this.detailsBtn.Name = "detailsBtn";
this.detailsBtn.Size = new System.Drawing.Size(100, 23);
this.detailsBtn.TabIndex = 4;
this.detailsBtn.Click += new System.EventHandler(this.DetailsClick);
//
// overarchingTableLayoutPanel
//
this.overarchingTableLayoutPanel.AutoSize = true;
this.overarchingTableLayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.overarchingTableLayoutPanel.ColumnCount = 1;
this.overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.overarchingTableLayoutPanel.Controls.Add(this.buttonTableLayoutPanel, 0, 1);
this.overarchingTableLayoutPanel.Controls.Add(this.pictureLabelTableLayoutPanel, 0, 0);
this.overarchingTableLayoutPanel.Location = new System.Drawing.Point(1, 0);
this.overarchingTableLayoutPanel.MinimumSize = new System.Drawing.Size(279, 50);
this.overarchingTableLayoutPanel.Name = "overarchingTableLayoutPanel";
this.overarchingTableLayoutPanel.RowCount = 2;
this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.overarchingTableLayoutPanel.Size = new System.Drawing.Size(290, 108);
this.overarchingTableLayoutPanel.TabIndex = 6;
//
// buttonTableLayoutPanel
//
this.buttonTableLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonTableLayoutPanel.AutoSize = true;
this.buttonTableLayoutPanel.ColumnCount = 3;
this.overarchingTableLayoutPanel.SetColumnSpan(this.buttonTableLayoutPanel, 2);
this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.buttonTableLayoutPanel.Controls.Add(this.cancelBtn, 2, 0);
this.buttonTableLayoutPanel.Controls.Add(this.okBtn, 1, 0);
this.buttonTableLayoutPanel.Controls.Add(this.detailsBtn, 0, 0);
this.buttonTableLayoutPanel.Location = new System.Drawing.Point(0, 79);
this.buttonTableLayoutPanel.Name = "buttonTableLayoutPanel";
this.buttonTableLayoutPanel.RowCount = 1;
this.buttonTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.buttonTableLayoutPanel.Size = new System.Drawing.Size(290, 29);
this.buttonTableLayoutPanel.TabIndex = 8;
//
// okBtn
//
this.okBtn.AutoSize = true;
this.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okBtn.Location = new System.Drawing.Point(131, 3);
this.okBtn.Name = "okBtn";
this.okBtn.Size = new System.Drawing.Size(75, 23);
this.okBtn.TabIndex = 1;
this.okBtn.Click += new System.EventHandler(this.OnButtonClick);
//
// cancelBtn
//
this.cancelBtn.AutoSize = true;
this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelBtn.Location = new System.Drawing.Point(212, 3);
this.cancelBtn.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
this.cancelBtn.Name = "cancelBtn";
this.cancelBtn.Size = new System.Drawing.Size(75, 23);
this.cancelBtn.TabIndex = 2;
this.cancelBtn.Click += new System.EventHandler(this.OnButtonClick);
//
// pictureLabelTableLayoutPanel
//
this.pictureLabelTableLayoutPanel.AutoSize = true;
this.pictureLabelTableLayoutPanel.AutoSizeMode = Forms.AutoSizeMode.GrowOnly;
this.pictureLabelTableLayoutPanel.ColumnCount = 2;
this.pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.pictureLabelTableLayoutPanel.Controls.Add(this.lblMessage, 1, 0);
this.pictureLabelTableLayoutPanel.Controls.Add(this.pictureBox, 0, 0);
this.pictureLabelTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureLabelTableLayoutPanel.Location = new System.Drawing.Point(3, 3);
this.pictureLabelTableLayoutPanel.Name = "pictureLabelTableLayoutPanel";
this.pictureLabelTableLayoutPanel.RowCount = 1;
this.pictureLabelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize));
this.pictureLabelTableLayoutPanel.Size = new System.Drawing.Size(284, 73);
this.pictureLabelTableLayoutPanel.TabIndex = 4;
//
// details
//
this.details.Location = new System.Drawing.Point(4, 114);
this.details.Multiline = true;
this.details.Name = "details";
this.details.ReadOnly = true;
this.details.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.details.Size = new System.Drawing.Size(273, 100);
this.details.TabIndex = 3;
this.details.TabStop = false;
this.details.Visible = false;
//
// Form1
//
this.AcceptButton = this.okBtn;
this.AutoSize = true;
this.AutoScaleMode = Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.CancelButton = this.cancelBtn;
this.ClientSize = new System.Drawing.Size(299, 113);
this.Controls.Add(this.details);
this.Controls.Add(this.overarchingTableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.overarchingTableLayoutPanel.ResumeLayout(false);
this.overarchingTableLayoutPanel.PerformLayout();
this.buttonTableLayoutPanel.ResumeLayout(false);
this.buttonTableLayoutPanel.PerformLayout();
this.pictureLabelTableLayoutPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void OnButtonClick(object s, EventArgs e) {
DialogResult = ((Button)s).DialogResult;
Close();
}
protected override void OnVisibleChanged(EventArgs e) {
if (this.Visible) {
// make sure the details button is sized properly
//
using (Graphics g = CreateGraphics()) {
SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText( this.ownerGrid, g, detailsBtn.Text, detailsBtn.Font);
int detailsWidth = (int) Math.Ceiling(sizef.Width);
detailsWidth += detailsBtn.Image.Width;
detailsBtn.Width = (int) Math.Ceiling(detailsWidth * (ownerGrid.UseCompatibleTextRendering ? 1.15f : 1.4f));
detailsBtn.Height = okBtn.Height;
}
// Update the location of the TextBox details
int x = details.Location.X;
int y = detailsBtn.Location.Y + detailsBtn.Height + detailsBtn.Margin.Bottom;
// Location is relative to its parent,
// therefore, we need to take its parent into consideration
Control parent = detailsBtn.Parent;
while(parent != null && !(parent is Form)) {
y += parent.Location.Y;
parent = parent.Parent;
}
details.Location = new System.Drawing.Point(x, y);
if (details.Visible) {
DetailsClick(details, EventArgs.Empty);
}
}
okBtn.Focus();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DeadCode.WME.Global.Actions;
using DeadCode.WME.Global;
namespace ActionsTest
{
public partial class Form2 : ActionForm, IActionProvider
{
TestProvider Test;
public Form2()
{
ActionManager.LoadActions(typeof(Form2));
Test = new TestProvider();
//ActContext.ActivateObject(this);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ActionStripItem i = ActContext.StripBuilder.DefineTestMenu();
ActContext.StripBuilder.AddToolStrip(i, menuStrip1.Items, true);
ActContext.StripBuilder.AddToolStrip(i, contextMenuStrip1.Items, true);
ActContext.StripBuilder.AddToolStrip(i, toolStrip1.Items, false);
ActContext.StripBuilder.RefreshManagedToolStrips();
}
bool Act = false;
private void button2_Click(object sender, EventArgs e)
{
if(!Act) ActContext.ActivateObject(ActiveObjectSlot.Application, this);
else ActContext.ActivateObject(ActiveObjectSlot.Application, null);
Act = !Act;
}
void Item_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("Test.Action1",
Caption = "Action 1",
IconName = "Graphics.Icons.breakpoint.png")
]
public void TestAction(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
MessageBox.Show("Action 1 invoked\n" + Param.Sender.GetType().ToString());
Param.Processed = true;
break;
case ActionParam.QueryType.Initialize:
((ToolStripItem)Param.Sender).ForeColor = Color.Red;
break;
case ActionParam.QueryType.GetState:
Param.State.Enabled = Action2Checked;
break;
}
}
private bool Action2Checked = true;
//////////////////////////////////////////////////////////////////////////
[ActionProp("Test.Action2",
Caption = "Action 2",
IconName = "Graphics.Icons.bookmark.bmp",
Type=ActionType.Toggle,
DisplayType=DisplayType.ImageAndText,
DisplayLabel=true,
ShortcutKeys=Keys.F12)
]
public void TestAction2(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
//MessageBox.Show("Action 2 invoked");
Action2Checked = !Action2Checked;
Param.Processed = true;
break;
case ActionParam.QueryType.GetState:
Param.State.Enabled = true;
Param.State.Checked = Action2Checked;
Param.State.Caption = Action2Checked ? "Checked" : "Unchecked";
break;
}
}
[ActionProp("Test.Action3", Caption = "Search", Tooltip = "Search something", Type = ActionType.Combo, DisplayLabel = true)]
public void TestAction3(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
MessageBox.Show(((ToolStripItem)Param.Sender).Text);
break;
case ActionParam.QueryType.Initialize:
ToolStripComboBox Combo = Param.Sender as ToolStripComboBox;
if(Combo!=null)
{
//Combo.DropDownStyle = ComboBoxStyle.DropDownList;
Combo.Items.Add("aaa");
Combo.Items.Add("bbb");
Combo.Items.Add("ccc");
Combo.AutoCompleteMode = AutoCompleteMode.Append;
Combo.AutoCompleteSource = AutoCompleteSource.ListItems;
}
break;
}
}
private void cccToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("combo");
}
private void toolStripComboBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
//((ToolStripComboBox)sender).PerformClick();
}
}
bool Act2;
private void button3_Click(object sender, EventArgs e)
{
if (!Act2) ActContext.ActivateObject(ActiveObjectSlot.Control, Test);
else ActContext.ActivateObject(ActiveObjectSlot.Control, null);
Act2 = !Act2;
}
private void button4_Click(object sender, EventArgs e)
{
menuStrip1.Visible = false;
}
private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
internal class TestProvider : IActionProvider
{
public TestProvider()
{
ActionManager.LoadActions(typeof(TestProvider));
}
[ActionProp("Test.Action1",
Caption = "Action 1 Test",
IconName = "Graphics.Icons.breakpoint.png")
]
public void TestAction(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
MessageBox.Show("Action 1 Test invoked\n" + Param.Sender.GetType().ToString());
Param.Processed = true;
break;
//case ActionParam.QueryType.GetState:
// Param.State.Enabled = true;
// break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("Test.Action2", Caption = "Action 2")]
public void TestAction2(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.GetState:
//Param.State.Visible = false;
break;
}
}
};
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCMSG
{
using System;
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// MS-OXCMSG protocol adapter. It is used to construct request messages and parse response message to communicate with the transport adapter.
/// </summary>
public partial class MS_OXCMSGAdapter : ManagedAdapterBase, IMS_OXCMSGAdapter
{
/// <summary>
/// Definition for default value of Output handle.
/// </summary>
public const uint DefaultOutputHandle = 0xFFFFFFFF;
/// <summary>
/// The OxcropsClient instance.
/// </summary>
private OxcropsClient oxcropsClient;
/// <summary>
/// Status of connection.
/// </summary>
private bool isConnected;
/// <summary>
/// Reset the adapter.
/// </summary>
public override void Reset()
{
if (this.isConnected)
{
this.RpcDisconnect();
}
base.Reset();
}
#region IMS_OXCMSGAdapter members
/// <summary>
/// Initialize the adapter.
/// </summary>
/// <param name="testSite">Test site.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
PropertyHelper.Initialize(testSite);
Site.DefaultProtocolDocShortName = "MS-OXCMSG";
Common.MergeConfiguration(this.Site);
this.oxcropsClient = new OxcropsClient(MapiContext.GetDefaultRpcContext(this.Site));
}
/// <summary>
/// Connect to the server.
/// </summary>
/// <param name="connectionType">The type of connection</param>
/// <param name="user">A string value indicates the domain account name that connects to server.</param>
/// <param name="password">A string value indicates the password of the user which is used.</param>
/// <param name="userDN">A string that identifies user who is making the EcDoConnectEx call</param>
/// <returns>A Boolean value indicating whether connects successfully.</returns>
public bool RpcConnect(ConnectionType connectionType, string user, string password, string userDN)
{
this.isConnected = this.oxcropsClient.Connect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
connectionType,
userDN,
Common.GetConfigurationPropertyValue("Domain", this.Site),
user,
password);
return this.isConnected;
}
/// <summary>
/// Disconnect from the server.
/// </summary>
/// <returns>Result of disconnecting.</returns>
public bool RpcDisconnect()
{
bool ret = this.oxcropsClient.Disconnect();
if (ret)
{
this.isConnected = false;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Send ROP request with single operation.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="insideObjHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="getPropertiesFlag">The flag indicate the test cases expect to get which object type's properties(message's properties or attachment's properties).</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> DoRopCall(ISerializable ropRequest, uint insideObjHandle, ref object response, ref byte[] rawData, GetPropertiesFlags getPropertiesFlag)
{
uint retValue;
return this.DoRopCall(ropRequest, insideObjHandle, ref response, ref rawData, getPropertiesFlag, out retValue);
}
/// <summary>
/// Send ROP request with single operation.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="insideObjHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="getPropertiesFlag">The flag indicate the test cases expect to get which object type's properties(message's properties or attachment's properties).</param>
/// <param name="returnValue">An unsigned integer value indicates the return value of call EcDoRpcExt2 method.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> DoRopCall(ISerializable ropRequest, uint insideObjHandle, ref object response, ref byte[] rawData, GetPropertiesFlags getPropertiesFlag, out uint returnValue)
{
List<ISerializable> requestRops = new List<ISerializable>
{
ropRequest
};
List<uint> requestSOH = new List<uint>
{
insideObjHandle
};
if (Common.IsOutputHandleInRopRequest(ropRequest))
{
// Add an element for server output object handle, set default value to 0xFFFFFFFF
requestSOH.Add(DefaultOutputHandle);
}
List<IDeserializable> responseRops = new List<IDeserializable>();
List<List<uint>> responseSOHs = new List<List<uint>>();
// 0x10008 specifies the maximum size of the rgbOut buffer to place in Response.
uint ret = this.oxcropsClient.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, 0x10008);
returnValue = ret;
if (ret == OxcRpcErrorCode.ECRpcFormat)
{
this.Site.Assert.Fail("Error RPC Format");
}
if (ret != 0)
{
return responseSOHs;
}
if (responseRops != null)
{
if (responseRops.Count > 0)
{
response = responseRops[0];
}
}
else
{
response = null;
}
if (ropRequest.GetType() == typeof(RopReleaseRequest))
{
return responseSOHs;
}
byte ropId = (byte)BitConverter.ToInt16(ropRequest.Serialize(), 0);
List<PropertyObj> pts = null;
switch (ropId)
{
case (byte)RopId.RopOpenMessage:
RopOpenMessageResponse openMessageResponse = (RopOpenMessageResponse)response;
// This check is for the open specification expectation for a particular request with some valid input parameters.
if (openMessageResponse.ReturnValue == 0x00000000)
{
this.VerifyRopOpenMessageResponse(openMessageResponse);
}
break;
case (byte)RopId.RopGetPropertiesSpecific:
// RopGetPropertiesSpecificRequest
pts = PropertyHelper.GetPropertyObjFromBuffer(((RopGetPropertiesSpecificRequest)ropRequest).PropertyTags, (RopGetPropertiesSpecificResponse)response);
foreach (PropertyObj pitem in pts)
{
// Verify capture code for MS-OXCMSG.
this.VerifyMessageSyntaxDataType(pitem);
}
PropertyObj propertyObjPidTagSubjectPrefix = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagSubjectPrefix);
PropertyObj propertyObjPidTagNormalizedSubject = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagNormalizedSubject);
// Verify the message of PidTagSubjectPrefixAndPidTagNormalizedSubject
if (PropertyHelper.IsPropertyValid(propertyObjPidTagSubjectPrefix) || PropertyHelper.IsPropertyValid(propertyObjPidTagNormalizedSubject))
{
this.VerifyMessageSyntaxPidTagSubjectPrefixAndPidTagNormalizedSubject(propertyObjPidTagSubjectPrefix, propertyObjPidTagNormalizedSubject);
}
// Verify the requirements of PidTagAttachmentLinkId and PidTagAttachmentFlags.
PropertyObj pidTagAttachmentLinkId = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachmentLinkId);
if (PropertyHelper.IsPropertyValid(pidTagAttachmentLinkId))
{
this.VerifyMessageSyntaxPidTagAttachmentLinkIdAndPidTagAttachmentFlags(pidTagAttachmentLinkId);
}
PropertyObj pidTagAttachmentFlags = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachmentFlags);
if (PropertyHelper.IsPropertyValid(pidTagAttachmentFlags))
{
this.VerifyMessageSyntaxPidTagAttachmentLinkIdAndPidTagAttachmentFlags(pidTagAttachmentFlags);
}
// Verify the requirements of PidTagDisplayName
PropertyObj pidTagDisplayName = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagDisplayName);
PropertyObj pidTagAttachLongFilename = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachLongFilename);
if (PropertyHelper.IsPropertyValid(pidTagDisplayName) && PropertyHelper.IsPropertyValid(pidTagAttachLongFilename))
{
this.VerifyMessageSyntaxPidTagDisplayName(pidTagDisplayName, pidTagAttachLongFilename);
}
PropertyObj pidTagObjectType = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagObjectType);
PropertyObj pidTagRecordKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagRecordKey);
this.VerifyPidTagObjectTypeAndPidTagRecordKey(pidTagObjectType, pidTagRecordKey);
break;
case (byte)RopId.RopGetPropertiesAll:
RopGetPropertiesAllResponse getPropertiesAllResponse = (RopGetPropertiesAllResponse)response;
pts = PropertyHelper.GetPropertyObjFromBuffer(getPropertiesAllResponse);
foreach (PropertyObj pitem in pts)
{
// Verify capture code for MS-OXCMSG.
this.VerifyMessageSyntaxDataType(pitem);
}
// Verify the requirements of PidTagArchiveDate
PropertyObj pidTagArchiveDateObj = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagArchiveDate);
PropertyObj pidTagStartDateEtc = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagStartDateEtc);
if (PropertyHelper.IsPropertyValid(pidTagArchiveDateObj))
{
if (PropertyHelper.IsPropertyValid(pidTagStartDateEtc))
{
byte[] byteDest = new byte[8];
Array.Copy((byte[])pidTagStartDateEtc.Value, 6, byteDest, 0, 8);
this.VerifyMessageSyntaxPidTagArchiveDate(pidTagArchiveDateObj, DateTime.FromFileTimeUtc(BitConverter.ToInt64(byteDest, 0)));
}
}
PropertyObj pidTagAccessLevel = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAccessLevel);
pidTagRecordKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagRecordKey);
if (getPropertiesFlag == GetPropertiesFlags.MessageProperties)
{
PropertyObj pidTagAccess = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAccess);
PropertyObj pidTagChangeKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagChangeKey);
PropertyObj pidTagCreationTime = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagCreationTime);
PropertyObj pidTagLastModificationTime = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagLastModificationTime);
PropertyObj pidTagLastModifierName = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagLastModifierName);
PropertyObj pidTagSearchKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagSearchKey);
// Verify properties PidTagAccess, PidTagAccessLevel, PidTagChangeKey, PidTagCreationTime, PidTagLastModificationTime, PidTagLastModifierName and PidTagSearchKey exist on all Message objects.
this.VerifyPropertiesExistOnAllMessageObject(pidTagAccess, pidTagAccessLevel, pidTagChangeKey, pidTagCreationTime, pidTagLastModificationTime, pidTagLastModifierName, pidTagSearchKey);
}
if (getPropertiesFlag == GetPropertiesFlags.AttachmentProperties)
{
// Verify properties PidTagAccessLevel and PidTagRecordKey exist on any Attachment object.
this.VerifyPropertiesExistOnAllAttachmentObject(pidTagAccessLevel, pidTagRecordKey);
}
break;
case (byte)RopId.RopCreateMessage:
RopCreateMessageResponse createMessageResponse = (RopCreateMessageResponse)response;
// Adapter requirements related with RopCreateMessage will be verified if the response is a successful one.
if (createMessageResponse.ReturnValue == 0x00000000)
{
int hasMessageId = createMessageResponse.HasMessageId;
this.VerifyMessageSyntaxHasMessageId(hasMessageId);
}
break;
case (byte)RopId.RopReadRecipients:
RopReadRecipientsResponse readRecipientsResponse = (RopReadRecipientsResponse)response;
// Adapter requirements related with RopReadRecipients will be verified if the response is a successful one.
if (readRecipientsResponse.ReturnValue == 0x00000000)
{
this.VerifyMessageSyntaxRowCount(readRecipientsResponse);
}
break;
case (byte)RopId.RopSetMessageStatus:
RopSetMessageStatusResponse setMessageStatusResponse = (RopSetMessageStatusResponse)response;
// Adapter requirements related with RopSetMessageStatus will be verified if the response is a successful one.
if (setMessageStatusResponse.ReturnValue == 0x00000000)
{
this.VerifyMessageSyntaxMessageStatusFlags(setMessageStatusResponse);
}
break;
case (byte)RopId.RopCreateAttachment:
RopCreateAttachmentResponse createAttachmentResponse = (RopCreateAttachmentResponse)response;
// Adapter requirements related with RopCreateAttachment will be verified if the response is a successful one.
if (createAttachmentResponse.ReturnValue == 0x00000000)
{
int id = (int)createAttachmentResponse.AttachmentID;
this.VerifyDataStructureRopCreateAttachmentResponse(createAttachmentResponse, id);
}
break;
case (byte)RopId.RopOpenEmbeddedMessage:
RopOpenEmbeddedMessageResponse openEmbeddedMessageResponse = (RopOpenEmbeddedMessageResponse)response;
// Adapter requirements related with RopOpenEmbeddedMessage will be verified if the response is a successful one.
if (openEmbeddedMessageResponse.ReturnValue == 0x00000000)
{
ulong mid = openEmbeddedMessageResponse.MessageId;
this.VerifyDataStructureRopOpenEmbeddedMessageResponse(openEmbeddedMessageResponse, mid);
}
break;
case (byte)RopId.RopSetMessageReadFlag:
RopSetMessageReadFlagResponse setMessageReadFlagResponse = (RopSetMessageReadFlagResponse)response;
// Adapter requirements related with RopSetMessageReadFlag will be verified if the response is a successful one.
if (setMessageReadFlagResponse.ReturnValue == 0x00000000)
{
this.VerifyMessageSyntaxReadStatusChanged(setMessageReadFlagResponse, (RopSetMessageReadFlagRequest)ropRequest);
}
break;
case (byte)RopId.RopSetReadFlags:
// Adapter requirements related with RopSetReadFlags will be verified if the response is a successful one.
if (((RopSetReadFlagsResponse)response).ReturnValue == 0x00000000)
{
this.VerifyRopSetReadFlagsResponse((RopSetReadFlagsResponse)response);
}
break;
case (byte)RopId.RopGetMessageStatus:
// Adapter requirements related with RopGetMessageStatus will be verified if the response is a successful one.
if (((RopSetMessageStatusResponse)response).ReturnValue == 0x00000000)
{
this.VerifyGetMessageStatusResponse((RopSetMessageStatusResponse)response);
}
break;
default:
break;
}
this.VerifyMAPITransport();
return responseSOHs;
}
/// <summary>
/// Get the named properties value of specified Message object.
/// </summary>
/// <param name="longIdProperties">The list of named properties</param>
/// <param name="messageHandle">The object handle of specified Message object.</param>
/// <returns>Returns named property values of specified Message object.</returns>
public Dictionary<PropertyNames, byte[]> GetNamedPropertyValues(List<PropertyNameObject> longIdProperties, uint messageHandle)
{
object response = null;
byte[] rawData = null;
#region Call RopGetPropertyIdsFromNames to get property ID.
PropertyName[] propertyNames = new PropertyName[longIdProperties.Count];
for (int i = 0; i < longIdProperties.Count; i++)
{
propertyNames[i] = longIdProperties[i].PropertyName;
}
RopGetPropertyIdsFromNamesRequest getPropertyIdsFromNamesRequest;
RopGetPropertyIdsFromNamesResponse getPropertyIdsFromNamesResponse;
getPropertyIdsFromNamesRequest.RopId = (byte)RopId.RopGetPropertyIdsFromNames;
getPropertyIdsFromNamesRequest.LogonId = 0x00;
getPropertyIdsFromNamesRequest.InputHandleIndex = 0x00;
getPropertyIdsFromNamesRequest.Flags = (byte)GetPropertyIdsFromNamesFlags.Create;
getPropertyIdsFromNamesRequest.PropertyNameCount = (ushort)propertyNames.Length;
getPropertyIdsFromNamesRequest.PropertyNames = propertyNames;
this.DoRopCall(getPropertyIdsFromNamesRequest, messageHandle, ref response, ref rawData, GetPropertiesFlags.None);
getPropertyIdsFromNamesResponse = (RopGetPropertyIdsFromNamesResponse)response;
Site.Assert.AreEqual<uint>(0, getPropertyIdsFromNamesResponse.ReturnValue, "Call RopGetPropertyIdsFromNames should success.");
#endregion
#region Call RopGetPropertiesSpecific to get the specific properties of specific message object.
// Get specific property for created message
RopGetPropertiesSpecificRequest getPropertiesSpecificRequest = new RopGetPropertiesSpecificRequest();
RopGetPropertiesSpecificResponse getPropertiesSpecificResponse;
getPropertiesSpecificRequest.RopId = (byte)RopId.RopGetPropertiesSpecific;
getPropertiesSpecificRequest.LogonId = 0x00;
getPropertiesSpecificRequest.InputHandleIndex = 0x00;
getPropertiesSpecificRequest.PropertySizeLimit = 0xFFFF;
PropertyTag[] tagArray = new PropertyTag[longIdProperties.Count];
for (int j = 0; j < getPropertyIdsFromNamesResponse.PropertyIds.Length; j++)
{
tagArray[j] = new PropertyTag
{
PropertyId = getPropertyIdsFromNamesResponse.PropertyIds[j].ID,
PropertyType = (ushort)longIdProperties[j].PropertyType
};
}
getPropertiesSpecificRequest.PropertyTagCount = (ushort)tagArray.Length;
getPropertiesSpecificRequest.PropertyTags = tagArray;
this.DoRopCall(getPropertiesSpecificRequest, messageHandle, ref response, ref rawData, GetPropertiesFlags.None);
getPropertiesSpecificResponse = (RopGetPropertiesSpecificResponse)response;
Site.Assert.AreEqual<uint>(0, getPropertiesSpecificResponse.ReturnValue, "Calling RopGetPropertiesSpecific should be successful.");
Dictionary<PropertyNames, byte[]> propertyList = new Dictionary<PropertyNames, byte[]>();
PropertyObj propertyObjPidLidCommonStart = null;
PropertyObj propertyObjPidLidCommonEnd = null;
for (int i = 0; i < getPropertiesSpecificResponse.RowData.PropertyValues.Count; i++)
{
PropertyObj propertyObj = new PropertyObj
{
PropertyName = longIdProperties[i].DisplayName,
ValueType = longIdProperties[i].PropertyType
};
PropertyHelper.GetPropertyObjFromBuffer(propertyObj, getPropertiesSpecificResponse.RowData.PropertyValues[i].Value);
// Verify requirements related with named properties PidNameKeywords, PidNameContentBase, PidNameAcceptLanguage and PidNameContentClass.
this.VerifyMessageSyntaxDataType(propertyObj);
if (propertyObj.PropertyName == PropertyNames.PidLidCommonStart)
{
propertyObjPidLidCommonStart = propertyObj;
}
if (propertyObj.PropertyName == PropertyNames.PidLidCommonEnd)
{
propertyObjPidLidCommonEnd = propertyObj;
}
propertyList.Add(longIdProperties[i].DisplayName, getPropertiesSpecificResponse.RowData.PropertyValues[i].Value);
}
// Verify the requirements of PidLidCommonStart and PidLidCommonEnd.
if (PropertyHelper.IsPropertyValid(propertyObjPidLidCommonStart) || PropertyHelper.IsPropertyValid(propertyObjPidLidCommonEnd))
{
this.VerifyMessageSyntaxPidLidCommonStartAndPidLidCommonEnd(propertyObjPidLidCommonStart, propertyObjPidLidCommonEnd);
}
#endregion
return propertyList;
}
#endregion
}
}
| |
//
// MessageDialog.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Xwt.Backends;
namespace Xwt
{
public static class MessageDialog
{
public static WindowFrame RootWindow { get; set; }
#region ShowError
public static void ShowError (string primaryText)
{
ShowError (RootWindow, primaryText);
}
public static void ShowError (WindowFrame parent, string primaryText)
{
ShowError (parent, primaryText, null);
}
public static void ShowError (string primaryText, string secondaryText)
{
ShowError (RootWindow, primaryText, secondaryText);
}
public static void ShowError (WindowFrame parent, string primaryText, string secondaryText)
{
GenericAlert (parent, StockIcons.Error, primaryText, secondaryText, Command.Ok);
}
#endregion
#region ShowWarning
public static void ShowWarning (string primaryText)
{
ShowWarning (RootWindow, primaryText);
}
public static void ShowWarning (WindowFrame parent, string primaryText)
{
ShowWarning (parent, primaryText, null);
}
public static void ShowWarning (string primaryText, string secondaryText)
{
ShowWarning (RootWindow, primaryText, secondaryText);
}
public static void ShowWarning (WindowFrame parent, string primaryText, string secondaryText)
{
GenericAlert (parent, StockIcons.Warning, primaryText, secondaryText, Command.Ok);
}
#endregion
#region ShowMessage
public static void ShowMessage (string primaryText)
{
ShowMessage (RootWindow, primaryText);
}
public static void ShowMessage (WindowFrame parent, string primaryText)
{
ShowMessage (parent, primaryText, null);
}
public static void ShowMessage (string primaryText, string secondaryText)
{
ShowMessage (RootWindow, primaryText, secondaryText);
}
public static void ShowMessage (Xwt.Drawing.Image icon, string primaryText, string secondaryText)
{
ShowMessage (RootWindow, icon, primaryText, secondaryText);
}
public static void ShowMessage (WindowFrame parent, string primaryText, string secondaryText)
{
ShowMessage (parent, StockIcons.Information, primaryText, secondaryText);
}
public static void ShowMessage (WindowFrame parent, Xwt.Drawing.Image icon, string primaryText, string secondaryText) {
GenericAlert (parent, icon, primaryText, secondaryText, Command.Ok);
}
#endregion
#region Confirm
public static bool Confirm (string primaryText, Command button)
{
return Confirm (primaryText, null, button);
}
public static bool Confirm (string primaryText, string secondaryText, Command button)
{
return GenericAlert (RootWindow, StockIcons.Question, primaryText, secondaryText, Command.Cancel, button) == button;
}
public static bool Confirm (string primaryText, Command button, bool confirmIsDefault)
{
return Confirm (primaryText, null, button, confirmIsDefault);
}
public static bool Confirm (string primaryText, string secondaryText, Command button, bool confirmIsDefault)
{
return GenericAlert (RootWindow, StockIcons.Question, primaryText, secondaryText, confirmIsDefault ? 0 : 1, Command.Cancel, button) == button;
}
public static bool Confirm (ConfirmationMessage message)
{
return GenericAlert (RootWindow, message) == message.ConfirmButton;
}
#endregion
#region AskQuestion
public static Command AskQuestion (string primaryText, params Command[] buttons)
{
return AskQuestion (primaryText, null, buttons);
}
public static Command AskQuestion (string primaryText, string secondaryText, params Command[] buttons)
{
return GenericAlert (RootWindow, StockIcons.Question, primaryText, secondaryText, buttons);
}
public static Command AskQuestion (string primaryText, int defaultButton, params Command[] buttons)
{
return AskQuestion (primaryText, null, defaultButton, buttons);
}
public static Command AskQuestion (string primaryText, string secondaryText, int defaultButton, params Command[] buttons)
{
return GenericAlert (RootWindow, StockIcons.Question, primaryText, secondaryText, defaultButton, buttons);
}
public static Command AskQuestion (QuestionMessage message)
{
return GenericAlert (RootWindow, message);
}
#endregion
static Command GenericAlert (WindowFrame parent, Xwt.Drawing.Image icon, string primaryText, string secondaryText, params Command[] buttons)
{
return GenericAlert (parent, icon, primaryText, secondaryText, buttons.Length - 1, buttons);
}
static Command GenericAlert (WindowFrame parent, Xwt.Drawing.Image icon, string primaryText, string secondaryText, int defaultButton, params Command[] buttons)
{
GenericMessage message = new GenericMessage () {
Icon = icon,
Text = primaryText,
SecondaryText = secondaryText,
DefaultButton = defaultButton
};
foreach (Command but in buttons)
message.Buttons.Add (but);
return GenericAlert (parent, message);
}
static Command GenericAlert (WindowFrame parent, MessageDescription message)
{
if (message.ApplyToAllButton != null)
return message.ApplyToAllButton;
IAlertDialogBackend backend = Toolkit.CurrentEngine.Backend.CreateBackend<IAlertDialogBackend> ();
backend.Initialize (Toolkit.CurrentEngine.Context);
using (backend) {
var res = backend.Run (parent ?? RootWindow, message);
if (backend.ApplyToAll)
message.ApplyToAllButton = res;
return res;
}
}
}
public class MessageDescription
{
public MessageDescription ()
{
DefaultButton = -1;
Buttons = new List<Command> ();
Options = new List<AlertOption> ();
}
public IList<Command> Buttons { get; private set; }
public IList<AlertOption> Options { get; private set; }
internal Command ApplyToAllButton { get; set; }
public Xwt.Drawing.Image Icon { get; set; }
public string Text { get; set; }
public string SecondaryText { get; set; }
public bool AllowApplyToAll { get; set; }
public int DefaultButton { get; set; }
public void AddOption (string id, string text, bool setByDefault)
{
Options.Add (new AlertOption (id, text) { Value = setByDefault });
}
public bool GetOptionValue (string id)
{
foreach (var op in Options)
if (op.Id == id)
return op.Value;
throw new ArgumentException ("Invalid option id");
}
public void SetOptionValue (string id, bool value)
{
foreach (var op in Options) {
if (op.Id == id) {
op.Value = value;
return;
}
}
throw new ArgumentException ("Invalid option id");
}
}
public class AlertOption
{
internal AlertOption (string id, string text)
{
this.Id = id;
this.Text = text;
}
public string Id { get; private set; }
public string Text { get; private set; }
public bool Value { get; set; }
}
public sealed class GenericMessage: MessageDescription
{
public GenericMessage ()
{
}
public GenericMessage (string text)
{
Text = text;
}
public GenericMessage (string text, string secondaryText): this (text)
{
SecondaryText = secondaryText;
}
public new IList<Command> Buttons {
get { return base.Buttons; }
}
}
public sealed class QuestionMessage: MessageDescription
{
public QuestionMessage ()
{
Icon = StockIcons.Question;
}
public QuestionMessage (string text): this ()
{
Text = text;
}
public QuestionMessage (string text, string secondaryText): this (text)
{
SecondaryText = secondaryText;
}
public new IList<Command> Buttons {
get { return base.Buttons; }
}
}
public sealed class ConfirmationMessage: MessageDescription
{
Command confirmButton;
public ConfirmationMessage ()
{
Icon = StockIcons.Question;
Buttons.Add (Command.Cancel);
}
public ConfirmationMessage (Command button): this ()
{
ConfirmButton = button;
}
public ConfirmationMessage (string primaryText, Command button): this (button)
{
Text = primaryText;
}
public ConfirmationMessage (string primaryText, string secondaryText, Command button): this (primaryText, button)
{
SecondaryText = secondaryText;
}
public Command ConfirmButton {
get { return confirmButton; }
set {
if (Buttons.Count == 2)
Buttons.RemoveAt (1);
Buttons.Add (value);
confirmButton = value;
}
}
public bool ConfirmIsDefault {
get {
return DefaultButton == 1;
}
set {
if (value)
DefaultButton = 1;
else
DefaultButton = 0;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Implementation.Debugging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Debugging
{
internal abstract partial class AbstractBreakpointResolver
{
// I believe this is a close approximation of the IVsDebugName string format produced
// by the native language service implementations:
//
// C#: csharp\radmanaged\DebuggerInteraction\BreakpointNameResolver.cs
// VB: vb\Language\VsEditor\Debugging\VsLanguageDebugInfo.vb
//
// The one clear deviation from the native implementation is VB properties. Resolving
// the name of a property in VB used to return all the accessor methods (using their
// metadata names) because setting a breakpoint directly on a property isn't supported
// in VB. In Roslyn, we'll keep things consistent and just return the property name.
// This means that VB users won't be able to set breakpoints on property accessors using
// Ctrl+B, but it would seem that a better solution to this problem would be to simply
// enable setting breakpoints on all accessors by setting a breakpoint on the property
// declaration (same as C# behavior).
private static readonly SymbolDisplayFormat s_vsDebugNameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle:
SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle:
SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions:
SymbolDisplayParameterOptions.IncludeOptionalBrackets |
SymbolDisplayParameterOptions.IncludeType,
propertyStyle:
SymbolDisplayPropertyStyle.NameOnly,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
protected readonly string Text;
private readonly string _language;
private readonly Solution _solution;
private readonly IEqualityComparer<string> _identifierComparer;
protected AbstractBreakpointResolver(
Solution solution,
string text,
string language,
IEqualityComparer<string> identifierComparer)
{
_solution = solution;
this.Text = text;
_language = language;
_identifierComparer = identifierComparer;
}
protected abstract void ParseText(out IList<NameAndArity> nameParts, out int? parameterCount);
protected abstract IEnumerable<ISymbol> GetMembers(INamedTypeSymbol type, string name);
protected abstract bool HasMethodBody(IMethodSymbol method, CancellationToken cancellationToken);
public async Task<IEnumerable<BreakpointResolutionResult>> DoAsync(CancellationToken cancellationToken)
{
var methods = await this.ResolveMethodsAsync(cancellationToken).ConfigureAwait(false);
return methods.Select(CreateBreakpoint).ToImmutableArrayOrEmpty();
}
private BreakpointResolutionResult CreateBreakpoint(ISymbol methodSymbol)
{
var location = methodSymbol.Locations.First(loc => loc.IsInSource);
var document = _solution.GetDocument(location.SourceTree);
var textSpan = new TextSpan(location.SourceSpan.Start, 0);
var vsDebugName = methodSymbol.ToDisplayString(s_vsDebugNameFormat);
return BreakpointResolutionResult.CreateSpanResult(document, textSpan, vsDebugName);
}
private async Task<IEnumerable<ISymbol>> ResolveMethodsAsync(CancellationToken cancellationToken)
{
IList<NameAndArity> nameParts;
int? parameterCount;
this.ParseText(out nameParts, out parameterCount);
// Notes: In C#, indexers can't be resolved by any name. This is acceptable, because the old language
// service wasn't able to resolve them either. In VB, parameterized properties will work in
// the same way as any other property.
// Destructors in C# can be resolved using the method name "Finalize". The resulting string
// representation will use C# language format ("C.~C()"). I verified that this works with
// "Break at Function" (breakpoint is correctly set and can be hit), so I don't see a reason
// to prohibit this (even though the old language service didn't support it).
var members = await FindMembersAsync(nameParts, cancellationToken).ConfigureAwait(false);
// Filter down the list of symbols to "applicable methods", specifically:
// - "regular" methods
// - constructors
// - destructors
// - properties
// - operators?
// - conversions?
// where "applicable" means that the method or property represents a valid place to set a breakpoint
// and that it has the expected number of parameters
return members.Where(m => IsApplicable(m, parameterCount, cancellationToken));
}
private async Task<IEnumerable<ISymbol>> FindMembersAsync(
IList<NameAndArity> nameParts, CancellationToken cancellationToken)
{
if (nameParts.Count == 0)
{
// If there were no name parts, then we don't have any members to return.
// We only expect to hit this condition when the name provided does not parse.
return SpecializedCollections.EmptyList<ISymbol>();
}
else if (nameParts.Count == 1)
{
// They're just searching for a method name. Have to look through every type to find
// it.
return FindMembers(await GetAllTypesAsync(cancellationToken).ConfigureAwait(false), nameParts[0]);
}
else if (nameParts.Count == 2)
{
// They have a type name and a method name. Find a type with a matching name and a
// method in that type.
var types = await GetAllTypesAsync(cancellationToken).ConfigureAwait(false);
types = types.Where(t => MatchesName(t, nameParts[0], _identifierComparer));
return FindMembers(types, nameParts[1]);
}
else
{
// They have a namespace or nested type qualified name. Walk up to the root namespace trying to match.
var containers = _solution.GetGlobalNamespacesAsync(cancellationToken).WaitAndGetResult(cancellationToken);
return FindMembers(containers, nameParts.ToArray());
}
}
private static bool MatchesName(INamespaceOrTypeSymbol typeOrNamespace, NameAndArity nameAndArity, IEqualityComparer<string> comparer)
{
return typeOrNamespace.TypeSwitch(
(INamespaceSymbol namespaceSymbol) =>
comparer.Equals(namespaceSymbol.Name, nameAndArity.Name) && nameAndArity.Arity == 0,
(INamedTypeSymbol typeSymbol) =>
comparer.Equals(typeSymbol.Name, nameAndArity.Name) &&
(nameAndArity.Arity == 0 || nameAndArity.Arity == typeSymbol.TypeArguments.Length));
}
private static bool MatchesNames(INamedTypeSymbol type, NameAndArity[] names, IEqualityComparer<string> comparer)
{
Debug.Assert(type != null);
Debug.Assert(names.Length >= 2);
INamespaceOrTypeSymbol container = type;
// The last element in "names" is the method/property name, but we're only matching against types here,
// so we'll skip the last one.
for (var i = names.Length - 2; i >= 0; i--)
{
if (!MatchesName(container, names[i], comparer))
{
return false;
}
container = ((INamespaceOrTypeSymbol)container.ContainingType) ?? container.ContainingNamespace;
// We ran out of containers to match against before we matched all the names, so this type isn't a match.
if ((container == null) && (i > 0))
{
return false;
}
}
return true;
}
private IEnumerable<ISymbol> FindMembers(IEnumerable<INamespaceOrTypeSymbol> containers, params NameAndArity[] names)
{
// Recursively expand the list of containers to include all types in all nested containers, then filter down to a
// set of candidate types by walking the up the enclosing containers matching by simple name.
var types = containers.SelectMany(c => GetTypeMembersRecursive(c)).Where(t => MatchesNames(t, names, _identifierComparer));
var lastName = names.Last();
return FindMembers(types, lastName);
}
private IEnumerable<ISymbol> FindMembers(IEnumerable<INamedTypeSymbol> types, NameAndArity nameAndArity)
{
// Get the matching members from all types (including constructors and explicit interface
// implementations). If there is a partial method, prefer returning the implementation over
// the definition (since the definition will not be a candidate for setting a breakpoint).
var members = types.SelectMany(t => GetMembers(t, nameAndArity.Name))
.Select(s => GetPartialImplementationPartOrNull(s) ?? s);
return nameAndArity.Arity == 0
? members
: members.OfType<IMethodSymbol>().Where(m => m.TypeParameters.Length == nameAndArity.Arity);
}
private async Task<IEnumerable<INamedTypeSymbol>> GetAllTypesAsync(CancellationToken cancellationToken)
{
var namespaces = await _solution.GetGlobalNamespacesAsync(cancellationToken).ConfigureAwait(false);
return namespaces.GetAllTypes(cancellationToken);
}
private static IMethodSymbol GetPartialImplementationPartOrNull(ISymbol symbol)
{
return (symbol.Kind == SymbolKind.Method) ? ((IMethodSymbol)symbol).PartialImplementationPart : null;
}
/// <summary>
/// Is this method or property a valid place to set a breakpoint and does it match the expected parameter count?
/// </summary>
private bool IsApplicable(ISymbol methodOrProperty, int? parameterCount, CancellationToken cancellationToken)
{
// You can only set a breakpoint on methods (including constructors/destructors) and properties.
var kind = methodOrProperty.Kind;
if (!(kind == SymbolKind.Method || kind == SymbolKind.Property))
{
return false;
}
// You can't set a breakpoint on an abstract method or property.
if (methodOrProperty.IsAbstract)
{
return false;
}
// If parameters were provided, check to make sure the method or property has the expected number
// of parameters (but we don't actually validate the type or name of the supplied parameters).
if (parameterCount != null)
{
if (methodOrProperty.TypeSwitch(
(IMethodSymbol method) => method.Parameters.Length != parameterCount,
(IPropertySymbol property) => property.Parameters.Length != parameterCount))
{
return false;
}
}
// Finally, check to make sure we have source, and if we've got a method symbol, make sure it
// has a body to set a breakpoint on.
if ((methodOrProperty.Language == _language) && methodOrProperty.Locations.Any(location => location.IsInSource))
{
if (methodOrProperty.IsKind(SymbolKind.Method))
{
return HasMethodBody((IMethodSymbol)methodOrProperty, cancellationToken);
}
// Non-abstract properties are always applicable, because you can set a breakpoint on the
// accessor methods (get and/or set).
return true;
}
return false;
}
private static IEnumerable<INamedTypeSymbol> GetTypeMembersRecursive(INamespaceOrTypeSymbol container)
{
return container.TypeSwitch(
(INamespaceSymbol namespaceSymbol) =>
namespaceSymbol.GetMembers().SelectMany(n => GetTypeMembersRecursive(n)),
(INamedTypeSymbol typeSymbol) =>
typeSymbol.GetTypeMembers().SelectMany(t => GetTypeMembersRecursive(t)).Concat(typeSymbol));
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public partial class ConcurrentQueueTests : ProducerConsumerCollectionTests
{
protected override IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>() => new ConcurrentQueue<T>();
protected override IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection) => new ConcurrentQueue<int>(collection);
protected override bool IsEmpty(IProducerConsumerCollection<int> pcc) => ((ConcurrentQueue<int>)pcc).IsEmpty;
protected override bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result) => ((ConcurrentQueue<T>)pcc).TryPeek(out result);
protected override bool ResetImplemented => false;
protected override IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection) => new QueueOracle(collection);
protected override string CopyToNoLengthParamName => null;
[Fact]
public void Concurrent_Enqueue_TryDequeue_AllItemsReceived()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer dequeues items until it gets as many as it expects
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryDequeue(out item))
{
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
else
{
Assert.Equal(0, item);
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer peeks and then dequeues the expected number of items
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryPeek(out item))
{
Assert.Equal(lastReceived + 1, item);
Assert.True(q.TryDequeue(out item));
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Theory]
[InlineData(1, 4, 1024)]
[InlineData(4, 1, 1024)]
[InlineData(3, 3, 1024)]
public void MultipleProducerConsumer_AllItemsTransferred(int producers, int consumers, int itemsPerProducer)
{
var cq = new ConcurrentQueue<int>();
var tasks = new List<Task>();
int totalItems = producers * itemsPerProducer;
int remainingItems = totalItems;
int sum = 0;
for (int i = 0; i < consumers; i++)
{
tasks.Add(Task.Factory.StartNew(() =>
{
while (Volatile.Read(ref remainingItems) > 0)
{
int item;
if (cq.TryDequeue(out item))
{
Interlocked.Add(ref sum, item);
Interlocked.Decrement(ref remainingItems);
}
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
for (int i = 0; i < producers; i++)
{
tasks.Add(Task.Factory.StartNew(() =>
{
for (int item = 1; item <= itemsPerProducer; item++)
{
cq.Enqueue(item);
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
Task.WaitAll(tasks.ToArray());
Assert.Equal(producers * (itemsPerProducer * (itemsPerProducer + 1) / 2), sum);
}
[Theory]
[InlineData(1, false)]
[InlineData(100, false)]
[InlineData(512, false)]
[InlineData(1, true)]
[InlineData(100, true)]
[InlineData(512, true)]
public void CopyTo_AllItemsCopiedAtCorrectLocation(int count, bool viaInterface)
{
var q = new ConcurrentQueue<int>(Enumerable.Range(0, count));
var c = (ICollection)q;
int[] arr = new int[count];
if (viaInterface)
{
c.CopyTo(arr, 0);
}
else
{
q.CopyTo(arr, 0);
}
Assert.Equal(q, arr);
if (count > 1)
{
int toRemove = count / 2;
int remaining = count - toRemove;
for (int i = 0; i < toRemove; i++)
{
int item;
Assert.True(q.TryDequeue(out item));
Assert.Equal(i, item);
}
if (viaInterface)
{
c.CopyTo(arr, 1);
}
else
{
q.CopyTo(arr, 1);
}
Assert.Equal(0, arr[0]);
for (int i = 0; i < remaining; i++)
{
Assert.Equal(arr[1 + i], i + toRemove);
}
}
}
[Fact]
public void IEnumerable_GetAllExpectedItems()
{
IEnumerable<int> enumerable1 = new ConcurrentQueue<int>(Enumerable.Range(1, 5));
IEnumerable enumerable2 = enumerable1;
int expectedNext = 1;
using (IEnumerator<int> enumerator1 = enumerable1.GetEnumerator())
{
IEnumerator enumerator2 = enumerable2.GetEnumerator();
while (enumerator1.MoveNext())
{
Assert.True(enumerator2.MoveNext());
Assert.Equal(expectedNext, enumerator1.Current);
Assert.Equal(expectedNext, enumerator2.Current);
expectedNext++;
}
Assert.False(enumerator2.MoveNext());
Assert.Equal(6, expectedNext);
}
}
[Fact]
public void ReferenceTypes_NulledAfterDequeue()
{
int iterations = 10; // any number <32 will do
var mres = new ManualResetEventSlim[iterations];
// Separated out into another method to ensure that even in debug
// the JIT doesn't force anything to be kept alive for longer than we need.
var queue = ((Func<ConcurrentQueue<Finalizable>>)(() =>
{
var q = new ConcurrentQueue<Finalizable>();
for (int i = 0; i < iterations; i++)
{
mres[i] = new ManualResetEventSlim();
q.Enqueue(new Finalizable(mres[i]));
}
for (int i = 0; i < iterations; i++)
{
Finalizable temp;
Assert.True(q.TryDequeue(out temp));
}
return q;
}))();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(Array.TrueForAll(mres, e => e.IsSet));
GC.KeepAlive(queue);
}
[Fact]
public void ManySegments_ConcurrentDequeues_RemainsConsistent()
{
var cq = new ConcurrentQueue<int>();
const int Iters = 10000;
for (int i = 0; i < Iters; i++)
{
cq.Enqueue(i);
cq.GetEnumerator().Dispose(); // force new segment
}
int dequeues = 0;
Parallel.For(0, Environment.ProcessorCount, i =>
{
while (!cq.IsEmpty)
{
int item;
if (cq.TryDequeue(out item))
{
Interlocked.Increment(ref dequeues);
}
}
});
Assert.Equal(0, cq.Count);
Assert.True(cq.IsEmpty);
Assert.Equal(Iters, dequeues);
}
[Fact]
public void ManySegments_ConcurrentEnqueues_RemainsConsistent()
{
var cq = new ConcurrentQueue<int>();
const int ItemsPerThread = 1000;
int threads = Environment.ProcessorCount;
Parallel.For(0, threads, i =>
{
for (int item = 0; item < ItemsPerThread; item++)
{
cq.Enqueue(item + (i * ItemsPerThread));
cq.GetEnumerator().Dispose();
}
});
Assert.Equal(ItemsPerThread * threads, cq.Count);
Assert.Equal(Enumerable.Range(0, ItemsPerThread * threads), cq.OrderBy(i => i));
}
/// <summary>Sets an event when finalized.</summary>
private sealed class Finalizable
{
private ManualResetEventSlim _mres;
public Finalizable(ManualResetEventSlim mres) { _mres = mres; }
~Finalizable() { _mres.Set(); }
}
protected sealed class QueueOracle : IProducerConsumerCollection<int>
{
private readonly Queue<int> _queue;
public QueueOracle(IEnumerable<int> collection) { _queue = new Queue<int>(collection); }
public int Count => _queue.Count;
public bool IsSynchronized => false;
public object SyncRoot => null;
public void CopyTo(Array array, int index) => ((ICollection)_queue).CopyTo(array, index);
public void CopyTo(int[] array, int index) => _queue.CopyTo(array, index);
public IEnumerator<int> GetEnumerator() => _queue.GetEnumerator();
public int[] ToArray() => _queue.ToArray();
public bool TryAdd(int item) { _queue.Enqueue(item); return true; }
public bool TryTake(out int item)
{
if (_queue.Count > 0)
{
item = _queue.Dequeue();
return true;
}
else
{
item = 0;
return false;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}
| |
// 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.
/*============================================================
**
** Class: SortedList
**
** Purpose: Represents a collection of key/value pairs
** that are sorted by the keys and are accessible
** by key and by index.
**
===========================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections
{
// The SortedList class implements a sorted list of keys and values. Entries in
// a sorted list are sorted by their keys and are accessible both by key and by
// index. The keys of a sorted list can be ordered either according to a
// specific IComparer implementation given when the sorted list is
// instantiated, or according to the IComparable implementation provided
// by the keys themselves. In either case, a sorted list does not allow entries
// with duplicate keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimToSize or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]
[DebuggerDisplay("Count = {Count}")]
#if FEATURE_CORECLR
[Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
#endif
public class SortedList : IDictionary
{
private Object[] _keys;
private Object[] _values;
private int _size;
private int _version;
private IComparer _comparer;
private KeyList _keyList;
private ValueList _valueList;
private Object _syncRoot;
private const int _defaultCapacity = 16;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
Init();
}
private void Init()
{
_keys = Array.Empty<Object>();
_values = Array.Empty<Object>();
_size = 0;
_comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
_keys = new Object[initialCapacity];
_values = new Object[initialCapacity];
_comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer comparer)
: this()
{
if (comparer != null) _comparer = comparer;
}
// Constructs a new sorted list with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(IComparer comparer, int capacity)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d)
: this(d, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d, IComparer comparer)
: this(comparer, (d != null ? d.Count : 0))
{
if (d == null)
throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary);
Contract.EndContractBlock();
d.Keys.CopyTo(_keys, 0);
d.Values.CopyTo(_values, 0);
// Array.Sort(Array keys, Array values, IComparer comparer) does not exist in System.Runtime contract v4.0.10.0.
// This works around that by sorting only on the keys and then assigning values accordingly.
Array.Sort(_keys, comparer);
for (int i = 0; i < _keys.Length; i++)
{
_values[i] = d[_keys[i]];
}
_size = d.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public virtual void Add(Object key, Object value)
{
if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_keys, 0, _size, key, _comparer);
if (i >= 0)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, GetKey(i), key));
Insert(~i, key, value);
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public virtual int Capacity
{
get
{
return _keys.Length;
}
set
{
if (value < Count)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _keys.Length)
{
if (value > 0)
{
Object[] newKeys = new Object[value];
Object[] newValues = new Object[value];
if (_size > 0)
{
Array.Copy(_keys, 0, newKeys, 0, _size);
Array.Copy(_values, 0, newValues, 0, _size);
}
_keys = newKeys;
_values = newValues;
}
else
{
// size can only be zero here.
Debug.Assert(_size == 0, "Size is not zero");
_keys = Array.Empty<Object>();
_values = Array.Empty<Object>();
}
}
}
}
// Returns the number of entries in this sorted list.
//
public virtual int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Keys
{
get
{
return GetKeyList();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Values
{
get
{
return GetValueList();
}
}
// Is this SortedList read-only?
public virtual bool IsReadOnly
{
get { return false; }
}
public virtual bool IsFixedSize
{
get { return false; }
}
// Is this SortedList synchronized (thread-safe)?
public virtual bool IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all entries from this sorted list.
public virtual void Clear()
{
// clear does not change the capacity
_version++;
Array.Clear(_keys, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
Array.Clear(_values, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
// Makes a virtually identical copy of this SortedList. This is a shallow
// copy. IE, the Objects in the SortedList are not cloned - we copy the
// references to those objects.
public virtual Object Clone()
{
SortedList sl = new SortedList(_size);
Array.Copy(_keys, 0, sl._keys, 0, _size);
Array.Copy(_values, 0, sl._values, 0, _size);
sl._size = _size;
sl._version = _version;
sl._comparer = _comparer;
// Don't copy keyList nor valueList.
return sl;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool Contains(Object key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool ContainsKey(Object key)
{
// Yes, this is a SPEC'ed duplicate of Contains().
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
public virtual bool ContainsValue(Object value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array);
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
for (int i = 0; i < Count; i++)
{
DictionaryEntry entry = new DictionaryEntry(_keys[i], _values[i]);
array.SetValue(entry, i + arrayIndex);
}
}
// Copies the values in this SortedList to an KeyValuePairs array.
// KeyValuePairs is different from Dictionary Entry in that it has special
// debugger attributes on its fields.
internal virtual KeyValuePairs[] ToKeyValuePairsArray()
{
KeyValuePairs[] array = new KeyValuePairs[Count];
for (int i = 0; i < Count; i++)
{
array[i] = new KeyValuePairs(_keys[i], _values[i]);
}
return array;
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the current capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = _keys.Length == 0 ? 16 : _keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > ArrayList.MaxArrayLength) newCapacity = ArrayList.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
public virtual Object GetByIndex(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return _values[index];
}
// Returns an IEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns an IDictionaryEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
public virtual IDictionaryEnumerator GetEnumerator()
{
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns the key of the entry at the given index.
//
public virtual Object GetKey(int index)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return _keys[index];
}
// Returns an IList representing the keys of this sorted list. The
// returned list is an alias for the keys of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding, inserting, or modifying elements
// (the Add, AddRange, Insert, InsertRange,
// Reverse, Set, SetRange, and Sort methods
// throw exceptions), but it does allow removal of elements (through the
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
public virtual IList GetKeyList()
{
if (_keyList == null) _keyList = new KeyList(this);
return _keyList;
}
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding or inserting elements (the
// Add, AddRange, Insert and InsertRange
// methods throw exceptions), but it does allow modification and removal of
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
public virtual IList GetValueList()
{
if (_valueList == null) _valueList = new ValueList(this);
return _valueList;
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
public virtual Object this[Object key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0) return _values[i];
return null;
}
set
{
if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_keys, 0, _size, key, _comparer);
if (i >= 0)
{
_values[i] = value;
_version++;
return;
}
Insert(~i, key, value);
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
public virtual int IndexOfKey(Object key)
{
if (key == null)
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
Contract.EndContractBlock();
int ret = Array.BinarySearch(_keys, 0, _size, key, _comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
public virtual int IndexOfValue(Object value)
{
return Array.IndexOf(_values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, Object key, Object value)
{
if (_size == _keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_keys, index, _keys, index + 1, _size - index);
Array.Copy(_values, index, _values, index + 1, _size - index);
}
_keys[index] = key;
_values[index] = value;
_size++;
_version++;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
public virtual void RemoveAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_keys, index + 1, _keys, index, _size - index);
Array.Copy(_values, index + 1, _values, index, _size - index);
}
_keys[_size] = null;
_values[_size] = null;
_version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
public virtual void Remove(Object key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
}
// Sets the value at an index to a given value. The previous value of
// the given entry is overwritten.
//
public virtual void SetByIndex(int index, Object value)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
_values[index] = value;
_version++;
}
// Returns a thread-safe SortedList.
//
public static SortedList Synchronized(SortedList list)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
Contract.EndContractBlock();
return new SyncSortedList(list);
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// sortedList.Clear();
// sortedList.TrimToSize();
//
public virtual void TrimToSize()
{
Capacity = _size;
}
private class SyncSortedList : SortedList
{
private SortedList _list;
private Object _root;
internal SyncSortedList(SortedList list)
{
_list = list;
_root = list.SyncRoot;
}
public override int Count
{
get { lock (_root) { return _list.Count; } }
}
public override Object SyncRoot
{
get { return _root; }
}
public override bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public override bool IsFixedSize
{
get { return _list.IsFixedSize; }
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object this[Object key]
{
get
{
lock (_root)
{
return _list[key];
}
}
set
{
lock (_root)
{
_list[key] = value;
}
}
}
public override void Add(Object key, Object value)
{
lock (_root)
{
_list.Add(key, value);
}
}
public override int Capacity
{
get { lock (_root) { return _list.Capacity; } }
}
public override void Clear()
{
lock (_root)
{
_list.Clear();
}
}
public override Object Clone()
{
lock (_root)
{
return _list.Clone();
}
}
public override bool Contains(Object key)
{
lock (_root)
{
return _list.Contains(key);
}
}
public override bool ContainsKey(Object key)
{
lock (_root)
{
return _list.ContainsKey(key);
}
}
public override bool ContainsValue(Object key)
{
lock (_root)
{
return _list.ContainsValue(key);
}
}
public override void CopyTo(Array array, int index)
{
lock (_root)
{
_list.CopyTo(array, index);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetByIndex(int index)
{
lock (_root)
{
return _list.GetByIndex(index);
}
}
public override IDictionaryEnumerator GetEnumerator()
{
lock (_root)
{
return _list.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetKey(int index)
{
lock (_root)
{
return _list.GetKey(index);
}
}
public override IList GetKeyList()
{
lock (_root)
{
return _list.GetKeyList();
}
}
public override IList GetValueList()
{
lock (_root)
{
return _list.GetValueList();
}
}
public override int IndexOfKey(Object key)
{
if (key == null)
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
Contract.EndContractBlock();
lock (_root)
{
return _list.IndexOfKey(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int IndexOfValue(Object value)
{
lock (_root)
{
return _list.IndexOfValue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void RemoveAt(int index)
{
lock (_root)
{
_list.RemoveAt(index);
}
}
public override void Remove(Object key)
{
lock (_root)
{
_list.Remove(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void SetByIndex(int index, Object value)
{
lock (_root)
{
_list.SetByIndex(index, value);
}
}
internal override KeyValuePairs[] ToKeyValuePairsArray()
{
return _list.ToKeyValuePairsArray();
}
public override void TrimToSize()
{
lock (_root)
{
_list.TrimToSize();
}
}
}
private class SortedListEnumerator : IDictionaryEnumerator
{
private SortedList _sortedList;
private Object _key;
private Object _value;
private int _index;
private int _startIndex; // Store for Reset.
private int _endIndex;
private int _version;
private bool _current; // Is the current element valid?
private int _getObjectRetType; // What should GetObject return?
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
internal SortedListEnumerator(SortedList sortedList, int index, int count,
int getObjRetType)
{
_sortedList = sortedList;
_index = index;
_startIndex = index;
_endIndex = index + count;
_version = sortedList._version;
_getObjectRetType = getObjRetType;
_current = false;
}
public virtual Object Key
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return _key;
}
}
public virtual bool MoveNext()
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < _endIndex)
{
_key = _sortedList._keys[_index];
_value = _sortedList._values[_index];
_index++;
_current = true;
return true;
}
_key = null;
_value = null;
_current = false;
return false;
}
public virtual DictionaryEntry Entry
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return new DictionaryEntry(_key, _value);
}
}
public virtual Object Current
{
get
{
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
if (_getObjectRetType == Keys)
return _key;
else if (_getObjectRetType == Values)
return _value;
else
return new DictionaryEntry(_key, _value);
}
}
public virtual Object Value
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return _value;
}
}
public virtual void Reset()
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = _startIndex;
_current = false;
_key = null;
_value = null;
}
}
private class KeyList : IList
{
private SortedList _sortedList;
internal KeyList(SortedList sortedList)
{
_sortedList = sortedList;
}
public virtual int Count
{
get { return _sortedList._size; }
}
public virtual bool IsReadOnly
{
get { return true; }
}
public virtual bool IsFixedSize
{
get { return true; }
}
public virtual bool IsSynchronized
{
get { return _sortedList.IsSynchronized; }
}
public virtual Object SyncRoot
{
get { return _sortedList.SyncRoot; }
}
public virtual int Add(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return 0; // suppress compiler warning
}
public virtual void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual bool Contains(Object key)
{
return _sortedList.Contains(key);
}
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(_sortedList._keys, 0, array, arrayIndex, _sortedList.Count);
}
public virtual void Insert(int index, Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual Object this[int index]
{
get
{
return _sortedList.GetKey(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator(_sortedList, 0, _sortedList.Count, SortedListEnumerator.Keys);
}
public virtual int IndexOf(Object key)
{
if (key == null)
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_sortedList._keys, 0,
_sortedList.Count, key, _sortedList._comparer);
if (i >= 0) return i;
return -1;
}
public virtual void Remove(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
private class ValueList : IList
{
private SortedList _sortedList;
internal ValueList(SortedList sortedList)
{
_sortedList = sortedList;
}
public virtual int Count
{
get { return _sortedList._size; }
}
public virtual bool IsReadOnly
{
get { return true; }
}
public virtual bool IsFixedSize
{
get { return true; }
}
public virtual bool IsSynchronized
{
get { return _sortedList.IsSynchronized; }
}
public virtual Object SyncRoot
{
get { return _sortedList.SyncRoot; }
}
public virtual int Add(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual bool Contains(Object value)
{
return _sortedList.ContainsValue(value);
}
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(_sortedList._values, 0, array, arrayIndex, _sortedList.Count);
}
public virtual void Insert(int index, Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual Object this[int index]
{
get
{
return _sortedList.GetByIndex(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator(_sortedList, 0, _sortedList.Count, SortedListEnumerator.Values);
}
public virtual int IndexOf(Object value)
{
return Array.IndexOf(_sortedList._values, value, 0, _sortedList.Count);
}
public virtual void Remove(Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
// internal debug view class for sorted list
internal class SortedListDebugView
{
private SortedList _sortedList;
public SortedListDebugView(SortedList sortedList)
{
if (sortedList == null)
{
throw new ArgumentNullException(nameof(sortedList));
}
Contract.EndContractBlock();
_sortedList = sortedList;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePairs[] Items
{
get
{
return _sortedList.ToKeyValuePairsArray();
}
}
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Lucene.Net.Search
{
/*
* 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.
*/
//Used to hold non-generic nested types
public static class FieldValueHitQueue
{
// had to change from internal to public, due to public accessability of FieldValueHitQueue
public class Entry : ScoreDoc
{
public int Slot { get; set; } // LUCENENET NOTE: For some reason, this was not made readonly in the original
public Entry(int slot, int doc, float score)
: base(doc, score)
{
this.Slot = slot;
}
public override string ToString()
{
return "slot:" + Slot + " " + base.ToString();
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is just one comparer.
/// </summary>
internal sealed class OneComparerFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
private int oneReverseMul;
public OneComparerFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
SortField field = fields[0];
SetComparer(0, field.GetComparer(size, 0));
oneReverseMul = field.reverse ? -1 : 1;
ReverseMul[0] = oneReverseMul;
}
/// <summary> Returns whether <c>a</c> is less relevant than <c>b</c>.</summary>
/// <param name="hitA">ScoreDoc</param>
/// <param name="hitB">ScoreDoc</param>
/// <returns><c>true</c> if document <c>a</c> should be sorted after document <c>b</c>.</returns>
protected internal override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int c = oneReverseMul * m_firstComparer.Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
return c > 0;
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is more than one comparer.
/// </summary>
internal sealed class MultiComparersFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
public MultiComparersFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
int numComparers = m_comparers.Length;
for (int i = 0; i < numComparers; ++i)
{
SortField field = fields[i];
m_reverseMul[i] = field.reverse ? -1 : 1;
SetComparer(i, field.GetComparer(size, i));
}
}
protected internal override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int numComparers = m_comparers.Length;
for (int i = 0; i < numComparers; ++i)
{
int c = m_reverseMul[i] * m_comparers[i].Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
// Short circuit
return c > 0;
}
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
}
/// <summary> Creates a hit queue sorted by the given list of fields.
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length <c>numHits</c>.
/// </summary>
/// <param name="fields"><see cref="SortField"/> array we are sorting by in priority order (highest
/// priority first); cannot be <c>null</c> or empty
/// </param>
/// <param name="size">The number of hits to retain. Must be greater than zero.
/// </param>
/// <exception cref="IOException">If there is a low-level IO error</exception>
public static FieldValueHitQueue<T> Create<T>(SortField[] fields, int size)
where T : FieldValueHitQueue.Entry
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
if (fields.Length == 1)
{
return new FieldValueHitQueue.OneComparerFieldValueHitQueue<T>(fields, size);
}
else
{
return new FieldValueHitQueue.MultiComparersFieldValueHitQueue<T>(fields, size);
}
}
}
/// <summary>
/// Expert: A hit queue for sorting by hits by terms in more than one field.
/// Uses <c>FieldCache.DEFAULT</c> for maintaining
/// internal term lookup tables.
/// <para/>
/// @lucene.experimental
/// @since 2.9 </summary>
/// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
/// <seealso cref="FieldCache"/>
public abstract class FieldValueHitQueue<T> : Util.PriorityQueue<T>
where T : FieldValueHitQueue.Entry
{
// prevent instantiation and extension.
internal FieldValueHitQueue(SortField[] fields, int size)
: base(size)
{
// When we get here, fields.length is guaranteed to be > 0, therefore no
// need to check it again.
// All these are required by this class's API - need to return arrays.
// Therefore even in the case of a single comparer, create an array
// anyway.
this.m_fields = fields;
int numComparers = fields.Length;
m_comparers = new FieldComparer[numComparers];
m_reverseMul = new int[numComparers];
}
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual FieldComparer[] Comparers => m_comparers;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual int[] ReverseMul => m_reverseMul;
public virtual void SetComparer(int pos, FieldComparer comparer)
{
if (pos == 0)
{
m_firstComparer = comparer;
}
m_comparers[pos] = comparer;
}
/// <summary>
/// Stores the sort criteria being used. </summary>
protected readonly SortField[] m_fields;
protected readonly FieldComparer[] m_comparers; // use setComparer to change this array
protected FieldComparer m_firstComparer; // this must always be equal to comparers[0]
protected readonly int[] m_reverseMul;
internal FieldComparer FirstComparer => this.m_firstComparer;
// LUCENENET NOTE: We don't need this declaration because we are using
// a generic constraint on T
//public abstract bool LessThan(FieldValueHitQueue.Entry a, FieldValueHitQueue.Entry b);
/// <summary>
/// Given a queue <see cref="FieldValueHitQueue.Entry"/>, creates a corresponding <see cref="FieldDoc"/>
/// that contains the values used to sort the given document.
/// These values are not the raw values out of the index, but the internal
/// representation of them. This is so the given search hit can be collated by
/// a MultiSearcher with other search hits.
/// </summary>
/// <param name="entry"> The <see cref="FieldValueHitQueue.Entry"/> used to create a <see cref="FieldDoc"/> </param>
/// <returns> The newly created <see cref="FieldDoc"/> </returns>
/// <seealso cref="IndexSearcher.Search(Query,Filter,int,Sort)"/>
internal virtual FieldDoc FillFields(FieldValueHitQueue.Entry entry)
{
int n = m_comparers.Length;
IComparable[] fields = new IComparable[n];
for (int i = 0; i < n; ++i)
{
fields[i] = m_comparers[i][entry.Slot];
}
//if (maxscore > 1.0f) doc.score /= maxscore; // normalize scores
return new FieldDoc(entry.Doc, entry.Score, fields);
}
/// <summary>
/// Returns the <see cref="SortField"/>s being used by this hit queue. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
internal virtual SortField[] Fields => m_fields;
}
}
| |
using System;
using System.Drawing;
using FoxTrader.UI.ControlInternal;
using OpenTK.Input;
namespace FoxTrader.UI.Control
{
/// <summary>Base slider</summary>
internal class Slider : GameControl
{
protected readonly SliderBar m_sliderBar;
protected float m_max;
protected float m_min;
protected int m_notchCount;
protected bool m_snapToNotches;
protected float m_value;
/// <summary>Initializes a new instance of the <see cref="Slider" /> class</summary>
/// <param name="c_parentControl">Parent control</param>
protected Slider(GameControl c_parentControl) : base(c_parentControl)
{
SetBounds(new Rectangle(0, 0, 32, 128));
m_sliderBar = new SliderBar(this);
m_sliderBar.Dragged += OnMoved;
m_min = 0.0f;
m_max = 1.0f;
m_snapToNotches = false;
m_notchCount = 5;
m_value = 0.0f;
KeyboardInputEnabled = true;
IsTabable = true;
}
/// <summary>Number of notches on the slider axis</summary>
public int NotchCount
{
get
{
return m_notchCount;
}
set
{
m_notchCount = value;
}
}
/// <summary>Determines whether the slider should snap to notches</summary>
public bool SnapToNotches
{
get
{
return m_snapToNotches;
}
set
{
m_snapToNotches = value;
}
}
/// <summary>Minimum value</summary>
public float Min
{
get
{
return m_min;
}
set
{
SetRange(value, m_max);
}
}
/// <summary>Maximum value</summary>
public float Max
{
get
{
return m_max;
}
set
{
SetRange(m_min, value);
}
}
/// <summary>Current value</summary>
public float Value
{
get
{
return m_min + (m_value * (m_max - m_min));
}
set
{
if (value < m_min)
{
value = m_min;
}
if (value > m_max)
{
value = m_max;
}
// Normalize Value
value = (value - m_min) / (m_max - m_min);
SetValueInternal(value);
Redraw();
}
}
/// <summary>Invoked when the value has been changed</summary>
public event ValueEventHandler ValueChanged;
public override void OnKeyDown(KeyboardKeyEventArgs c_keyboardKeyEventArgs)
{
switch (c_keyboardKeyEventArgs.Key)
{
case Key.Right:
case Key.Up:
{
Value = Value + 1;
}
break;
case Key.Left:
case Key.Down:
{
Value = Value - 1;
}
break;
case Key.Home:
{
Value = m_min;
}
break;
case Key.End:
{
Value = m_max;
}
break;
}
}
protected virtual void OnMoved(GameControl c_control)
{
SetValueInternal(CalculateValue());
}
protected virtual float CalculateValue()
{
return 0;
}
protected virtual void UpdateBarFromValue()
{
}
protected virtual void SetValueInternal(float c_value)
{
if (m_snapToNotches)
{
c_value = (float)Math.Floor((c_value * m_notchCount) + 0.5f);
c_value /= m_notchCount;
}
if (m_value != c_value)
{
m_value = c_value;
ValueChanged?.Invoke(this);
}
UpdateBarFromValue();
}
/// <summary>Sets the value range</summary>
/// <param name="c_min">Minimum value</param>
/// <param name="c_max">Maximum value</param>
public void SetRange(float c_min, float c_max)
{
m_min = c_min;
m_max = c_max;
}
/// <summary>Renders the focus overlay</summary>
/// <param name="c_skin">Skin to use</param>
protected override void RenderFocus(Skin c_skin)
{
if (GetCanvas().KeyboardFocus != this || !IsTabable)
{
return;
}
c_skin.DrawKeyboardHighlight(this, RenderBounds, 0);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// 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 Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Commands.Sql.Database.Model;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Database.Cmdlet
{
/// <summary>
/// Cmdlet to create a new Azure Sql Database
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureRmSqlDatabase", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Medium)]
public class SetAzureSqlDatabase : AzureSqlDatabaseCmdletBase<IEnumerable<AzureSqlDatabaseModel>>
{
private const string UpdateParameterSetName = "Update";
private const string RenameParameterSetName = "Rename";
/// <summary>
/// Gets or sets the name of the Azure SQL Database
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2,
HelpMessage = "The name of the Azure SQL Database.")]
[Alias("Name")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the maximum size of the Azure SQL Database in bytes
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The maximum size of the Azure SQL Database in bytes.",
ParameterSetName = UpdateParameterSetName)]
[ValidateNotNullOrEmpty]
public long MaxSizeBytes { get; set; }
/// <summary>
/// Gets or sets the edition to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The edition to assign to the Azure SQL Database.",
ParameterSetName = UpdateParameterSetName)]
[ValidateNotNullOrEmpty]
public DatabaseEdition Edition { get; set; }
/// <summary>
/// Gets or sets the name of the service objective to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the service objective to assign to the Azure SQL Database.",
ParameterSetName = UpdateParameterSetName)]
[ValidateNotNullOrEmpty]
public string RequestedServiceObjectiveName { get; set; }
/// <summary>
/// Gets or sets the name of the Elastic Pool to put the database in
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The name of the Elastic Pool to put the database in.",
ParameterSetName = UpdateParameterSetName)]
[ValidateNotNullOrEmpty]
public string ElasticPoolName { get; set; }
/// <summary>
/// Gets or sets the read scale option to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The read scale option to assign to the Azure SQL Database.(Enabled/Disabled)",
ParameterSetName = UpdateParameterSetName)]
[ValidateNotNullOrEmpty]
public DatabaseReadScale ReadScale { get; set; }
/// <summary>
/// Gets or sets the tags associated with the Azure Sql Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The tags to associate with the Azure Sql Database",
ParameterSetName = UpdateParameterSetName)]
[Alias("Tag")]
public Hashtable Tags { get; set; }
/// <summary>
/// Gets or sets the zone redundant option to assign to the Azure SQL Database
/// </summary>
[Parameter(Mandatory = false,
HelpMessage = "The zone redundancy to associate with the Azure Sql Database",
ParameterSetName = UpdateParameterSetName)]
public SwitchParameter ZoneRedundant { get; set; }
/// <summary>
/// Gets or sets the new name.
/// </summary>
[Parameter(Mandatory = true,
HelpMessage = "The new name to rename the database to.",
ParameterSetName = RenameParameterSetName)]
public string NewName { get; set; }
/// <summary>
/// Gets or sets whether or not to run this cmdlet in the background as a job
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
/// <summary>
/// Overriding to add warning message
/// </summary>
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
}
/// <summary>
/// Get the entities from the service
/// </summary>
/// <returns>The list of entities</returns>
protected override IEnumerable<AzureSqlDatabaseModel> GetEntity()
{
return new List<AzureSqlDatabaseModel>() {
ModelAdapter.GetDatabase(this.ResourceGroupName, this.ServerName, this.DatabaseName)
};
}
/// <summary>
/// Create the model from user input
/// </summary>
/// <param name="model">Model retrieved from service</param>
/// <returns>The model that was passed in</returns>
protected override IEnumerable<AzureSqlDatabaseModel> ApplyUserInputToModel(IEnumerable<AzureSqlDatabaseModel> model)
{
List<Model.AzureSqlDatabaseModel> newEntity = new List<AzureSqlDatabaseModel>();
if (this.ParameterSetName == UpdateParameterSetName)
{
newEntity.Add(new AzureSqlDatabaseModel()
{
ResourceGroupName = ResourceGroupName,
ServerName = ServerName,
DatabaseName = DatabaseName,
Edition = Edition,
MaxSizeBytes = MaxSizeBytes,
RequestedServiceObjectiveName = RequestedServiceObjectiveName,
Tags = TagsConversionHelper.ReadOrFetchTags(this, model.FirstOrDefault().Tags),
ElasticPoolName = ElasticPoolName,
Location = model.FirstOrDefault().Location,
ReadScale = ReadScale,
ZoneRedundant =
MyInvocation.BoundParameters.ContainsKey("ZoneRedundant")
? (bool?) ZoneRedundant.ToBool()
: null
});
}
return newEntity;
}
/// <summary>
/// Update the database
/// </summary>
/// <param name="entity">The output of apply user input to model</param>
/// <returns>The input entity</returns>
protected override IEnumerable<AzureSqlDatabaseModel> PersistChanges(IEnumerable<AzureSqlDatabaseModel> entity)
{
switch (this.ParameterSetName)
{
case UpdateParameterSetName:
return new List<AzureSqlDatabaseModel>
{
ModelAdapter.UpsertDatabaseWithNewSdk(
this.ResourceGroupName,
this.ServerName,
new AzureSqlDatabaseCreateOrUpdateModel
{
Database = entity.First()
})
};
case RenameParameterSetName:
ModelAdapter.RenameDatabase(
this.ResourceGroupName,
this.ServerName,
this.DatabaseName,
this.NewName);
return new List<AzureSqlDatabaseModel>
{
ModelAdapter.GetDatabase(
this.ResourceGroupName,
this.ServerName,
this.NewName)
};
default:
throw new ArgumentException(this.ParameterSetName);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.