context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for RouteFiltersOperations. /// </summary> public static partial class RouteFiltersOperationsExtensions { /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> public static void Delete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName) { operations.DeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> public static RouteFilter Get(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, routeFilterName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> GetAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> public static RouteFilter CreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> CreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> public static RouteFilter Update(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters) { return operations.UpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> UpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<RouteFilter> ListByResourceGroup(this IRouteFiltersOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListByResourceGroupAsync(this IRouteFiltersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<RouteFilter> List(this IRouteFiltersOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListAsync(this IRouteFiltersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> public static void BeginDelete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName) { operations.BeginDeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> public static RouteFilter BeginCreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> BeginCreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> public static RouteFilter BeginUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters) { return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> BeginUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RouteFilter> ListByResourceGroupNext(this IRouteFiltersOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListByResourceGroupNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RouteFilter> ListNext(this IRouteFiltersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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/")] [InlineData("/tmp/", null)] 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, original); 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('.'); } // Now no longer throws unless over ~32K Assert.NotNull(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_MaxPathNotTooLong() { // Shouldn't throw anymore Path.GetFullPath(@"C:\" + new string('a', 255) + @"\"); } [PlatformSpecific(PlatformID.Windows)] [Fact] public static void GetFullPath_Windows_PathTooLong() { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\")); } [PlatformSpecific(PlatformID.Windows)] [Theory] [InlineData(@"C:\", @"C:\")] [InlineData(@"C:\.", @"C:\")] [InlineData(@"C:\..", @"C:\")] [InlineData(@"C:\..\..", @"C:\")] [InlineData(@"C:\A\..", @"C:\")] [InlineData(@"C:\..\..\A\..", @"C:\")] public static void GetFullPath_Windows_RelativeRoot(string path, string expected) { Assert.Equal(Path.GetFullPath(path), expected); } [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); }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.Speech.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Speech.V1; using Google.LongRunning; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedSpeechClientSnippets { /// <summary>Snippet for RecognizeAsync</summary> public async Task RecognizeAsync() { // Snippet: RecognizeAsync(RecognitionConfig,RecognitionAudio,CallSettings) // Additional: RecognizeAsync(RecognitionConfig,RecognitionAudio,CancellationToken) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request RecognizeResponse response = await speechClient.RecognizeAsync(config, audio); // End snippet } /// <summary>Snippet for Recognize</summary> public void Recognize() { // Snippet: Recognize(RecognitionConfig,RecognitionAudio,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request RecognizeResponse response = speechClient.Recognize(config, audio); // End snippet } /// <summary>Snippet for RecognizeAsync</summary> public async Task RecognizeAsync_RequestObject() { // Snippet: RecognizeAsync(RecognizeRequest,CallSettings) // Additional: RecognizeAsync(RecognizeRequest,CancellationToken) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognizeRequest request = new RecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request RecognizeResponse response = await speechClient.RecognizeAsync(request); // End snippet } /// <summary>Snippet for Recognize</summary> public void Recognize_RequestObject() { // Snippet: Recognize(RecognizeRequest,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognizeRequest request = new RecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request RecognizeResponse response = speechClient.Recognize(request); // End snippet } /// <summary>Snippet for LongRunningRecognizeAsync</summary> public async Task LongRunningRecognizeAsync() { // Snippet: LongRunningRecognizeAsync(RecognitionConfig,RecognitionAudio,CallSettings) // Additional: LongRunningRecognizeAsync(RecognitionConfig,RecognitionAudio,CancellationToken) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(config, audio); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognize</summary> public void LongRunningRecognize() { // Snippet: LongRunningRecognize(RecognitionConfig,RecognitionAudio,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(config, audio); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognizeAsync</summary> public async Task LongRunningRecognizeAsync_RequestObject() { // Snippet: LongRunningRecognizeAsync(LongRunningRecognizeRequest,CallSettings) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) LongRunningRecognizeRequest request = new LongRunningRecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(request); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognize</summary> public void LongRunningRecognize_RequestObject() { // Snippet: LongRunningRecognize(LongRunningRecognizeRequest,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) LongRunningRecognizeRequest request = new LongRunningRecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(request); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for StreamingRecognize</summary> public async Task StreamingRecognize() { // Snippet: StreamingRecognize(CallSettings,BidirectionalStreamingSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize streaming call, retrieving the stream object SpeechClient.StreamingRecognizeStream duplexStream = speechClient.StreamingRecognize(); // Sending requests and retrieving responses can be arbitrarily interleaved. // Exact sequence will depend on client/server behavior. // Create task to do something with responses from server Task responseHandlerTask = Task.Run(async () => { IAsyncEnumerator<StreamingRecognizeResponse> responseStream = duplexStream.ResponseStream; while (await responseStream.MoveNext()) { StreamingRecognizeResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed }); // Send requests to the server bool done = false; while (!done) { // Initialize a request StreamingRecognizeRequest request = new StreamingRecognizeRequest(); // Stream a request to the server await duplexStream.WriteAsync(request); // Set "done" to true when sending requests is complete } // Complete writing requests to the stream await duplexStream.WriteCompleteAsync(); // Await the response handler. // This will complete once all server responses have been processed. await responseHandlerTask; // End snippet } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.PythonTools.EnvironmentsList.Properties; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; using Microsoft.VisualStudioTools.Wpf; namespace Microsoft.PythonTools.EnvironmentsList { internal partial class ConfigurationExtension : UserControl { public static readonly ICommand Apply = new RoutedCommand(); public static readonly ICommand Reset = new RoutedCommand(); public static readonly ICommand AutoDetect = new RoutedCommand(); public static readonly ICommand Remove = new RoutedCommand(); private readonly ConfigurationExtensionProvider _provider; public ConfigurationExtension(ConfigurationExtensionProvider provider) { _provider = provider; DataContextChanged += ConfigurationExtension_DataContextChanged; InitializeComponent(); } void ConfigurationExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var view = e.NewValue as EnvironmentView; if (view != null) { var current = Subcontext.DataContext as ConfigurationEnvironmentView; if (current == null || current.EnvironmentView != view) { var cev = new ConfigurationEnvironmentView(view); _provider.ResetConfiguration(cev); Subcontext.DataContext = cev; } } } private void Apply_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && _provider.IsConfigurationChanged(view); e.Handled = true; } private void Apply_Executed(object sender, ExecutedRoutedEventArgs e) { _provider.ApplyConfiguration((ConfigurationEnvironmentView)e.Parameter); e.Handled = true; } private void Reset_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && _provider.IsConfigurationChanged(view); e.Handled = true; } private void Reset_Executed(object sender, ExecutedRoutedEventArgs e) { _provider.ResetConfiguration((ConfigurationEnvironmentView)e.Parameter); e.Handled = true; } private void Remove_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null; e.Handled = true; } private void Remove_Executed(object sender, ExecutedRoutedEventArgs e) { _provider.RemoveConfiguration((ConfigurationEnvironmentView)e.Parameter); e.Handled = true; } private void Browse_CanExecute(object sender, CanExecuteRoutedEventArgs e) { Commands.CanExecute(null, sender, e); } private void Browse_Executed(object sender, ExecutedRoutedEventArgs e) { Commands.Executed(null, sender, e); } private void SelectAllText(object sender, RoutedEventArgs e) { var tb = sender as TextBox; if (tb != null) { tb.SelectAll(); } } private void AutoDetect_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && !view.IsAutoDetectRunning && ( Directory.Exists(view.PrefixPath) || File.Exists(view.InterpreterPath) || File.Exists(view.WindowsInterpreterPath) ); } private async void AutoDetect_Executed(object sender, ExecutedRoutedEventArgs e) { var view = (ConfigurationEnvironmentView)e.Parameter; try { view.IsAutoDetectRunning = true; CommandManager.InvalidateRequerySuggested(); var newView = await AutoDetectAsync(view.Values); view.Values = newView; CommandManager.InvalidateRequerySuggested(); } finally { view.IsAutoDetectRunning = false; } } private async Task<ConfigurationValues> AutoDetectAsync(ConfigurationValues view) { if (!Directory.Exists(view.PrefixPath)) { if (File.Exists(view.InterpreterPath)) { view.PrefixPath = Path.GetDirectoryName(view.InterpreterPath); } else if (File.Exists(view.WindowsInterpreterPath)) { view.PrefixPath = Path.GetDirectoryName(view.WindowsInterpreterPath); } else if (Directory.Exists(view.LibraryPath)) { view.PrefixPath = Path.GetDirectoryName(view.LibraryPath); } else { // Don't have enough information, so abort without changing // any settings. return view; } while (Directory.Exists(view.PrefixPath) && !File.Exists(CommonUtils.FindFile(view.PrefixPath, "site.py"))) { view.PrefixPath = Path.GetDirectoryName(view.PrefixPath); } } if (!Directory.Exists(view.PrefixPath)) { // If view.PrefixPath is not valid by this point, we can't find anything // else, so abort withou changing any settings. return view; } if (!File.Exists(view.InterpreterPath)) { view.InterpreterPath = CommonUtils.FindFile( view.PrefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable, firstCheck: new[] { "scripts" } ); } if (!File.Exists(view.WindowsInterpreterPath)) { view.WindowsInterpreterPath = CommonUtils.FindFile( view.PrefixPath, CPythonInterpreterFactoryConstants.WindowsExecutable, firstCheck: new[] { "scripts" } ); } if (!Directory.Exists(view.LibraryPath)) { var sitePy = CommonUtils.FindFile( view.PrefixPath, "os.py", firstCheck: new[] { "lib" } ); if (File.Exists(sitePy)) { view.LibraryPath = Path.GetDirectoryName(sitePy); } } if (File.Exists(view.InterpreterPath)) { using (var output = ProcessOutput.RunHiddenAndCapture( view.InterpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))" )) { var exitCode = await output; if (exitCode == 0) { view.VersionName = output.StandardOutputLines.FirstOrDefault() ?? view.VersionName; } } var binaryType = Microsoft.PythonTools.Interpreter.NativeMethods.GetBinaryType(view.InterpreterPath); if (binaryType == ProcessorArchitecture.Amd64) { view.ArchitectureName = "64-bit"; } else if (binaryType == ProcessorArchitecture.X86) { view.ArchitectureName = "32-bit"; } } return view; } } sealed class ConfigurationExtensionProvider : IEnvironmentViewExtension { private FrameworkElement _wpfObject; private readonly ConfigurablePythonInterpreterFactoryProvider _factoryProvider; internal ConfigurationExtensionProvider(ConfigurablePythonInterpreterFactoryProvider factoryProvider) { _factoryProvider = factoryProvider; } public void ApplyConfiguration(ConfigurationEnvironmentView view) { _factoryProvider.SetOptions(new InterpreterFactoryCreationOptions { Id = view.EnvironmentView.Factory.Id, Description = view.Description, PrefixPath = view.PrefixPath, InterpreterPath = view.InterpreterPath, WindowInterpreterPath = view.WindowsInterpreterPath, LibraryPath = view.LibraryPath, PathEnvironmentVariableName = view.PathEnvironmentVariable, Architecture = view.ArchitectureName == "64-bit" ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86, LanguageVersionString = view.VersionName }); } public bool IsConfigurationChanged(ConfigurationEnvironmentView view) { var factory = view.EnvironmentView.Factory; var arch = factory.Configuration.Architecture == ProcessorArchitecture.Amd64 ? "64-bit" : "32-bit"; return view.Description != factory.Description || view.PrefixPath != factory.Configuration.PrefixPath || view.InterpreterPath != factory.Configuration.InterpreterPath || view.WindowsInterpreterPath != factory.Configuration.WindowsInterpreterPath || view.LibraryPath != factory.Configuration.LibraryPath || view.PathEnvironmentVariable != factory.Configuration.PathEnvironmentVariable || view.ArchitectureName != arch || view.VersionName != factory.Configuration.Version.ToString(); } public void ResetConfiguration(ConfigurationEnvironmentView view) { var factory = view.EnvironmentView.Factory; view.Description = factory.Description; view.PrefixPath = factory.Configuration.PrefixPath; view.InterpreterPath = factory.Configuration.InterpreterPath; view.WindowsInterpreterPath = factory.Configuration.WindowsInterpreterPath; view.LibraryPath = factory.Configuration.LibraryPath; view.PathEnvironmentVariable = factory.Configuration.PathEnvironmentVariable; view.ArchitectureName = factory.Configuration.Architecture == ProcessorArchitecture.Amd64 ? "64-bit" : "32-bit"; view.VersionName = factory.Configuration.Version.ToString(); } public void RemoveConfiguration(ConfigurationEnvironmentView view) { var factory = view.EnvironmentView.Factory; _factoryProvider.RemoveInterpreter(factory.Id); } public int SortPriority { get { return -9; } } public string LocalizedDisplayName { get { return Resources.ConfigurationExtensionDisplayName; } } public FrameworkElement WpfObject { get { if (_wpfObject == null) { _wpfObject = new ConfigurationExtension(this); } return _wpfObject; } } public object HelpContent { get { return Resources.ConfigurationExtensionHelpContent; } } } struct ConfigurationValues { public string Description; public string PrefixPath; public string InterpreterPath; public string WindowsInterpreterPath; public string LibraryPath; public string PathEnvironmentVariable; public string VersionName; public string ArchitectureName; } sealed class ConfigurationEnvironmentView : INotifyPropertyChanged { private static readonly string[] _architectureNames = new[] { "32-bit", "64-bit" }; private static readonly string[] _versionNames = new[] { "2.5", "2.6", "2.7", "3.0", "3.1", "3.2", "3.3", "3.4", "3.5" }; private readonly EnvironmentView _view; private bool _isAutoDetectRunning; private ConfigurationValues _values; public ConfigurationEnvironmentView(EnvironmentView view) { _view = view; } public EnvironmentView EnvironmentView { get { return _view; } } public static IList<string> ArchitectureNames { get { return _architectureNames; } } public static IList<string> VersionNames { get { return _versionNames; } } public bool IsAutoDetectRunning { get { return _isAutoDetectRunning; } set { if (_isAutoDetectRunning != value) { _isAutoDetectRunning = value; OnPropertyChanged(); } } } public ConfigurationValues Values { get { return _values; } set { Description = value.Description; PrefixPath = value.PrefixPath; InterpreterPath = value.InterpreterPath; WindowsInterpreterPath = value.WindowsInterpreterPath; LibraryPath = value.LibraryPath; PathEnvironmentVariable = value.PathEnvironmentVariable; VersionName = value.VersionName; ArchitectureName = value.ArchitectureName; } } public string Description { get { return _values.Description; } set { if (_values.Description != value) { _values.Description = value; OnPropertyChanged(); } } } public string PrefixPath { get { return _values.PrefixPath; } set { if (_values.PrefixPath != value) { _values.PrefixPath = value; OnPropertyChanged(); } } } public string InterpreterPath { get { return _values.InterpreterPath; } set { if (_values.InterpreterPath != value) { _values.InterpreterPath = value; OnPropertyChanged(); } } } public string WindowsInterpreterPath { get { return _values.WindowsInterpreterPath; } set { if (_values.WindowsInterpreterPath != value) { _values.WindowsInterpreterPath = value; OnPropertyChanged(); } } } public string LibraryPath { get { return _values.LibraryPath; } set { if (_values.LibraryPath != value) { _values.LibraryPath = value; OnPropertyChanged(); } } } public string PathEnvironmentVariable { get { return _values.PathEnvironmentVariable; } set { if (_values.PathEnvironmentVariable != value) { _values.PathEnvironmentVariable = value; OnPropertyChanged(); } } } public string ArchitectureName { get { return _values.ArchitectureName; } set { if (_values.ArchitectureName != value) { _values.ArchitectureName = value; OnPropertyChanged(); } } } public string VersionName { get { return _values.VersionName; } set { if (_values.VersionName != value) { _values.VersionName = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { var evt = PropertyChanged; if (evt != null) { evt(this, new PropertyChangedEventArgs(propertyName)); } } } }
// ------------------------------------------- // Control Freak 2 // Copyright (C) 2013-2016 Dan's Game Tools // http://DansGameTools.com // ------------------------------------------- #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace ControlFreak2Editor.Internal { public class TreeView : TreeViewElem { public float indentInc; public TreeViewElem selectedElem; public Vector2 scrollPos; public int treeElemDrawCount; // --------------- public TreeView() : base(null) { this.indentInc = 16; this.view = this; } // ------------------ public bool IsEmpty() { return (this.children.Count == 0); } // ---------------- public int GetElemDrawCount() { return this.treeElemDrawCount; } // ---------------------- public void DrawTreeGUI() { this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, GUILayout.ExpandWidth(true)); this.treeElemDrawCount = 0; this.DrawGUI(0); EditorGUILayout.EndScrollView(); } // --------------------- public void Select(TreeViewElem elem) { this.selectedElem = elem; } } // ------------------ public class TreeViewElem { public TreeView view; public string name; public TreeViewElem parent; public List<TreeViewElem> children; public bool isFoldedOut; protected bool dirtyFlag; // ------------------- public TreeViewElem(TreeView view) { this.isFoldedOut = true; this.view = view; this.children = new List<TreeViewElem>(8); } public enum TriState { True, False, Mixed } // ------------------ virtual protected void OnSetState(int stateId, int state) { } virtual protected int OnGetState(int stateId, int prevState) { return prevState; } virtual protected void OnDrawGUI(float indent) { } virtual protected void OnInvalidate() { } virtual protected bool IsVisible() { return true; } // ------------------ public TreeViewElem Find(string path) { int separatorPos = path.IndexOf("/"); string curLevelName = ((separatorPos < 0) ? path : path.Substring(0, separatorPos)); foreach (TreeViewElem c in this.children) { if (c.name.Equals(curLevelName, System.StringComparison.OrdinalIgnoreCase)) return ((separatorPos < 0) ? c : c.Find(path.Substring(separatorPos))); } return null; } // ------------------- public void AddChild(TreeViewElem elem) { if ((elem.parent != null) && (elem.parent != this)) elem.parent.RemoveChild(elem); this.children.Add(elem); elem.parent = this; } // ----------------- public void RemoveChild(TreeViewElem elem) { this.children.Remove(elem); } // ---------------- public void SetState(int stateId, int state) { this.SetStateRecursively(stateId, state); this.InvalidateDownwards(false); } // -------------------- private void SetStateRecursively(int stateId, int state) { this.OnSetState(stateId, state); for (int i = 0; i < this.children.Count; ++i) this.children[i].SetState(stateId, state); } // ------------------- public int GetState(int stateId, int undefinedValue, int defaultValue) { int v = this.GetStateRecursively(stateId, undefinedValue); return ((v == undefinedValue) ? defaultValue : v); } // ------------------- private int GetStateRecursively(int stateId, int curValue) //undefinedValue, int defaultValue) { // int curValue = undefinedValue; if (this.children.Count == 0) return this.OnGetState(stateId, curValue); // ? TriState.TRUE : TriState.FALSE); //int state = curValue; //TriState.FALSE; for (int i = 0; i < this.children.Count; ++i) { curValue = this.children[i].GetStateRecursively(stateId, curValue); //, undefinedValue); } // if (curValue == undefinedValue) // return defaultValue; return curValue; //state; } // ------------------ public void SetDirtyFlag() { for (TreeViewElem elem = this; elem != null; elem = elem.parent) elem.dirtyFlag = true; } // ------------------ protected void DrawGUI(float indent) { if (this.IsVisible()) { this.OnDrawGUI(indent); ++this.view.treeElemDrawCount; } if (!this.isFoldedOut) return; if (this != this.view) indent += this.view.indentInc; for (int i = 0; i < this.children.Count; ++i) this.children[i].DrawGUI(indent); } // -------------------- public void InvalidateUpwards(bool forced) { if (!forced && !this.dirtyFlag) return; this.OnInvalidate(); this.dirtyFlag = false; for (int i = 0; i < this.children.Count; ++i) this.children[i].InvalidateUpwards(forced); } // ------------------ public void InvalidateDownwards(bool forced) { if (!forced && !this.dirtyFlag) return; this.OnInvalidate(); this.dirtyFlag = false; if (this.parent != null) this.parent.InvalidateDownwards(forced); } // ------------------ public delegate TreeViewElem ElemConstructor(TreeViewElem root, string elemPath, string elemName); // ------------------- static public TreeViewElem CreateDirectoryStructure(TreeViewElem root, string fullPath, ElemConstructor folderConstructor) { if (fullPath.IndexOf('\\') >= 0) fullPath = fullPath.Replace('\\', '/'); int startPos = 0; int sepPos = 0; TreeViewElem parent = root; for (; (startPos < fullPath.Length); startPos = (sepPos + 1)) { sepPos = fullPath.IndexOf("/", startPos); if (sepPos == startPos) continue; if (sepPos < 0) sepPos = fullPath.Length; string folderName = fullPath.Substring(startPos, (sepPos - startPos)); //Debug.Log("\tCreate sub folder [" + folderName + "] of [" + path + "]"); TreeViewElem folderElem = parent.Find(folderName); // as FolderElem; if (folderElem == null) { //Debug.Log("\tNOT found..."); folderElem = folderConstructor(root, fullPath.Substring(0, sepPos), folderName); folderElem.name = folderName; folderElem.parent = parent; parent.AddChild(folderElem); } else { //Debug.Log("\tFOUND!"); } parent = folderElem; } return parent; } } } #endif
#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.Globalization; using System.Text; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq.JsonPath { internal class JPath { private readonly string _expression; public List<PathFilter> Filters { get; private set; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, "expression"); _expression = expression; Filters = new List<PathFilter>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; if (_expression.Length == 0) return; EatWhitespace(); if (_expression[_currentIndex] == '$') { _currentIndex++; EnsureLength("Unexpected end while parsing path."); if (_expression[_currentIndex] != '.') throw new JsonException("Unexpected character while parsing path: " + _expression[_currentIndex]); currentPartStartIndex = _currentIndex; } if (!ParsePath(Filters, currentPartStartIndex, false)) { int lastCharacterIndex = _currentIndex; EatWhitespace(); if (_currentIndex < _expression.Length) throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]); } } private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query) { bool scan = false; bool followingIndexer = false; bool followingDot = false; bool ended = false; while (_currentIndex < _expression.Length && !ended) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); scan = false; } filters.Add(ParseIndexer(currentChar)); _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = true; followingDot = false; break; case ']': case ')': ended = true; break; case ' ': //EatWhitespace(); if (_currentIndex < _expression.Length) ended = true; break; case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") member = null; PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); scan = false; } if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.') { scan = true; _currentIndex++; } _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = false; followingDot = true; break; default: if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&')) { ended = true; } else { if (followingIndexer) throw new JsonException("Unexpected character following indexer: " + currentChar); _currentIndex++; } break; } } bool atPathEnd = (_currentIndex == _expression.Length); if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") member = null; PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); } else { // no field name following dot in path and at end of base path/query if (followingDot && (atPathEnd || query)) throw new JsonException("Unexpected end while parsing path."); } return atPathEnd; } private PathFilter ParseIndexer(char indexerOpenChar) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] == '\'') { return ParseQuotedField(indexerCloseChar); } else if (_expression[_currentIndex] == '?') { return ParseQuery(indexerCloseChar); } else { return ParseArrayIndexer(indexerCloseChar); } } private PathFilter ParseArrayIndexer(char indexerCloseChar) { int start = _currentIndex; int? end = null; List<int> indexes = null; int colonCount = 0; int? startIndex = null; int? endIndex = null; int? step = null; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (currentCharacter == ' ') { end = _currentIndex; EatWhitespace(); continue; } if (currentCharacter == indexerCloseChar) { int length = (end ?? _currentIndex) - start; if (indexes != null) { if (length == 0) throw new JsonException("Array index expected."); string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); indexes.Add(index); return new ArrayMultipleIndexFilter { Indexes = indexes }; } else if (colonCount > 0) { if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 1) endIndex = index; else step = index; } return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step }; } else { if (length == 0) throw new JsonException("Array index expected."); string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); return new ArrayIndexFilter { Index = index }; } } else if (currentCharacter == ',') { int length = (end ?? _currentIndex) - start; if (length == 0) throw new JsonException("Array index expected."); if (indexes == null) indexes = new List<int>(); string indexer = _expression.Substring(start, length); indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (currentCharacter == '*') { _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); return new ArrayIndexFilter(); } else if (currentCharacter == ':') { int length = (end ?? _currentIndex) - start; if (length > 0) { string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 0) startIndex = index; else if (colonCount == 1) endIndex = index; else step = index; } colonCount++; _currentIndex++; EatWhitespace(); start = _currentIndex; end = null; } else if (!char.IsDigit(currentCharacter) && currentCharacter != '-') { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } else { if (end != null) throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); _currentIndex++; } } throw new JsonException("Path ended with open indexer."); } private void EatWhitespace() { while (_currentIndex < _expression.Length) { if (_expression[_currentIndex] != ' ') break; _currentIndex++; } } private PathFilter ParseQuery(char indexerCloseChar) { _currentIndex++; EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] != '(') throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); _currentIndex++; QueryExpression expression = ParseExpression(); _currentIndex++; EnsureLength("Path ended with open indexer."); EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); return new QueryFilter { Expression = expression }; } private QueryExpression ParseExpression() { QueryExpression rootExpression = null; CompositeExpression parentExpression = null; while (_currentIndex < _expression.Length) { EatWhitespace(); if (_expression[_currentIndex] != '@') throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]); _currentIndex++; List<PathFilter> expressionPath = new List<PathFilter>(); if (ParsePath(expressionPath, _currentIndex, true)) throw new JsonException("Path ended with open query."); EatWhitespace(); EnsureLength("Path ended with open query."); QueryOperator op; object value = null; if (_expression[_currentIndex] == ')' || _expression[_currentIndex] == '|' || _expression[_currentIndex] == '&') { op = QueryOperator.Exists; } else { op = ParseOperator(); EatWhitespace(); EnsureLength("Path ended with open query."); value = ParseValue(); EatWhitespace(); EnsureLength("Path ended with open query."); } BooleanQueryExpression booleanExpression = new BooleanQueryExpression { Path = expressionPath, Operator = op, Value = (op != QueryOperator.Exists) ? new JValue(value) : null }; if (_expression[_currentIndex] == ')') { if (parentExpression != null) { parentExpression.Expressions.Add(booleanExpression); return rootExpression; } return booleanExpression; } if (_expression[_currentIndex] == '&' && Match("&&")) { if (parentExpression == null || parentExpression.Operator != QueryOperator.And) { CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; if (parentExpression != null) parentExpression.Expressions.Add(andExpression); parentExpression = andExpression; if (rootExpression == null) rootExpression = parentExpression; } parentExpression.Expressions.Add(booleanExpression); } if (_expression[_currentIndex] == '|' && Match("||")) { if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) { CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; if (parentExpression != null) parentExpression.Expressions.Add(orExpression); parentExpression = orExpression; if (rootExpression == null) rootExpression = parentExpression; } parentExpression.Expressions.Add(booleanExpression); } } throw new JsonException("Path ended with open query."); } private object ParseValue() { char currentChar = _expression[_currentIndex]; if (currentChar == '\'') { return ReadQuotedString(); } else if (char.IsDigit(currentChar) || currentChar == '-') { StringBuilder sb = new StringBuilder(); sb.Append(currentChar); _currentIndex++; while (_currentIndex < _expression.Length) { currentChar = _expression[_currentIndex]; if (currentChar == ' ' || currentChar == ')') { string numberText = sb.ToString(); if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1) { double d; if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) return d; else throw new JsonException("Could not read query value."); } else { long l; if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l)) return l; else throw new JsonException("Could not read query value."); } } else { sb.Append(currentChar); _currentIndex++; } } } else if (currentChar == 't') { if (Match("true")) return true; } else if (currentChar == 'f') { if (Match("false")) return false; } else if (currentChar == 'n') { if (Match("null")) return null; } throw new JsonException("Could not read query value."); } private string ReadQuotedString() { StringBuilder sb = new StringBuilder(); _currentIndex++; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; if (currentChar == '\\' && _currentIndex + 1 < _expression.Length) { _currentIndex++; if (_expression[_currentIndex] == '\'') sb.Append('\''); else if (_expression[_currentIndex] == '\\') sb.Append('\\'); else throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]); _currentIndex++; } else if (currentChar == '\'') { _currentIndex++; { return sb.ToString(); } } else { _currentIndex++; sb.Append(currentChar); } } throw new JsonException("Path ended with an open string."); } private bool Match(string s) { int currentPosition = _currentIndex; foreach (char c in s) { if (currentPosition < _expression.Length && _expression[currentPosition] == c) currentPosition++; else return false; } _currentIndex = currentPosition; return true; } private QueryOperator ParseOperator() { if (_currentIndex + 1 >= _expression.Length) throw new JsonException("Path ended with open query."); if (Match("==")) return QueryOperator.Equals; if (Match("!=") || Match("<>")) return QueryOperator.NotEquals; if (Match("<=")) return QueryOperator.LessThanOrEquals; if (Match("<")) return QueryOperator.LessThan; if (Match(">=")) return QueryOperator.GreaterThanOrEquals; if (Match(">")) return QueryOperator.GreaterThan; throw new JsonException("Could not read query operator."); } private PathFilter ParseQuotedField(char indexerCloseChar) { //_currentIndex++; //int start = _currentIndex; List<string> fields = null; while (_currentIndex < _expression.Length) { string field = ReadQuotedString(); //_currentIndex++; //EnsureLength("Path ended with open indexer."); EatWhitespace(); EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] == indexerCloseChar) { _currentIndex++; if (fields != null) { fields.Add(field); return new FieldMultipleFilter { Names = fields }; } else { return new FieldFilter { Name = field }; } } else if (_expression[_currentIndex] == ',') { _currentIndex++; EatWhitespace(); if (fields == null) fields = new List<string>(); fields.Add(field); } else { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); } } throw new JsonException("Path ended with open indexer."); } private void EnsureLength(string message) { if (_currentIndex >= _expression.Length) throw new JsonException(message); } internal IEnumerable<JToken> Evaluate(JToken t, bool errorWhenNoMatch) { return Evaluate(Filters, t, errorWhenNoMatch); } internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken t, bool errorWhenNoMatch) { IEnumerable<JToken> current = new[] { t }; foreach (PathFilter filter in filters) { current = filter.ExecuteFilter(current, errorWhenNoMatch); } return current; } } }
using System; using LanguageExt.Common; using LanguageExt.Effects.Traits; namespace LanguageExt { public static partial class Prelude { /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Error error, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Error error, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Error error, Func<Error, Eff<A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Error error, Func<Error, Eff<A>> Fail) => ma | matchError(e => e == error, Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Error error, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, _ => Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Error error, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, _ => Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Error error, Eff<A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e == error, _ => Fail); /// <summary> /// Catch an error if the error matches the argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Error error, Eff<A> Fail) => ma | matchError(e => e == error, _ => Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, int errorCode, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, int errorCode, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, int errorCode, Func<Error, Eff<A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, int errorCode, Func<Error, Eff<A>> Fail) => ma | matchError(e => e.Code == errorCode, Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, string errorText, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, _ => Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, string errorText, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, _ => Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, string errorText, Eff<A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, _ => Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, string errorText, Eff<A> Fail) => ma | matchError(e => e.Message == errorText, _ => Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, int errorCode, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, _ => Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, int errorCode, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, _ => Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, int errorCode, Eff<A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Code == errorCode, _ => Fail); /// <summary> /// Catch an error if the error `Code` matches the `errorCode` argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, int errorCode, Eff<A> Fail) => ma | matchError(e => e.Code == errorCode, _ => Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, string errorText, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, string errorText, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, string errorText, Func<Error, Eff<A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Message == errorText, Fail); /// <summary> /// Catch an error if the error message matches the `errorText` argument provided /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, string errorText, Func<Error, Eff<A>> Fail) => ma | matchError(e => e.Message == errorText, Fail); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Exception, bool> predicate, Func<Exception, Eff<A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail(e)); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Func<Exception, bool> predicate, Func<Exception, Eff<A>> Fail) => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail(e)); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Exception, bool> predicate, Eff<A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Func<Exception, bool> predicate, Eff<A> Fail) => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Exception, bool> predicate, Func<Exception, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail(e)); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Func<Exception, bool> predicate, Func<Exception, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail(e)); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Exception, bool> predicate, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail); /// <summary> /// Catch an error if it's of a specific exception type /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Func<Exception, bool> predicate, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(e => e.Exception.Map(predicate).IfNone(false), e => Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, e => Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Eff<RT, A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, e => Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Eff<A> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, e => Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Eff<A> Fail) => ma | matchError(static _ => true, e => Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<A> ma, Func<Error, Eff<RT, A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<RT, A> Catch<RT, A>(this Eff<RT, A> ma, Func<Error, Eff<A>> Fail) where RT : struct, HasCancel<RT> => ma | matchError(static _ => true, Fail); /// <summary> /// Catch all errors /// </summary> public static Eff<A> Catch<A>(this Eff<A> ma, Func<Error, Eff<A>> Fail) => ma | matchError(static _ => true, Fail); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Microsoft.Scripting; using MSAst = System.Linq.Expressions; using System.Linq.Expressions; using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; public abstract class Node : MSAst.Expression { internal static readonly BlockExpression EmptyBlock = Ast.Block(AstUtils.Empty()); internal static readonly MSAst.Expression[] EmptyExpression = new MSAst.Expression[0]; internal static ParameterExpression FunctionStackVariable = Ast.Variable(typeof(List<FunctionStack>), "$funcStack"); internal static readonly LabelTarget GeneratorLabel = Ast.Label(typeof(object), "$generatorLabel"); private static readonly ParameterExpression _lineNumberUpdated = Ast.Variable(typeof(bool), "$lineUpdated"); private static readonly ParameterExpression _lineNoVar = Ast.Parameter(typeof(int), "$lineNo"); protected Node() { } #region Public API public ScopeStatement Parent { get; set; } public void SetLoc(PythonAst globalParent, int start, int end) { IndexSpan = new IndexSpan(start, end > start ? end - start : start); Parent = globalParent; } public void SetLoc(PythonAst globalParent, IndexSpan span) { IndexSpan = span; Parent = globalParent; } public IndexSpan IndexSpan { get; set; } public SourceLocation Start => GlobalParent.IndexToLocation(StartIndex); public SourceLocation End => GlobalParent.IndexToLocation(EndIndex); public int EndIndex { get { return IndexSpan.End; } set { IndexSpan = new IndexSpan(IndexSpan.Start, value - IndexSpan.Start); } } public int StartIndex { get { return IndexSpan.Start; } set { IndexSpan = new IndexSpan(value, 0); } } internal SourceLocation IndexToLocation(int index) { if (index == -1) { return SourceLocation.Invalid; } var locs = GlobalParent._lineLocations; int match = Array.BinarySearch(locs, index); if (match < 0) { // If our index = -1, it means we're on the first line. if (match == -1) { return new SourceLocation(index, 1, index + 1); } // If we couldn't find an exact match for this line number, get the nearest // matching line number less than this one match = ~match - 1; } return new SourceLocation(index, match + 2, index - locs[match] + 1); } public SourceSpan Span => new SourceSpan(Start, End); public abstract void Walk(PythonWalker walker); public virtual string NodeName => GetType().Name; #endregion #region Base Class Overrides /// <summary> /// Returns true if the node can throw, false otherwise. Used to determine /// whether or not we need to update the current dynamic stack info. /// </summary> internal virtual bool CanThrow { get { return true; } } public override bool CanReduce { get { return true; } } public override MSAst.ExpressionType NodeType { get { return MSAst.ExpressionType.Extension; } } public override string ToString() { return GetType().Name; } #endregion #region Internal APIs internal PythonAst GlobalParent { get { Node cur = this; while (!(cur is PythonAst)) { Debug.Assert(cur != null); cur = cur.Parent; } return (PythonAst)cur; } } internal bool EmitDebugSymbols => GlobalParent.EmitDebugSymbols; internal bool StripDocStrings => GlobalParent.PyContext.PythonOptions.StripDocStrings; internal bool Optimize => GlobalParent.PyContext.PythonOptions.Optimize; internal virtual string GetDocumentation(Statement/*!*/ stmt) { if (StripDocStrings) { return null; } return stmt.Documentation; } #endregion #region Transformation Helpers internal static MSAst.Expression[] ToObjectArray(ReadOnlySpan<Expression> expressions) { MSAst.Expression[] to = new MSAst.Expression[expressions.Length]; for (int i = 0; i < expressions.Length; i++) { to[i] = AstUtils.Convert(expressions[i], typeof(object)); } return to; } internal static MSAst.Expression TransformOrConstantNull(Expression expression, Type/*!*/ type) { if (expression == null) { return AstUtils.Constant(null, type); } else { return AstUtils.Convert(expression, type); } } internal MSAst.Expression TransformAndDynamicConvert(Expression expression, Type/*!*/ type) { Debug.Assert(expression != null); MSAst.Expression res = expression; // Do we need conversion? if (!CanAssign(type, expression.Type)) { // ensure we're reduced before we check for dynamic expressions. var reduced = expression.Reduce(); if (reduced is LightDynamicExpression) { reduced = reduced.Reduce(); } // Add conversion step to the AST MSAst.DynamicExpression ae = reduced as MSAst.DynamicExpression; ReducableDynamicExpression rde = reduced as ReducableDynamicExpression; if ((ae != null && ae.Binder is PythonBinaryOperationBinder) || (rde != null && rde.Binder is PythonBinaryOperationBinder)) { // create a combo site which does the conversion PythonBinaryOperationBinder binder; IList<MSAst.Expression> args; if (ae != null) { binder = (PythonBinaryOperationBinder)ae.Binder; args = ArrayUtils.ToArray(ae.Arguments); } else { binder = (PythonBinaryOperationBinder)rde.Binder; args = rde.Args; } ParameterMappingInfo[] infos = new ParameterMappingInfo[args.Count]; for (int i = 0; i < infos.Length; i++) { infos[i] = ParameterMappingInfo.Parameter(i); } res = Expression.Dynamic( GlobalParent.PyContext.BinaryOperationRetType( binder, GlobalParent.PyContext.Convert( type, ConversionResultKind.ExplicitCast ) ), type, args ); } else { res = GlobalParent.Convert( type, ConversionResultKind.ExplicitCast, reduced ); } } return res; } internal static bool CanAssign(Type/*!*/ to, Type/*!*/ from) => to.IsAssignableFrom(from) && (to.IsValueType == from.IsValueType); internal static MSAst.Expression/*!*/ ConvertIfNeeded(MSAst.Expression/*!*/ expression, Type/*!*/ type) { Debug.Assert(expression != null); // Do we need conversion? if (!CanAssign(type, expression.Type)) { // Add conversion step to the AST expression = AstUtils.Convert(expression, type); } return expression; } internal static MSAst.Expression TransformMaybeSingleLineSuite(Statement body, SourceLocation prevStart) { if (body.GlobalParent.IndexToLocation(body.StartIndex).Line != prevStart.Line) { return body; } MSAst.Expression res = body.Reduce(); res = RemoveDebugInfo(prevStart.Line, res); if (res.Type != typeof(void)) { res = AstUtils.Void(res); } return res; } internal static MSAst.Expression RemoveDebugInfo(int prevStart, MSAst.Expression res) { if (res is MSAst.BlockExpression block && block.Expressions.Count > 0) { // body on the same line as an if, don't generate a 2nd sequence point if (block.Expressions[0] is MSAst.DebugInfoExpression dbgInfo && dbgInfo.StartLine == prevStart) { // we remove the debug info based upon how it's generated in DebugStatement.AddDebugInfo which is // the helper method which adds the debug info. if (block.Type == typeof(void)) { Debug.Assert(block.Expressions.Count == 3); Debug.Assert(block.Expressions[2] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear); res = block.Expressions[1]; } else { Debug.Assert(block.Expressions.Count == 4); Debug.Assert(block.Expressions[3] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear); Debug.Assert(block.Expressions[1] is MSAst.BinaryExpression && ((MSAst.BinaryExpression)block.Expressions[2]).NodeType == MSAst.ExpressionType.Assign); res = ((MSAst.BinaryExpression)block.Expressions[1]).Right; } } } return res; } /// <summary> /// Creates a method frame for tracking purposes and enforces recursion /// </summary> internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) => new FramedCodeExpression(localContext, codeObject, body); /// <summary> /// Removes the frames from generated code for when we're compiling the tracing delegate /// which will track the frames it's self. /// </summary> internal static MSAst.Expression RemoveFrame(MSAst.Expression expression) => new FramedCodeVisitor().Visit(expression); private class FramedCodeVisitor : ExpressionVisitor { public override MSAst.Expression Visit(MSAst.Expression node) { if (node is FramedCodeExpression framedCode) { return framedCode.Body; } return base.Visit(node); } } private sealed class FramedCodeExpression : MSAst.Expression { private readonly MSAst.Expression _localContext, _codeObject; public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) { _localContext = localContext; _codeObject = codeObject; Body = body; } public override ExpressionType NodeType => ExpressionType.Extension; public MSAst.Expression Body { get; } public override MSAst.Expression Reduce() { return AstUtils.Try( Ast.Assign( FunctionStackVariable, Ast.Call( AstMethods.PushFrame, _localContext, _codeObject ) ), Body ).Finally( Ast.Call( FunctionStackVariable, typeof(List<FunctionStack>).GetMethod("RemoveAt"), Ast.Add( Ast.Property( FunctionStackVariable, "Count" ), Ast.Constant(-1) ) ) ); } public override Type Type => Body.Type; public override bool CanReduce => true; protected override MSAst.Expression VisitChildren(ExpressionVisitor visitor) { var localContext = visitor.Visit(_localContext); var codeObject = visitor.Visit(_codeObject); var body = visitor.Visit(Body); if (localContext != _localContext || _codeObject != codeObject || body != Body) { return new FramedCodeExpression(localContext, codeObject, body); } return this; } } internal static MSAst.Expression/*!*/ MakeAssignment(MSAst.ParameterExpression/*!*/ variable, MSAst.Expression/*!*/ right) { return Ast.Assign(variable, AstUtils.Convert(right, variable.Type)); } internal MSAst.Expression MakeAssignment(MSAst.ParameterExpression variable, MSAst.Expression right, SourceSpan span) { return GlobalParent.AddDebugInfoAndVoid(Ast.Assign(variable, AstUtils.Convert(right, variable.Type)), span); } internal static MSAst.Expression/*!*/ AssignValue(MSAst.Expression/*!*/ expression, MSAst.Expression value) { Debug.Assert(expression != null); Debug.Assert(value != null); if (expression is IPythonVariableExpression pyGlobal) { return pyGlobal.Assign(value); } return Ast.Assign(expression, value); } internal static MSAst.Expression/*!*/ Delete(MSAst.Expression/*!*/ expression) { if (expression is IPythonVariableExpression pyGlobal) { return pyGlobal.Delete(); } return Ast.Assign(expression, Ast.Field(null, typeof(Uninitialized).GetField(nameof(Uninitialized.Instance)))); } #endregion #region Basic Line Number Infrastructure /// <summary> /// A temporary variable to track if the current line number has been emitted via the fault update block. /// /// For example consider: /// /// try: /// raise Exception() /// except Exception, e: /// # do something here /// raise /// /// At "do something here" we need to have already emitted the line number, when we re-raise we shouldn't add it /// again. If we handled the exception then we should have set the bool back to false. /// /// We also sometimes directly check _lineNoUpdated to avoid creating this unless we have nested exceptions. /// </summary> internal static MSAst.ParameterExpression/*!*/ LineNumberUpdated { get { return _lineNumberUpdated; } } internal static MSAst.Expression UpdateLineNumber(int line) { return Ast.Assign(LineNumberExpression, AstUtils.Constant(line)); } internal static MSAst.Expression UpdateLineUpdated(bool updated) { return Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated)); } internal static MSAst.Expression PushLineUpdated(bool updated, MSAst.ParameterExpression saveCurrent) { return MSAst.Expression.Block( Ast.Assign(saveCurrent, LineNumberUpdated), Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated)) ); } internal static MSAst.Expression PopLineUpdated(MSAst.ParameterExpression saveCurrent) { return Ast.Assign(LineNumberUpdated, saveCurrent); } /// <summary> /// A temporary variable to track the current line number /// </summary> internal static MSAst.ParameterExpression/*!*/ LineNumberExpression { get { return _lineNoVar; } } #endregion } }
// // PlaybackShuffleActions.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (C) 2008 Scott Peterson // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using Mono.Unix; using Gtk; using Hyena; using Hyena.Gui; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.PlaybackController; using Banshee.Collection.Database; namespace Banshee.Gui { public class PlaybackShuffleActions : BansheeActionGroup, IEnumerable<RadioAction> { private RadioAction active_action; private RadioAction saved_action; private PlaybackActions playback_actions; private const string shuffle_off_action = "Shuffle_off"; private Dictionary<int, string> shuffle_modes = new Dictionary<int, string> (); public RadioAction Active { get { return active_action; } set { active_action = value; ServiceManager.PlaybackController.ShuffleMode = shuffle_modes[active_action.Value]; } } public new bool Sensitive { get { return base.Sensitive; } set { base.Sensitive = value; OnChanged (); } } public event EventHandler Changed; public PlaybackShuffleActions (InterfaceActionService actionService, PlaybackActions playbackActions) : base (actionService, "PlaybackShuffle") { playback_actions = playbackActions; Actions.AddActionGroup (this); Add (new ActionEntry [] { new ActionEntry ("ShuffleMenuAction", null, Catalog.GetString ("Shuffle"), null, Catalog.GetString ("Shuffle"), null) }); ServiceManager.PlaybackController.ShuffleModeChanged += OnShuffleModeChanged; ServiceManager.PlaybackController.SourceChanged += OnPlaybackSourceChanged; SetShuffler (Banshee.Collection.Database.Shuffler.Playback); } private Shuffler shuffler; public void SetShuffler (Shuffler shuffler) { if (this.shuffler == shuffler) { return; } if (this.shuffler != null) { this.shuffler.RandomModeAdded -= OnShufflerChanged; this.shuffler.RandomModeRemoved -= OnShufflerChanged; } this.shuffler = shuffler; this.shuffler.RandomModeAdded += OnShufflerChanged; this.shuffler.RandomModeRemoved += OnShufflerChanged; UpdateActions (); } private void OnShufflerChanged (RandomBy random_by) { UpdateActions (); } private void UpdateActions () { // Clear out the old options foreach (string id in shuffle_modes.Values) { Remove (String.Format ("Shuffle_{0}", id)); } shuffle_modes.Clear (); var radio_group = new RadioActionEntry [shuffler.RandomModes.Count]; int i = 0; // Add all the shuffle options foreach (var random_by in shuffler.RandomModes) { string action_name = String.Format ("Shuffle_{0}", random_by.Id); int id = shuffle_modes.Count; shuffle_modes[id] = random_by.Id; radio_group[i++] = new RadioActionEntry ( action_name, null, random_by.Label, null, random_by.Description, id); } Add (radio_group, 0, OnActionChanged); // Set the icons foreach (var random_by in shuffler.RandomModes) { this[String.Format ("Shuffle_{0}", random_by.Id)].IconName = random_by.IconName ?? "media-playlist-shuffle"; } this[shuffle_off_action].StockId = Gtk.Stock.MediaNext; var action = this[ConfigIdToActionName (ShuffleMode.Get ())]; if (action is RadioAction) { Active = (RadioAction)action; } else { Active = (RadioAction)this[shuffle_off_action]; } Active.Activate (); OnChanged (); } private void OnShuffleModeChanged (object o, EventArgs<string> args) { if (shuffle_modes[active_action.Value] != args.Value) { // This happens only when changing the mode using DBus. // In this case we need to locate the action by its value. ThreadAssist.ProxyToMain (delegate { foreach (RadioAction action in this) { if (shuffle_modes[action.Value] == args.Value) { active_action = action; break; } } }); } if (saved_action == null) { ShuffleMode.Set (ActionNameToConfigId (active_action.Name)); } OnChanged(); } private void OnPlaybackSourceChanged (object o, EventArgs args) { var source = ServiceManager.PlaybackController.Source; if (saved_action == null && !source.CanShuffle) { saved_action = Active; Active = this[shuffle_off_action] as RadioAction; Sensitive = false; } else if (saved_action != null && source.CanShuffle) { Active = saved_action; saved_action = null; Sensitive = true; } } private void OnActionChanged (object o, ChangedArgs args) { Active = args.Current; } private void OnChanged () { playback_actions["NextAction"].StockId = Active.StockId; playback_actions["NextAction"].IconName = Active.IconName; EventHandler handler = Changed; if (handler != null) { handler (this, EventArgs.Empty); } } public void AttachSubmenu (string menuItemPath) { MenuItem parent = Actions.UIManager.GetWidget (menuItemPath) as MenuItem; parent.Submenu = CreateMenu (); } public MenuItem CreateSubmenu () { MenuItem parent = (MenuItem)this["ShuffleMenuAction"].CreateMenuItem (); parent.Submenu = CreateMenu (); return parent; } public Menu CreateMenu () { return CreateMenu (false); } public Menu CreateMenu (bool withRepeatActions) { Menu menu = new Gtk.Menu (); bool separator = false; foreach (RadioAction action in this) { menu.Append (action.CreateMenuItem ()); if (!separator) { separator = true; menu.Append (new SeparatorMenuItem ()); } } if (withRepeatActions) { menu.Append (new SeparatorMenuItem ()); menu.Append (ServiceManager.Get<InterfaceActionService> ().PlaybackActions.RepeatActions.CreateSubmenu ()); } menu.ShowAll (); return menu; } public IEnumerator<RadioAction> GetEnumerator () { foreach (string id in shuffle_modes.Values) { yield return (RadioAction)this[String.Format ("Shuffle_{0}", id)]; } } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } private static string ConfigIdToActionName (string configuration) { return "S" + configuration.Substring (1); } private static string ActionNameToConfigId (string actionName) { return actionName.ToLowerInvariant (); } public static readonly SchemaEntry<string> ShuffleMode = new SchemaEntry<string> ( "playback", "shuffle_mode", "off", "Shuffle playback", "Shuffle mode (shuffle_off, shuffle_song, shuffle_artist, shuffle_album, shuffle_rating, shuffle_score)" ); } }
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.Graphics; using Android.Graphics.Drawables; using Android.Views; using System; namespace com.bytewild.imaging.cropping { public class HighlightView { // The View displaying the image. private View context; public enum ModifyMode { None, Move, Grow } private ModifyMode mode = ModifyMode.None; private RectF imageRect; // in image space RectF cropRect; // in image space public Matrix matrix; private bool maintainAspectRatio = false; private float initialAspectRatio; private Drawable resizeDrawableWidth; private Drawable resizeDrawableHeight; private Paint focusPaint = new Paint(); private Paint noFocusPaint = new Paint(); private Paint outlinePaint = new Paint(); [Flags] public enum HitPosition { None, GrowLeftEdge, GrowRightEdge, GrowTopEdge, GrowBottomEdge, Move } #region Constructor public HighlightView(View ctx) { context = ctx; } #endregion #region Properties public bool Focused { get; set; } public bool Hidden { get; set; } public Rect DrawRect // in screen space { get; private set; } // Returns the cropping rectangle in image space. public Rect CropRect { get { return new Rect((int)cropRect.Left, (int)cropRect.Top, (int)cropRect.Right, (int)cropRect.Bottom); } } public ModifyMode Mode { get { return mode; } set { if (value != mode) { mode = value; context.Invalidate(); } } } #endregion #region Public methods // Handles motion (dx, dy) in screen space. // The "edge" parameter specifies which edges the user is dragging. public void HandleMotion(HitPosition edge, float dx, float dy) { Rect r = computeLayout(); if (edge == HitPosition.None) { return; } else if (edge == HitPosition.Move) { // Convert to image space before sending to moveBy(). moveBy(dx * (cropRect.Width() / r.Width()), dy * (cropRect.Height() / r.Height())); } else { if (!edge.HasFlag(HitPosition.GrowLeftEdge) && !edge.HasFlag(HitPosition.GrowRightEdge)) { dx = 0; } if (!edge.HasFlag(HitPosition.GrowTopEdge) && !edge.HasFlag(HitPosition.GrowBottomEdge)) { dy = 0; } // Convert to image space before sending to growBy(). float xDelta = dx * (cropRect.Width() / r.Width()); float yDelta = dy * (cropRect.Height() / r.Height()); growBy((edge.HasFlag(HitPosition.GrowLeftEdge) ? -1 : 1) * xDelta, (edge.HasFlag(HitPosition.GrowTopEdge) ? -1 : 1) * yDelta); } } public void Draw(Canvas canvas) { if (Hidden) { return; } canvas.Save(); if (!Focused) { outlinePaint.Color = Color.White; canvas.DrawRect(DrawRect, outlinePaint); } else { Rect viewDrawingRect = new Rect(); context.GetDrawingRect(viewDrawingRect); outlinePaint.Color = Color.White;// new Color(0XFF, 0xFF, 0x8A, 0x00); focusPaint.Color = new Color(50, 50, 50, 125); Path path = new Path(); path.AddRect(new RectF(DrawRect), Path.Direction.Cw); canvas.ClipPath(path, Region.Op.Difference); canvas.DrawRect(viewDrawingRect, focusPaint); canvas.Restore(); canvas.DrawPath(path, outlinePaint); if (mode == ModifyMode.Grow) { int left = DrawRect.Left + 1; int right = DrawRect.Right + 1; int top = DrawRect.Top + 4; int bottom = DrawRect.Bottom + 3; int widthWidth = resizeDrawableWidth.IntrinsicWidth / 2; int widthHeight = resizeDrawableWidth.IntrinsicHeight / 2; int heightHeight = resizeDrawableHeight.IntrinsicHeight / 2; int heightWidth = resizeDrawableHeight.IntrinsicWidth / 2; int xMiddle = DrawRect.Left + ((DrawRect.Right - DrawRect.Left) / 2); int yMiddle = DrawRect.Top + ((DrawRect.Bottom - DrawRect.Top) / 2); resizeDrawableWidth.SetBounds(left - widthWidth, yMiddle - widthHeight, left + widthWidth, yMiddle + widthHeight); resizeDrawableWidth.Draw(canvas); resizeDrawableWidth.SetBounds(right - widthWidth, yMiddle - widthHeight, right + widthWidth, yMiddle + widthHeight); resizeDrawableWidth.Draw(canvas); resizeDrawableHeight.SetBounds(xMiddle - heightWidth, top - heightHeight, xMiddle + heightWidth, top + heightHeight); resizeDrawableHeight.Draw(canvas); resizeDrawableHeight.SetBounds(xMiddle - heightWidth, bottom - heightHeight, xMiddle + heightWidth, bottom + heightHeight); resizeDrawableHeight.Draw(canvas); } } } // Determines which edges are hit by touching at (x, y). public HitPosition GetHit(float x, float y) { Rect r = computeLayout(); float hysteresis = 20F; var retval = HitPosition.None; // verticalCheck makes sure the position is between the top and // the bottom edge (with some tolerance). Similar for horizCheck. bool verticalCheck = (y >= r.Top - hysteresis) && (y < r.Bottom + hysteresis); bool horizCheck = (x >= r.Left - hysteresis) && (x < r.Right + hysteresis); // Check whether the position is near some edge(s). if ((Math.Abs(r.Left - x) < hysteresis) && verticalCheck) { retval |= HitPosition.GrowLeftEdge; } if ((Math.Abs(r.Right - x) < hysteresis) && verticalCheck) { retval |= HitPosition.GrowRightEdge; } if ((Math.Abs(r.Top - y) < hysteresis) && horizCheck) { retval |= HitPosition.GrowTopEdge; } if ((Math.Abs(r.Bottom - y) < hysteresis) && horizCheck) { retval |= HitPosition.GrowBottomEdge; } // Not near any edge but inside the rectangle: move. if (retval == HitPosition.None && r.Contains((int)x, (int)y)) { retval = HitPosition.Move; } return retval; } public void Invalidate() { DrawRect = computeLayout(); } public void Setup(Matrix m, Rect imageRect, RectF cropRect, bool maintainAspectRatio) { matrix = new Matrix(m); this.cropRect = cropRect; this.imageRect = new RectF(imageRect); this.maintainAspectRatio = maintainAspectRatio; initialAspectRatio = cropRect.Width() / cropRect.Height(); DrawRect = computeLayout(); focusPaint.SetARGB(125, 50, 50, 50); noFocusPaint.SetARGB(125, 50, 50, 50); outlinePaint.StrokeWidth = 3; outlinePaint.SetStyle(Paint.Style.Stroke); outlinePaint.AntiAlias = true; mode = ModifyMode.None; init(); } #endregion #region Private helpers private void init() { var resources = context.Resources; resizeDrawableWidth = resources.GetDrawable(Resource.Drawable.camera_crop_width); resizeDrawableHeight = resources.GetDrawable(Resource.Drawable.camera_crop_height); } // Grows the cropping rectange by (dx, dy) in image space. private void moveBy(float dx, float dy) { Rect invalRect = new Rect(DrawRect); cropRect.Offset(dx, dy); // Put the cropping rectangle inside image rectangle. cropRect.Offset( Math.Max(0, imageRect.Left - cropRect.Left), Math.Max(0, imageRect.Top - cropRect.Top)); cropRect.Offset( Math.Min(0, imageRect.Right - cropRect.Right), Math.Min(0, imageRect.Bottom - cropRect.Bottom)); DrawRect = computeLayout(); invalRect.Union(DrawRect); invalRect.Inset(-10, -10); context.Invalidate(invalRect); } // Grows the cropping rectange by (dx, dy) in image space. private void growBy(float dx, float dy) { if (maintainAspectRatio) { if (dx != 0) { dy = dx / initialAspectRatio; } else if (dy != 0) { dx = dy * initialAspectRatio; } } // Don't let the cropping rectangle grow too fast. // Grow at most half of the difference between the image rectangle and // the cropping rectangle. RectF r = new RectF(cropRect); if (dx > 0F && r.Width() + 2 * dx > imageRect.Width()) { float adjustment = (imageRect.Width() - r.Width()) / 2F; dx = adjustment; if (maintainAspectRatio) { dy = dx / initialAspectRatio; } } if (dy > 0F && r.Height() + 2 * dy > imageRect.Height()) { float adjustment = (imageRect.Height() - r.Height()) / 2F; dy = adjustment; if (maintainAspectRatio) { dx = dy * initialAspectRatio; } } r.Inset(-dx, -dy); // Don't let the cropping rectangle shrink too fast. float widthCap = 25F; if (r.Width() < widthCap) { r.Inset(-(widthCap - r.Width()) / 2F, 0F); } float heightCap = maintainAspectRatio ? (widthCap / initialAspectRatio) : widthCap; if (r.Height() < heightCap) { r.Inset(0F, -(heightCap - r.Height()) / 2F); } // Put the cropping rectangle inside the image rectangle. if (r.Left < imageRect.Left) { r.Offset(imageRect.Left - r.Left, 0F); } else if (r.Right > imageRect.Right) { r.Offset(-(r.Right - imageRect.Right), 0); } if (r.Top < imageRect.Top) { r.Offset(0F, imageRect.Top - r.Top); } else if (r.Bottom > imageRect.Bottom) { r.Offset(0F, -(r.Bottom - imageRect.Bottom)); } cropRect.Set(r); DrawRect = computeLayout(); context.Invalidate(); } // Maps the cropping rectangle from image space to screen space. private Rect computeLayout() { RectF r = new RectF(cropRect.Left, cropRect.Top, cropRect.Right, cropRect.Bottom); matrix.MapRect(r); return new Rect((int)Math.Round(r.Left), (int)Math.Round(r.Top), (int)Math.Round(r.Right), (int)Math.Round(r.Bottom)); } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundCurrentDirectionSingle() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundCurrentDirectionSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar; private Vector128<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static SimpleUnaryOpTest__RoundCurrentDirectionSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__RoundCurrentDirectionSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.RoundCurrentDirection( Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.RoundCurrentDirection( Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.RoundCurrentDirection( Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.RoundCurrentDirection( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionSingle(); var result = Sse41.RoundCurrentDirection(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.RoundCurrentDirection(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); 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), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirection)}<Single>(Vector128<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Text; using System.Linq; using System.Linq.Expressions; namespace MonoDroid { public class NetProxyGenerator : CodeGenerator { static Dictionary<string, System.Type> myJniTypes = new Dictionary<string, System.Type>(); static readonly string[] myKeywords = new string[] { "namespace", "in", "out", "checked", "params", "lock", "ref", "internal", "out", "object", "string", "bool" }; static readonly int myTypeCount = 3; static string[] myReplaceKeyword = new string[myKeywords.Length]; static string[] myStartKeywords = new string[myKeywords.Length]; static string[] myStartReplaceKeywords = new string[myKeywords.Length]; static string[] myEndKeywords = new string[myKeywords.Length]; static string[] myEndReplaceKeywords = new string[myKeywords.Length]; static string[] myContainKeywords = new string[myKeywords.Length]; static string[] myContainReplaceKeywords = new string[myKeywords.Length]; static string EscapeName(string name) { return EscapeName(name, true); } static string EscapeName(string name, bool doExactMatchOnTypes) { for (int i = 0; i < myKeywords.Length; i++) { var keyword = myStartKeywords[i]; if (!name.StartsWith(keyword)) continue; name = myStartReplaceKeywords[i] + name.Substring(keyword.Length); break; } for (int i = 0; i < myKeywords.Length; i++) { var keyword = myEndKeywords[i]; if (!name.EndsWith(keyword)) continue; name = name.Substring(0, name.Length - keyword.Length) + myEndReplaceKeywords[i]; break; } for (int i = 0; i < myKeywords.Length; i++) { var keyword = myContainKeywords[i]; if (!name.Contains(keyword)) continue; name = name.Replace(keyword, myContainReplaceKeywords[i]); } for (int i = 0; i < (doExactMatchOnTypes ? myKeywords.Length : myKeywords.Length - myTypeCount); i++) { if (name != myKeywords[i]) continue; name = myReplaceKeyword[i]; } return name; } public Type FindType(string typeName) { if (typeName == null) return null; typeName = typeName.TrimEnd(']', '['); return myModel.FindType(typeName); } public void AddAllTypes(ObjectModel model, HashSet<Type> hash, Type type) { if (type == null) return; if (hash.Contains(type)) return; hash.Add(type); AddAllTypes(model, hash, type.ParentType); foreach (var iface in type.InterfaceTypes) { AddAllTypes(model, hash, iface); } foreach (var field in type.Fields) { AddAllTypes(model, hash, FindType(field.Type)); } foreach (var method in type.Methods) { AddAllTypes(model, hash, method.ReturnType ?? FindType(method.Return)); foreach (var par in method.Parameters) AddAllTypes(model, hash, FindType(par)); } } ObjectModel myModel; HashSet<Type> myTypesOfInterest = new HashSet<Type>(); protected override void Prepare (ObjectModel model) { myModel = model; var androidTypes = from type in myModel.Types where type.Name.StartsWith("android.") && !type.Name.StartsWith("android.test.") select type; //var androidTypes = from type in myModel.Types where type.Name == "java.lang.Object" select type; foreach (var type in androidTypes) { AddAllTypes(myModel, myTypesOfInterest, type); } foreach (var type in model.Types) { type.Name = EscapeName(type.Name); foreach (var method in type.Methods) { method.Name = EscapeName(method.Name); for (int i = 0; i < method.Parameters.Count; i++) { method.Parameters[i] = EscapeName(method.Parameters[i], false); } if (method.Return != null) { method.Return = EscapeName(method.Return, false); } // jni4net exposes java.util.List.listIterator with a return type of Iterator, and not ListIterator... // massage this so it works. //if ((type.Name == "java.util.AbstractList" || type.Name == "java.util.concurrent.CopyOnWriteArrayList") && method.Name == "listIterator") // method.Return = "java.util.Iterator"; } if (type.Parent != null) type.Parent = EscapeName(type.Parent); for (int i = 0; i < type.Interfaces.Count; i++) { type.Interfaces[i] = EscapeName(type.Interfaces[i]); } for (int i = 0; i < type.Fields.Count; i++) { type.Fields[i].Name = EscapeName(type.Fields[i].Name); type.Fields[i].Type = EscapeName(type.Fields[i].Type, false); } } } static NetProxyGenerator() { /* Assembly jniAssembly = typeof(net.sf.jni4net.Bridge).Assembly; foreach (var type in jniAssembly.GetTypes()) { myJniTypes.Add(type.FullName, type); } */ for (int i = 0; i < myKeywords.Length; i++) { string keyword = myKeywords[i]; myReplaceKeyword[i] = '@' + keyword; myStartKeywords[i] = keyword + '.'; myStartReplaceKeywords[i] = '@' + keyword + '.'; myEndKeywords[i] = '.' + keyword; myEndReplaceKeywords[i] = ".@" + keyword; myContainKeywords[i] = '.' + keyword + '.'; myContainReplaceKeywords[i] = ".@" + keyword + '.'; } } //List<Method> myExtensionMethods = new List<Method>(); protected override void BeginNamespace (Type type) { //myExtensionMethods.Clear(); WriteLine("namespace {0}", type.Namespace); WriteLine("{"); } /* protected override void EndNamespace (Type type) { if (myExtensionMethods.Count > 0) { myIndent++; WriteLine("public static class {0}ExtensionMethods", type.SimpleName); WriteLine("{"); myIndent++; foreach (var em in myExtensionMethods) { Write("public static {0} {1}(", false, em.Return, em.Name); Write("this global::{0} __this", false, em.Type.Name); if (em.Parameters.Count > 0) Write(","); WriteDelimited(em.Parameters, (v, i) => string.Format("{0} arg{1}", v == "java.lang.CharSequence" ? "string" : v, i), ","); WriteLine(")"); WriteLine("{"); myIndent++; if (em.Return != "void") Write("return"); Write("__this.{0}(", false, em.Name); WriteDelimited(em.Parameters, (v, i) => string.Format("{0}arg{1}", v == "java.lang.CharSequence" ? "(global::java.lang.String)" : string.Empty, i), ","); WriteLine(");"); myIndent--; WriteLine("}"); } myIndent--; WriteLine("}"); myIndent--; } base.EndNamespace (type); } */ protected override string GetFilePath (Type type) { var file = Path.Combine(type.Namespace.Replace('.', Path.DirectorySeparatorChar), type.SimpleName + ".cs").Replace("@", string.Empty); return Path.Combine("generated", file); } protected override bool BeginType (Type type) { myInitJni.Clear(); if (myJniTypes.ContainsKey(type.Name) || !myTypesOfInterest.Contains(type)) return false; if (type.WrappedInterface == null) { if (type.IsInterface) { WriteLine("[global::MonoJavaBridge.JavaInterface(typeof(global::{0}_))]", type.Name); } else if (type.Abstract) { WriteLine("[global::MonoJavaBridge.JavaClass(typeof(global::{0}_))]", type.Name); } else { WriteLine("[global::MonoJavaBridge.JavaClass()]"); } } else { WriteLine("[global::MonoJavaBridge.JavaProxy(typeof(global::{0}))]", type.Name.Substring(0, type.Name.Length - 1)); //WriteLine("[global::net.sf.jni4net.attributes.ClrWrapperAttribute(typeof(global::{0}), typeof(global::{0}_))]", type.WrappedInterface); } Write(type.Scope); if (type.IsNew) Write("new"); if (type.Abstract && !type.IsInterface) Write("abstract"); if (type.IsSealed) Write("sealed"); if (type.Static) Write("static"); if (type.IsInterface) Write("interface {0}", type.SimpleName); else Write("partial class {0}", type.SimpleName); if (type.Parent != null || type.Interfaces.Count > 0) Write(":"); if (type.IsInterface && type.Interfaces.Count == 0) Write(" : global::MonoJavaBridge.IJavaObject"); if (type.Parent != null) Write(type.Parent, false); if (!type.IsInterface && type.Interfaces.Count > 0) { Write(","); } WriteDelimited(type.InterfaceTypes, (v, i) => type.Qualifier.StartsWith(v.Qualifier) ? v.SimpleName : v.Name, ","); WriteLine(); WriteLine("{"); if (!type.IsInterface && !type.Static) { myIndent++; WriteLine("internal {0}static global::MonoJavaBridge.JniGlobalHandle staticClass;", type.Parent == null || myJniTypes.ContainsKey(type.Parent) ? "" : "new "); /* if (!type.HasEmptyConstructor) { WriteLine("public {0}(){{}}", type.SimpleName); } */ WriteLine("static {0}()", type.SimpleName); WriteLine("{"); myIndent++; //WriteLine("global::net.sf.jni4net.utils.Registry.RegisterType(typeof(global::{0}), true, global::net.sf.jni4net.jni.JNIEnv.ThreadEnv);", type.Name); WriteLine("InitJNI();"); myIndent--; WriteLine("}"); /* if (!type.Abstract) { WriteLine("private sealed class ContructionHelper : global::net.sf.jni4net.utils.IConstructionHelper", myJniTypes.ContainsKey(type.Parent) ? string.Empty : "new "); WriteLine("{"); myIndent++; WriteLine("public global::net.sf.jni4net.jni.IJvmProxy CreateProxy(global::net.sf.jni4net.jni.JNIEnv @__env)"); WriteLine("{"); myIndent++; WriteLine("return new global::{0}(@__env);", type.Name); myIndent--; WriteLine("}"); myIndent--; WriteLine("}"); } */ WriteLine("{1} {0}(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)", type.SimpleName, type.IsSealed ? "internal" : "protected"); WriteLine("{"); WriteLine("}"); myIndent--; } return true; } void AddAllInterfaces(Type interfaceType, HashSet<Type> interfaces) { if (!interfaces.Contains(interfaceType)) interfaces.Add(interfaceType); foreach (var i in interfaceType.InterfaceTypes) { AddAllInterfaces(i, interfaces); } } void GenerateInterfaceStubs(Type interfaceType) { WriteLine(); /* WriteLine("public partial class {0}_", interfaceType.SimpleName); WriteLine("{"); myIndent++; WriteLine("public static global::java.lang.Class _class"); WriteLine("{"); myIndent++; WriteLine("get {{ return __{0}.staticClass; }}", interfaceType.SimpleName); myIndent--; WriteLine("}"); myIndent--; WriteLine("}"); WriteLine(); */ Type wrapperType = new Type(); wrapperType.WrappedInterface = interfaceType.Name; wrapperType.WrappedInterfaceType = interfaceType; //wrapperType.Name = interfaceType.Name.Insert(interfaceType.Name.LastIndexOf('.') + 1, "_"); wrapperType.Name = interfaceType.Name + "_"; wrapperType.Scope = interfaceType.Scope; wrapperType.IsSealed = true; if (interfaceType.IsInterface) { wrapperType.Parent = "java.lang.Object"; wrapperType.ParentType = myModel.FindType("java.lang.Object"); wrapperType.Interfaces.Add(interfaceType.Name); wrapperType.InterfaceTypes.Add(interfaceType); var h = new HashSet<Type>(); AddAllInterfaces(interfaceType, h); foreach (var i in h) { foreach (var m in i.Methods) { var mc = new Method(); mc.Type = wrapperType; mc.Name = i.Name + "." + m.Name; //mc.Scope = "public"; mc.Parameters.AddRange(m.Parameters); mc.ParameterTypes.AddRange(m.ParameterTypes); mc.Return = m.Return; mc.ReturnType = m.ReturnType; if (!wrapperType.Methods.Contains(mc)) wrapperType.Methods.Add(mc); } } } else { wrapperType.Parent = interfaceType.Name; wrapperType.ParentType = interfaceType; var curType = interfaceType; var allImplementedMethods = new Methods(); while (curType != null) { foreach (var m in curType.Methods) { if (!m.Abstract) { if (!allImplementedMethods.Contains(m)) allImplementedMethods.Add(m); continue; } if (allImplementedMethods.Contains(m)) continue; var mc = new Method(); mc.Type = wrapperType; mc.Name = m.Name; mc.Scope = m.Scope; mc.IsOverride = true; mc.Parameters.AddRange(m.Parameters); mc.ParameterTypes.AddRange(m.ParameterTypes); mc.Return = m.Return; mc.ReturnType = m.ReturnType; if (!wrapperType.Methods.Contains(mc)) wrapperType.Methods.Add(mc); } curType = curType.ParentType; } } myTypesOfInterest.Add(wrapperType); myIndent--; GenerateType(wrapperType); myIndent++; } protected override void EndType (Type type) { if (type.IsInterface || type.Static) { myInitJni.Clear(); base.EndType(type); if (type.IsInterface) GenerateInterfaceStubs(type); return; } myIndent++; WriteLine("private static void InitJNI()"); WriteLine("{"); myIndent++; WriteLine("global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;"); if (type.WrappedInterface == null) WriteLine("global::{0}.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"{1}\"));", type.Name, GetJavaName(type).Replace('.', '/')); else WriteLine("global::{0}.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"{1}\"));", type.Name, GetJavaName(type.WrappedInterfaceType).Replace('.', '/')); foreach (var initJni in myInitJni) { WriteLine(initJni); } myIndent--; WriteLine("}"); myIndent--; myInitJni.Clear(); base.EndType(type); if (type.Abstract) GenerateInterfaceStubs(type); } List<string> myInitJni = new List<string>(); int myMemberCounter = 0; protected override void EmitField (Field field) { if (field.Scope == "protected") return; bool hasValue = !string.IsNullOrEmpty(field.Value); if (!hasValue) WriteLine("internal static global::MonoJavaBridge.FieldId _{0}{1};", field.Name.Replace("@",""), myMemberCounter++); Write(field.Scope); if (field.Static) Write("static"); Write("{0}{1}", ObjectModel.IsSystemType(field.Type) ? string.Empty : "global::", field.Type); Write(field.Name, false); WriteLine(); WriteLine("{"); myIndent++; WriteLine("get"); WriteLine("{"); if (hasValue) { myIndent++; string val = field.Value; val = val.Replace("\\" , "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n"); if (field.Type == "java.lang.String") { Write("return \"{0}\"", false, val); } else if (field.Type == "char") { val = val.Replace("'", "\\'"); // there's a weird compile error happening here due to unicode chars or something... if (field.Name == "HEX_INPUT" || field.Name == "PICKER_DIALOG_INPUT") val = "0"; Write("return '{0}'", false, val); } else { Write("return {0}", false, field.Value); } if (field.Type == "long") Write("L", false); else if (field.Type == "float") Write("f", false); WriteLine(";"); myIndent--; } else { myIndent++; WriteLine("return default({0}{1});", ObjectModel.IsSystemType(field.Type) ? string.Empty : "global::", field.Type); myIndent--; } WriteLine("}"); if (!field.IsReadOnly) { WriteLine("set"); WriteLine("{"); WriteLine("}"); } myIndent--; WriteLine("}"); } public static string GetMethodSignature(Method method) { StringBuilder ret = new StringBuilder(); ret.Append('('); for (int i = 0; i < method.Parameters.Count; i++) { var typeName = method.Parameters[i]; var type = method.ParameterTypes[i]; ret.Append(GetSignature(type, typeName)); } ret.Append(')'); ret.Append(GetSignature(method.ReturnType, method.Return)); return ret.ToString(); } public static string GetJavaName(Type type) { string typeName = type.SimpleName; var root = type; while (root.NestingClass != null) { typeName = root.NestingClass.SimpleName + "$" + typeName; root = root.NestingClass; } typeName = root.Namespace + "." + typeName; return typeName; } public static string GetSignature(Type type, string typeName) { if (type == null && typeName == null) return "V"; if (type != null) typeName = GetJavaName(type); typeName = typeName.Replace('_', '$'); string low = typeName.ToLowerInvariant(); int arr = low.LastIndexOf("["); string array = ""; while (arr != -1) { array += "["; low = low.Substring(0, arr); arr = low.LastIndexOf("["); } switch (low) { case "bool": return array + "Z"; case "int": return array + "I"; case "double": return array + "D"; case "float": return array + "F"; case "short": return array + "S"; case "long": return array + "J"; case "char": return array + "C"; case "byte": return array + "B"; case "void": return array + "V"; default: return array + "L" + typeName.Substring(0, low.Length).Replace('.', '/') + ";"; } } public static string GetMethodStatement(Method method) { if (method.IsConstructor) return "global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject({1});"; var type = method.ReturnType; var typeName = method.Return; if (typeName == "void") return "@__env.Call{0}VoidMethod({1});"; switch (typeName) { case "bool": return "return @__env.Call{0}BooleanMethod({1});"; case "int": return "return @__env.Call{0}IntMethod({1});"; case "double": return "return @__env.Call{0}DoubleMethod({1});"; case "float": return "return @__env.Call{0}FloatMethod({1});"; case "short": return "return @__env.Call{0}ShortMethod({1});"; case "long": return "return @__env.Call{0}LongMethod({1});"; case "char": return "return @__env.Call{0}CharMethod({1});"; case "byte": return "return @__env.Call{0}ByteMethod({1});"; } StringBuilder ret = new StringBuilder(); /* if (typeName.EndsWith("[]")) { // TODO: Actually return something ret.Append("return null;//"); } else { if (typeName == "java.lang.Object" || (type != null && type.IsInterface)) { ret.AppendFormat("return global::net.sf.jni4net.utils.Convertor.FullJ2C<{0}>", typeName); } else { ret.AppendFormat("return global::net.sf.jni4net.utils.Convertor.StrongJ2Cp<{0}>", typeName); } } */ if (method.Return == null) Console.WriteLine(method.ToString() + "::" + method.Type); if (method.Return.EndsWith("[]")) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<{0}>", method.Return.Substring(0, method.Return.Length - 2)); else if (method.ReturnType.IsInterface) ret.AppendFormat("return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::{0}>", method.Return); else ret.Append("return global::MonoJavaBridge.JavaBridge.WrapJavaObject"); //ret.AppendFormat("(typeof({0}), ", method.Return); ret.Append("(@__env.Call{0}ObjectMethod({1}))"); ret.AppendFormat(" as {0};", method.Return); return ret.ToString(); } /* public string GetParameterStatement(Type parameterType, string parameter) { switch (parameter) { case "bool": case "int": case "double": case "float": case "short": case "long": case "char": case "byte": return "ParPrimC2J({0})"; //case "java.lang.CharSequence": // return "ParStrongCp2J((java.lang.String){0})"; case "bool[]": case "int[]": case "double[]": case "float[]": case "short[]": case "long[]": case "char[]": case "byte[]": return "ParArrayPrimC2J(@__env, {0})"; } if (parameter.EndsWith("[][]")) { return "ParArrayStrongCp2J(@__env, {0})"; } if (parameter.EndsWith("[]")) { var stripParameter = parameter.Substring(0, parameter.Length - "[]".Length); string element = stripParameter.Replace("@", ""); if (element == "java.lang.Object" || myModel.FindType(element).IsInterface) return string.Format("ParArrayFullC2J<{0}, {1}>", parameter, stripParameter) + "(@__env, {0})"; return "ParArrayStrongCp2J(@__env, {0})"; } if (parameter == "java.lang.Object" || parameterType.IsInterface) return "ParFullC2J(@__env, {0})"; return "ParStrongCp2J({0})"; } */ public string GetParameterStatement(Type parameterType, string parameter) { return "ConvertToValue({0})"; } protected override void EmitMethod (Method method) { if (method.IsSynthetic) return; if (method.IsOverride && !method.IsConstructor && !method.Abstract && !method.Static) { Type parent = method.Type.ParentType; string sig = method.ToSignatureString(); while (parent != null) { if (myJniTypes.ContainsKey(parent.Name) && parent.Methods.Dictionary.ContainsKey(sig)) { var jniType = myJniTypes[parent.Name]; // see if the method exists to override try { if (jniType.GetMethod(method.Name) == null) return; } catch (AmbiguousMatchException) { } } parent = parent.ParentType; } } //if (method.PropertyType != null && method.Name.StartsWith("set")) // return; string methodId = null; if (!method.Type.IsInterface) { string signature = GetMethodSignature(method); if (method.Name.LastIndexOf('.') == -1) methodId = method.Name; else methodId = method.Name.Substring(method.Name.LastIndexOf('.') + 1); string methodIdLookup = methodId; methodId = string.Format("_{0}{1}", methodId.Replace("@",""), myMemberCounter++); string initJni = string.Format("global::{0}.{1} = @__env.Get{4}MethodIDNoThrow(global::{0}.staticClass, \"{2}\", \"{3}\");", method.Type.Name, methodId, method.IsConstructor ? "<init>" : methodIdLookup, signature, method.Static ? "Static" : string.Empty); myInitJni.Add(initJni); WriteLine("internal static global::MonoJavaBridge.MethodId {0};", methodId); //WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]"); Write(method.Scope); if (method.Abstract) Write("abstract"); else { if (method.Static) { Write("static"); } else if (!method.IsConstructor) { if (method.IsOverride) { if (method.IsSealed) Write("sealed"); Write("override"); } else if (!method.Type.IsSealed && method.Scope != string.Empty) Write("virtual"); } //Write("extern"); } } // TODO: Reflect on the jni4net type, and see if the method exists or not. // This is a hack to prevent some compiler warnings. if (method.IsNew && (method.Name != "clone" || !myJniTypes.ContainsKey(method.Type.Parent))) Write("new"); if (method.Return != null) Write("{0}{1}", ObjectModel.IsSystemType(method.Return) ? string.Empty : "global::", method.Return); Write(method.Name, false); Write("(", false); //WriteDelimited(method.Parameters, (v, i) => string.Format("{0} arg{1}", v == "java.lang.CharSequence" && !method.Name.Contains('.') ? "string" : v, i), ","); WriteDelimited(method.Parameters, (v, i) => string.Format("{0} arg{1}", v, i), ","); if (method.Type.IsInterface || method.Abstract || method.Scope == "internal") { WriteLine(");"); } else { Write(")"); if (method.IsConstructor) Write(" : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)"); WriteLine(); WriteLine("{"); myIndent++; // TODO: Remove this if statement when array returns are properly supported WriteLine("global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;"); var statement = GetMethodStatement(method); StringBuilder parBuilder = new StringBuilder(); if (method.Static || method.IsConstructor) parBuilder.AppendFormat("{0}.staticClass, ", method.Type.Name); else parBuilder.Append("this.JvmHandle, "); parBuilder.AppendFormat("global::{0}.{1}", method.Type.Name, methodId); //if (method.IsConstructor) // parBuilder.Append(", this"); bool hasCharSequenceArgument = false; for (int i = 0; i < method.Parameters.Count; i++) { parBuilder.Append(", "); var parType = method.ParameterTypes[i]; var par = method.Parameters[i]; if (par == "java.lang.CharSequence") hasCharSequenceArgument = true; parBuilder.Append("global::MonoJavaBridge.JavaBridge."); parBuilder.Append(string.Format(GetParameterStatement(parType, par), "arg" + i)); } if (method.Static || method.IsConstructor) { WriteLine(statement, method.Static ? "Static" : string.Empty, parBuilder); if (method.IsConstructor) WriteLine("Init(@__env, handle);"); } else { WriteLine("if (!IsClrObject)", method.Type.Name); myIndent++; WriteLine(statement, string.Empty, parBuilder); myIndent--; WriteLine("else"); myIndent++; WriteLine(statement, "NonVirtual", string.Format(parBuilder.ToString().Replace("this.JvmHandle, ", "this.JvmHandle, global::{0}.staticClass, "), method.Type.Name)); myIndent--; } myIndent--; WriteLine("}"); if (hasCharSequenceArgument && !method.IsConstructor && method.Scope == "public" && !method.Static) { var em = method; //myExtensionMethods.Add(method); Write("public {0} {1}(", false, em.Return, em.Name); //Write("this global::{0} __this", false, em.Type.Name); WriteDelimited(em.Parameters, (v, i) => string.Format("{0} arg{1}", v == "java.lang.CharSequence" ? "string" : v, i), ","); WriteLine(")"); WriteLine("{"); myIndent++; if (em.Return != "void") Write("return"); Write("{0}(", false, em.Name); WriteDelimited(em.Parameters, (v, i) => string.Format("{0}arg{1}", v == "java.lang.CharSequence" ? "(global::java.lang.CharSequence)(global::java.lang.String)" : string.Empty, i), ","); WriteLine(");"); myIndent--; WriteLine("}"); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDsaOpenSsl.Tests { public static class EcDsaOpenSslTests { [Fact] public static void DefaultCtor() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public static void Ctor224() { int expectedKeySize = 224; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor384() { int expectedKeySize = 384; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor521() { int expectedKeySize = 521; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void CtorHandle224() { IntPtr ecKey = EC_KEY_new_by_curve_name(NID_secp224r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = EC_KEY_generate_key(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } EC_KEY_free(ecKey); } [Fact] public static void CtorHandle384() { IntPtr ecKey = EC_KEY_new_by_curve_name(NID_secp384r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = EC_KEY_generate_key(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } EC_KEY_free(ecKey); } [Fact] public static void CtorHandle521() { IntPtr ecKey = EC_KEY_new_by_curve_name(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = EC_KEY_generate_key(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } EC_KEY_free(ecKey); } [Fact] public static void CtorHandleDuplicate() { IntPtr ecKey = EC_KEY_new_by_curve_name(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = EC_KEY_generate_key(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did his own ref-count bump. EC_KEY_free(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public static void KeySizeProp() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); e.KeySize = 224; Assert.Equal(224, e.KeySize); e.Exercise(); } } [Fact] public static void VerifyDuplicateKey_ValidHandle() { byte[] data = ByteUtils.RepeatByte(0x71, 11); using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { using (ECDsa second = new ECDsaOpenSsl(firstHandle)) { byte[] signed = second.SignData(data, HashAlgorithmName.SHA512); Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512)); } } } [Fact] public static void VerifyDuplicateKey_DistinctHandles() { using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public static void VerifyDuplicateKey_RefCounts() { byte[] data = ByteUtils.RepeatByte(0x74, 11); byte[] signature; ECDsa second; using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { signature = first.SignData(data, HashAlgorithmName.SHA384); second = new ECDsaOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) { Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384)); } } [Fact] public static void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new RSAOpenSsl(pkey)); } [Fact] public static void VerifyDuplicateKey_InvalidHandle() { using (ECDsaOpenSsl ecdsa = new ECDsaOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey)); } } private static void Exercise(this ECDsaOpenSsl e) { // Make a few calls on this to ensure we aren't broken due to bad/prematurely released handles. int keySize = e.KeySize; byte[] data = new byte[0x10]; byte[] sig = e.SignData(data, 0, data.Length, HashAlgorithmName.SHA1); bool verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.True(verified); sig[sig.Length - 1]++; verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.False(verified); } private const int NID_secp224r1 = 713; private const int NID_secp384r1 = 715; private const int NID_secp521r1 = 716; [DllImport("libcrypto")] private static extern IntPtr EC_KEY_new_by_curve_name(int nid); [DllImport("libcrypto")] private static extern int EC_KEY_generate_key(IntPtr ecKey); [DllImport("libcrypto")] private static extern void EC_KEY_free(IntPtr r); } }
using System; namespace Versioning { public class Project : Sage_Object { /* Autogenerated by sage_wrapper_generator.pl */ SageDataObject120.Project proj12; SageDataObject130.Project proj13; SageDataObject140.Project proj14; SageDataObject150.Project proj15; SageDataObject160.Project proj16; SageDataObject170.Project proj17; public Project(object inner, int version) : base(version) { this.Inner = inner; switch (m_version) { case 12: { proj12 = (SageDataObject120.Project)inner; return; } case 13: { proj13 = (SageDataObject130.Project)inner; return; } case 14: { proj14 = (SageDataObject140.Project)inner; return; } case 15: { proj15 = (SageDataObject150.Project)inner; return; } case 16: { proj16 = (SageDataObject160.Project)inner; return; } case 17: { proj17 = (SageDataObject170.Project)inner; return; } default: throw new InvalidOperationException("ver"); } } /* Autogenerated with data_generator.pl */ // temp2.pl public bool Delete() { switch (m_version) { case 12: return proj12.Delete(); case 13: return proj13.Delete(); case 14: return proj14.Delete(); case 15: return proj15.Delete(); case 16: return proj16.Delete(); case 17: return proj17.Delete(); default: throw new InvalidOperationException("ver"); } } public bool Load(object index) { object temp = index; switch (m_version) { case 12: return proj12.Load(ref temp); case 13: return proj13.Load(ref temp); case 14: return proj14.Load(ref temp); case 15: return proj15.Load(ref temp); case 16: return proj16.Load(ref temp); case 17: return proj17.Load(ref temp); default: throw new InvalidOperationException("ver"); } } public bool Update() { switch (m_version) { case 12: return proj12.Update(); case 13: return proj13.Update(); case 14: return proj14.Update(); case 15: return proj15.Update(); case 16: return proj16.Update(); case 17: return proj17.Update(); default: throw new InvalidOperationException("ver"); } } public int ProjectID { get { switch (m_version) { case 12: return proj12.ProjectID; case 13: return proj13.ProjectID; case 14: return proj14.ProjectID; case 15: return proj15.ProjectID; case 16: return proj16.ProjectID; case 17: return proj17.ProjectID; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.ProjectID = value; return; } case 13: { proj13.ProjectID = value; return; } case 14: { proj14.ProjectID = value; return; } case 15: { proj15.ProjectID = value; return; } case 16: { proj16.ProjectID = value; return; } case 17: { proj17.ProjectID = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Reference { get { switch (m_version) { case 12: return proj12.Reference; case 13: return proj13.Reference; case 14: return proj14.Reference; case 15: return proj15.Reference; case 16: return proj16.Reference; case 17: return proj17.Reference; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Reference = value; return; } case 13: { proj13.Reference = value; return; } case 14: { proj14.Reference = value; return; } case 15: { proj15.Reference = value; return; } case 16: { proj16.Reference = value; return; } case 17: { proj17.Reference = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Address1 { get { switch (m_version) { case 12: return proj12.Address1; case 13: return proj13.Address1; case 14: return proj14.Address1; case 15: return proj15.Address1; case 16: return proj16.Address1; case 17: return proj17.Address1; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Address1 = value; return; } case 13: { proj13.Address1 = value; return; } case 14: { proj14.Address1 = value; return; } case 15: { proj15.Address1 = value; return; } case 16: { proj16.Address1 = value; return; } case 17: { proj17.Address1 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Address2 { get { switch (m_version) { case 12: return proj12.Address2; case 13: return proj13.Address2; case 14: return proj14.Address2; case 15: return proj15.Address2; case 16: return proj16.Address2; case 17: return proj17.Address2; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Address2 = value; return; } case 13: { proj13.Address2 = value; return; } case 14: { proj14.Address2 = value; return; } case 15: { proj15.Address2 = value; return; } case 16: { proj16.Address2 = value; return; } case 17: { proj17.Address2 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Address3 { get { switch (m_version) { case 12: return proj12.Address3; case 13: return proj13.Address3; case 14: return proj14.Address3; case 15: return proj15.Address3; case 16: return proj16.Address3; case 17: return proj17.Address3; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Address3 = value; return; } case 13: { proj13.Address3 = value; return; } case 14: { proj14.Address3 = value; return; } case 15: { proj15.Address3 = value; return; } case 16: { proj16.Address3 = value; return; } case 17: { proj17.Address3 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Address4 { get { switch (m_version) { case 12: return proj12.Address4; case 13: return proj13.Address4; case 14: return proj14.Address4; case 15: return proj15.Address4; case 16: return proj16.Address4; case 17: return proj17.Address4; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Address4 = value; return; } case 13: { proj13.Address4 = value; return; } case 14: { proj14.Address4 = value; return; } case 15: { proj15.Address4 = value; return; } case 16: { proj16.Address4 = value; return; } case 17: { proj17.Address4 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Address5 { get { switch (m_version) { case 12: return proj12.Address5; case 13: return proj13.Address5; case 14: return proj14.Address5; case 15: return proj15.Address5; case 16: return proj16.Address5; case 17: return proj17.Address5; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Address5 = value; return; } case 13: { proj13.Address5 = value; return; } case 14: { proj14.Address5 = value; return; } case 15: { proj15.Address5 = value; return; } case 16: { proj16.Address5 = value; return; } case 17: { proj17.Address5 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Analysis1 { get { switch (m_version) { case 12: return proj12.Analysis1; case 13: return proj13.Analysis1; case 14: return proj14.Analysis1; case 15: return proj15.Analysis1; case 16: return proj16.Analysis1; case 17: return proj17.Analysis1; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Analysis1 = value; return; } case 13: { proj13.Analysis1 = value; return; } case 14: { proj14.Analysis1 = value; return; } case 15: { proj15.Analysis1 = value; return; } case 16: { proj16.Analysis1 = value; return; } case 17: { proj17.Analysis1 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Analysis2 { get { switch (m_version) { case 12: return proj12.Analysis2; case 13: return proj13.Analysis2; case 14: return proj14.Analysis2; case 15: return proj15.Analysis2; case 16: return proj16.Analysis2; case 17: return proj17.Analysis2; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Analysis2 = value; return; } case 13: { proj13.Analysis2 = value; return; } case 14: { proj14.Analysis2 = value; return; } case 15: { proj15.Analysis2 = value; return; } case 16: { proj16.Analysis2 = value; return; } case 17: { proj17.Analysis2 = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Analysis3 { get { switch (m_version) { case 12: return proj12.Analysis3; case 13: return proj13.Analysis3; case 14: return proj14.Analysis3; case 15: return proj15.Analysis3; case 16: return proj16.Analysis3; case 17: return proj17.Analysis3; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Analysis3 = value; return; } case 13: { proj13.Analysis3 = value; return; } case 14: { proj14.Analysis3 = value; return; } case 15: { proj15.Analysis3 = value; return; } case 16: { proj16.Analysis3 = value; return; } case 17: { proj17.Analysis3 = value; return; } default: throw new InvalidOperationException("ver"); } } } public double BilledNet { get { switch (m_version) { case 12: return proj12.BilledNet; case 13: return proj13.BilledNet; case 14: return proj14.BilledNet; case 15: return proj15.BilledNet; case 16: return proj16.BilledNet; case 17: return proj17.BilledNet; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.BilledNet = value; return; } case 13: { proj13.BilledNet = value; return; } case 14: { proj14.BilledNet = value; return; } case 15: { proj15.BilledNet = value; return; } case 16: { proj16.BilledNet = value; return; } case 17: { proj17.BilledNet = value; return; } default: throw new InvalidOperationException("ver"); } } } public double BilledVAT { get { switch (m_version) { case 12: return proj12.BilledVAT; case 13: return proj13.BilledVAT; case 14: return proj14.BilledVAT; case 15: return proj15.BilledVAT; case 16: return proj16.BilledVAT; case 17: return proj17.BilledVAT; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.BilledVAT = value; return; } case 13: { proj13.BilledVAT = value; return; } case 14: { proj14.BilledVAT = value; return; } case 15: { proj15.BilledVAT = value; return; } case 16: { proj16.BilledVAT = value; return; } case 17: { proj17.BilledVAT = value; return; } default: throw new InvalidOperationException("ver"); } } } public double CommittedCost { get { switch (m_version) { //case 12: return proj12.CommittedCost; //case 13: return proj13.CommittedCost; //case 14: return proj14.CommittedCost; //case 15: return proj15.CommittedCost; case 16: return proj16.CommittedCost; case 17: return proj17.CommittedCost; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { //case 12: { proj12.CommittedCost = value; return; } //case 13: { proj13.CommittedCost = value; return; } //case 14: { proj14.CommittedCost = value; return; } //case 15: { proj15.CommittedCost = value; return; } case 16: { proj16.CommittedCost = value; return; } case 17: { proj17.CommittedCost = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Contact { get { switch (m_version) { case 12: return proj12.Contact; case 13: return proj13.Contact; case 14: return proj14.Contact; case 15: return proj15.Contact; case 16: return proj16.Contact; case 17: return proj17.Contact; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Contact = value; return; } case 13: { proj13.Contact = value; return; } case 14: { proj14.Contact = value; return; } case 15: { proj15.Contact = value; return; } case 16: { proj16.Contact = value; return; } case 17: { proj17.Contact = value; return; } default: throw new InvalidOperationException("ver"); } } } public object Country { get { switch (m_version) { case 12: return proj12.Country; case 13: return proj13.Country; case 14: return proj14.Country; case 15: return proj15.Country; case 16: return proj16.Country; case 17: return proj17.Country; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Country = value; return; } case 13: { proj13.Country = value; return; } case 14: { proj14.Country = value; return; } case 15: { proj15.Country = value; return; } case 16: { proj16.Country = value; return; } case 17: { proj17.Country = value; return; } default: throw new InvalidOperationException("ver"); } } } public object Customer { get { switch (m_version) { case 12: return proj12.Customer; case 13: return proj13.Customer; case 14: return proj14.Customer; case 15: return proj15.Customer; case 16: return proj16.Customer; case 17: return proj17.Customer; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Customer = value; return; } case 13: { proj13.Customer = value; return; } case 14: { proj14.Customer = value; return; } case 15: { proj15.Customer = value; return; } case 16: { proj16.Customer = value; return; } case 17: { proj17.Customer = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Description { get { switch (m_version) { case 12: return proj12.Description; case 13: return proj13.Description; case 14: return proj14.Description; case 15: return proj15.Description; case 16: return proj16.Description; case 17: return proj17.Description; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Description = value; return; } case 13: { proj13.Description = value; return; } case 14: { proj14.Description = value; return; } case 15: { proj15.Description = value; return; } case 16: { proj16.Description = value; return; } case 17: { proj17.Description = value; return; } default: throw new InvalidOperationException("ver"); } } } public string EMail { get { switch (m_version) { case 12: return proj12.EMail; case 13: return proj13.EMail; case 14: return proj14.EMail; case 15: return proj15.EMail; case 16: return proj16.EMail; case 17: return proj17.EMail; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.EMail = value; return; } case 13: { proj13.EMail = value; return; } case 14: { proj14.EMail = value; return; } case 15: { proj15.EMail = value; return; } case 16: { proj16.EMail = value; return; } case 17: { proj17.EMail = value; return; } default: throw new InvalidOperationException("ver"); } } } public DateTime EndDate { get { switch (m_version) { case 12: return proj12.EndDate; case 13: return proj13.EndDate; case 14: return proj14.EndDate; case 15: return proj15.EndDate; case 16: return proj16.EndDate; case 17: return proj17.EndDate; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.EndDate = value; return; } case 13: { proj13.EndDate = value; return; } case 14: { proj14.EndDate = value; return; } case 15: { proj15.EndDate = value; return; } case 16: { proj16.EndDate = value; return; } case 17: { proj17.EndDate = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Fax { get { switch (m_version) { case 12: return proj12.Fax; case 13: return proj13.Fax; case 14: return proj14.Fax; case 15: return proj15.Fax; case 16: return proj16.Fax; case 17: return proj17.Fax; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Fax = value; return; } case 13: { proj13.Fax = value; return; } case 14: { proj14.Fax = value; return; } case 15: { proj15.Fax = value; return; } case 16: { proj16.Fax = value; return; } case 17: { proj17.Fax = value; return; } default: throw new InvalidOperationException("ver"); } } } public DateTime LastBilledDate { get { switch (m_version) { case 12: return proj12.LastBilledDate; case 13: return proj13.LastBilledDate; case 14: return proj14.LastBilledDate; case 15: return proj15.LastBilledDate; case 16: return proj16.LastBilledDate; case 17: return proj17.LastBilledDate; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.LastBilledDate = value; return; } case 13: { proj13.LastBilledDate = value; return; } case 14: { proj14.LastBilledDate = value; return; } case 15: { proj15.LastBilledDate = value; return; } case 16: { proj16.LastBilledDate = value; return; } case 17: { proj17.LastBilledDate = value; return; } default: throw new InvalidOperationException("ver"); } } } public DateTime LastCostDate { get { switch (m_version) { case 12: return proj12.LastCostDate; case 13: return proj13.LastCostDate; case 14: return proj14.LastCostDate; case 15: return proj15.LastCostDate; case 16: return proj16.LastCostDate; case 17: return proj17.LastCostDate; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.LastCostDate = value; return; } case 13: { proj13.LastCostDate = value; return; } case 14: { proj14.LastCostDate = value; return; } case 15: { proj15.LastCostDate = value; return; } case 16: { proj16.LastCostDate = value; return; } case 17: { proj17.LastCostDate = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Name { get { switch (m_version) { case 12: return proj12.Name; case 13: return proj13.Name; case 14: return proj14.Name; case 15: return proj15.Name; case 16: return proj16.Name; case 17: return proj17.Name; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Name = value; return; } case 13: { proj13.Name = value; return; } case 14: { proj14.Name = value; return; } case 15: { proj15.Name = value; return; } case 16: { proj16.Name = value; return; } case 17: { proj17.Name = value; return; } default: throw new InvalidOperationException("ver"); } } } public string OrderNumber { get { switch (m_version) { case 12: return proj12.OrderNumber; case 13: return proj13.OrderNumber; case 14: return proj14.OrderNumber; case 15: return proj15.OrderNumber; case 16: return proj16.OrderNumber; case 17: return proj17.OrderNumber; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.OrderNumber = value; return; } case 13: { proj13.OrderNumber = value; return; } case 14: { proj14.OrderNumber = value; return; } case 15: { proj15.OrderNumber = value; return; } case 16: { proj16.OrderNumber = value; return; } case 17: { proj17.OrderNumber = value; return; } default: throw new InvalidOperationException("ver"); } } } public double OutstandingToBill { get { switch (m_version) { case 12: return proj12.OutstandingToBill; case 13: return proj13.OutstandingToBill; case 14: return proj14.OutstandingToBill; case 15: return proj15.OutstandingToBill; case 16: return proj16.OutstandingToBill; case 17: return proj17.OutstandingToBill; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.OutstandingToBill = value; return; } case 13: { proj13.OutstandingToBill = value; return; } case 14: { proj14.OutstandingToBill = value; return; } case 15: { proj15.OutstandingToBill = value; return; } case 16: { proj16.OutstandingToBill = value; return; } case 17: { proj17.OutstandingToBill = value; return; } default: throw new InvalidOperationException("ver"); } } } public double PriceQuoted { get { switch (m_version) { case 12: return proj12.PriceQuoted; case 13: return proj13.PriceQuoted; case 14: return proj14.PriceQuoted; case 15: return proj15.PriceQuoted; case 16: return proj16.PriceQuoted; case 17: return proj17.PriceQuoted; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.PriceQuoted = value; return; } case 13: { proj13.PriceQuoted = value; return; } case 14: { proj14.PriceQuoted = value; return; } case 15: { proj15.PriceQuoted = value; return; } case 16: { proj16.PriceQuoted = value; return; } case 17: { proj17.PriceQuoted = value; return; } default: throw new InvalidOperationException("ver"); } } } public double ProfitToDate { get { switch (m_version) { case 12: return proj12.ProfitToDate; case 13: return proj13.ProfitToDate; case 14: return proj14.ProfitToDate; case 15: return proj15.ProfitToDate; case 16: return proj16.ProfitToDate; case 17: return proj17.ProfitToDate; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.ProfitToDate = value; return; } case 13: { proj13.ProfitToDate = value; return; } case 14: { proj14.ProfitToDate = value; return; } case 15: { proj15.ProfitToDate = value; return; } case 16: { proj16.ProfitToDate = value; return; } case 17: { proj17.ProfitToDate = value; return; } default: throw new InvalidOperationException("ver"); } } } public DateTime StartDate { get { switch (m_version) { case 12: return proj12.StartDate; case 13: return proj13.StartDate; case 14: return proj14.StartDate; case 15: return proj15.StartDate; case 16: return proj16.StartDate; case 17: return proj17.StartDate; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.StartDate = value; return; } case 13: { proj13.StartDate = value; return; } case 14: { proj14.StartDate = value; return; } case 15: { proj15.StartDate = value; return; } case 16: { proj16.StartDate = value; return; } case 17: { proj17.StartDate = value; return; } default: throw new InvalidOperationException("ver"); } } } public object Status { get { switch (m_version) { case 12: return proj12.Status; case 13: return proj13.Status; case 14: return proj14.Status; case 15: return proj15.Status; case 16: return proj16.Status; case 17: return proj17.Status; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Status = value; return; } case 13: { proj13.Status = value; return; } case 14: { proj14.Status = value; return; } case 15: { proj15.Status = value; return; } case 16: { proj16.Status = value; return; } case 17: { proj17.Status = value; return; } default: throw new InvalidOperationException("ver"); } } } public string Telehpone { get { switch (m_version) { case 12: return proj12.Telehpone; case 13: return proj13.Telehpone; case 14: return proj14.Telehpone; case 15: return proj15.Telehpone; case 16: return proj16.Telehpone; case 17: return proj17.Telehpone; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Telehpone = value; return; } case 13: { proj13.Telehpone = value; return; } case 14: { proj14.Telehpone = value; return; } case 15: { proj15.Telehpone = value; return; } case 16: { proj16.Telehpone = value; return; } case 17: { proj17.Telehpone = value; return; } default: throw new InvalidOperationException("ver"); } } } public double TotalBilled { get { switch (m_version) { case 12: return proj12.TotalBilled; case 13: return proj13.TotalBilled; case 14: return proj14.TotalBilled; case 15: return proj15.TotalBilled; case 16: return proj16.TotalBilled; case 17: return proj17.TotalBilled; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.TotalBilled = value; return; } case 13: { proj13.TotalBilled = value; return; } case 14: { proj14.TotalBilled = value; return; } case 15: { proj15.TotalBilled = value; return; } case 16: { proj16.TotalBilled = value; return; } case 17: { proj17.TotalBilled = value; return; } default: throw new InvalidOperationException("ver"); } } } public double TotalBudget { get { switch (m_version) { case 12: return proj12.TotalBudget; case 13: return proj13.TotalBudget; case 14: return proj14.TotalBudget; case 15: return proj15.TotalBudget; case 16: return proj16.TotalBudget; case 17: return proj17.TotalBudget; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.TotalBudget = value; return; } case 13: { proj13.TotalBudget = value; return; } case 14: { proj14.TotalBudget = value; return; } case 15: { proj15.TotalBudget = value; return; } case 16: { proj16.TotalBudget = value; return; } case 17: { proj17.TotalBudget = value; return; } default: throw new InvalidOperationException("ver"); } } } public double TotalCost { get { switch (m_version) { case 12: return proj12.TotalCost; case 13: return proj13.TotalCost; case 14: return proj14.TotalCost; case 15: return proj15.TotalCost; case 16: return proj16.TotalCost; case 17: return proj17.TotalCost; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.TotalCost = value; return; } case 13: { proj13.TotalCost = value; return; } case 14: { proj14.TotalCost = value; return; } case 15: { proj15.TotalCost = value; return; } case 16: { proj16.TotalCost = value; return; } case 17: { proj17.TotalCost = value; return; } default: throw new InvalidOperationException("ver"); } } } public object Transactions { get { switch (m_version) { case 12: return proj12.Transactions; case 13: return proj13.Transactions; case 14: return proj14.Transactions; case 15: return proj15.Transactions; case 16: return proj16.Transactions; case 17: return proj17.Transactions; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Transactions = value; return; } case 13: { proj13.Transactions = value; return; } case 14: { proj14.Transactions = value; return; } case 15: { proj15.Transactions = value; return; } case 16: { proj16.Transactions = value; return; } case 17: { proj17.Transactions = value; return; } default: throw new InvalidOperationException("ver"); } } } public double Variance { get { switch (m_version) { case 12: return proj12.Variance; case 13: return proj13.Variance; case 14: return proj14.Variance; case 15: return proj15.Variance; case 16: return proj16.Variance; case 17: return proj17.Variance; default: throw new InvalidOperationException("ver"); } } set { switch (m_version) { case 12: { proj12.Variance = value; return; } case 13: { proj13.Variance = value; return; } case 14: { proj14.Variance = value; return; } case 15: { proj15.Variance = value; return; } case 16: { proj16.Variance = value; return; } case 17: { proj17.Variance = value; return; } default: throw new InvalidOperationException("ver"); } } } public object Inner { get; private set; } } }
/******************************************************************************* * * Copyright (C) 2013-2014 Frozen North Computing * * 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.Drawing; using System.Runtime.InteropServices; #if FN2D_WIN using OpenTK.Graphics.OpenGL; #elif FN2D_IOS || FN2D_AND using OpenTK.Graphics; using OpenTK.Graphics.ES11; using ArrayCap = OpenTK.Graphics.ES11.All; using BeginMode = OpenTK.Graphics.ES11.All; using BufferTarget = OpenTK.Graphics.ES11.All; using BufferUsageHint = OpenTK.Graphics.ES11.All; using ColorPointerType = OpenTK.Graphics.ES11.All; using EnableCap = OpenTK.Graphics.ES11.All; using StringName = OpenTK.Graphics.ES11.All; using TexCoordPointerType = OpenTK.Graphics.ES11.All; using VertexPointerType = OpenTK.Graphics.ES11.All; #endif namespace FrozenNorth.OpenGL.FN2D { /// <summary> /// OpenGL 2D vertex, texture coordinate, color and index arrays for drawing. /// </summary> public class FN2DArrays : IDisposable { // public constants public const int DefaultAllocationIncrement = 64; // internal types #if FN2D_WIN protected static DrawElementsType UnsignedIntElement = DrawElementsType.UnsignedInt; #elif FN2D_IOS protected static All UnsignedIntElement = All.UnsignedIntOes; #elif FN2D_AND protected static All UnsignedIntElement = All.UnsignedInt; #endif // font system variables private static FN2DArraysList arrays = null; // capabilities variables private static bool usingVBO = false; private static bool usingOESVBO = false; private static bool gotUsingVBO = false; // instance variables private BeginMode drawMode; private int allocInc; private FN2DVertex[] buffer; private float[] vertices; private float[] texCoords; private byte[] colors; private uint[] indices; private uint numVertices; private uint numTexCoords; private uint numColors; private uint numIndices; private int arrayId; private int indexId; private bool changed; /// <summary> /// Initializes the arrays system. /// </summary> public static bool OpenArraysManager(string path = null) { if (arrays == null) { arrays = new FN2DArraysList(); } return true; } /// <summary> /// Cleans up the arrays system. /// </summary> public static void CloseArraysManager() { if (arrays != null) { for (int i = arrays.Count - 1; i >= 0; i--) { FN2DArrays arr = arrays[i]; arrays.RemoveAt(i); arr.Dispose(); } arrays = null; } } /// <summary> /// Creates an empty set of arrays. /// </summary> /// <param name="drawMode">OpenGL drawing mode.</param> /// <param name="allocInc">Allocation increment.</param> /// <returns>A new FN2DArrays object.</returns> public static FN2DArrays Create(BeginMode drawMode = BeginMode.Triangles, int allocInc = DefaultAllocationIncrement) { OpenArraysManager(); FN2DArrays arr = new FN2DArrays(drawMode, allocInc); if (arr != null) { arrays.Add(arr); } return arr; } /// <summary> /// Destroys an existing set of arrays and creates a new, empty set /// of arrays with the same drawing mode and allocation increment. /// </summary> /// <param name="arr">Set of arrays to be destroyed. Can be null.</param> /// <returns>A new FN2DArrays object.</returns> public static FN2DArrays Create(FN2DArrays arr) { BeginMode drawMode = BeginMode.Triangles; int allocInc = DefaultAllocationIncrement; if (arr != null) { drawMode = arr.DrawMode; allocInc = arr.AllocationIncrement; } Destroy(arr); return Create(drawMode, allocInc); } /// <summary> /// Destroys a set of arrays. /// </summary> /// <param name="arr">Sets of arrays to be destroyed.</param> public static void Destroy(FN2DArrays arr) { if (arrays != null && arr != null) { arrays.Remove(arr); arr.Dispose(); } } /// <summary> /// Constructor - Creates an empty set of arrays. /// </summary> /// <param name="drawMode">OpenGL drawing mode.</param> /// <param name="allocInc">Allocation increment.</param> private FN2DArrays(BeginMode drawMode = BeginMode.Triangles, int allocInc = 64) { this.drawMode = drawMode; this.allocInc = allocInc; Clear(); } /// <summary> /// Destructor - Calls Dispose(). /// </summary> ~FN2DArrays() { Dispose(false); } /// <summary> /// Releases all resource used by the object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Frees unmanaged resources and calls Dispose() on the member objects. /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { // delete the buffers if (arrayId != 0) { GL.DeleteBuffers(1, ref arrayId); arrayId = 0; } if (indexId != 0) { GL.DeleteBuffers(1, ref indexId); indexId = 0; } arrays.Remove(this); } // clear the arrays Clear(); } /// <summary> /// Writes the VBO buffers to the GPU if they've changed. /// </summary> private void SetVboData() { if (UsingVBO && changed) { // create, bind and upload the vertices to a buffer if (arrayId == 0) { GL.GenBuffers(1, out arrayId); } GL.BindBuffer(BufferTarget.ArrayBuffer, arrayId); if (numVertices != 0) { GL.BufferData<FN2DVertex>(BufferTarget.ArrayBuffer, (IntPtr)(Marshal.SizeOf(buffer[0]) * numVertices), buffer, BufferUsageHint.DynamicDraw); } else { GL.BufferData(BufferTarget.ArrayBuffer, IntPtr.Zero, IntPtr.Zero, BufferUsageHint.DynamicDraw); } GL.BindBuffer(BufferTarget.ArrayBuffer, 0); // create, bind and upload the indices to a buffer if (indexId == 0) { GL.GenBuffers(1, out indexId); } GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexId); if (numIndices != 0) { GL.BufferData<uint>(BufferTarget.ElementArrayBuffer, (IntPtr)(Marshal.SizeOf(indices[0]) * numIndices), indices, BufferUsageHint.DynamicDraw); } else { GL.BufferData(BufferTarget.ElementArrayBuffer, IntPtr.Zero, IntPtr.Zero, BufferUsageHint.DynamicDraw); } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); } changed = false; } /// <summary> /// Allocates the arrays and resets the array indexes. /// </summary> /// <param name="numVertices">Number of vertices.</param> /// <param name="numTexCoords">Number of texture coordinates.</param> /// <param name="numColors">Number of colors.</param> /// <param name="numIndices">Number of indices.</param> public void Alloc(int numVertices, int numTexCoords, int numColors, int numIndices) { Clear(); if (UsingVBO) { buffer = new FN2DVertex[numVertices]; } else { vertices = new float[numVertices * 2]; texCoords = new float[numTexCoords * 2]; colors = new byte[numColors * 4]; } indices = new uint[numIndices]; } /// <summary> /// Allocates the arrays for a number of rectangles and resets the array indexes. /// </summary> /// <param name="numRects">Number of rectangles.</param> /// <param name="withTextures">True to allocate the texture coordinates array, false not to.</param> /// <param name="withColors">True to allocate the colors array, false not to.</param> public void AllocRects(int numRects, bool withTextures, bool withColors) { Alloc(numRects * 4, withTextures ? (numRects * 4) : 0, withColors ? (numRects * 4) : 0, numRects * 6); } /// <summary> /// Clears the arrays and resets the array indexes. /// </summary> public void Clear() { // clear the object references buffer = null; vertices = null; texCoords = null; colors = null; indices = null; // reset the array counts numVertices = 0; numTexCoords = 0; numColors = 0; numIndices = 0; // set the changed flag changed = true; } /// <summary> /// Adds a vertex. /// </summary> /// <param name="x">The X value.</param> /// <param name="y">The Y value.</param> /// <returns>The index at which the vertex was added.</returns> public uint AddVertex(float x, float y) { if (UsingVBO) { if (buffer == null) { buffer = new FN2DVertex[allocInc]; } else if (numVertices == buffer.Length) { Array.Resize(ref buffer, buffer.Length + allocInc); } buffer[numVertices].x = x; buffer[numVertices].y = y; } else { if (vertices == null) { vertices = new float[allocInc * 2]; } else if (numVertices * 2 == vertices.Length) { Array.Resize(ref vertices, vertices.Length + allocInc * 2); } vertices[numVertices * 2] = x; vertices[numVertices * 2 + 1] = y; } numVertices++; changed = true; return numVertices - 1; } /// <summary> /// Adds a vertex with a color. /// </summary> /// <param name="x">The X value.</param> /// <param name="y">The Y value.</param> /// <param name="r">The color's red value.</param> /// <param name="g">The color's green value.</param> /// <param name="b">The color's blue value.</param> /// <param name="a">The color's alpha value.</param> /// <returns>The index at which the vertex was added.</returns> public uint AddVertex(float x, float y, byte r, byte g, byte b, byte a) { AddColor(r, g, b, a); return AddVertex(x, y); } /// <summary> /// Adds a vertex with a color. /// </summary> /// <param name="x">The X value.</param> /// <param name="y">The Y value.</param> /// <param name="color">The color value.</param> /// <returns>The index at which the vertex was added.</returns> public uint AddVertex(float x, float y, Color color) { return AddVertex(x, y, color.R, color.G, color.B, color.A); } /// <summary> /// Adds the vertices for a rectangle. /// </summary> /// <param name="x1">The top-left X value.</param> /// <param name="y1">The top-left Y value.</param> /// <param name="x2">The bottom-right X value.</param> /// <param name="y2">The bottom-right Y value.</param> /// <returns>The index at which the vertices were added.</returns> public uint AddRectVertices(float x1, float y1, float x2, float y2) { uint index = AddVertex(x1, y1); AddVertex(x2, y1); AddVertex(x2, y2); AddVertex(x1, y2); return index; } /// <summary> /// Adds a texture coordinate. /// </summary> /// <param name="x">The X value.</param> /// <param name="y">The Y value.</param> /// <returns>The index at which the texture coordinate was added.</returns> public uint AddTexCoord(float x, float y) { if (UsingVBO) { if (buffer == null) { buffer = new FN2DVertex[allocInc]; } else if (numTexCoords == buffer.Length) { Array.Resize(ref buffer, buffer.Length + allocInc); } buffer[numTexCoords].s = x; buffer[numTexCoords].t = y; } else { if (texCoords == null) { texCoords = new float[allocInc * 2]; } else if (numTexCoords * 2 == texCoords.Length) { Array.Resize(ref texCoords, texCoords.Length + allocInc * 2); } texCoords[numTexCoords * 2] = x; texCoords[numTexCoords * 2 + 1] = y; } numTexCoords++; changed = true; return numTexCoords - 1; } /// <summary> /// Adds the texture coordinates for a rectangle. /// </summary> /// <param name="x1">The top-left X value.</param> /// <param name="y1">The top-left Y value.</param> /// <param name="x2">The bottom-right X value.</param> /// <param name="y2">The bottom-right Y value.</param> /// <returns>The index at which the texture coordinates were added.</returns> public uint AddRectTexCoords(float x1, float y1, float x2, float y2) { uint index = AddTexCoord(x1, y1); AddTexCoord(x2, y1); AddTexCoord(x2, y2); AddTexCoord(x1, y2); return index; } /// <summary> /// Adds a color. /// </summary> /// <param name="r">The color's red value.</param> /// <param name="g">The color's green value.</param> /// <param name="b">The color's blue value.</param> /// <param name="a">The color's alpha value.</param> /// <returns>The index at which the color was added.</returns> public uint AddColor(byte r, byte g, byte b, byte a) { if (UsingVBO) { if (buffer == null) { buffer = new FN2DVertex[allocInc]; } else if (numColors == buffer.Length) { Array.Resize(ref buffer, buffer.Length + allocInc); } buffer[numColors].r = r; buffer[numColors].g = g; buffer[numColors].b = b; buffer[numColors].a = a; } else { uint i = numColors * 4; if (colors == null) { colors = new byte[allocInc * 4]; } else if (i == colors.Length) { Array.Resize(ref colors, colors.Length + allocInc * 4); } colors[i++] = r; colors[i++] = g; colors[i++] = b; colors[i++] = a; } numColors++; changed = true; return numColors - 1; } /// <summary> /// Adds the colors for a rectangle. /// </summary> /// <param name="r">The color's red value.</param> /// <param name="g">The color's green value.</param> /// <param name="b">The color's blue value.</param> /// <param name="a">The color's alpha value.</param> /// <returns>The index at which the colors were added.</returns> public uint AddRectColors(byte r, byte g, byte b, byte a) { uint index = AddColor(r, g, b, a); AddColor(r, g, b, a); AddColor(r, g, b, a); AddColor(r, g, b, a); return index; } /// <summary> /// Adds the colors for a rectangle. /// </summary> /// <param name="color">The color value.</param> /// <returns>The index at which the colors were added.</returns> public uint AddRectColors(Color color) { return AddRectColors(color.R, color.G, color.B, color.A); } /// <summary> /// Adds the colors for a rectangle. /// </summary> /// <param name="color">The color value.</param> /// <returns>The index at which the colors were added.</returns> public uint AddRectColors(Color topColor, Color bottomColor) { uint index = AddColor(topColor.R, topColor.G, topColor.B, topColor.A); AddColor(topColor.R, topColor.G, topColor.B, topColor.A); AddColor(bottomColor.R, bottomColor.G, bottomColor.B, bottomColor.A); AddColor(bottomColor.R, bottomColor.G, bottomColor.B, bottomColor.A); return index; } /// <summary> /// Adds an index. /// </summary> /// <param name="el">The element index to be added.</param> /// <returns>The index at which the index was added.</returns> public uint AddIndex(uint el) { if (indices == null) { indices = new uint[allocInc]; } else if (numIndices == indices.Length) { Array.Resize(ref indices, indices.Length + allocInc); } indices[numIndices++] = el; changed = true; return numIndices - 1; } /// <summary> /// Adds the indices for a rectangle. /// </summary> /// <param name="el">The element index at which the rectangle begins.</param> /// <returns>The index at which the indices were added.</returns> public uint AddRectIndices(uint el) { uint index = AddIndex(el + 2); AddIndex(el + 3); AddIndex(el + 1); AddIndex(el + 3); AddIndex(el + 1); AddIndex(el); return index; } /// <summary> /// Adds a rectangle with texture coordinates to the arrays. /// </summary> /// <param name="vx1">Vertex x1.</param> /// <param name="vy1">Vertex y1.</param> /// <param name="vx2">Vertex x2.</param> /// <param name="vy2">Vertex y2.</param> /// <param name="tx1">Texture coordinate x1.</param> /// <param name="ty1">Texture coordinate y1.</param> /// <param name="tx2">Texture coordinate x2.</param> /// <param name="ty2">Texture coordinate y2.</param> public void AddRect(float vx1, float vy1, float vx2, float vy2, float tx1, float ty1, float tx2, float ty2) { uint i = AddRectVertices(vx1, vy1, vx2, vy2); AddRectTexCoords(tx1, ty1, tx2, ty2); AddRectIndices(i); } /// <summary> /// Adds a rectangle with texture coordinates and a color to the arrays. /// </summary> /// <param name="vx1">Vertex x1.</param> /// <param name="vy1">Vertex y1.</param> /// <param name="vx2">Vertex x2.</param> /// <param name="vy2">Vertex y2.</param> /// <param name="tx1">Texture coordinate x1.</param> /// <param name="ty1">Texture coordinate y1.</param> /// <param name="tx2">Texture coordinate x2.</param> /// <param name="ty2">Texture coordinate y2.</param> /// <param name="color">Color to draw within the rectangle.</param> public void AddRect(float vx1, float vy1, float vx2, float vy2, float tx1, float ty1, float tx2, float ty2, Color color) { AddRect(vx1, vy1, vx2, vy2, tx1, ty1, tx2, ty2); AddRectColors(color); } /// <summary> /// Adds a rectangle with a color to the arrays. /// </summary> /// <param name="vx1">Vertex x1.</param> /// <param name="vy1">Vertex y1.</param> /// <param name="vx2">Vertex x2.</param> /// <param name="vy2">Vertex y2.</param> /// <param name="color">Color to draw within the rectangle.</param> public void AddRect(float vx1, float vy1, float vx2, float vy2, Color color) { uint i = AddRectVertices(vx1, vy1, vx2, vy2); AddRectColors(color); AddRectIndices(i); } /// <summary> /// Adds a rectangle with a horizontal gradient color to the arrays. /// </summary> /// <param name="vx1">Vertex x1.</param> /// <param name="vy1">Vertex y1.</param> /// <param name="vx2">Vertex x2.</param> /// <param name="vy2">Vertex y2.</param> /// <param name="color">Color to draw at the top of the rectangle.</param> /// <param name="color">Color to draw at the bottom of the rectangle.</param> public void AddRect(float vx1, float vy1, float vx2, float vy2, Color topColor, Color bottomColor) { uint i = AddRectVertices(vx1, vy1, vx2, vy2); AddRectColors(topColor, bottomColor); AddRectIndices(i); } /// <summary> /// Offsets the vertices by a specific amount. /// </summary> /// <param name="offset">Offset to be applied to all vertices.</param> public void OffsetVertices(PointF offset) { if (UsingVBO) { for (int i = 0; i < numVertices; i++) { buffer[i].x += offset.X; buffer[i].y += offset.Y; } } else { for (int i = 0; i < numVertices; i++) { vertices[i * 2] += offset.X; vertices[i * 2 + 1] += offset.Y; } } changed = true; } /// <summary> /// Gets the current number of vertices. /// </summary> public uint NumVertices { get { return numVertices; } } /// <summary> /// Gets the current number of texture coordinates. /// </summary> public uint NumTexCoords { get { return numTexCoords; } } /// <summary> /// Gets the current number of colors. /// </summary> public uint NumColors { get { return numColors; } } /// <summary> /// Gets the current number of indices. /// </summary> public uint NumIndices { get { return numIndices; } } /// <summary> /// Gets or sets the draw mode. /// </summary> public BeginMode DrawMode { get { return drawMode; } set { drawMode = value; } } /// <summary> /// Gets or sets the allocation increment. /// </summary> public int AllocationIncrement { get { return allocInc; } set { allocInc = value; } } /// <summary> /// Draws the arrays. /// </summary> public void Draw() { SetVboData(); if (numVertices != 0 || numTexCoords != 0 || numColors != 0 || numIndices != 0) { // enable the appropriate arrays if (numVertices != 0) { GL.EnableClientState(ArrayCap.VertexArray); } if (numTexCoords != 0) { GL.EnableClientState(ArrayCap.TextureCoordArray); } if (numColors != 0) { GL.EnableClientState(ArrayCap.ColorArray); } // draw from our buffer if we're using VBO's if (UsingVBO) { // bind the array buffer GL.BindBuffer(BufferTarget.ArrayBuffer, arrayId); // set the arrays int stride = Marshal.SizeOf(buffer[0]); if (numVertices != 0) { GL.VertexPointer(2, VertexPointerType.Float, stride, IntPtr.Zero); } int offset = Marshal.SizeOf(buffer[0].x) + Marshal.SizeOf(buffer[0].y); if (numTexCoords != 0) { GL.TexCoordPointer(2, TexCoordPointerType.Float, stride, (IntPtr)offset); } offset += Marshal.SizeOf(buffer[0].s) + Marshal.SizeOf(buffer[0].t); if (numColors != 0) { GL.ColorPointer(4, ColorPointerType.UnsignedByte, stride, (IntPtr)offset); } // draw the arrays if (numIndices != 0) { GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexId); GL.DrawElements(drawMode, (int)numIndices, UnsignedIntElement, IntPtr.Zero); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); } else { GL.DrawArrays(drawMode, 0, (int)numVertices); } // clear the array buffer binding GL.BindBuffer(BufferTarget.ArrayBuffer, 0); } // draw from our arrays if we're not using VBO's else { // set the arrays, initialize the state if (numVertices != 0) { GL.VertexPointer<float>(2, VertexPointerType.Float, 0, vertices); } if (numTexCoords != 0) { GL.TexCoordPointer<float>(2, TexCoordPointerType.Float, 0, texCoords); } if (numColors != 0) { GL.ColorPointer<byte>(4, ColorPointerType.UnsignedByte, 0, colors); } // draw the arrays if (numIndices != 0) { GL.DrawElements<uint>(drawMode, (int)numIndices, UnsignedIntElement, indices); } else { GL.DrawArrays(drawMode, 0, (int)numVertices); } //Dump("Draw"); // clear the arrays if (numVertices != 0) { GL.VertexPointer(2, VertexPointerType.Float, 0, IntPtr.Zero); } if (numTexCoords != 0) { GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero); } if (numColors != 0) { GL.ColorPointer(4, ColorPointerType.UnsignedByte, 0, IntPtr.Zero); } } // disable the arrays GL.DisableClientState(ArrayCap.TextureCoordArray); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.ColorArray); } } /// <summary> /// Writes the arrays to the consoled /// </summary> public void Dump(string text) { Console.WriteLine("FN2DArrays " + text); if (usingVBO) { if (numVertices != 0) { Console.Write(" Vertices(" + numVertices + "):"); for (int i = 0; i < numVertices; i++) Console.Write(" " + buffer[i].x + "," + buffer[i].y); Console.WriteLine(); } if (numTexCoords != 0) { Console.Write(" TexCoords(" + numTexCoords + "):"); for (int i = 0; i < numTexCoords; i++) Console.Write(" " + buffer[i].s + "," + buffer[i].t); Console.WriteLine(); } if (numColors != 0) { Console.Write(" Colors(" + numColors + "):"); for (int i = 0; i < numColors; i++) Console.Write(" " + buffer[i].r + "," + buffer[i].g + "," + buffer[i].b + "," + buffer[i].a); Console.WriteLine(); } } else { if (numVertices != 0) { Console.Write(" Vertices(" + numVertices + "):"); for (int i = 0; i < numVertices * 2; i += 2) Console.Write(" " + vertices[i] + "," + vertices[i + 1]); Console.WriteLine(); } if (numTexCoords != 0) { Console.Write(" TexCoords(" + numTexCoords + "):"); for (int i = 0; i < numTexCoords * 2; i += 2) Console.Write(" " + texCoords[i] + "," + texCoords[i + 1]); Console.WriteLine(); } if (numColors != 0) { Console.Write(" Colors(" + numColors + "):"); for (int i = 0; i < numColors * 4; i += 4) Console.Write(" " + colors[i] + "," + colors[i + 1] + "," + colors[i + 2] + "," + colors[i + 3]); Console.WriteLine(); } } if (numIndices != 0) { Console.Write(" Indices(" + numIndices + "):"); for (int i = 0; i < numIndices; i++) Console.Write(" " + indices[i]); Console.WriteLine(); } } /// <summary> /// Determines if we can use vertex buffer objects (VBO's). /// </summary> private static bool UsingVBO { get { if (!gotUsingVBO) { usingVBO = GL.GetString(StringName.Extensions).Contains("GL_ARB_vertex_buffer_object"); //usingVBO = false; usingOESVBO = GL.GetString(StringName.Extensions).Contains("GL_OES_vertex_array_object"); Console.WriteLine("OpenGL: usingVBO = " + usingVBO + " usingOESVBO = " + usingOESVBO); gotUsingVBO = true; } return usingVBO; } } } /// <summary> /// OpenGL 2D list of arrays. /// </summary> public class FN2DArraysList : List<FN2DArrays> { }; /// <summary> /// OpenGL 2D vertex used for VBO access. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct FN2DVertex { public float x, y; public float s, t; public byte r, g, b, a; } }
using System; using System.Runtime.InteropServices; using CorDebugInterop; using Debug = System.Diagnostics.Debug; using nanoFramework.Tools.Debugger.WireProtocol; using BreakpointDef = nanoFramework.Tools.Debugger.WireProtocol.Commands.Debugging_Execution_BreakpointDef; namespace nanoFramework.Tools.VisualStudio.Debugger { //Superclass for all nanoCLR breakpoints public abstract class CorDebugBreakpointBase { static ushort s_idNull = 0; static ushort s_idNext = 1; private CorDebugProcess m_process; private CorDebugAppDomain m_appDomain; private bool m_fActive; protected readonly BreakpointDef m_breakpointDef; protected CorDebugBreakpointBase( CorDebugProcess process ) { m_breakpointDef = new BreakpointDef(); m_breakpointDef.m_id = s_idNext++; m_breakpointDef.m_pid = BreakpointDef.c_PID_ANY; m_appDomain = null; m_process = process; Debug.Assert(s_idNext != s_idNull); } protected CorDebugBreakpointBase(CorDebugAppDomain appDomain) : this(appDomain.Process) { m_appDomain = appDomain; } public CorDebugAppDomain AppDomain { [System.Diagnostics.DebuggerHidden] get { return m_appDomain; } } public virtual bool IsMatch( BreakpointDef breakpointDef ) { return breakpointDef.m_id == this.m_breakpointDef.m_id; } public ushort Kind { [System.Diagnostics.DebuggerHidden] get { return m_breakpointDef.m_flags; } set { m_breakpointDef.m_flags = value; Dirty(); } } protected CorDebugProcess Process { [System.Diagnostics.DebuggerHidden] get { return m_process; } } public bool Active { [System.Diagnostics.DebuggerHidden] get { return m_fActive; } set { if (m_fActive != value) { m_fActive = value; m_process.RegisterBreakpoint(this, m_fActive); Dirty(); } } } public void Dirty() { m_process.DirtyBreakpoints(); } public virtual void Hit(BreakpointDef breakpointDef) { } public virtual bool ShouldBreak(BreakpointDef breakpointDef) { return true; } public virtual bool Equals(CorDebugBreakpointBase breakpoint) { return this.Equals( (object)breakpoint ); } public BreakpointDef Debugging_Execution_BreakpointDef { [System.Diagnostics.DebuggerHidden] get { return m_breakpointDef; } } } public class CLREventsBreakpoint : CorDebugBreakpointBase { public CLREventsBreakpoint(CorDebugProcess process) : base (process) { this.Kind = BreakpointDef.c_EXCEPTION_THROWN | BreakpointDef.c_EXCEPTION_CAUGHT | #if NO_THREAD_CREATED_EVENTS BreakpointDef.c_EVAL_COMPLETE | #else BreakpointDef.c_THREAD_CREATED | BreakpointDef.c_THREAD_TERMINATED | #endif BreakpointDef.c_ASSEMBLIES_LOADED | BreakpointDef.c_BREAK; this.Active = true; } public override void Hit(BreakpointDef breakpointDef) { #if NO_THREAD_CREATED_EVENTS if ((breakpointDef.m_flags & BreakpointDef.c_EVAL_COMPLETE) != 0) EvalComplete(breakpointDef); #else if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_CREATED) != 0) ThreadCreated(breakpointDef); else if ((breakpointDef.m_flags & BreakpointDef.c_THREAD_TERMINATED) != 0) ThreadTerminated(breakpointDef); #endif else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_THROWN) != 0) ExceptionThrown(breakpointDef); else if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0) ExceptionCaught(breakpointDef); else if ((breakpointDef.m_flags & BreakpointDef.c_ASSEMBLIES_LOADED) != 0) AssembliesLoaded(breakpointDef); else if ((breakpointDef.m_flags & BreakpointDef.c_BREAK) != 0) Break(breakpointDef); else Debug.Assert(false, "unknown CLREvent breakpoint"); } #if NO_THREAD_CREATED_EVENTS private void EvalComplete(BreakpointDef breakpointDef) { CorDebugThread thread = Process.GetThread(breakpointDef.m_pid); //This currently gets called after BreakpointHit updates the list of threads. //This should nop as long as func-eval happens on separate threads. Debug.Assert(thread == null); Process.RemoveThread(thread); } #else private void ThreadTerminated(BreakpointDef breakpointDef) { CorDebugThread thread = Process.GetThread(breakpointDef.m_pid); // Thread could be NULL if this function is called as result of Thread.Abort in // managed application and application does not catch expeption. // ThreadTerminated is called after thread exits in managed application. if ( thread != null ) { Process.RemoveThread( thread ); } } private void ThreadCreated(BreakpointDef breakpointDef) { CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid); Debug.Assert(thread == null || thread.IsVirtualThread); if (thread == null) { thread = new CorDebugThread(this.Process, breakpointDef.m_pid, null); this.Process.AddThread(thread); } } #endif public override bool ShouldBreak(Commands.Debugging_Execution_BreakpointDef breakpointDef) { if ((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0) { //This if statement remains for compatibility with nanoCLR pre exception filtering support. if((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) == 0) return false; } return true; } private void ExceptionThrown(BreakpointDef breakpointDef) { CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid); thread.StoppedOnException(); CorDebugFrame frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depth); bool fIsEval = thread.IsVirtualThread; bool fUnhandled = (breakpointDef.m_depthExceptionHandler == BreakpointDef.c_DEPTH_UNCAUGHT); if (this.Process.Engine.Capabilities.ExceptionFilters) { switch (breakpointDef.m_depthExceptionHandler) { case BreakpointDef.c_DEPTH_EXCEPTION_FIRST_CHANCE: Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE)); break; case BreakpointDef.c_DEPTH_EXCEPTION_USERS_CHANCE: Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE)); break; case BreakpointDef.c_DEPTH_EXCEPTION_HANDLER_FOUND: Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND)); break; } } else { Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE)); uint depthMin = (fUnhandled) ? 0 : breakpointDef.m_depthExceptionHandler; for (uint depth = breakpointDef.m_depth; depth >= depthMin; depth--) { frame = thread.Chain.GetFrameFromDepthnanoCLR(depth); if (frame != null && frame.Function.HasSymbols && frame.Function.PdbxMethod.IsJMC) { Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, frame.IP_nanoCLR, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE)); break; } if (depth == 0) { break; } } if(!fUnhandled) { frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depthExceptionHandler); Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, breakpointDef.m_IP, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND)); } } if (fUnhandled) { //eval threads are virtual, and although the physical thread has an unhandled exception, the //virtual thread does not. The eval thread will get killed, but the rest of the thread chain will //survive, no need to confuse cpde by throwing an unhandled exception if (fIsEval) { CorDebugEval eval = thread.CurrentEval; eval.StoppedOnUnhandledException(); Debug.Assert(thread.IsVirtualThread); CorDebugThread threadT = thread.GetRealCorDebugThread(); CorDebugFrame frameT = threadT.Chain.ActiveFrame; //fake event to let debugging of unhandled exception occur. //Frame probably needs to be an InternalStubFrame??? frame = thread.Chain.GetFrameFromDepthCLR(thread.Chain.NumFrames - 1); #if DEBUG CorDebugInternalFrame internalFrame = frame as CorDebugInternalFrame; Debug.Assert(internalFrame != null && internalFrame.FrameType == CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL); #endif Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, frame, 0, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_CATCH_HANDLER_FOUND)); } else { Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackException(thread, null, uint.MaxValue, CorDebugExceptionCallbackType.DEBUG_EXCEPTION_UNHANDLED)); } } } private void ExceptionCaught(BreakpointDef breakpointDef) { CorDebugThread thread = this.Process.GetThread(breakpointDef.m_pid); CorDebugFrame frame = thread.Chain.GetFrameFromDepthnanoCLR(breakpointDef.m_depth); Debug.Assert((breakpointDef.m_flags & BreakpointDef.c_EXCEPTION_UNWIND) != 0); Process.EnqueueEvent(new ManagedCallbacks.ManagedCallbackExceptionUnwind(thread, frame, CorDebugExceptionUnwindCallbackType.DEBUG_EXCEPTION_INTERCEPTED)); } private void AssembliesLoaded(BreakpointDef breakpointDef) { this.Process.UpdateAssemblies(); } private void Break(BreakpointDef breakpointDef) { CorDebugThread thread = Process.GetThread(breakpointDef.m_pid); Process.EnqueueEvent( new ManagedCallbacks.ManagedCallbackBreak( thread ) ); } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test { [TestFixture] public class IntervalTest { private static readonly Instant SampleStart = Instant.FromTicksSinceUnixEpoch(-300); private static readonly Instant SampleEnd = Instant.FromTicksSinceUnixEpoch(400); [Test] public void Construction_Success() { var interval = new Interval(SampleStart, SampleEnd); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleEnd, interval.End); } [Test] public void Construction_EqualStartAndEnd() { var interval = new Interval(SampleStart, SampleStart); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleStart, interval.End); Assert.AreEqual(NodaTime.Duration.Zero, interval.Duration); } [Test] public void Construction_EndBeforeStart() { Assert.Throws<ArgumentOutOfRangeException>(() => new Interval(SampleEnd, SampleStart)); } [Test] public void Equals() { TestHelper.TestEqualsStruct( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(null, SampleEnd), new Interval(null, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(null, null), new Interval(null, null), new Interval(NodaConstants.UnixEpoch, SampleEnd)); } [Test] public void Operators() { TestHelper.TestOperatorEquality( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); } [Test] public void Duration() { var interval = new Interval(SampleStart, SampleEnd); Assert.AreEqual(NodaTime.Duration.FromTicks(700), interval.Duration); } /// <summary> /// Using the default constructor is equivalent to a zero duration. /// </summary> [Test] public void DefaultConstructor() { var actual = new Interval(); Assert.AreEqual(NodaTime.Duration.Zero, actual.Duration); } [Test] public void BinarySerialization() { TestHelper.AssertBinaryRoundtrip(new Interval(SampleStart, SampleEnd)); TestHelper.AssertBinaryRoundtrip(new Interval(null, SampleEnd)); TestHelper.AssertBinaryRoundtrip(new Interval(SampleStart, null)); TestHelper.AssertBinaryRoundtrip(new Interval(null, null)); } [Test] public void ToStringUsesExtendedIsoFormat() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2, 120).InUtc().ToInstant(); var value = new Interval(start, end); Assert.AreEqual("2013-04-12T17:53:23.1234567Z/2013-10-12T17:01:02.12Z", value.ToString()); } [Test] public void ToString_Infinite() { var value = new Interval(null, null); Assert.AreEqual("StartOfTime/EndOfTime", value.ToString()); } [Test] public void XmlSerialization() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-04-12T17:53:23.1234567Z\" end=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_Extremes() { var value = new Interval(Instant.MinValue, Instant.MaxValue); TestHelper.AssertXmlRoundtrip(value, "<value start=\"-9998-01-01T00:00:00Z\" end=\"9999-12-31T23:59:59.999999999Z\" />"); } [Test] public void XmlSerialization_ExtraContent() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertParsableXml(value, "<value start=\"2013-04-12T17:53:23.1234567Z\" end=\"2013-10-12T17:01:02Z\">Text<child attr=\"value\"/>Text 2</value>"); } [Test] public void XmlSerialization_SwapAttributeOrder() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertParsableXml(value, "<value end=\"2013-10-12T17:01:02Z\" start=\"2013-04-12T17:53:23.1234567Z\" />"); } [Test] public void XmlSerialization_FromBeginningOfTime() { var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(null, end); TestHelper.AssertXmlRoundtrip(value, "<value end=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_ToEndOfTime() { var start = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, null); TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_AllOfTime() { var value = new Interval(null, null); TestHelper.AssertXmlRoundtrip(value, "<value />"); } [Test] [TestCase("<value start=\"2013-15-12T17:53:23Z\" end=\"2013-11-12T17:53:23Z\"/>", typeof(UnparsableValueException), Description = "Invalid month in start")] [TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-15-12T17:53:23Z\"/>", typeof(UnparsableValueException), Description = "Invalid month in end")] [TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-11-12T16:53:23Z\"/>", typeof(ArgumentOutOfRangeException), Description = "End before start")] public void XmlSerialization_Invalid(string xml, Type expectedExceptionType) { TestHelper.AssertXmlInvalid<Interval>(xml, expectedExceptionType); } [Test] [TestCase("1990-01-01T00:00:00Z", false, Description = "Before interval")] [TestCase("2000-01-01T00:00:00Z", true, Description = "Start of interval")] [TestCase("2010-01-01T00:00:00Z", true, Description = "Within interval")] [TestCase("2020-01-01T00:00:00Z", false, Description = "End instant of interval")] [TestCase("2030-01-01T00:00:00Z", false, Description = "After interval")] public void Contains(string candidateText, bool expectedResult) { var start = Instant.FromUtc(2000, 1, 1, 0, 0); var end = Instant.FromUtc(2020, 1, 1, 0, 0); var interval = new Interval(start, end); var candidate = InstantPattern.ExtendedIsoPattern.Parse(candidateText).Value; Assert.AreEqual(expectedResult, interval.Contains(candidate)); } [Test] public void Contains_Infinite() { var interval = new Interval(null, null); Assert.IsTrue(interval.Contains(Instant.MaxValue)); Assert.IsTrue(interval.Contains(Instant.MinValue)); } [Test] public void HasStart() { Assert.IsTrue(new Interval(Instant.MinValue, null).HasStart); Assert.IsFalse(new Interval(null, Instant.MinValue).HasStart); } [Test] public void HasEnd() { Assert.IsTrue(new Interval(null, Instant.MaxValue).HasEnd); Assert.IsFalse(new Interval(Instant.MaxValue, null).HasEnd); } [Test] public void Start() { Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(NodaConstants.UnixEpoch, null).Start); Interval noStart = new Interval(null, NodaConstants.UnixEpoch); Assert.Throws<InvalidOperationException>(() => noStart.Start.ToString()); } [Test] public void End() { Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(null, NodaConstants.UnixEpoch).End); Interval noEnd = new Interval(NodaConstants.UnixEpoch, null); Assert.Throws<InvalidOperationException>(() => noEnd.End.ToString()); } [Test] public void Contains_EmptyInterval() { var instant = NodaConstants.UnixEpoch; var interval = new Interval(instant, instant); Assert.IsFalse(interval.Contains(instant)); } [Test] public void Contains_EmptyInterval_MaxValue() { var instant = Instant.MaxValue; var interval = new Interval(instant, instant); // This would have been true under Noda Time 1.x Assert.IsFalse(interval.Contains(instant)); } } }
// Bezier.cs // // Implementations for splines and paths with various degrees of smoothness. A 'path', or 'spline', is arbitrarily long // and may be composed of smaller path sections called 'curves'. For example, a Bezier path is made from multiple // Bezier curves. // // Regarding naming, the word 'spline' refers to any path that is composed of piecewise parts. Strictly speaking one // could call a composite of multiple Bezier curves a 'Bezier Spline' but it is not a common term. In this file the // word 'path' is used for a composite of Bezier curves. // // Copyright (c) 2006, 2017 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; // A CubicBezierCurve represents a single segment of a Bezier path. It knows how to interpret 4 CVs using the Bezier basis // functions. This class implements cubic Bezier curves -- not linear or quadratic. class CubicBezierCurve { Vector3[] controlVerts = new Vector3[4]; public CubicBezierCurve(Vector3[] cvs) { // Cubic Bezier curves require 4 cvs. Assert.IsTrue(cvs.Length == 4); for (int cv = 0; cv < 4; cv++) controlVerts[cv] = cvs[cv]; } public Vector3 GetPoint(float t) // t E [0, 1]. { Assert.IsTrue((t >= 0.0f) && (t <= 1.0f)); float c = 1.0f - t; // The Bernstein polynomials. float bb0 = c*c*c; float bb1 = 3*t*c*c; float bb2 = 3*t*t*c; float bb3 = t*t*t; Vector3 point = controlVerts[0]*bb0 + controlVerts[1]*bb1 + controlVerts[2]*bb2 + controlVerts[3]*bb3; return point; } public Vector3 GetTangent(float t) // t E [0, 1]. { // See: http://bimixual.org/AnimationLibrary/beziertangents.html Assert.IsTrue((t >= 0.0f) && (t <= 1.0f)); Vector3 q0 = controlVerts[0] + ((controlVerts[1] - controlVerts[0]) * t); Vector3 q1 = controlVerts[1] + ((controlVerts[2] - controlVerts[1]) * t); Vector3 q2 = controlVerts[2] + ((controlVerts[3] - controlVerts[2]) * t); Vector3 r0 = q0 + ((q1 - q0) * t); Vector3 r1 = q1 + ((q2 - q1) * t); Vector3 tangent = r1 - r0; return tangent; } public float GetClosestParam(Vector3 pos, float paramThreshold = 0.000001f) { return GetClosestParamRec(pos, 0.0f, 1.0f, paramThreshold); } float GetClosestParamRec(Vector3 pos, float beginT, float endT, float thresholdT) { float mid = (beginT + endT)/2.0f; // Base case for recursion. if ((endT - beginT) < thresholdT) return mid; // The two halves have param range [start, mid] and [mid, end]. We decide which one to use by using a midpoint param calculation for each section. float paramA = (beginT+mid) / 2.0f; float paramB = (mid+endT) / 2.0f; Vector3 posA = GetPoint(paramA); Vector3 posB = GetPoint(paramB); float distASq = (posA - pos).sqrMagnitude; float distBSq = (posB - pos).sqrMagnitude; if (distASq < distBSq) endT = mid; else beginT = mid; // The (tail) recursive call. return GetClosestParamRec(pos, beginT, endT, thresholdT); } } // A CubicBezierPath is made of a collection of cubic Bezier curves. If two points are supplied they become the end // points of one CubicBezierCurve and the 2 interior CVs are generated, creating a small straight line. For 3 points // the middle point will be on both CubicBezierCurves and each curve will have equal tangents at that point. public class CubicBezierPath { public enum Type { Open, Closed } Type type = Type.Open; int numCurveSegments = 0; int numControlVerts = 0; Vector3[] controlVerts = null; // The term 'knot' is another name for a point right on the path (an interpolated point). With this constructor the // knots are supplied and interpolated. knots.length (the number of knots) must be >= 2. Interior Cvs are generated // transparently and automatically. public CubicBezierPath(Vector3[] knots, Type t = Type.Open) { InterpolatePoints(knots, t); } public Type GetPathType() { return type; } public bool IsClosed() { return (type == Type.Closed) ? true : false; } public bool IsValid() { return (numCurveSegments > 0) ? true : false; } public void Clear() { controlVerts = null; type = Type.Open; numCurveSegments = 0; numControlVerts = 0; } // A closed path will have one more segment than an open for the same number of interpolated points. public int GetNumCurveSegments() { return numCurveSegments; } public float GetMaxParam() { return (float)numCurveSegments; } // Access to the raw CVs. public int GetNumControlVerts() { return numControlVerts; } public Vector3[] GetControlVerts() { return controlVerts; } public float ComputeApproxLength() { if (!IsValid()) return 0.0f; // For a closed path this still works if you consider the last point as separate from the first. That is, a closed // path is just like an open except the last interpolated point happens to match the first. int numInterpolatedPoints = numCurveSegments + 1; if (numInterpolatedPoints < 2) return 0.0f; float totalDist = 0.0f; for (int n = 1; n < numInterpolatedPoints; n++) { Vector3 a = controlVerts[(n-1)*3]; Vector3 b = controlVerts[n*3]; totalDist += (a - b).magnitude; } if (totalDist == 0.0f) return 0.0f; return totalDist; } public float ComputeApproxParamPerUnitLength() { float length = ComputeApproxLength(); return (float)numCurveSegments / length; } public float ComputeApproxNormParamPerUnitLength() { float length = ComputeApproxLength(); return 1.0f / length; } // Interpolates the supplied points. Internally generates any necessary CVs. knots.length (number of knots) // must be >= 2. public void InterpolatePoints(Vector3[] knots, Type t) { int numKnots = knots.Length; Assert.IsTrue(numKnots >= 2); Clear(); type = t; switch (type) { case Type.Open: { numCurveSegments = numKnots - 1; numControlVerts = 3*numKnots - 2; controlVerts = new Vector3[numControlVerts]; // Place the interpolated CVs. for (int n = 0; n < numKnots; n++) controlVerts[n*3] = knots[n]; // Place the first and last non-interpolated CVs. Vector3 initialPoint = (knots[1] - knots[0]) * 0.25f; // Interpolate 1/4 away along first segment. controlVerts[1] = knots[0] + initialPoint; Vector3 finalPoint = (knots[numKnots-2] - knots[numKnots-1]) * 0.25f; // Interpolate 1/4 backward along last segment. controlVerts[numControlVerts-2] = knots[numKnots-1] + finalPoint; // Now we'll do all the interior non-interpolated CVs. for (int k = 1; k < numCurveSegments; k++) { Vector3 a = knots[k-1] - knots[k]; Vector3 b = knots[k+1] - knots[k]; float aLen = a.magnitude; float bLen = b.magnitude; if ((aLen > 0.0f) && (bLen > 0.0f)) { float abLen = (aLen + bLen) / 8.0f; Vector3 ab = (b/bLen) - (a/aLen); ab.Normalize(); ab *= abLen; controlVerts[k*3 - 1] = knots[k] - ab; controlVerts[k*3 + 1] = knots[k] + ab; } else { controlVerts[k*3 - 1] = knots[k]; controlVerts[k*3 + 1] = knots[k]; } } break; } case Type.Closed: { numCurveSegments = numKnots; // We duplicate the first point at the end so we have contiguous memory to look of the curve value. That's // what the +1 is for. numControlVerts = 3*numKnots + 1; controlVerts = new Vector3[numControlVerts]; // First lets place the interpolated CVs and duplicate the first into the last CV slot. for (int n = 0; n < numKnots; n++) controlVerts[n*3] = knots[n]; controlVerts[numControlVerts-1] = knots[0]; // Now we'll do all the interior non-interpolated CVs. We go to k=NumCurveSegments which will compute the // two CVs around the zeroth knot (points[0]). for (int k = 1; k <= numCurveSegments; k++) { int modkm1 = k-1; int modkp1 = (k+1) % numCurveSegments; int modk = k % numCurveSegments; Vector3 a = knots[modkm1] - knots[modk]; Vector3 b = knots[modkp1] - knots[modk]; float aLen = a.magnitude; float bLen = b.magnitude; int mod3km1 = 3*k - 1; // Need the -1 so the end point is a duplicated start point. int mod3kp1 = (3*k + 1) % (numControlVerts-1); if ((aLen > 0.0f) && (bLen > 0.0f)) { float abLen = (aLen + bLen) / 8.0f; Vector3 ab = (b/bLen) - (a/aLen); ab.Normalize(); ab *= abLen; controlVerts[mod3km1] = knots[modk] - ab; controlVerts[mod3kp1] = knots[modk] + ab; } else { controlVerts[mod3km1] = knots[modk]; controlVerts[mod3kp1] = knots[modk]; } } break; } } } // For a closed path the last CV must match the first. public void SetControlVerts(Vector3[] cvs, Type t) { int numCVs = cvs.Length; Assert.IsTrue(numCVs > 0); Assert.IsTrue( ((t == Type.Open) && (numCVs >= 4)) || ((t == Type.Closed) && (numCVs >= 7)) ); Assert.IsTrue(((numCVs-1) % 3) == 0); Clear(); type = t; numControlVerts = numCVs; numCurveSegments = ((numCVs - 1) / 3); controlVerts = cvs; } // t E [0, numSegments]. If the type is closed, the number of segments is one more than the equivalent open path. public Vector3 GetPoint(float t) { // Only closed paths accept t values out of range. if (type == Type.Closed) { while (t < 0.0f) t += (float)numCurveSegments; while (t > (float)numCurveSegments) t -= (float)numCurveSegments; } else { t = Mathf.Clamp(t, 0.0f, (float)numCurveSegments); } Assert.IsTrue((t >= 0) && (t <= (float)numCurveSegments)); // Segment 0 is for t E [0, 1). The last segment is for t E [NumCurveSegments-1, NumCurveSegments]. // The following 'if' statement deals with the final inclusive bracket on the last segment. The cast must truncate. int segment = (int)t; if (segment >= numCurveSegments) segment = numCurveSegments - 1; Vector3[] curveCVs = new Vector3[4]; curveCVs[0] = controlVerts[3*segment + 0]; curveCVs[1] = controlVerts[3*segment + 1]; curveCVs[2] = controlVerts[3*segment + 2]; curveCVs[3] = controlVerts[3*segment + 3]; CubicBezierCurve bc = new CubicBezierCurve(curveCVs); return bc.GetPoint(t - (float)segment); } // Does the same as GetPoint except that t is normalized to be E [0, 1] over all segments. The beginning of the curve // is at t = 0 and the end at t = 1. Closed paths allow a value bigger than 1 in which case they loop. public Vector3 GetPointNorm(float t) { return GetPoint(t * (float)numCurveSegments); } // Similar to GetPoint but returns the tangent at the specified point on the path. The tangent is not normalized. // The longer the tangent the 'more influence' it has pulling the path in that direction. public Vector3 GetTangent(float t) { // Only closed paths accept t values out of range. if (type == Type.Closed) { while (t < 0.0f) t += (float)numCurveSegments; while (t > (float)numCurveSegments) t -= (float)numCurveSegments; } else { t = Mathf.Clamp(t, 0.0f, (float)numCurveSegments); } Assert.IsTrue((t >= 0) && (t <= (float)numCurveSegments)); // Segment 0 is for t E [0, 1). The last segment is for t E [NumCurveSegments-1, NumCurveSegments]. // The following 'if' statement deals with the final inclusive bracket on the last segment. The cast must truncate. int segment = (int)t; if (segment >= numCurveSegments) segment = numCurveSegments - 1; Vector3[] curveCVs = new Vector3[4]; curveCVs[0] = controlVerts[3*segment + 0]; curveCVs[1] = controlVerts[3*segment + 1]; curveCVs[2] = controlVerts[3*segment + 2]; curveCVs[3] = controlVerts[3*segment + 3]; CubicBezierCurve bc = new CubicBezierCurve(curveCVs); return bc.GetTangent(t - (float)segment); } public Vector3 GetTangentNorm(float t) { return GetTangent(t * (float)numCurveSegments); } // This function returns a single closest point. There may be more than one point on the path at the same distance. // Use ComputeApproxParamPerUnitLength to determine a good paramThreshold. eg. Say you want a 15cm threshold, // use: paramThreshold = ComputeApproxParamPerUnitLength() * 0.15f. public float ComputeClosestParam(Vector3 pos, float paramThreshold) { float minDistSq = float.MaxValue; float closestParam = 0.0f; for (int startIndex = 0; startIndex < controlVerts.Length - 1; startIndex += 3) { Vector3[] curveCVs = new Vector3[4]; for (int i = 0; i < 4; i++) curveCVs[i] = controlVerts[startIndex+i]; CubicBezierCurve curve = new CubicBezierCurve(curveCVs); float curveClosestParam = curve.GetClosestParam(pos, paramThreshold); Vector3 curvePos = curve.GetPoint(curveClosestParam); float distSq = (curvePos - pos).sqrMagnitude; if (distSq < minDistSq) { minDistSq = distSq; float startParam = ((float)startIndex) / 3.0f; closestParam = startParam + curveClosestParam; } } return closestParam; } // Same as above but returns a t value E [0, 1]. You'll need to use a paramThreshold like // ComputeApproxParamPerUnitLength() * 0.15f if you want a 15cm tolerance. public float ComputeClosestNormParam(Vector3 pos, float paramThreshold) { return ComputeClosestParam(pos, paramThreshold * (float)numCurveSegments); } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.Fcmdata.v1beta1 { /// <summary>The Fcmdata Service.</summary> public class FcmdataService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public FcmdataService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public FcmdataService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "fcmdata"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://fcmdata.googleapis.com/"; #else "https://fcmdata.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://fcmdata.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Firebase Cloud Messaging Data API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Firebase Cloud Messaging Data API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for Fcmdata requests.</summary> public abstract class FcmdataBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new FcmdataBaseServiceRequest instance.</summary> protected FcmdataBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Fcmdata parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; AndroidApps = new AndroidAppsResource(service); } /// <summary>Gets the AndroidApps resource.</summary> public virtual AndroidAppsResource AndroidApps { get; } /// <summary>The "androidApps" collection of methods.</summary> public class AndroidAppsResource { private const string Resource = "androidApps"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public AndroidAppsResource(Google.Apis.Services.IClientService service) { this.service = service; DeliveryData = new DeliveryDataResource(service); } /// <summary>Gets the DeliveryData resource.</summary> public virtual DeliveryDataResource DeliveryData { get; } /// <summary>The "deliveryData" collection of methods.</summary> public class DeliveryDataResource { private const string Resource = "deliveryData"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public DeliveryDataResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>List aggregate delivery data for the given Android application.</summary> /// <param name="parent"> /// Required. The application for which to list delivery data. Format: /// `projects/{project_id}/androidApps/{app_id}` /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>List aggregate delivery data for the given Android application.</summary> public class ListRequest : FcmdataBaseServiceRequest<Google.Apis.Fcmdata.v1beta1.Data.GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The application for which to list delivery data. Format: /// `projects/{project_id}/androidApps/{app_id}` /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// The maximum number of entries to return. The service may return fewer than this value. If /// unspecified, at most 1,000 entries will be returned. The maximum value is 10,000; values above /// 10,000 will be capped to 10,000. This default may change over time. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A page token, received from a previous `ListAndroidDeliveryDataRequest` call. Provide this to /// retrieve the subsequent page. When paginating, all other parameters provided to /// `ListAndroidDeliveryDataRequest` must match the call that provided the page token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/deliveryData"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/androidApps/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } } } namespace Google.Apis.Fcmdata.v1beta1.Data { /// <summary>Message delivery data for a given date, app, and analytics label combination.</summary> public class GoogleFirebaseFcmDataV1beta1AndroidDeliveryData : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The analytics label associated with the messages sent. All messages sent without an analytics label will be /// grouped together in a single entry. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("analyticsLabel")] public virtual string AnalyticsLabel { get; set; } /// <summary>The app ID to which the messages were sent.</summary> [Newtonsoft.Json.JsonPropertyAttribute("appId")] public virtual string AppId { get; set; } /// <summary>The data for the specified appId, date, and analyticsLabel.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual GoogleFirebaseFcmDataV1beta1Data Data { get; set; } /// <summary>The date represented by this entry.</summary> [Newtonsoft.Json.JsonPropertyAttribute("date")] public virtual GoogleTypeDate Date { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Data detailing messaging delivery</summary> public class GoogleFirebaseFcmDataV1beta1Data : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Count of messages accepted by FCM intended to Android devices. The targeted device must have opted in to the /// collection of usage and diagnostic information. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("countMessagesAccepted")] public virtual System.Nullable<long> CountMessagesAccepted { get; set; } /// <summary> /// Additional information about delivery performance for messages that were successfully delivered. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("deliveryPerformancePercents")] public virtual GoogleFirebaseFcmDataV1beta1DeliveryPerformancePercents DeliveryPerformancePercents { get; set; } /// <summary>Additional general insights about message delivery.</summary> [Newtonsoft.Json.JsonPropertyAttribute("messageInsightPercents")] public virtual GoogleFirebaseFcmDataV1beta1MessageInsightPercents MessageInsightPercents { get; set; } /// <summary>Mutually exclusive breakdown of message delivery outcomes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("messageOutcomePercents")] public virtual GoogleFirebaseFcmDataV1beta1MessageOutcomePercents MessageOutcomePercents { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Overview of delivery performance for messages that were successfully delivered. All percentages are calculated /// with countMessagesAccepted as the denominator. These categories are not mutually exclusive; a message can be /// delayed for multiple reasons. /// </summary> public class GoogleFirebaseFcmDataV1beta1DeliveryPerformancePercents : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The percentage of accepted messages that were delayed because the device was in doze mode. Only [normal /// priority /// messages](https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message) /// should be delayed due to doze mode. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("delayedDeviceDoze")] public virtual System.Nullable<float> DelayedDeviceDoze { get; set; } /// <summary> /// The percentage of accepted messages that were delayed because the target device was not connected at the /// time of sending. These messages were eventually delivered when the device reconnected. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("delayedDeviceOffline")] public virtual System.Nullable<float> DelayedDeviceOffline { get; set; } /// <summary> /// The percentage of accepted messages that were delayed due to message throttling, such as [collapsible /// message throttling](https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_throttling) /// or [maximum message rate /// throttling](https://firebase.google.com/docs/cloud-messaging/concept-options#device_throttling). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("delayedMessageThrottled")] public virtual System.Nullable<float> DelayedMessageThrottled { get; set; } /// <summary> /// The percentage of accepted messages that were delayed because the intended device user-profile was /// [stopped](https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages) on the target /// device at the time of the send. The messages were eventually delivered when the user-profile was started /// again. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("delayedUserStopped")] public virtual System.Nullable<float> DelayedUserStopped { get; set; } /// <summary> /// The percentage of accepted messages that were delivered to the device without delay from the FCM system. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("deliveredNoDelay")] public virtual System.Nullable<float> DeliveredNoDelay { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ListAndroidDeliveryData.</summary> public class GoogleFirebaseFcmDataV1beta1ListAndroidDeliveryDataResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The delivery data for the provided app. There will be one entry per combination of app, date, and analytics /// label. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("androidDeliveryData")] public virtual System.Collections.Generic.IList<GoogleFirebaseFcmDataV1beta1AndroidDeliveryData> AndroidDeliveryData { get; set; } /// <summary> /// A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no /// subsequent pages. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Additional information about message delivery. All percentages are calculated with countMessagesAccepted as the /// denominator. /// </summary> public class GoogleFirebaseFcmDataV1beta1MessageInsightPercents : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The percentage of accepted messages that had their priority lowered from high to normal due to [app standby /// buckets](https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("priorityLowered")] public virtual System.Nullable<float> PriorityLowered { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Percentage breakdown of message delivery outcomes. These categories are mutually exclusive. All percentages are /// calculated with countMessagesAccepted as the denominator. These categories may not account for all message /// outcomes. /// </summary> public class GoogleFirebaseFcmDataV1beta1MessageOutcomePercents : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The percentage of all accepted messages that were successfully delivered to the device.</summary> [Newtonsoft.Json.JsonPropertyAttribute("delivered")] public virtual System.Nullable<float> Delivered { get; set; } /// <summary> /// The percentage of accepted messages that were dropped because the application was force stopped on the /// device at the time of delivery and retries were unsuccessful. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("droppedAppForceStopped")] public virtual System.Nullable<float> DroppedAppForceStopped { get; set; } /// <summary> /// The percentage of accepted messages that were dropped because the target device is inactive. FCM will drop /// messages if the target device is deemed inactive by our servers. If a device does reconnect, we call /// [OnDeletedMessages()](https://firebase.google.com/docs/cloud-messaging/android/receive#override-ondeletedmessages) /// in our SDK instead of delivering the messages. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("droppedDeviceInactive")] public virtual System.Nullable<float> DroppedDeviceInactive { get; set; } /// <summary> /// The percentage of accepted messages that were dropped due to [too many undelivered non-collapsible /// messages](https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages). /// Specifically, each app instance can only have 100 pending messages stored on our servers for a device which /// is disconnected. When that device reconnects, those messages are delivered. When there are more than the /// maximum pending messages, we call /// [OnDeletedMessages()](https://firebase.google.com/docs/cloud-messaging/android/receive#override-ondeletedmessages) /// in our SDK instead of delivering the messages. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("droppedTooManyPendingMessages")] public virtual System.Nullable<float> DroppedTooManyPendingMessages { get; set; } /// <summary> /// The percentage of messages accepted on this day that were not dropped and not delivered, due to the device /// being disconnected (as of the end of the America/Los_Angeles day when the message was sent to FCM). A /// portion of these messages will be delivered the next day when the device connects but others may be destined /// to devices that ultimately never reconnect. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("pending")] public virtual System.Nullable<float> Pending { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either /// specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one /// of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year /// (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a /// zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * /// google.type.DateTime * google.protobuf.Timestamp /// </summary> public class GoogleTypeDate : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a /// year and month where the day isn't significant. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("day")] public virtual System.Nullable<int> Day { get; set; } /// <summary>Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.</summary> [Newtonsoft.Json.JsonPropertyAttribute("month")] public virtual System.Nullable<int> Month { get; set; } /// <summary>Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.</summary> [Newtonsoft.Json.JsonPropertyAttribute("year")] public virtual System.Nullable<int> Year { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Lucene version compatibility level 4.8.1 using J2N; using Lucene.Net.Analysis.Standard; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Util; namespace Lucene.Net.Analysis.Cjk { /* * 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. */ // LUCENENET specific - converted constants from CJKBigramFilter // into a flags enum. [System.Flags] public enum CJKScript { /// <summary> /// bigram flag for Han Ideographs </summary> HAN = 1, /// <summary> /// bigram flag for Hiragana </summary> HIRAGANA = 2, /// <summary> /// bigram flag for Katakana </summary> KATAKANA = 4, /// <summary> /// bigram flag for Hangul </summary> HANGUL = 8, /// <summary> /// bigram flag for all scripts </summary> ALL = 0xff } /// <summary> /// Forms bigrams of CJK terms that are generated from <see cref="StandardTokenizer"/> /// or ICUTokenizer. /// <para> /// CJK types are set by these tokenizers, but you can also use /// <see cref="CJKBigramFilter(TokenStream, CJKScript)"/> to explicitly control which /// of the CJK scripts are turned into bigrams. /// </para> /// <para> /// By default, when a CJK character has no adjacent characters to form /// a bigram, it is output in unigram form. If you want to always output /// both unigrams and bigrams, set the <code>outputUnigrams</code> /// flag in <see cref="CJKBigramFilter.CJKBigramFilter(TokenStream, CJKScript, bool)"/>. /// This can be used for a combined unigram+bigram approach. /// </para> /// <para> /// In all cases, all non-CJK input is passed thru unmodified. /// </para> /// </summary> public sealed class CJKBigramFilter : TokenFilter { // configuration // LUCENENET specific - made flags into their own [Flags] enum named CJKScript and de-nested from this type /// <summary> /// when we emit a bigram, its then marked as this type </summary> public const string DOUBLE_TYPE = "<DOUBLE>"; /// <summary> /// when we emit a unigram, its then marked as this type </summary> public const string SINGLE_TYPE = "<SINGLE>"; // the types from standardtokenizer private static readonly string HAN_TYPE = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.IDEOGRAPHIC]; private static readonly string HIRAGANA_TYPE = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.HIRAGANA]; private static readonly string KATAKANA_TYPE = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.KATAKANA]; private static readonly string HANGUL_TYPE = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.HANGUL]; // sentinel value for ignoring a script private static readonly string NO = "<NO>"; // these are set to either their type or NO if we want to pass them thru private readonly string doHan; private readonly string doHiragana; private readonly string doKatakana; private readonly string doHangul; // true if we should output unigram tokens always private readonly bool outputUnigrams; private bool ngramState; // false = output unigram, true = output bigram private readonly ICharTermAttribute termAtt; private readonly ITypeAttribute typeAtt; private readonly IOffsetAttribute offsetAtt; private readonly IPositionIncrementAttribute posIncAtt; private readonly IPositionLengthAttribute posLengthAtt; // buffers containing codepoint and offsets in parallel private int[] buffer = new int[8]; private int[] startOffset = new int[8]; private int[] endOffset = new int[8]; // length of valid buffer private int bufferLen; // current buffer index private int index; // the last end offset, to determine if we should bigram across tokens private int lastEndOffset; private bool exhausted; /// <summary> /// Calls <see cref="CJKBigramFilter.CJKBigramFilter(TokenStream, CJKScript)"> /// CJKBigramFilter(@in, CJKScript.HAN | CJKScript.HIRAGANA | CJKScript.KATAKANA | CJKScript.HANGUL)</see> /// </summary> /// <param name="in"> /// Input <see cref="TokenStream"/> </param> public CJKBigramFilter(TokenStream @in) : this(@in, CJKScript.HAN | CJKScript.HIRAGANA | CJKScript.KATAKANA | CJKScript.HANGUL) { } /// <summary> /// Calls <see cref="CJKBigramFilter.CJKBigramFilter(TokenStream, CJKScript, bool)"> /// CJKBigramFilter(in, flags, false)</see> /// </summary> /// <param name="in"> /// Input <see cref="TokenStream"/> </param> /// <param name="flags"> OR'ed set from <see cref="CJKScript.HAN"/>, <see cref="CJKScript.HIRAGANA"/>, /// <see cref="CJKScript.KATAKANA"/>, <see cref="CJKScript.HANGUL"/> </param> public CJKBigramFilter(TokenStream @in, CJKScript flags) : this(@in, flags, false) { } /// <summary> /// Create a new <see cref="CJKBigramFilter"/>, specifying which writing systems should be bigrammed, /// and whether or not unigrams should also be output. </summary> /// <param name="in"> /// Input <see cref="TokenStream"/> </param> /// <param name="flags"> OR'ed set from <see cref="CJKScript.HAN"/>, <see cref="CJKScript.HIRAGANA"/>, /// <see cref="CJKScript.KATAKANA"/>, <see cref="CJKScript.HANGUL"/> </param> /// <param name="outputUnigrams"> true if unigrams for the selected writing systems should also be output. /// when this is false, this is only done when there are no adjacent characters to form /// a bigram. </param> public CJKBigramFilter(TokenStream @in, CJKScript flags, bool outputUnigrams) : base(@in) { doHan = (flags & CJKScript.HAN) == 0 ? NO : HAN_TYPE; doHiragana = (flags & CJKScript.HIRAGANA) == 0 ? NO : HIRAGANA_TYPE; doKatakana = (flags & CJKScript.KATAKANA) == 0 ? NO : KATAKANA_TYPE; doHangul = (flags & CJKScript.HANGUL) == 0 ? NO : HANGUL_TYPE; this.outputUnigrams = outputUnigrams; this.termAtt = AddAttribute<ICharTermAttribute>(); this.typeAtt = AddAttribute<ITypeAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); this.posIncAtt = AddAttribute<IPositionIncrementAttribute>(); this.posLengthAtt = AddAttribute<IPositionLengthAttribute>(); } /* * much of this complexity revolves around handling the special case of a * "lone cjk character" where cjktokenizer would output a unigram. this * is also the only time we ever have to captureState. */ public override bool IncrementToken() { while (true) { if (HasBufferedBigram) { // case 1: we have multiple remaining codepoints buffered, // so we can emit a bigram here. if (outputUnigrams) { // when also outputting unigrams, we output the unigram first, // then rewind back to revisit the bigram. // so an input of ABC is A + (rewind)AB + B + (rewind)BC + C // the logic in hasBufferedUnigram ensures we output the C, // even though it did actually have adjacent CJK characters. if (ngramState) { FlushBigram(); } else { FlushUnigram(); index--; } ngramState = !ngramState; } else { FlushBigram(); } return true; } else if (DoNext()) { // case 2: look at the token type. should we form any n-grams? string type = typeAtt.Type; if (type == doHan || type == doHiragana || type == doKatakana || type == doHangul) { // acceptable CJK type: we form n-grams from these. // as long as the offsets are aligned, we just add these to our current buffer. // otherwise, we clear the buffer and start over. if (offsetAtt.StartOffset != lastEndOffset) // unaligned, clear queue { if (HasBufferedUnigram) { // we have a buffered unigram, and we peeked ahead to see if we could form // a bigram, but we can't, because the offsets are unaligned. capture the state // of this peeked data to be revisited next time thru the loop, and dump our unigram. loneState = CaptureState(); FlushUnigram(); return true; } index = 0; bufferLen = 0; } Refill(); } else { // not a CJK type: we just return these as-is. if (HasBufferedUnigram) { // we have a buffered unigram, and we peeked ahead to see if we could form // a bigram, but we can't, because its not a CJK type. capture the state // of this peeked data to be revisited next time thru the loop, and dump our unigram. loneState = CaptureState(); FlushUnigram(); return true; } return true; } } else { // case 3: we have only zero or 1 codepoints buffered, // so not enough to form a bigram. But, we also have no // more input. So if we have a buffered codepoint, emit // a unigram, otherwise, its end of stream. if (HasBufferedUnigram) { FlushUnigram(); // flush our remaining unigram return true; } return false; } } } private State loneState; // rarely used: only for "lone cjk characters", where we emit unigrams /// <summary> /// looks at next input token, returning false is none is available /// </summary> private bool DoNext() { if (loneState != null) { RestoreState(loneState); loneState = null; return true; } else { if (exhausted) { return false; } else if (m_input.IncrementToken()) { return true; } else { exhausted = true; return false; } } } /// <summary> /// refills buffers with new data from the current token. /// </summary> private void Refill() { // compact buffers to keep them smallish if they become large // just a safety check, but technically we only need the last codepoint if (bufferLen > 64) { int last = bufferLen - 1; buffer[0] = buffer[last]; startOffset[0] = startOffset[last]; endOffset[0] = endOffset[last]; bufferLen = 1; index -= last; } char[] termBuffer = termAtt.Buffer; int len = termAtt.Length; int start = offsetAtt.StartOffset; int end = offsetAtt.EndOffset; int newSize = bufferLen + len; buffer = ArrayUtil.Grow(buffer, newSize); startOffset = ArrayUtil.Grow(startOffset, newSize); endOffset = ArrayUtil.Grow(endOffset, newSize); lastEndOffset = end; if (end - start != len) { // crazy offsets (modified by synonym or charfilter): just preserve for (int i = 0, cp = 0; i < len; i += Character.CharCount(cp)) { cp = buffer[bufferLen] = Character.CodePointAt(termBuffer, i, len); startOffset[bufferLen] = start; endOffset[bufferLen] = end; bufferLen++; } } else { // normal offsets for (int i = 0, cp = 0, cpLen = 0; i < len; i += cpLen) { cp = buffer[bufferLen] = Character.CodePointAt(termBuffer, i, len); cpLen = Character.CharCount(cp); startOffset[bufferLen] = start; start = endOffset[bufferLen] = start + cpLen; bufferLen++; } } } /// <summary> /// Flushes a bigram token to output from our buffer /// This is the normal case, e.g. ABC -> AB BC /// </summary> private void FlushBigram() { ClearAttributes(); char[] termBuffer = termAtt.ResizeBuffer(4); // maximum bigram length in code units (2 supplementaries) int len1 = Character.ToChars(buffer[index], termBuffer, 0); int len2 = len1 + Character.ToChars(buffer[index + 1], termBuffer, len1); termAtt.Length = len2; offsetAtt.SetOffset(startOffset[index], endOffset[index + 1]); typeAtt.Type = DOUBLE_TYPE; // when outputting unigrams, all bigrams are synonyms that span two unigrams if (outputUnigrams) { posIncAtt.PositionIncrement = 0; posLengthAtt.PositionLength = 2; } index++; } /// <summary> /// Flushes a unigram token to output from our buffer. /// This happens when we encounter isolated CJK characters, either the whole /// CJK string is a single character, or we encounter a CJK character surrounded /// by space, punctuation, english, etc, but not beside any other CJK. /// </summary> private void FlushUnigram() { ClearAttributes(); char[] termBuffer = termAtt.ResizeBuffer(2); // maximum unigram length (2 surrogates) int len = Character.ToChars(buffer[index], termBuffer, 0); termAtt.Length = len; offsetAtt.SetOffset(startOffset[index], endOffset[index]); typeAtt.Type = SINGLE_TYPE; index++; } /// <summary> /// True if we have multiple codepoints sitting in our buffer /// </summary> private bool HasBufferedBigram => bufferLen - index > 1; /// <summary> /// True if we have a single codepoint sitting in our buffer, where its future /// (whether it is emitted as unigram or forms a bigram) depends upon not-yet-seen /// inputs. /// </summary> private bool HasBufferedUnigram { get { if (outputUnigrams) { // when outputting unigrams always return bufferLen - index == 1; } else { // otherwise its only when we have a lone CJK character return bufferLen == 1 && index == 0; } } } public override void Reset() { base.Reset(); bufferLen = 0; index = 0; lastEndOffset = 0; loneState = null; exhausted = false; ngramState = 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 System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TelemData = System.Collections.Generic.KeyValuePair<string, object>; using Xunit; namespace System.Diagnostics.Tests { /// <summary> /// Tests for DiagnosticSource and DiagnosticListener /// </summary> public class DiagnosticSourceTest { /// <summary> /// Trivial example of passing an integer /// </summary> [Fact] public void IntPayload() { using (DiagnosticListener listener = new DiagnosticListener("TestingIntPayload")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); } // unsubscribe // Make sure that after unsubscribing, we don't get more events. source.Write("IntPayload", 5); Assert.Equal(1, result.Count); } } /// <summary> /// slightly less trivial of passing a structure with a couple of fields /// </summary> [Fact] public void StructPayload() { using (DiagnosticListener listener = new DiagnosticListener("TestingStructPayload")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); Assert.Equal("StructPayload", result[0].Key); var payload = (Payload)result[0].Value; Assert.Equal(67, payload.Id); Assert.Equal("Hi", payload.Name); } source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); } } /// <summary> /// Tests the IObserver OnCompleted callback. /// </summary> [Fact] public void Completed() { var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); var listener = new DiagnosticListener("TestingCompleted"); var subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); Assert.False(observer.Completed); // The listener dies listener.Dispose(); Assert.True(observer.Completed); // confirm that we can unsubscribe without crashing subscription.Dispose(); // If we resubscribe after dispose, but it does not do anything. subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void BasicIsEnabled() { using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); bool seenUninteresting = false; bool seenStructPayload = false; Predicate<string> predicate = delegate (string name) { if (name == "Uninteresting") seenUninteresting = true; if (name == "StructPayload") seenStructPayload = true; return name == "StructPayload"; }; // Assert.False(listener.IsEnabled()); Since other things might turn on all DiagnosticSources, we can't ever test that it is not enabled. using (listener.Subscribe(new ObserverToList<TelemData>(result), predicate)) { Assert.False(source.IsEnabled("Uninteresting")); Assert.False(source.IsEnabled("Uninteresting", "arg1", "arg2")); Assert.True(source.IsEnabled("StructPayload")); Assert.True(source.IsEnabled("StructPayload", "arg1", "arg2")); Assert.True(seenUninteresting); Assert.True(seenStructPayload); Assert.True(listener.IsEnabled()); } } } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void IsEnabledMultipleArgs() { using (DiagnosticListener listener = new DiagnosticListener("TestingIsEnabledMultipleArgs")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); Func<string, object, object, bool> isEnabled = (name, arg1, arg2) => { if (arg1 != null) return (bool) arg1; if (arg2 != null) return (bool) arg2; return true; }; using (listener.Subscribe(new ObserverToList<TelemData>(result), isEnabled)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null, null)); Assert.True(source.IsEnabled("event", null, true)); Assert.False(source.IsEnabled("event", false, false)); Assert.False(source.IsEnabled("event", false, null)); Assert.False(source.IsEnabled("event", null, false)); } } } /// <summary> /// Test if it works when you have two subscribers active simultaneously /// </summary> [Fact] public void MultiSubscriber() { using (DiagnosticListener listener = new DiagnosticListener("TestingMultiSubscriber")) { DiagnosticSource source = listener; var subscriber1Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber1Predicate = name => (name == "DataForSubscriber1"); var subscriber1Observer = new ObserverToList<TelemData>(subscriber1Result); var subscriber2Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber2Predicate = name => (name == "DataForSubscriber2"); var subscriber2Observer = new ObserverToList<TelemData>(subscriber2Result); // Get two subscribers going. using (var subscription1 = listener.Subscribe(subscriber1Observer, subscriber1Predicate)) { using (var subscription2 = listener.Subscribe(subscriber2Observer, subscriber2Predicate)) { // Things that neither subscribe to get filtered out. if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); subscriber2Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("UnfilteredData", subscriber2Result[0].Key); Assert.Equal(3, (int)subscriber2Result[0].Value); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 happens to get it Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key); Assert.Equal(1, (int)subscriber2Result[0].Value); /****************************************************/ subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 happens to get it Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key); Assert.Equal(2, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key); Assert.Equal(2, (int)subscriber2Result[0].Value); } // subscriber2 drops out /*********************************************************************/ /* Only Subscriber 1 is left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 filters Assert.Equal(0, subscriber1Result.Count); // Subscriber 2 has dropped out Assert.Equal(0, subscriber2Result.Count); } // subscriber1 drops out /*********************************************************************/ /* No Subscribers are left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. listener.Write("UnfilteredData", 3); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); } } /// <summary> /// Stresses the Subscription routine by having many threads subscribe and /// unsubscribe concurrently /// </summary> [Fact] public void MultiSubscriberStress() { using (DiagnosticListener listener = new DiagnosticListener("MultiSubscriberStressTest")) { DiagnosticSource source = listener; var random = new Random(); // Beat on the default listener by subscribing and unsubscribing on many threads simultaneously. var factory = new TaskFactory(); // To the whole stress test 10 times. This keeps the task array size needed down while still // having lots of concurrency. for (int j = 0; j < 20; j++) { // Spawn off lots of concurrent activity var tasks = new Task[1000]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = factory.StartNew(delegate (object taskData) { int taskNum = (int)taskData; var taskName = "Task" + taskNum; var result = new List<KeyValuePair<string, object>>(); Predicate<string> predicate = (name) => name == taskName; Predicate<KeyValuePair<string, object>> filter = (keyValue) => keyValue.Key == taskName; // set up the observer to only see events set with the task name as the name. var observer = new ObserverToList<TelemData>(result, filter, taskName); using (listener.Subscribe(observer, predicate)) { source.Write(taskName, taskNum); Assert.Equal(1, result.Count); Assert.Equal(taskName, result[0].Key); Assert.Equal(taskNum, result[0].Value); // Spin a bit randomly. This mixes of the lifetimes of the subscriptions and makes it // more stressful var cnt = random.Next(10, 100) * 1000; while (0 < --cnt) GC.KeepAlive(""); } // Unsubscribe // Send the notification again, to see if it now does NOT come through (count remains unchanged). source.Write(taskName, -1); Assert.Equal(1, result.Count); }, i); } Task.WaitAll(tasks); } } } /// <summary> /// Tests if as we create new DiagnosticListerns, we get callbacks for them /// </summary> [Fact] public void AllListenersAddRemove() { using (DiagnosticListener listener = new DiagnosticListener("TestListen0")) { DiagnosticSource source = listener; // This callback will return the listener that happens on the callback DiagnosticListener returnedListener = null; Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { // Other tests can be running concurrently with this test, which will make // this callback fire for those listeners as well. We only care about // the Listeners we generate here so ignore any that d if (!listen.Name.StartsWith("TestListen")) return; Assert.Null(returnedListener); Assert.NotNull(listen); returnedListener = listen; }; // Subscribe, which delivers catch-up event for the Default listener using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // Now we unsubscribe // Create an dispose a listener, but we won't get a callback for it. using (new DiagnosticListener("TestListen")) { } Assert.Null(returnedListener); // No callback was made // Resubscribe using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; // add two new subscribers using (var listener1 = new DiagnosticListener("TestListen1")) { Assert.Equal("TestListen1", listener1.Name); Assert.Equal(listener1, returnedListener); returnedListener = null; using (var listener2 = new DiagnosticListener("TestListen2")) { Assert.Equal("TestListen2", listener2.Name); Assert.Equal(listener2, returnedListener); returnedListener = null; } // Dispose of listener2 } // Dispose of listener1 } // Unsubscribe // Check that we are back to just the DefaultListener. using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // cleanup } } /// <summary> /// Tests that the 'catchupList' of active listeners is accurate even as we /// add and remove DiagnosticListeners randomly. /// </summary> [Fact] public void AllListenersCheckCatchupList() { var expected = new List<DiagnosticListener>(); var list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); for (int i = 0; i < 50; i++) { expected.Insert(0, (new DiagnosticListener("TestListener" + i))); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); } // Remove the element randomly. var random = new Random(0); while (0 < expected.Count) { var toRemoveIdx = random.Next(0, expected.Count - 1); // Always leave the Default listener. var toRemoveListener = expected[toRemoveIdx]; toRemoveListener.Dispose(); // Kill it (which removes it from the list) expected.RemoveAt(toRemoveIdx); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list.Count, expected.Count); Assert.Equal(list, expected); } } /// <summary> /// Stresses the AllListeners by having many threads be adding and removing. /// </summary> [OuterLoop] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(35539)] [InlineData(100, 100)] // run multiple times to stress it further [InlineData(100, 101)] [InlineData(100, 102)] [InlineData(100, 103)] [InlineData(100, 104)] public void AllSubscriberStress(int numThreads, int numListenersPerThread) { // No listeners have been created yet Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); // Run lots of threads to add/remove listeners Task.WaitAll(Enumerable.Range(0, numThreads).Select(i => Task.Factory.StartNew(delegate { // Create a set of DiagnosticListeners, which add themselves to the AllListeners list. var listeners = new List<DiagnosticListener>(numListenersPerThread); for (int j = 0; j < numListenersPerThread; j++) { var listener = new DiagnosticListener($"{nameof(AllSubscriberStress)}_Task {i} TestListener{j}"); listeners.Add(listener); } // They are all in the list. List<DiagnosticListener> list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.Contains(listener, list)); // Dispose them all, first the even then the odd, just to mix it up and be more stressful. for (int j = 0; j < listeners.Count; j += 2) // even listeners[j].Dispose(); for (int j = 1; j < listeners.Count; j += 2) // odd listeners[j].Dispose(); // None should be left in the list list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.DoesNotContain(listener, list)); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); // None of the created listeners should remain Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); } [Fact] public void DoubleDisposeOfListener() { var listener = new DiagnosticListener("TestingDoubleDisposeOfListener"); int completionCount = 0; IDisposable subscription = listener.Subscribe(MakeObserver<KeyValuePair<string, object>>(_ => { }, () => completionCount++)); listener.Dispose(); listener.Dispose(); subscription.Dispose(); subscription.Dispose(); Assert.Equal(1, completionCount); } [Fact] public void ListenerToString() { string name = Guid.NewGuid().ToString(); using (var listener = new DiagnosticListener(name)) { Assert.Equal(name, listener.ToString()); } } [Fact] public void DisposeAllListenerSubscriptionInSameOrderSubscribed() { int count1 = 0, count2 = 0, count3 = 0; IDisposable sub1 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count1++)); IDisposable sub2 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count2++)); IDisposable sub3 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count3++)); Assert.Equal(0, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); Assert.Equal(1, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); // dispose again just to make sure nothing bad happens sub2.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(0, count3); sub2.Dispose(); sub3.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(1, count3); sub3.Dispose(); } [Fact] public void SubscribeWithNullPredicate() { using (DiagnosticListener listener = new DiagnosticListener("TestingSubscribeWithNullPredicate")) { Predicate<string> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(listener.IsEnabled("event")); Assert.True(listener.IsEnabled("event", null)); Assert.True(listener.IsEnabled("event", "arg1")); Assert.True(listener.IsEnabled("event", "arg1", "arg2")); } } using (DiagnosticListener listener = new DiagnosticListener("TestingSubscribeWithNullPredicate")) { DiagnosticSource source = listener; Func<string, object, object, bool> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null)); Assert.True(source.IsEnabled("event", "arg1")); Assert.True(source.IsEnabled("event", "arg1", "arg2")); } } } [Fact] public void ActivityImportExport() { using (DiagnosticListener listener = new DiagnosticListener("TestingBasicIsEnabled")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); bool seenPredicate = false; Func<string, object, object, bool> predicate = delegate (string name, object obj1, object obj2) { seenPredicate = true; return true; }; Activity importerActivity = new Activity("activityImporter"); object importer = "MyImporterObject"; bool seenActivityImport = false; Action<Activity, object> activityImport = delegate (Activity activity, object payload) { Assert.Equal(activity.GetHashCode(), importerActivity.GetHashCode()); Assert.Equal(importer, payload); seenActivityImport = true; }; Activity exporterActivity = new Activity("activityExporter"); object exporter = "MyExporterObject"; bool seenActivityExport = false; Action<Activity, object> activityExport = delegate (Activity activity, object payload) { Assert.Equal(activity.GetHashCode(), exporterActivity.GetHashCode()); Assert.Equal(exporter, payload); seenActivityExport = true; }; // Use the Subscribe that allows you to hook the OnActivityImport and OnActivityExport calls. using (listener.Subscribe(new ObserverToList<TelemData>(result), predicate, activityImport, activityExport)) { if (listener.IsEnabled("IntPayload")) listener.Write("IntPayload", 5); Assert.True(seenPredicate); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); listener.OnActivityImport(importerActivity, importer); Assert.True(seenActivityImport); listener.OnActivityExport(exporterActivity, exporter); Assert.True(seenActivityExport); } } } #region Helpers /// <summary> /// Returns the list of active diagnostic listeners. /// </summary> /// <returns></returns> private static List<DiagnosticListener> GetActiveListenersWithPrefix(string prefix) { var ret = new List<DiagnosticListener>(); Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { if (listen.Name.StartsWith(prefix)) ret.Add(listen); }; // Subscribe, which gives you the list using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { } // Unsubscribe to remove side effects. return ret; } /// <summary> /// Used to make an observer out of an action delegate. /// </summary> public static IObserver<T> MakeObserver<T>( Action<T> onNext = null, Action onCompleted = null) { return new Observer<T>(onNext, onCompleted); } /// <summary> /// Used in the implementation of MakeObserver. /// </summary> /// <typeparam name="T"></typeparam> private class Observer<T> : IObserver<T> { public Observer(Action<T> onNext, Action onCompleted) { _onNext = onNext ?? new Action<T>(_ => { }); _onCompleted = onCompleted ?? new Action(() => { }); } public void OnCompleted() { _onCompleted(); } public void OnError(Exception error) { } public void OnNext(T value) { _onNext(value); } private Action<T> _onNext; private Action _onCompleted; } #endregion } // Takes an IObserver and returns a List<T> that are the elements observed. // Will assert on error and 'Completed' is set if the 'OnCompleted' callback // is issued. internal class ObserverToList<T> : IObserver<T> { public ObserverToList(List<T> output, Predicate<T> filter = null, string name = null) { _output = output; _output.Clear(); _filter = filter; _name = name; } public bool Completed { get; private set; } #region private public void OnCompleted() { Completed = true; } public void OnError(Exception error) { Assert.True(false, "Error happened on IObserver"); } public void OnNext(T value) { Assert.False(Completed); if (_filter == null || _filter(value)) _output.Add(value); } private List<T> _output; private Predicate<T> _filter; private string _name; // for debugging #endregion } /// <summary> /// Trivial class used for payloads. (Usually anonymous types are used. /// </summary> internal class Payload { public string Name { get; set; } public int Id { 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.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; namespace System.Data.OleDb { using SysTx = Transactions; public sealed partial class OleDbConnection : DbConnection { private static readonly DbConnectionFactory _connectionFactory = OleDbConnectionFactory.SingletonInstance; private DbConnectionOptions _userConnectionOptions; private DbConnectionPoolGroup _poolGroup; private DbConnectionInternal _innerConnection; private int _closeCount; // used to distinguish between different uses of this object, so we don't have to maintain a list of it's children public OleDbConnection() : base() { GC.SuppressFinalize(this); _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } // Copy Constructor private void CopyFrom(OleDbConnection connection) { // V1.2.3300 ADP.CheckArgumentNull(connection, "connection"); _userConnectionOptions = connection.UserConnectionOptions; _poolGroup = connection.PoolGroup; // Match the original connection's behavior for whether the connection was never opened, // but ensure Clone is in the closed state. if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection) { _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } else { _innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance; } } internal DbConnectionFactory ConnectionFactory { get { return _connectionFactory; } } internal DbConnectionOptions ConnectionOptions { get { System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); } } private string ConnectionString_Get() { bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); } private void ConnectionString_Set(string value) { DbConnectionPoolKey key = new DbConnectionPoolKey(value); ConnectionString_Set(key); } private void ConnectionString_Set(DbConnectionPoolKey key) { DbConnectionOptions connectionOptions = null; System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions); DbConnectionInternal connectionInternal = InnerConnection; bool flag = connectionInternal.AllowSetConnectionString; if (flag) { //try { // NOTE: There's a race condition with multiple threads changing // ConnectionString and any thread throws an exception // Closed->Busy: prevent Open during set_ConnectionString flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal); if (flag) { _userConnectionOptions = connectionOptions; _poolGroup = poolGroup; _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance; } //} //catch { // // recover from exceptions to avoid sticking in busy state // SetInnerConnectionFrom(connectionInternal, DbConnectionClosedBusy.SingletonInstance); // throw; //} } if (!flag) { throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); } } internal DbConnectionInternal InnerConnection { get { return _innerConnection; } } internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup { get { return _poolGroup; } set { // when a poolgroup expires and the connection eventually activates, the pool entry will be replaced Debug.Assert(null != value, "null poolGroup"); _poolGroup = value; } } internal DbConnectionOptions UserConnectionOptions { get { return _userConnectionOptions; } } internal void AddWeakReference(object value, int tag) { InnerConnection.AddWeakReference(value, tag); } override protected DbCommand CreateDbCommand() { DbCommand command = null; DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; command = providerFactory.CreateCommand(); command.Connection = this; return command; } override protected void Dispose(bool disposing) { if (disposing) { _userConnectionOptions = null; _poolGroup = null; Close(); } DisposeMe(disposing); base.Dispose(disposing); // notify base classes } partial void RepairInnerConnection(); //// NOTE: This is just a private helper because OracleClient V1.1 shipped //// with a different argument name and it's a breaking change to not use //// the same argument names in V2.0 (VB Named Parameter Binding--Ick) //private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction) { // SysTx.Transaction indigoTransaction = null; // if (null != transaction) { // indigoTransaction = SysTx.TransactionInterop.GetTransactionFromDtcTransaction((SysTx.IDtcTransaction)transaction); // } // RepairInnerConnection(); // // NOTE: since transaction enlistment involves round trips to the // // server, we don't want to lock here, we'll handle the race conditions // // elsewhere. // InnerConnection.EnlistTransaction(indigoTransaction); // // NOTE: If this outer connection were to be GC'd while we're // // enlisting, the pooler would attempt to reclaim the inner connection // // while we're attempting to enlist; not sure how likely that is but // // we should consider a GC.KeepAlive(this) here. // GC.KeepAlive(this); //} override public void EnlistTransaction(SysTx.Transaction transaction) { // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to // enlist in a different transaction. DbConnectionInternal innerConnection = InnerConnection; // NOTE: since transaction enlistment involves round trips to the // server, we don't want to lock here, we'll handle the race conditions // elsewhere. SysTx.Transaction enlistedTransaction = innerConnection.EnlistedTransaction; if (enlistedTransaction != null) { // Allow calling enlist if already enlisted (no-op) if (enlistedTransaction.Equals(transaction)) { return; } // Allow enlisting in a different transaction if the enlisted transaction has completed. if (enlistedTransaction.TransactionInformation.Status == SysTx.TransactionStatus.Active) { throw ADP.TransactionPresent(); } } RepairInnerConnection(); InnerConnection.EnlistTransaction(transaction); // NOTE: If this outer connection were to be GC'd while we're // enlisting, the pooler would attempt to reclaim the inner connection // while we're attempting to enlist; not sure how likely that is but // we should consider a GC.KeepAlive(this) here. GC.KeepAlive(this); } override public DataTable GetSchema() { return this.GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null); } override public DataTable GetSchema(string collectionName) { return this.GetSchema(collectionName, null); } override public DataTable GetSchema(string collectionName, string[] restrictionValues) { // NOTE: This is virtual because not all providers may choose to support // returning schema data return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues); } internal void NotifyWeakReference(int message) { InnerConnection.NotifyWeakReference(message); } internal void PermissionDemand() { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); if ((null == connectionOptions) || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions userConnectionOptions = UserConnectionOptions; Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); } internal void RemoveWeakReference(object value) { InnerConnection.RemoveWeakReference(value); } // OpenBusy->Closed (previously opened) // Connecting->Open internal void SetInnerConnectionEvent(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; if ((originalState != currentState) && (ConnectionState.Closed == currentState)) { // Increment the close count whenever we switch to Closed unchecked { _closeCount++; } } _innerConnection = to; if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState) { OnStateChange(DbConnectionInternal.StateChangeOpen); } else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState) { OnStateChange(DbConnectionInternal.StateChangeClosed); } else { Debug.Assert(false, "unexpected state switch"); if (originalState != currentState) { OnStateChange(new StateChangeEventArgs(originalState, currentState)); } } } // Closed->Connecting: prevent set_ConnectionString during Open // Open->OpenBusy: guarantee internal connection is returned to correct pool // Closed->ClosedBusy: prevent Open during set_ConnectionString internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) { // Set's the internal connection, verifying that it's a specific value before doing so. Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != from, "from null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange<DbConnectionInternal>(ref _innerConnection, to, from)); return result; } // ClosedBusy->Closed (never opened) // Connecting->Closed (exception during open, return to previous closed state) internal void SetInnerConnectionTo(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value Debug.Assert(null != _innerConnection, "null InnerConnection"); Debug.Assert(null != to, "to null InnerConnection"); _innerConnection = to; } } }
#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 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Collections.Specialized; using System.Xml; using Prebuild.Core.Nodes; namespace Prebuild.Core.Utilities { /// <summary> /// /// </summary> public class Helper { #region Fields static bool checkForOSVariables; /// <summary> /// /// </summary> public static bool CheckForOSVariables { get { return checkForOSVariables; } set { checkForOSVariables = value; } } #endregion #region Public Methods #region String Parsing public delegate string StringLookup(string key); /// <summary> /// Gets a collection of StringLocationPair objects that represent the matches /// </summary> /// <param name="target">The target.</param> /// <param name="beforeGroup">The before group.</param> /// <param name="afterGroup">The after group.</param> /// <param name="includeDelimitersInSubstrings">if set to <c>true</c> [include delimiters in substrings].</param> /// <returns></returns> public static StringCollection FindGroups(string target, string beforeGroup, string afterGroup, bool includeDelimitersInSubstrings) { if( beforeGroup == null ) { throw new ArgumentNullException("beforeGroup"); } if( afterGroup == null ) { throw new ArgumentNullException("afterGroup"); } StringCollection results = new StringCollection(); if(target == null || target.Length == 0) { return results; } int beforeMod = 0; int afterMod = 0; if(includeDelimitersInSubstrings) { //be sure to not exlude the delims beforeMod = beforeGroup.Length; afterMod = afterGroup.Length; } int startIndex = 0; while((startIndex = target.IndexOf(beforeGroup,startIndex)) != -1) { int endIndex = target.IndexOf(afterGroup,startIndex);//the index of the char after it if(endIndex == -1) { break; } int length = endIndex - startIndex - beforeGroup.Length;//move to the first char in the string string substring = target.Substring(startIndex + beforeGroup.Length - beforeMod, length - afterMod); results.Add(substring); //results.Add(new StringLocationPair(substring,startIndex)); startIndex = endIndex + 1; //the Interpolate*() methods will not work if expressions are expandded inside expression due to an optimization //so start after endIndex } return results; } /// <summary> /// Replaces the groups. /// </summary> /// <param name="target">The target.</param> /// <param name="beforeGroup">The before group.</param> /// <param name="afterGroup">The after group.</param> /// <param name="lookup">The lookup.</param> /// <returns></returns> public static string ReplaceGroups(string target, string beforeGroup, string afterGroup, StringLookup lookup) { if( target == null ) { throw new ArgumentNullException("target"); } //int targetLength = target.Length; StringCollection strings = FindGroups(target,beforeGroup,afterGroup,false); if( lookup == null ) { throw new ArgumentNullException("lookup"); } foreach(string substring in strings) { target = target.Replace(beforeGroup + substring + afterGroup, lookup(substring) ); } return target; } /// <summary> /// Replaces ${var} statements in a string with the corresonding values as detirmined by the lookup delegate /// </summary> /// <param name="target">The target.</param> /// <param name="lookup">The lookup.</param> /// <returns></returns> public static string InterpolateForVariables(string target, StringLookup lookup) { return ReplaceGroups(target, "${" , "}" , lookup); } /// <summary> /// Replaces ${var} statements in a string with the corresonding environment variable with name var /// </summary> /// <param name="target"></param> /// <returns></returns> public static string InterpolateForEnvironmentVariables(string target) { return InterpolateForVariables(target, new StringLookup(Environment.GetEnvironmentVariable)); } #endregion /// <summary> /// Translates the value. /// </summary> /// <param name="translateType">Type of the translate.</param> /// <param name="translationItem">The translation item.</param> /// <returns></returns> public static object TranslateValue(Type translateType, string translationItem) { if(translationItem == null) { return null; } try { string lowerVal = translationItem.ToLower(); if(translateType == typeof(bool)) { return (lowerVal == "true" || lowerVal == "1" || lowerVal == "y" || lowerVal == "yes" || lowerVal == "on"); } else if(translateType == typeof(int)) { return (Int32.Parse(translationItem)); } else { return translationItem; } } catch(FormatException) { return null; } } /// <summary> /// Deletes if exists. /// </summary> /// <param name="file">The file.</param> /// <returns></returns> public static bool DeleteIfExists(string file) { string resFile = null; try { resFile = ResolvePath(file); } catch(ArgumentException) { return false; } if(!File.Exists(resFile)) { return false; } File.Delete(resFile); return true; } static readonly char seperator = Path.DirectorySeparatorChar; // This little gem was taken from the NeL source, thanks guys! /// <summary> /// Makes a relative path /// </summary> /// <param name="startPath">Path to start from</param> /// <param name="endPath">Path to end at</param> /// <returns>Path that will get from startPath to endPath</returns> public static string MakePathRelativeTo(string startPath, string endPath) { string tmp = NormalizePath(startPath, seperator); string src = NormalizePath(endPath, seperator); string prefix = ""; while(true) { if((String.Compare(tmp, 0, src, 0, tmp.Length) == 0)) { string ret; int size = tmp.Length; if(size == src.Length) { return "./"; } if((src.Length > tmp.Length) && src[tmp.Length - 1] != seperator) { } else { ret = prefix + endPath.Substring(size, endPath.Length - size); ret = ret.Trim(); if(ret[0] == seperator) { ret = "." + ret; } return NormalizePath(ret); } } if(tmp.Length < 2) { break; } int lastPos = tmp.LastIndexOf(seperator, tmp.Length - 2); int prevPos = tmp.IndexOf(seperator); if((lastPos == prevPos) || (lastPos == -1)) { break; } tmp = tmp.Substring(0, lastPos + 1); prefix += ".." + seperator.ToString(); } return endPath; } /// <summary> /// Resolves the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string ResolvePath(string path) { string tmpPath = NormalizePath(path); if(tmpPath.Length < 1) { tmpPath = "."; } tmpPath = Path.GetFullPath(tmpPath); if(!File.Exists(tmpPath) && !Directory.Exists(tmpPath)) { throw new ArgumentException("Path could not be resolved: " + tmpPath); } return tmpPath; } /// <summary> /// Normalizes the path. /// </summary> /// <param name="path">The path.</param> /// <param name="separatorCharacter">The separator character.</param> /// <returns></returns> public static string NormalizePath(string path, char separatorCharacter) { if(path == null || path == "" || path.Length < 1) { return ""; } string tmpPath = path.Replace('\\', '/'); tmpPath = tmpPath.Replace('/', separatorCharacter); return tmpPath; } /// <summary> /// Normalizes the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string NormalizePath(string path) { return NormalizePath(path, Path.DirectorySeparatorChar); } /// <summary> /// Ends the path. /// </summary> /// <param name="path">The path.</param> /// <param name="separatorCharacter">The separator character.</param> /// <returns></returns> public static string EndPath(string path, char separatorCharacter) { if(path == null || path == "" || path.Length < 1) { return ""; } if(!path.EndsWith(separatorCharacter.ToString())) { return (path + separatorCharacter); } return path; } /// <summary> /// Ends the path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static string EndPath(string path) { return EndPath(path, Path.DirectorySeparatorChar); } /// <summary> /// Makes the file path. /// </summary> /// <param name="path">The path.</param> /// <param name="name">The name.</param> /// <param name="ext">The ext.</param> /// <returns></returns> public static string MakeFilePath(string path, string name, string ext) { string ret = EndPath(NormalizePath(path)); if( name == null ) { throw new ArgumentNullException("name"); } ret += name; if(!name.EndsWith("." + ext)) { ret += "." + ext; } //foreach(char c in Path.GetInvalidPathChars()) //{ // ret = ret.Replace(c, '_'); //} return ret; } /// <summary> /// Makes the file path. /// </summary> /// <param name="path">The path.</param> /// <param name="name">The name.</param> /// <returns></returns> public static string MakeFilePath(string path, string name) { string ret = EndPath(NormalizePath(path)); if( name == null ) { throw new ArgumentNullException("name"); } ret += name; //foreach (char c in Path.GetInvalidPathChars()) //{ // ret = ret.Replace(c, '_'); //} return ret; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public static string MakeReferencePath(string path) { string ret = EndPath(NormalizePath(path)); //foreach (char c in Path.GetInvalidPathChars()) //{ // ret = ret.Replace(c, '_'); //} return ret; } /// <summary> /// Sets the current dir. /// </summary> /// <param name="path">The path.</param> public static void SetCurrentDir(string path) { if( path == null ) { throw new ArgumentNullException("path"); } if(path.Length < 1) { return; } Environment.CurrentDirectory = path; } /// <summary> /// Checks the type. /// </summary> /// <param name="typeToCheck">The type to check.</param> /// <param name="attr">The attr.</param> /// <param name="inter">The inter.</param> /// <returns></returns> public static object CheckType(Type typeToCheck, Type attr, Type inter) { if(typeToCheck == null || attr == null) { return null; } object[] attrs = typeToCheck.GetCustomAttributes(attr, false); if(attrs == null || attrs.Length < 1) { return null; } if( inter == null ) { throw new ArgumentNullException("inter"); } if(typeToCheck.GetInterface(inter.FullName) == null) { return null; } return attrs[0]; } /// <summary> /// Attributes the value. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="def">The def.</param> /// <returns></returns> public static string AttributeValue(XmlNode node, string attr, string def) { if( node == null ) { throw new ArgumentNullException("node"); } if(node.Attributes[attr] == null) { return def; } string val = node.Attributes[attr].Value; if(!CheckForOSVariables) { return val; } return InterpolateForEnvironmentVariables(val); } /// <summary> /// Parses the boolean. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="defaultValue">if set to <c>true</c> [default value].</param> /// <returns></returns> public static bool ParseBoolean(XmlNode node, string attr, bool defaultValue) { if( node == null ) { throw new ArgumentNullException("node"); } if(node.Attributes[attr] == null) { return defaultValue; } return bool.Parse(node.Attributes[attr].Value); } /// <summary> /// Enums the attribute value. /// </summary> /// <param name="node">The node.</param> /// <param name="attr">The attr.</param> /// <param name="enumType">Type of the enum.</param> /// <param name="def">The def.</param> /// <returns></returns> public static object EnumAttributeValue(XmlNode node, string attr, Type enumType, object def) { if( def == null ) { throw new ArgumentNullException("def"); } string val = AttributeValue(node, attr, def.ToString()); return Enum.Parse(enumType, val, true); } /// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <param name="projectType"></param> /// <returns></returns> public static string AssemblyFullName(string assemblyName, ProjectType projectType) { return assemblyName + (projectType == ProjectType.Library ? ".dll" : ".exe"); } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/storagetransfer/v1/transfer.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Storagetransfer.V1 { /// <summary> /// Transfers data between between Google Cloud Storage buckets or from a data /// source external to Google to a Cloud Storage bucket. /// </summary> public static class StorageTransferService { static readonly string __ServiceName = "google.storagetransfer.v1.StorageTransferService"; static readonly Marshaller<global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest> __Marshaller_GetGoogleServiceAccountRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.GoogleServiceAccount> __Marshaller_GoogleServiceAccount = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.GoogleServiceAccount.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.CreateTransferJobRequest> __Marshaller_CreateTransferJobRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.CreateTransferJobRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.TransferJob> __Marshaller_TransferJob = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.TransferJob.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.UpdateTransferJobRequest> __Marshaller_UpdateTransferJobRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.UpdateTransferJobRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.GetTransferJobRequest> __Marshaller_GetTransferJobRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.GetTransferJobRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.ListTransferJobsRequest> __Marshaller_ListTransferJobsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.ListTransferJobsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.ListTransferJobsResponse> __Marshaller_ListTransferJobsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.ListTransferJobsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.PauseTransferOperationRequest> __Marshaller_PauseTransferOperationRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.PauseTransferOperationRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Storagetransfer.V1.ResumeTransferOperationRequest> __Marshaller_ResumeTransferOperationRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Storagetransfer.V1.ResumeTransferOperationRequest.Parser.ParseFrom); static readonly Method<global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest, global::Google.Storagetransfer.V1.GoogleServiceAccount> __Method_GetGoogleServiceAccount = new Method<global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest, global::Google.Storagetransfer.V1.GoogleServiceAccount>( MethodType.Unary, __ServiceName, "GetGoogleServiceAccount", __Marshaller_GetGoogleServiceAccountRequest, __Marshaller_GoogleServiceAccount); static readonly Method<global::Google.Storagetransfer.V1.CreateTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob> __Method_CreateTransferJob = new Method<global::Google.Storagetransfer.V1.CreateTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob>( MethodType.Unary, __ServiceName, "CreateTransferJob", __Marshaller_CreateTransferJobRequest, __Marshaller_TransferJob); static readonly Method<global::Google.Storagetransfer.V1.UpdateTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob> __Method_UpdateTransferJob = new Method<global::Google.Storagetransfer.V1.UpdateTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob>( MethodType.Unary, __ServiceName, "UpdateTransferJob", __Marshaller_UpdateTransferJobRequest, __Marshaller_TransferJob); static readonly Method<global::Google.Storagetransfer.V1.GetTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob> __Method_GetTransferJob = new Method<global::Google.Storagetransfer.V1.GetTransferJobRequest, global::Google.Storagetransfer.V1.TransferJob>( MethodType.Unary, __ServiceName, "GetTransferJob", __Marshaller_GetTransferJobRequest, __Marshaller_TransferJob); static readonly Method<global::Google.Storagetransfer.V1.ListTransferJobsRequest, global::Google.Storagetransfer.V1.ListTransferJobsResponse> __Method_ListTransferJobs = new Method<global::Google.Storagetransfer.V1.ListTransferJobsRequest, global::Google.Storagetransfer.V1.ListTransferJobsResponse>( MethodType.Unary, __ServiceName, "ListTransferJobs", __Marshaller_ListTransferJobsRequest, __Marshaller_ListTransferJobsResponse); static readonly Method<global::Google.Storagetransfer.V1.PauseTransferOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PauseTransferOperation = new Method<global::Google.Storagetransfer.V1.PauseTransferOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "PauseTransferOperation", __Marshaller_PauseTransferOperationRequest, __Marshaller_Empty); static readonly Method<global::Google.Storagetransfer.V1.ResumeTransferOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_ResumeTransferOperation = new Method<global::Google.Storagetransfer.V1.ResumeTransferOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "ResumeTransferOperation", __Marshaller_ResumeTransferOperationRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of StorageTransferService</summary> public abstract class StorageTransferServiceBase { /// <summary> /// Returns the Google service account that is used by Storage Transfer /// Service to access buckets in the project where transfers /// run or in other projects. Each Google service account is associated /// with one Google Cloud Platform Console project. Users /// should add this service account to the Google Cloud Storage bucket /// ACLs to grant access to Storage Transfer Service. This service /// account is created and owned by Storage Transfer Service and can /// only be used by Storage Transfer Service. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Storagetransfer.V1.GoogleServiceAccount> GetGoogleServiceAccount(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a transfer job that runs periodically. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Storagetransfer.V1.TransferJob> CreateTransferJob(global::Google.Storagetransfer.V1.CreateTransferJobRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates a transfer job. Updating a job's transfer spec does not affect /// transfer operations that are running already. Updating the scheduling /// of a job is not allowed. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Storagetransfer.V1.TransferJob> UpdateTransferJob(global::Google.Storagetransfer.V1.UpdateTransferJobRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a transfer job. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Storagetransfer.V1.TransferJob> GetTransferJob(global::Google.Storagetransfer.V1.GetTransferJobRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists transfer jobs. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Storagetransfer.V1.ListTransferJobsResponse> ListTransferJobs(global::Google.Storagetransfer.V1.ListTransferJobsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Pauses a transfer operation. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PauseTransferOperation(global::Google.Storagetransfer.V1.PauseTransferOperationRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Resumes a transfer operation that is paused. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> ResumeTransferOperation(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for StorageTransferService</summary> public class StorageTransferServiceClient : ClientBase<StorageTransferServiceClient> { /// <summary>Creates a new client for StorageTransferService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public StorageTransferServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for StorageTransferService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public StorageTransferServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected StorageTransferServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected StorageTransferServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Returns the Google service account that is used by Storage Transfer /// Service to access buckets in the project where transfers /// run or in other projects. Each Google service account is associated /// with one Google Cloud Platform Console project. Users /// should add this service account to the Google Cloud Storage bucket /// ACLs to grant access to Storage Transfer Service. This service /// account is created and owned by Storage Transfer Service and can /// only be used by Storage Transfer Service. /// </summary> public virtual global::Google.Storagetransfer.V1.GoogleServiceAccount GetGoogleServiceAccount(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGoogleServiceAccount(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the Google service account that is used by Storage Transfer /// Service to access buckets in the project where transfers /// run or in other projects. Each Google service account is associated /// with one Google Cloud Platform Console project. Users /// should add this service account to the Google Cloud Storage bucket /// ACLs to grant access to Storage Transfer Service. This service /// account is created and owned by Storage Transfer Service and can /// only be used by Storage Transfer Service. /// </summary> public virtual global::Google.Storagetransfer.V1.GoogleServiceAccount GetGoogleServiceAccount(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetGoogleServiceAccount, null, options, request); } /// <summary> /// Returns the Google service account that is used by Storage Transfer /// Service to access buckets in the project where transfers /// run or in other projects. Each Google service account is associated /// with one Google Cloud Platform Console project. Users /// should add this service account to the Google Cloud Storage bucket /// ACLs to grant access to Storage Transfer Service. This service /// account is created and owned by Storage Transfer Service and can /// only be used by Storage Transfer Service. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.GoogleServiceAccount> GetGoogleServiceAccountAsync(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGoogleServiceAccountAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the Google service account that is used by Storage Transfer /// Service to access buckets in the project where transfers /// run or in other projects. Each Google service account is associated /// with one Google Cloud Platform Console project. Users /// should add this service account to the Google Cloud Storage bucket /// ACLs to grant access to Storage Transfer Service. This service /// account is created and owned by Storage Transfer Service and can /// only be used by Storage Transfer Service. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.GoogleServiceAccount> GetGoogleServiceAccountAsync(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetGoogleServiceAccount, null, options, request); } /// <summary> /// Creates a transfer job that runs periodically. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob CreateTransferJob(global::Google.Storagetransfer.V1.CreateTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTransferJob(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a transfer job that runs periodically. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob CreateTransferJob(global::Google.Storagetransfer.V1.CreateTransferJobRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateTransferJob, null, options, request); } /// <summary> /// Creates a transfer job that runs periodically. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> CreateTransferJobAsync(global::Google.Storagetransfer.V1.CreateTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTransferJobAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a transfer job that runs periodically. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> CreateTransferJobAsync(global::Google.Storagetransfer.V1.CreateTransferJobRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateTransferJob, null, options, request); } /// <summary> /// Updates a transfer job. Updating a job's transfer spec does not affect /// transfer operations that are running already. Updating the scheduling /// of a job is not allowed. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob UpdateTransferJob(global::Google.Storagetransfer.V1.UpdateTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateTransferJob(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a transfer job. Updating a job's transfer spec does not affect /// transfer operations that are running already. Updating the scheduling /// of a job is not allowed. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob UpdateTransferJob(global::Google.Storagetransfer.V1.UpdateTransferJobRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateTransferJob, null, options, request); } /// <summary> /// Updates a transfer job. Updating a job's transfer spec does not affect /// transfer operations that are running already. Updating the scheduling /// of a job is not allowed. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> UpdateTransferJobAsync(global::Google.Storagetransfer.V1.UpdateTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateTransferJobAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a transfer job. Updating a job's transfer spec does not affect /// transfer operations that are running already. Updating the scheduling /// of a job is not allowed. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> UpdateTransferJobAsync(global::Google.Storagetransfer.V1.UpdateTransferJobRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateTransferJob, null, options, request); } /// <summary> /// Gets a transfer job. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob GetTransferJob(global::Google.Storagetransfer.V1.GetTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetTransferJob(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a transfer job. /// </summary> public virtual global::Google.Storagetransfer.V1.TransferJob GetTransferJob(global::Google.Storagetransfer.V1.GetTransferJobRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetTransferJob, null, options, request); } /// <summary> /// Gets a transfer job. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> GetTransferJobAsync(global::Google.Storagetransfer.V1.GetTransferJobRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetTransferJobAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a transfer job. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.TransferJob> GetTransferJobAsync(global::Google.Storagetransfer.V1.GetTransferJobRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetTransferJob, null, options, request); } /// <summary> /// Lists transfer jobs. /// </summary> public virtual global::Google.Storagetransfer.V1.ListTransferJobsResponse ListTransferJobs(global::Google.Storagetransfer.V1.ListTransferJobsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTransferJobs(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists transfer jobs. /// </summary> public virtual global::Google.Storagetransfer.V1.ListTransferJobsResponse ListTransferJobs(global::Google.Storagetransfer.V1.ListTransferJobsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTransferJobs, null, options, request); } /// <summary> /// Lists transfer jobs. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.ListTransferJobsResponse> ListTransferJobsAsync(global::Google.Storagetransfer.V1.ListTransferJobsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTransferJobsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists transfer jobs. /// </summary> public virtual AsyncUnaryCall<global::Google.Storagetransfer.V1.ListTransferJobsResponse> ListTransferJobsAsync(global::Google.Storagetransfer.V1.ListTransferJobsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTransferJobs, null, options, request); } /// <summary> /// Pauses a transfer operation. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty PauseTransferOperation(global::Google.Storagetransfer.V1.PauseTransferOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PauseTransferOperation(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Pauses a transfer operation. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty PauseTransferOperation(global::Google.Storagetransfer.V1.PauseTransferOperationRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PauseTransferOperation, null, options, request); } /// <summary> /// Pauses a transfer operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PauseTransferOperationAsync(global::Google.Storagetransfer.V1.PauseTransferOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PauseTransferOperationAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Pauses a transfer operation. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PauseTransferOperationAsync(global::Google.Storagetransfer.V1.PauseTransferOperationRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PauseTransferOperation, null, options, request); } /// <summary> /// Resumes a transfer operation that is paused. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty ResumeTransferOperation(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ResumeTransferOperation(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Resumes a transfer operation that is paused. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty ResumeTransferOperation(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ResumeTransferOperation, null, options, request); } /// <summary> /// Resumes a transfer operation that is paused. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ResumeTransferOperationAsync(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ResumeTransferOperationAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Resumes a transfer operation that is paused. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ResumeTransferOperationAsync(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ResumeTransferOperation, null, options, request); } protected override StorageTransferServiceClient NewInstance(ClientBaseConfiguration configuration) { return new StorageTransferServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(StorageTransferServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetGoogleServiceAccount, serviceImpl.GetGoogleServiceAccount) .AddMethod(__Method_CreateTransferJob, serviceImpl.CreateTransferJob) .AddMethod(__Method_UpdateTransferJob, serviceImpl.UpdateTransferJob) .AddMethod(__Method_GetTransferJob, serviceImpl.GetTransferJob) .AddMethod(__Method_ListTransferJobs, serviceImpl.ListTransferJobs) .AddMethod(__Method_PauseTransferOperation, serviceImpl.PauseTransferOperation) .AddMethod(__Method_ResumeTransferOperation, serviceImpl.ResumeTransferOperation).Build(); } } } #endregion
using System; using Umbraco.Core.Logging; using System.IO; using System.Linq; using Umbraco.Core.IO; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Events; namespace Umbraco.Core.Services { /// <summary> /// These are used currently to return the temporary 'operation' interfaces for services /// which are used to return a status from operational methods so we can determine if things are /// cancelled, etc... /// /// These will be obsoleted in v8 since all real services methods will be changed to have the correct result. /// </summary> public static class ServiceWithResultExtensions { public static IContentServiceOperations WithResult(this IContentService contentService) { return (IContentServiceOperations)contentService; } public static IMediaServiceOperations WithResult(this IMediaService mediaService) { return (IMediaServiceOperations)mediaService; } } /// <summary> /// The Umbraco ServiceContext, which provides access to the following services: /// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>, /// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>. /// </summary> public class ServiceContext { private Lazy<IMigrationEntryService> _migrationEntryService; private Lazy<IPublicAccessService> _publicAccessService; private Lazy<ITaskService> _taskService; private Lazy<IDomainService> _domainService; private Lazy<IAuditService> _auditService; private Lazy<ILocalizedTextService> _localizedTextService; private Lazy<ITagService> _tagService; private Lazy<IContentService> _contentService; private Lazy<IUserService> _userService; private Lazy<IMemberService> _memberService; private Lazy<IMediaService> _mediaService; private Lazy<IContentTypeService> _contentTypeService; private Lazy<IDataTypeService> _dataTypeService; private Lazy<IFileService> _fileService; private Lazy<ILocalizationService> _localizationService; private Lazy<IPackagingService> _packagingService; private Lazy<IServerRegistrationService> _serverRegistrationService; private Lazy<IEntityService> _entityService; private Lazy<IRelationService> _relationService; private Lazy<IApplicationTreeService> _treeService; private Lazy<ISectionService> _sectionService; private Lazy<IMacroService> _macroService; private Lazy<IMemberTypeService> _memberTypeService; private Lazy<IMemberGroupService> _memberGroupService; private Lazy<INotificationService> _notificationService; private Lazy<IExternalLoginService> _externalLoginService; private Lazy<IRedirectUrlService> _redirectUrlService; internal IdkMap IdkMap { get; private set; } /// <summary> /// public ctor - will generally just be used for unit testing all items are optional and if not specified, the defaults will be used /// </summary> /// <param name="contentService"></param> /// <param name="mediaService"></param> /// <param name="contentTypeService"></param> /// <param name="dataTypeService"></param> /// <param name="fileService"></param> /// <param name="localizationService"></param> /// <param name="packagingService"></param> /// <param name="entityService"></param> /// <param name="relationService"></param> /// <param name="memberGroupService"></param> /// <param name="memberTypeService"></param> /// <param name="memberService"></param> /// <param name="userService"></param> /// <param name="sectionService"></param> /// <param name="treeService"></param> /// <param name="tagService"></param> /// <param name="notificationService"></param> /// <param name="localizedTextService"></param> /// <param name="auditService"></param> /// <param name="domainService"></param> /// <param name="taskService"></param> /// <param name="macroService"></param> /// <param name="publicAccessService"></param> /// <param name="externalLoginService"></param> /// <param name="migrationEntryService"></param> /// <param name="redirectUrlService"></param> public ServiceContext( IContentService contentService = null, IMediaService mediaService = null, IContentTypeService contentTypeService = null, IDataTypeService dataTypeService = null, IFileService fileService = null, ILocalizationService localizationService = null, IPackagingService packagingService = null, IEntityService entityService = null, IRelationService relationService = null, IMemberGroupService memberGroupService = null, IMemberTypeService memberTypeService = null, IMemberService memberService = null, IUserService userService = null, ISectionService sectionService = null, IApplicationTreeService treeService = null, ITagService tagService = null, INotificationService notificationService = null, ILocalizedTextService localizedTextService = null, IAuditService auditService = null, IDomainService domainService = null, ITaskService taskService = null, IMacroService macroService = null, IPublicAccessService publicAccessService = null, IExternalLoginService externalLoginService = null, IMigrationEntryService migrationEntryService = null, IRedirectUrlService redirectUrlService = null) { if (migrationEntryService != null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => migrationEntryService); if (externalLoginService != null) _externalLoginService = new Lazy<IExternalLoginService>(() => externalLoginService); if (auditService != null) _auditService = new Lazy<IAuditService>(() => auditService); if (localizedTextService != null) _localizedTextService = new Lazy<ILocalizedTextService>(() => localizedTextService); if (tagService != null) _tagService = new Lazy<ITagService>(() => tagService); if (contentService != null) _contentService = new Lazy<IContentService>(() => contentService); if (mediaService != null) _mediaService = new Lazy<IMediaService>(() => mediaService); if (contentTypeService != null) _contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService); if (dataTypeService != null) _dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService); if (fileService != null) _fileService = new Lazy<IFileService>(() => fileService); if (localizationService != null) _localizationService = new Lazy<ILocalizationService>(() => localizationService); if (packagingService != null) _packagingService = new Lazy<IPackagingService>(() => packagingService); if (entityService != null) _entityService = new Lazy<IEntityService>(() => entityService); if (relationService != null) _relationService = new Lazy<IRelationService>(() => relationService); if (sectionService != null) _sectionService = new Lazy<ISectionService>(() => sectionService); if (memberGroupService != null) _memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService); if (memberTypeService != null) _memberTypeService = new Lazy<IMemberTypeService>(() => memberTypeService); if (treeService != null) _treeService = new Lazy<IApplicationTreeService>(() => treeService); if (memberService != null) _memberService = new Lazy<IMemberService>(() => memberService); if (userService != null) _userService = new Lazy<IUserService>(() => userService); if (notificationService != null) _notificationService = new Lazy<INotificationService>(() => notificationService); if (domainService != null) _domainService = new Lazy<IDomainService>(() => domainService); if (taskService != null) _taskService = new Lazy<ITaskService>(() => taskService); if (macroService != null) _macroService = new Lazy<IMacroService>(() => macroService); if (publicAccessService != null) _publicAccessService = new Lazy<IPublicAccessService>(() => publicAccessService); if (redirectUrlService != null) _redirectUrlService = new Lazy<IRedirectUrlService>(() => redirectUrlService); } /// <summary> /// Creates a service context with a RepositoryFactory which is used to construct Services /// </summary> /// <param name="repositoryFactory"></param> /// <param name="provider"></param> /// <param name="cache"></param> /// <param name="logger"></param> /// <param name="eventMessagesFactory"></param> public ServiceContext( RepositoryFactory repositoryFactory, IScopeUnitOfWorkProvider provider, CacheHelper cache, ILogger logger, IEventMessagesFactory eventMessagesFactory) { if (repositoryFactory == null) throw new ArgumentNullException("repositoryFactory"); if (provider == null) throw new ArgumentNullException("provider"); if (cache == null) throw new ArgumentNullException("cache"); if (logger == null) throw new ArgumentNullException("logger"); if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory"); EventMessagesFactory = eventMessagesFactory; IdkMap = new IdkMap(provider); BuildServiceCache(provider, cache, repositoryFactory, logger, eventMessagesFactory, IdkMap); } /// <summary> /// Builds the various services /// </summary> private void BuildServiceCache( IScopeUnitOfWorkProvider provider, CacheHelper cache, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IdkMap idkMap) { EventMessagesFactory = eventMessagesFactory; if (_migrationEntryService == null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => new MigrationEntryService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_externalLoginService == null) _externalLoginService = new Lazy<IExternalLoginService>(() => new ExternalLoginService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_publicAccessService == null) _publicAccessService = new Lazy<IPublicAccessService>(() => new PublicAccessService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_taskService == null) _taskService = new Lazy<ITaskService>(() => new TaskService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_domainService == null) _domainService = new Lazy<IDomainService>(() => new DomainService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_auditService == null) _auditService = new Lazy<IAuditService>(() => new AuditService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_localizedTextService == null) { _localizedTextService = new Lazy<ILocalizedTextService>(() => new LocalizedTextService( new Lazy<LocalizedTextServiceFileSources>(() => { var mainLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); var appPlugins = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)); var configLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config + "/lang/")); var pluginLangFolders = appPlugins.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : appPlugins.GetDirectories() .SelectMany(x => x.GetDirectories("Lang")) .SelectMany(x => x.GetFiles("*.xml", SearchOption.TopDirectoryOnly)) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 5) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, false)); //user defined langs that overwrite the default, these should not be used by plugin creators var userLangFolders = configLangFolder.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : configLangFolder .GetFiles("*.user.xml", SearchOption.TopDirectoryOnly) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 10) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true)); return new LocalizedTextServiceFileSources( logger, cache.RuntimeCache, mainLangFolder, pluginLangFolders.Concat(userLangFolders)); }), logger)); } if (_notificationService == null) _notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger)); if (_serverRegistrationService == null) _serverRegistrationService = new Lazy<IServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_userService == null) _userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberService == null) _memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory, logger, eventMessagesFactory, _memberGroupService.Value, _dataTypeService.Value)); if (_contentService == null) _contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory, logger, eventMessagesFactory, _dataTypeService.Value, _userService.Value)); if (_mediaService == null) _mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory, logger, eventMessagesFactory, _dataTypeService.Value, _userService.Value)); if (_contentTypeService == null) _contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _contentService.Value, _mediaService.Value)); if (_dataTypeService == null) _dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_fileService == null) _fileService = new Lazy<IFileService>(() => new FileService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_localizationService == null) _localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_entityService == null) _entityService = new Lazy<IEntityService>(() => new EntityService( provider, repositoryFactory, logger, eventMessagesFactory, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value, idkMap)); if (_packagingService == null) _packagingService = new Lazy<IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _entityService.Value, _userService.Value, repositoryFactory, provider)); if (_relationService == null) _relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory, logger, eventMessagesFactory, _entityService.Value)); if (_treeService == null) _treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(logger, cache)); if (_sectionService == null) _sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, provider, cache)); if (_macroService == null) _macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberTypeService == null) _memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory, logger, eventMessagesFactory, _memberService.Value)); if (_tagService == null) _tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_memberGroupService == null) _memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory, logger, eventMessagesFactory)); if (_redirectUrlService == null) _redirectUrlService = new Lazy<IRedirectUrlService>(() => new RedirectUrlService(provider, repositoryFactory, logger, eventMessagesFactory)); } internal IEventMessagesFactory EventMessagesFactory { get; private set; } /// <summary> /// Gets the <see cref="IMigrationEntryService"/> /// </summary> public IMigrationEntryService MigrationEntryService { get { return _migrationEntryService.Value; } } /// <summary> /// Gets the <see cref="IPublicAccessService"/> /// </summary> public IPublicAccessService PublicAccessService { get { return _publicAccessService.Value; } } /// <summary> /// Gets the <see cref="ITaskService"/> /// </summary> public ITaskService TaskService { get { return _taskService.Value; } } /// <summary> /// Gets the <see cref="IDomainService"/> /// </summary> public IDomainService DomainService { get { return _domainService.Value; } } /// <summary> /// Gets the <see cref="IAuditService"/> /// </summary> public IAuditService AuditService { get { return _auditService.Value; } } /// <summary> /// Gets the <see cref="ILocalizedTextService"/> /// </summary> public ILocalizedTextService TextService { get { return _localizedTextService.Value; } } /// <summary> /// Gets the <see cref="INotificationService"/> /// </summary> public INotificationService NotificationService { get { return _notificationService.Value; } } /// <summary> /// Gets the <see cref="ServerRegistrationService"/> /// </summary> public IServerRegistrationService ServerRegistrationService { get { return _serverRegistrationService.Value; } } /// <summary> /// Gets the <see cref="ITagService"/> /// </summary> public ITagService TagService { get { return _tagService.Value; } } /// <summary> /// Gets the <see cref="IMacroService"/> /// </summary> public IMacroService MacroService { get { return _macroService.Value; } } /// <summary> /// Gets the <see cref="IEntityService"/> /// </summary> public IEntityService EntityService { get { return _entityService.Value; } } /// <summary> /// Gets the <see cref="IRelationService"/> /// </summary> public IRelationService RelationService { get { return _relationService.Value; } } /// <summary> /// Gets the <see cref="IContentService"/> /// </summary> public IContentService ContentService { get { return _contentService.Value; } } /// <summary> /// Gets the <see cref="IContentTypeService"/> /// </summary> public IContentTypeService ContentTypeService { get { return _contentTypeService.Value; } } /// <summary> /// Gets the <see cref="IDataTypeService"/> /// </summary> public IDataTypeService DataTypeService { get { return _dataTypeService.Value; } } /// <summary> /// Gets the <see cref="IFileService"/> /// </summary> public IFileService FileService { get { return _fileService.Value; } } /// <summary> /// Gets the <see cref="ILocalizationService"/> /// </summary> public ILocalizationService LocalizationService { get { return _localizationService.Value; } } /// <summary> /// Gets the <see cref="IMediaService"/> /// </summary> public IMediaService MediaService { get { return _mediaService.Value; } } /// <summary> /// Gets the <see cref="PackagingService"/> /// </summary> public IPackagingService PackagingService { get { return _packagingService.Value; } } /// <summary> /// Gets the <see cref="UserService"/> /// </summary> public IUserService UserService { get { return _userService.Value; } } /// <summary> /// Gets the <see cref="MemberService"/> /// </summary> public IMemberService MemberService { get { return _memberService.Value; } } /// <summary> /// Gets the <see cref="SectionService"/> /// </summary> public ISectionService SectionService { get { return _sectionService.Value; } } /// <summary> /// Gets the <see cref="ApplicationTreeService"/> /// </summary> public IApplicationTreeService ApplicationTreeService { get { return _treeService.Value; } } /// <summary> /// Gets the MemberTypeService /// </summary> public IMemberTypeService MemberTypeService { get { return _memberTypeService.Value; } } /// <summary> /// Gets the MemberGroupService /// </summary> public IMemberGroupService MemberGroupService { get { return _memberGroupService.Value; } } public IExternalLoginService ExternalLoginService { get { return _externalLoginService.Value; } } /// <summary> /// Gets the RedirectUrlService. /// </summary> public IRedirectUrlService RedirectUrlService { get { return _redirectUrlService.Value; } } } }
using System.Linq; using System.Reflection; using System.Web.Mvc; using NGM.Forum.Models; using NGM.Forum.Extensions; using NGM.Forum.Services; using Orchard; using Orchard.ContentManagement; using Orchard.DisplayManagement; using Orchard.Localization; using Orchard.Settings; using Orchard.UI.Admin; using Orchard.UI.Navigation; using Orchard.UI.Notify; namespace NGM.Forum.Controllers { [ValidateInput(false), Admin] public class ForumAdminController : Controller, IUpdateModel { private readonly IOrchardServices _orchardServices; private readonly IForumService _forumService; private readonly IThreadService _threadService; private readonly ISiteService _siteService; private readonly IContentManager _contentManager; public ForumAdminController(IOrchardServices orchardServices, IForumService forumService, IThreadService threadService, ISiteService siteService, IContentManager contentManager, IShapeFactory shapeFactory) { _orchardServices = orchardServices; _forumService = forumService; _threadService = threadService; _siteService = siteService; _contentManager = contentManager; T = NullLocalizer.Instance; Shape = shapeFactory; } dynamic Shape { get; set; } public Localizer T { get; set; } public ActionResult Create(string type) { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); if (string.IsNullOrWhiteSpace(type)) { var forumTypes = _forumService.GetForumTypes(); if (forumTypes.Count > 1) return Redirect(Url.ForumSelectTypeForAdmin()); if (forumTypes.Count == 0) { _orchardServices.Notifier.Warning(T("You have no forum types available. Add one to create a forum.")); return Redirect(Url.DashboardForAdmin()); } type = forumTypes.Single().Name; } var forum = _contentManager.New<ForumPart>(type); if (forum == null) return HttpNotFound(); var model = _contentManager.BuildEditor(forum); return View((object)model); } public ActionResult SelectType() { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); var forumTypes = _forumService.GetForumTypes(); var model = Shape.ViewModel(ForumTypes: forumTypes); return View(model); } [HttpPost, ActionName("Create")] public ActionResult CreatePOST(string type) { if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, T("Not allowed to create forums"))) return new HttpUnauthorizedResult(); if (string.IsNullOrWhiteSpace(type)) { var forumTypes = _forumService.GetForumTypes(); if (forumTypes.Count > 1) return Redirect(Url.ForumSelectTypeForAdmin()); if (forumTypes.Count == 0) { _orchardServices.Notifier.Warning(T("You have no forum types available. Add one to create a forum.")); return Redirect(Url.DashboardForAdmin()); } type = forumTypes.Single().Name; } var forum = _contentManager.New<ForumPart>(type); _contentManager.Create(forum, VersionOptions.Draft); var model = _contentManager.UpdateEditor(forum, this); if (!ModelState.IsValid) { _orchardServices.TransactionManager.Cancel(); return View((object)model); } _contentManager.Publish(forum.ContentItem); return Redirect(Url.ForumForAdmin(forum)); } public ActionResult Edit(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); dynamic model = _contentManager.BuildEditor(forum); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Edit")] [InternalFormValueRequired("submit.Save")] public ActionResult EditPOST(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.DraftRequired); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); dynamic model = _contentManager.UpdateEditor(forum, this); if (!ModelState.IsValid) { _orchardServices.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } _contentManager.Publish(forum.ContentItem); _orchardServices.Notifier.Information(T("Forum information updated")); return Redirect(Url.ForumsForAdmin()); } [HttpPost, ActionName("Edit")] [InternalFormValueRequired("submit.Delete")] public ActionResult EditDeletePOST(int forumId) { return Remove(forumId); } [HttpPost] public ActionResult Remove(int forumId) { var forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to edit forum"))) return new HttpUnauthorizedResult(); _forumService.Delete(forum); _orchardServices.Notifier.Information(T("Forum was successfully deleted")); return Redirect(Url.ForumsForAdmin()); } public ActionResult List() { var list = _orchardServices.New.List(); list.AddRange(_forumService.Get(VersionOptions.Latest) .Select(b => { var forum = _contentManager.BuildDisplay(b, "SummaryAdmin"); forum.TotalPostCount = _threadService.Get(b, VersionOptions.Latest).Count(); return forum; })); dynamic viewModel = _orchardServices.New.ViewModel() .ContentItems(list); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)viewModel); } public ActionResult Item(int forumId, PagerParameters pagerParameters) { Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); ForumPart forum = _forumService.Get(forumId, VersionOptions.Latest); if (forum == null) return HttpNotFound(); if (!_orchardServices.Authorizer.Authorize(Permissions.ManageForums, forum, T("Not allowed to view forum"))) return new HttpUnauthorizedResult(); var threads = _threadService.Get(forum, pager.GetStartIndex(), pager.PageSize, VersionOptions.Latest).ToArray(); var threadsShapes = threads.Select(bp => _contentManager.BuildDisplay(bp, "SummaryAdmin")).ToArray(); dynamic forumShape = _contentManager.BuildDisplay(forum, "DetailAdmin"); var list = Shape.List(); list.AddRange(threadsShapes); forumShape.Content.Add(Shape.Parts_Forums_Thread_ListAdmin(ContentItems: list), "5"); var totalItemCount = _threadService.Count(forum, VersionOptions.Latest); forumShape.Content.Add(Shape.Pager(pager).TotalItemCount(totalItemCount), "Content:after"); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)forumShape); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } public class InternalFormValueRequiredAttribute : ActionMethodSelectorAttribute { private readonly string _submitButtonName; public InternalFormValueRequiredAttribute(string submitButtonName) { _submitButtonName = submitButtonName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { var value = controllerContext.HttpContext.Request.Form[_submitButtonName]; return !string.IsNullOrEmpty(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.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions.Interpreter { internal abstract class SubInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Sub"; } } private SubInstruction() { } internal sealed class SubInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l - (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l - (Int16)r); } frame.StackIndex--; return +1; } } internal sealed class SubInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l - (Int64)r); } frame.StackIndex--; return +1; } } internal sealed class SubUInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l - (UInt16)r); } frame.StackIndex--; return +1; } } internal sealed class SubUInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l - (UInt32)r); } frame.StackIndex--; return +1; } } internal sealed class SubUInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((UInt64)l - (UInt64)r); } frame.StackIndex--; return +1; } } internal sealed class SubSingle : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); } frame.StackIndex--; return +1; } } internal sealed class SubDouble : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); case TypeCode.Single: return s_single ?? (s_single = new SubSingle()); case TypeCode.Double: return s_double ?? (s_double = new SubDouble()); default: throw Error.ExpressionNotSupportedForType("Sub", type); } } public override string ToString() { return "Sub()"; } } internal abstract class SubOvfInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "SubOvf"; } } private SubOvfInstruction() { } internal sealed class SubOvfInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l - (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l - (Int16)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l - (Int64)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l - (UInt16)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l - (UInt32)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l - (Int16)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfSingle : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfDouble : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubOvfInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubOvfInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); case TypeCode.Single: return s_single ?? (s_single = new SubOvfSingle()); case TypeCode.Double: return s_double ?? (s_double = new SubOvfDouble()); default: throw Error.ExpressionNotSupportedForType("SubOvf", type); } } public override string ToString() { return "SubOvf()"; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WpfView.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The wpf view. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper.View { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Management.Instrumentation; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using Minesweeper.Models; using Minesweeper.Models.Interfaces; using Minesweeper.Views; using WpfMinesweeper.Models; using WpfMinesweeper.Properties; /// <summary> /// The Windows Presentation Foundation view. /// </summary> public class WpfView : IMinesweeperView { /// <summary> /// The cell height and width. /// </summary> private const int CellHeightAndWidth = 20; /// <summary> /// The buttons. /// </summary> private readonly List<WpfMinesweeperButton> buttons; /// <summary> /// The images. /// </summary> private readonly List<ImageBrush> images; /// <summary> /// The win grid. /// </summary> private readonly Grid win; /// <summary> /// The is grid initialized. /// </summary> private bool isGridInitialized; /// <summary> /// The last column. /// </summary> private int lastCol; /// <summary> /// The last row. /// </summary> private int lastRow; /// <summary> /// Initializes a new instance of the <see cref="WpfView"/> class. /// </summary> /// <param name="window"> /// The window. /// </param> public WpfView(Grid window) { // Keep global grid for later use this.win = window; this.isGridInitialized = false; // Keep reference to all grid buttons this.buttons = new List<WpfMinesweeperButton>(); // Initialize all resource pictures, and keep them in ram for performance this.images = new List<ImageBrush> { ImageFactory.CreateImage(Resources.mine), ImageFactory.CreateImage(Resources.flag) }; } /// <summary> /// The add player event. /// </summary> public event EventHandler AddPlayerEvent; /// <summary> /// The open cell event. /// </summary> public event EventHandler OpenCellEvent; /// <summary> /// The protect cell event. /// </summary> public event EventHandler ProtectCellEvent; /// <summary> /// The show score board event. /// </summary> public event EventHandler ShowScoreBoardEvent; /// <summary> /// The display time. /// </summary> /// <param name="timer"> /// The game timer. /// </param> public void DisplayTime(int timer) { var timeLabel = (Label)this.win.FindName("TimeLabel"); if (timeLabel == null) { throw new InstanceNotFoundException("Cannot find time label element!"); } timeLabel.Content = timer.ToString("D3"); } /// <summary> /// The display moves. /// </summary> /// <param name="moves"> /// The game moves. /// </param> public void DisplayMoves(int moves) { var movesLabel = (Label)this.win.FindName("ScoreLabel"); if (movesLabel == null) { throw new InstanceNotFoundException("Cannot find time label element!"); } movesLabel.Content = moves.ToString("D3"); } /// <summary> /// The display score board. /// </summary> /// <param name="board"> /// The score board. /// </param> public void DisplayScoreBoard(List<MinesweeperPlayer> board) { var scoresWindow = new ScoresWindow(board); scoresWindow.Show(); } /// <summary> /// The display grid. /// </summary> /// <param name="grid"> /// The game grid. /// </param> public void DisplayGrid(IMinesweeperGrid grid) { var rows = grid.Rows; var cols = grid.Cols; if (grid.NeighborMinesCount(this.lastRow, this.lastCol) == 0) { this.isGridInitialized = false; } if (this.isGridInitialized) { var i = this.lastRow; var j = this.lastCol; var button = this.buttons.First(x => x.Name == "Button_" + i.ToString() + "_" + j.ToString()); this.UpdateCellButton(grid, button); } else { this.buttons.Clear(); this.win.Children.Clear(); for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { var button = new WpfMinesweeperButton { Row = rows, Col = cols }; button.Name = "Button_" + i + "_" + j; button.HorizontalAlignment = HorizontalAlignment.Left; button.VerticalAlignment = VerticalAlignment.Top; button.Width = CellHeightAndWidth; button.Height = CellHeightAndWidth; button.Margin = new Thickness(i * CellHeightAndWidth, j * CellHeightAndWidth, 0, 0); button.Click += this.CellButtonClick; button.MouseRightButtonUp += this.ButtonOnMouseRightButtonUp; button.Row = i; button.Col = j; this.UpdateCellButton(grid, button); this.win.Children.Add(button); this.buttons.Add(button); } } this.isGridInitialized = true; } } /// <summary> /// The display game over. /// </summary> /// <param name="gameResult"> /// The game result. /// </param> public void DisplayGameOver(bool gameResult) { this.isGridInitialized = false; if (gameResult == false) { MessageBox.Show("Game Over!", "Minesweeper", MessageBoxButton.OK, MessageBoxImage.Error); } else { var unprotectedButtons = this.buttons.Where(b => (string)b.Content == string.Empty); foreach (var upb in unprotectedButtons) { upb.Background = this.images[1]; } var protectedButtons = this.buttons.Where(b => b.Background.Equals(this.images[1])); foreach (var pb in protectedButtons) { pb.IsHitTestVisible = false; } var inputBox = new InputBox(this.PlayerAdd); inputBox.Show(); } } /// <summary> /// The score item click. /// </summary> public void ScoreItemClick() { if (this.ShowScoreBoardEvent != null) { this.ShowScoreBoardEvent.Invoke(this, EventArgs.Empty); } } /// <summary> /// The update cell button. /// </summary> /// <param name="grid"> /// The game grid. /// </param> /// <param name="button"> /// The button. /// </param> private void UpdateCellButton(IMinesweeperGrid grid, WpfMinesweeperButton button) { var i = button.Row; var j = button.Col; var color = new System.Windows.Media.Color(); if (grid.IsCellProtected(i, j)) { button.Background = this.images[1]; } else if (grid.IsCellRevealed(i, j)) { button.ClearValue(Control.BackgroundProperty); button.Background = new SolidColorBrush(Colors.LightGray); if (grid.HasCellBomb(i, j)) { button.Background = this.images[0]; } else { switch (grid.NeighborMinesCount(i, j)) { case 1: color = Colors.Blue; break; case 2: color = Colors.Green; break; case 3: color = Colors.Red; break; case 4: color = Colors.Indigo; break; case 5: color = Colors.DarkSlateGray; break; case 6: color = Colors.DarkRed; break; case 7: color = Colors.DarkBlue; break; case 8: color = Colors.Black; break; } if (grid.NeighborMinesCount(i, j) != 0) { button.Content = grid.NeighborMinesCount(i, j).ToString(); button.Foreground = new SolidColorBrush(color); } } button.IsHitTestVisible = false; } else { button.Background = new SolidColorBrush(Colors.AliceBlue); button.Content = string.Empty; } } /// <summary> /// The player add. /// </summary> /// <param name="name"> /// The player name. /// </param> private void PlayerAdd(string name) { var movesLabel = (Label)this.win.FindName("ScoreLabel"); var timeLabel = (Label)this.win.FindName("TimeLabel"); if (movesLabel == null || timeLabel == null) { throw new NullReferenceException("Move or time labels are not available!"); } var args = new MinesweeperAddPlayerEventArgs { PlayerName = name }; if (this.AddPlayerEvent != null) { this.AddPlayerEvent.Invoke(this, args); } } /// <summary> /// The button on mouse right button up. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="mouseButtonEventArgs"> /// The mouse button event args. /// </param> private void ButtonOnMouseRightButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs) { if ((sender as WpfMinesweeperButton) == null) { throw new NullReferenceException("No object given!"); } var args = new MinesweeperCellClickEventArgs { Row = ((WpfMinesweeperButton)sender).Row, Col = ((WpfMinesweeperButton)sender).Col }; this.lastCol = args.Col; this.lastRow = args.Row; if (this.ProtectCellEvent != null) { this.ProtectCellEvent.Invoke(this, args); } } /// <summary> /// The button_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The click event. /// </param> private void CellButtonClick(object sender, RoutedEventArgs e) { if ((sender as WpfMinesweeperButton) == null) { throw new NullReferenceException("No object given!"); } var args = new MinesweeperCellClickEventArgs { Row = ((WpfMinesweeperButton)sender).Row, Col = ((WpfMinesweeperButton)sender).Col }; this.lastCol = args.Col; this.lastRow = args.Row; if (this.OpenCellEvent != null) { this.OpenCellEvent.Invoke(this, 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; using System.Collections; using System.Runtime.InteropServices; public enum TestEnum { red = 1, green = 2, blue = 4, } [StructLayout(LayoutKind.Sequential)] public struct AA { public object m_objField1; public static long Static1(Array param1, ushort[,] param2, ref int[,,][,,] param3, ulong[,] param4, float[][,,] param5) { long[,] local1 = (new long[100u, 30u]); #pragma warning disable 1718 while ((param1 != param1)) #pragma warning restore 1718 { for (App.m_lFwd1 = ((long)(6.0)); App.m_bFwd2; App.m_ulFwd3 -= ((ulong)(8u))) { byte local2 = App.m_byFwd4; do { long[,,,] local3 = (new long[4u, 68u, 35u, 15u]); while (App.m_bFwd2) { #pragma warning disable 1717 param1 = (param1 = param1); #pragma warning restore 1717 param3 = ((int[,,][,,])(param1)); do { ulong local4 = ((ulong)(108.0f)); String[][][,,,,] local5 = (new String[14u][][,,,,]); #pragma warning disable 1718 for (App.m_sbyFwd5 *= App.m_sbyFwd5; (local4 != local4); App.m_fFwd6 = 28.0f ) #pragma warning restore 1718 { bool[][][,,,] local6 = new bool[][][,,,] { (new bool[53u][,,,]) }; char local7 = '\x6f'; } param4[((int)(108.0f)), 27] /= local4; } while ((param1 == null)); try { } catch (Exception) { bool local8 = true; TypedReference local9 = __makeref(App.m_chFwd7); } return ((long)(91.0f)); } } while (App.m_bFwd2); if ((null != param1)) if (App.m_bFwd2) for (App.m_uFwd8++; Convert.ToBoolean(local2); App.m_shFwd9 -= ((short)(61)) ) { float[,] local10 = (new float[16u, 15u]); } } if ((param1 != null)) for (App.m_fFwd6 *= 55.0f; App.m_bFwd2; App.m_sbyFwd5 -= ((sbyte)(122))) { object local11 = new AA().m_objField1; sbyte[,,][] local12 = (new sbyte[108u, 78u, 18u][]); } try { bool local13 = true; } catch (IndexOutOfRangeException) { AA[,,][,][] local14 = (new AA[71u, 60u, 84u][,][]); } } return App.m_lFwd1; } public static TestEnum[] Static2() { AA[,] local15 = (new AA[47u, 85u]); uint local16 = 106u; try { short[,,][,][] local17 = (new short[91u, 93u, 91u][,][]); try { ulong[] local18 = (new ulong[102u]); do { ushort[,,,,] local19 = (new ushort[29u, 107u, 46u, 25u, 125u]); char local20 = '\x3f'; if (App.m_bFwd2) #pragma warning disable 1718 if ((local16 != local16)) #pragma warning restore 1718 do { ushort[,] local21 = (new ushort[119u, 19u]); } while (App.m_bFwd2); local19[28, 103, ((int)(local20)), ((int)(60u)), 79] -= App.m_ushFwd10; try { float local22 = 29.0f; long local23 = App.m_lFwd1; } catch (Exception) { byte[,,][,,][][,] local24 = (new byte[27u, 16u, 23u][,,][][,]); TypedReference local25 = __makeref(App.m_axFwd11); } } while (App.m_bFwd2); local17[2, 27, 54][107, 25][3] = ((short)(local16)); local17[107, ((int)('\x11')), 115][97, ((int)(local16))][11] += ((short)(4.0 )); return new TestEnum[] { 0, TestEnum.blue }; } catch (IndexOutOfRangeException) { sbyte local26 = ((sbyte)(45)); short local27 = ((short)(80.0)); } AA.Static1( ((Array)(null)), (new ushort[79u, local16]), ref App.m_aiFwd12, (new ulong[30u, local16]), (new float[local16][,,])); } catch (InvalidOperationException) { } if (App.m_bFwd2) do { sbyte local28 = App.m_sbyFwd5; } while (App.m_bFwd2); else { } local15[47, ((int)(124.0f))] = new AA(); try { } catch (InvalidOperationException) { } if (App.m_bFwd2) local15[88, 123].m_objField1 = ((object)(true)); return (new TestEnum[local16]); } } public class App { private static int Main() { try { AA.Static1( ((Array)(null)), (new ushort[1u, 44u]), ref App.m_aiFwd12, (new ulong[107u, 41u]), new float[][,,] { (new float[87u, 93u, 100u]), (new float[27u, 39u, 9u]) }); } catch (Exception) { } try { AA.Static2(); } catch (Exception) { } return 100; } public static long m_lFwd1; public static bool m_bFwd2; public static ulong m_ulFwd3; public static byte m_byFwd4; public static sbyte m_sbyFwd5; public static float m_fFwd6; public static char m_chFwd7; public static uint m_uFwd8; public static short m_shFwd9; public static ushort m_ushFwd10; public static TestEnum[,] m_axFwd11; public static int[,,][,,] m_aiFwd12; }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Demo.Domain.Service.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* Copyright 2018 Backendless Corporation. and FUNX Corporation., All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 UnityEngine; using System; using System.Collections.Generic; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using BackendlessAPI; using BackendlessAPI.Engine; using Weborb.Client; using Weborb.Util; public class BackendlessPlugin : MonoBehaviour { #if ENABLE_PUSH_PLUGIN #if UNITY_ANDROID private static AndroidJavaObject activity = null; #elif UNITY_IOS || UNITY_TVOS [System.Runtime.InteropServices.DllImport("__Internal")] extern static public void setListenerGameObject(string listenerName); [System.Runtime.InteropServices.DllImport("__Internal")] extern static public void registerForRemoteNotifications(); [System.Runtime.InteropServices.DllImport("__Internal")] extern static public void unregisterForRemoteNotifications(); #endif #endif private static BackendlessPlugin _instance = null; public static BackendlessPlugin Instance { get { return _instance; } } public enum ENVIRONMENT { dev, prod } [SerializeField] private ENVIRONMENT version = ENVIRONMENT.dev; [SerializeField] private string DevelopmentAppID; [SerializeField] private string DevelopmentApiKey; [SerializeField] private string ProductionAppID; [SerializeField] private string ProductionApiKey; public string applicationId { get { return version == ENVIRONMENT.prod ? ProductionAppID : DevelopmentAppID; } set { } } public string APIKey { get { return version == ENVIRONMENT.prod ? ProductionApiKey : DevelopmentApiKey; } set { } } void Awake() { // This is needed so that the Unity client cannot connect to Backendless RT // Also, it is needed on Android, so it can communicate via HTTPS ServicePointManager.ServerCertificateValidationCallback = (p1, p2, p3, p4) => true; DontDestroyOnLoad(this); if (_instance == null) { _instance = this; } else { DestroyImmediate(this.gameObject); // avoid duplicate BackendlessPlugin GameObjects return; } Backendless.URL = "https://api.backendless.com"; // This redirects any logging inside of the Backendless SDK into Unity's Debug.log Weborb.Util.Logging.Log.addLogger( "unitylogger", new BackendlessPlugin.UnityLogger() ); // Initialize Backendless Backendless.InitApp(applicationId, APIKey ); // Default network timeout (this must be set after Backendless.InitApp) Backendless.Timeout = 30000; // 30 secs // Backendless.Data.MapTableToType("Devices", typeof(/* type of a class that models one of your tables on Backendless and inherits Backendless Entity */)); #if ENABLE_PUSH_PLUGIN Backendless.Messaging.SetUnityRegisterDevice(UnityRegisterDevice, UnityUnregisterDevice); #if UNITY_ANDROID && !UNITY_EDITOR AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = jc.GetStatic<AndroidJavaObject>("currentActivity"); activity.Call("setUnityGameObject", this.gameObject.name); #elif (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR setListenerGameObject(this.gameObject.name); #endif #endif #if UNITY_IOS || UNITY_TVOS || UNITY_ANDROID /* In order to use the .NET SDK we needed some hardcoded logic here to make sure some of its code was properly compiled for AOT on iOS. We'd get errors like the following when trying to delete the a record from a table. Error: Code = , Message = Attempting to call method 'Weborb.Client.HttpEngine::SendRequest<System.Int64>' for which no ahead of time (AOT) code was generated., Detail = UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object) UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[]) UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:LogError(Object) <FinalizeSellItem>c__AnonStoreyA5:<>m__C1(BackendlessFault) BackendlessAPI.Async.ErrorHandler:Invoke(BackendlessFault) BackendlessAPI.Engine.Invoker:InvokeAsync(String, String, Object[], Boolean, AsyncCallback`1) BackendlessAPI.Engine.Invoker:InvokeAsync(String, String, Object[], AsyncCallback`1) BackendlessAPI.Service.PersistenceService:Remove(T, AsyncCallback`1) BackendlessAPI.Data.DataStoreImpl`1:Remove(T, AsyncCallback`1) <FinalizeSellItem>c__AnonStoreyA5:<>m__BF() System.Action:Invoke() Loom:Update() */ try { IdInfo idInfo = new IdInfo(); HttpEngine httpEngine = new Weborb.Client.HttpEngine("http://api.backendless.com", idInfo); httpEngine.SendRequest<Boolean>(null, null, null, null, null); httpEngine.SendRequest<Int64>(null, null, null, null, null); } catch (Exception e) { // ignore } #endif } #if ENABLE_PUSH_PLUGIN public static void UnityRegisterDevice(string GCMSenderID, List<String> channels, DateTime? timestamp) { #if UNITY_ANDROID DateTime expiration = (timestamp == null ? new DateTime(0) : (DateTime) timestamp); activity.Call("registerDevice", GCMSenderID, expiration.Ticks); #elif UNITY_IOS registerForRemoteNotifications(); #endif } public static void UnityUnregisterDevice() { #if UNITY_ANDROID activity.Call("unregisterDevice"); #elif UNITY_IOS unregisterForRemoteNotifications(); #endif } void setDeviceToken(string deviceToken) { Backendless.Messaging.DeviceRegistration.DeviceToken = deviceToken; } void setDeviceId(string deviceId) { Backendless.Messaging.DeviceRegistration.DeviceId = deviceId; } void setOs(string os) { Backendless.Messaging.DeviceRegistration.Os = os; } void setOsVersion(string osVersion) { Backendless.Messaging.DeviceRegistration.OsVersion = osVersion; } void setExpiration(long expiration) { Backendless.Messaging.DeviceRegistration.Expiration = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(expiration); } void registerDeviceOnServer(string dummy) { Debug.Log("registerDeviceOnServer()"); Backendless.Messaging.RegisterDeviceOnServer(); } void unregisterDeviceOnServer(string dummy) { Debug.Log("unregisterDeviceOnServer()"); Backendless.Messaging.UnregisterDeviceOnServer(); } public void onDidFailToRegisterForRemoteNotificationsWithError(string error) { Debug.LogError("onDidFailToRegisterForRemoteNotificationsWithError() error=" + error); } void onPushMessage(string message) { Debug.Log("onPushMessage() message=" + message); } #endif private class UnityLogger : Weborb.Util.Logging.AbstractLogger { public override void fireEvent(string category, object eventObject, DateTime timestamp) { Debug.Log( String.Format("{0}: {1}- {2}", timestamp.ToShortTimeString(), category, eventObject )); } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="none" email=""/> // <version>$Revision: 3440 $</version> // </file> using System; using System.Drawing; using System.Text; namespace ICSharpCode.TextEditor.Document { public enum BracketMatchingStyle { Before, After } public class DefaultTextEditorProperties : ITextEditorProperties { int tabIndent = 4; int indentationSize = 4; IndentStyle indentStyle = IndentStyle.Smart; DocumentSelectionMode documentSelectionMode = DocumentSelectionMode.Normal; Encoding encoding = System.Text.Encoding.UTF8; BracketMatchingStyle bracketMatchingStyle = BracketMatchingStyle.After; FontContainer fontContainer; static Font DefaultFont; public DefaultTextEditorProperties() { if (DefaultFont == null) { DefaultFont = new Font("Courier New", 10); } this.fontContainer = new FontContainer(DefaultFont); } bool allowCaretBeyondEOL = false; bool caretLine = false; bool showMatchingBracket = true; bool showLineNumbers = true; bool showSpaces = false; bool showTabs = false; bool showEOLMarker = false; bool showInvalidLines = false; bool isIconBarVisible = false; bool enableFolding = true; bool showHorizontalRuler = false; bool showVerticalRuler = true; bool convertTabsToSpaces = false; System.Drawing.Text.TextRenderingHint textRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault; bool mouseWheelScrollDown = true; bool mouseWheelTextZoom = true; bool hideMouseCursor = false; bool cutCopyWholeLine = true; int verticalRulerRow = 80; LineViewerStyle lineViewerStyle = LineViewerStyle.None; string lineTerminator = "\r\n"; bool autoInsertCurlyBracket = true; bool supportReadOnlySegments = false; public int TabIndent { get { return tabIndent; } set { tabIndent = value; } } public int IndentationSize { get { return indentationSize; } set { indentationSize = value; } } public IndentStyle IndentStyle { get { return indentStyle; } set { indentStyle = value; } } public bool CaretLine { get { return caretLine; } set { caretLine = value; } } public DocumentSelectionMode DocumentSelectionMode { get { return documentSelectionMode; } set { documentSelectionMode = value; } } public bool AllowCaretBeyondEOL { get { return allowCaretBeyondEOL; } set { allowCaretBeyondEOL = value; } } public bool ShowMatchingBracket { get { return showMatchingBracket; } set { showMatchingBracket = value; } } public bool ShowLineNumbers { get { return showLineNumbers; } set { showLineNumbers = value; } } public bool ShowSpaces { get { return showSpaces; } set { showSpaces = value; } } public bool ShowTabs { get { return showTabs; } set { showTabs = value; } } public bool ShowEOLMarker { get { return showEOLMarker; } set { showEOLMarker = value; } } public bool ShowInvalidLines { get { return showInvalidLines; } set { showInvalidLines = value; } } public bool IsIconBarVisible { get { return isIconBarVisible; } set { isIconBarVisible = value; } } public bool EnableFolding { get { return enableFolding; } set { enableFolding = value; } } public bool ShowHorizontalRuler { get { return showHorizontalRuler; } set { showHorizontalRuler = value; } } public bool ShowVerticalRuler { get { return showVerticalRuler; } set { showVerticalRuler = value; } } public bool ConvertTabsToSpaces { get { return convertTabsToSpaces; } set { convertTabsToSpaces = value; } } public System.Drawing.Text.TextRenderingHint TextRenderingHint { get { return textRenderingHint; } set { textRenderingHint = value; } } public bool MouseWheelScrollDown { get { return mouseWheelScrollDown; } set { mouseWheelScrollDown = value; } } public bool MouseWheelTextZoom { get { return mouseWheelTextZoom; } set { mouseWheelTextZoom = value; } } public bool HideMouseCursor { get { return hideMouseCursor; } set { hideMouseCursor = value; } } public bool CutCopyWholeLine { get { return cutCopyWholeLine; } set { cutCopyWholeLine = value; } } public Encoding Encoding { get { return encoding; } set { encoding = value; } } public int VerticalRulerRow { get { return verticalRulerRow; } set { verticalRulerRow = value; } } public LineViewerStyle LineViewerStyle { get { return lineViewerStyle; } set { lineViewerStyle = value; } } public string LineTerminator { get { return lineTerminator; } set { lineTerminator = value; } } public bool AutoInsertCurlyBracket { get { return autoInsertCurlyBracket; } set { autoInsertCurlyBracket = value; } } public Font Font { get { return fontContainer.DefaultFont; } set { fontContainer.DefaultFont = value; } } public FontContainer FontContainer { get { return fontContainer; } } public BracketMatchingStyle BracketMatchingStyle { get { return bracketMatchingStyle; } set { bracketMatchingStyle = value; } } public bool SupportReadOnlySegments { get { return supportReadOnlySegments; } set { supportReadOnlySegments = value; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.InvokeDelegateWithConditionalAccess { public class InvokeDelegateWithConditionalAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new InvokeDelegateWithConditionalAccessAnalyzer(), new InvokeDelegateWithConditionalAccessCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task Test1() { await TestAsync( @"class C { System.Action a; void Foo() { [||]var v = a; if (v != null) { v(); } } }", @" class C { System.Action a; void Foo() { a?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestInvertedIf() { await TestAsync( @"class C { System.Action a; void Foo() { [||]var v = a; if (null != v) { v(); } } }", @" class C { System.Action a; void Foo() { a?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestIfWithNoBraces() { await TestAsync( @"class C { System.Action a; void Foo() { [||]var v = a; if (null != v) v(); } }", @" class C { System.Action a; void Foo() { a?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestWithComplexExpression() { await TestAsync( @"class C { System.Action a; void Foo() { bool b = true; [||]var v = b ? a : null; if (v != null) { v(); } } }", @" class C { System.Action a; void Foo() { bool b = true; (b ? a : null)?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingWithElseClause() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]var v = a; if (v != null) { v(); } else {} } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnDeclarationWithMultipleVariables() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]var v = a, x = a; if (v != null) { v(); } } }"); } /// <remarks> /// With multiple variables in the same declaration, the fix _is not_ offered on the declaration /// itself, but _is_ offered on the invocation pattern. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestLocationWhereOfferedWithMultipleVariables() { await TestAsync( @"class C { System.Action a; void Foo() { var v = a, x = a; [||]if (v != null) { v(); } } }", @"class C { System.Action a; void Foo() { var v = a, x = a; v?.Invoke(); } }"); } /// <remarks> /// If we have a variable declaration and if it is read/written outside the delegate /// invocation pattern, the fix is not offered on the declaration. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnDeclarationIfUsedOutside() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]var v = a; if (v != null) { v(); } v = null; } }"); } /// <remarks> /// If we have a variable declaration and if it is read/written outside the delegate /// invocation pattern, the fix is not offered on the declaration but is offered on /// the invocation pattern itself. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestLocationWhereOfferedIfUsedOutside() { await TestAsync( @"class C { System.Action a; void Foo() { var v = a; [||]if (v != null) { v(); } v = null; } }", @"class C { System.Action a; void Foo() { var v = a; v?.Invoke(); v = null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestSimpleForm1() { await TestAsync( @" using System; class C { public event EventHandler E; void M() { [||]if (this.E != null) { this.E(this, EventArgs.Empty); } } }", @" using System; class C { public event EventHandler E; void M() { this.E?.Invoke(this, EventArgs.Empty); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestInElseClause1() { await TestAsync( @" using System; class C { public event EventHandler E; void M() { if (true != true) { } else [||]if (this.E != null) { this.E(this, EventArgs.Empty); } } }", @" using System; class C { public event EventHandler E; void M() { if (true != true) { } else { this.E?.Invoke(this, EventArgs.Empty); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestInElseClause2() { await TestAsync( @" using System; class C { public event EventHandler E; void M() { if (true != true) { } else [||]if (this.E != null) this.E(this, EventArgs.Empty); } }", @" using System; class C { public event EventHandler E; void M() { if (true != true) { } else this.E?.Invoke(this, EventArgs.Empty); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestTrivia1() { await TestAsync( @"class C { System.Action a; void Foo() { // Comment [||]var v = a; if (v != null) { v(); } } }", @"class C { System.Action a; void Foo() { // Comment a?.Invoke(); } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestTrivia2() { await TestAsync( @"class C { System.Action a; void Foo() { // Comment [||]if (a != null) { a(); } } }", @"class C { System.Action a; void Foo() { // Comment a?.Invoke(); } }", compareTokens: false); } /// <remarks> /// tests locations where the fix is offered. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestFixOfferedOnIf() { await TestAsync( @"class C { System.Action a; void Foo() { var v = a; [||]if (v != null) { v(); } } }", @" class C { System.Action a; void Foo() { a?.Invoke(); } }"); } /// <remarks> /// tests locations where the fix is offered. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestFixOfferedInsideIf() { await TestAsync( @"class C { System.Action a; void Foo() { var v = a; if (v != null) { [||]v(); } } }", @" class C { System.Action a; void Foo() { a?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnConditionalInvocation() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]var v = a; v?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnConditionalInvocation2() { await TestMissingAsync( @"class C { System.Action a; void Foo() { var v = a; [||]v?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnConditionalInvocation3() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]a?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnNonNullCheckExpressions() { await TestMissingAsync( @"class C { System.Action a; void Foo() { var v = a; if (v == a) { [||]v(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnNonNullCheckExpressions2() { await TestMissingAsync( @"class C { System.Action a; void Foo() { var v = a; if (v == null) { [||]v(); } } }"); } /// <remarks> /// if local declaration is not immediately preceding the invocation pattern, /// the fix is not offered on the declaration. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestLocalNotImmediatelyPrecedingNullCheckAndInvokePattern() { await TestMissingAsync( @"class C { System.Action a; void Foo() { [||]var v = a; int x; if (v != null) { v(); } } }"); } /// <remarks> /// if local declaration is not immediately preceding the invocation pattern, /// the fix is not offered on the declaration but is offered on the invocation pattern itself. /// </remarks> [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestLocalDNotImmediatelyPrecedingNullCheckAndInvokePattern2() { await TestAsync( @"class C { System.Action a; void Foo() { var v = a; int x; [||]if (v != null) { v(); } } }", @"class C { System.Action a; void Foo() { var v = a; int x; v?.Invoke(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)] public async Task TestMissingOnFunc() { await TestMissingAsync( @"class C { System.Func<int> a; int Foo() { var v = a; [||]if (v != null) { return v(); } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.DirectoryServices.Protocols { public partial class AddRequest : System.DirectoryServices.Protocols.DirectoryRequest { public AddRequest() { } public AddRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public AddRequest(string distinguishedName, string objectClass) { } public System.DirectoryServices.Protocols.DirectoryAttributeCollection Attributes { get { return default(System.DirectoryServices.Protocols.DirectoryAttributeCollection); } } public string DistinguishedName { get { return default(string); } set { } } } public partial class AddResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal AddResponse() { } } public partial class AsqRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public AsqRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public AsqRequestControl(string attributeName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { return default(string); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class AsqResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal AsqResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ResultCode Result { get { return default(System.DirectoryServices.Protocols.ResultCode); } } } public enum AuthType { Anonymous = 0, Basic = 1, Digest = 4, Dpa = 6, External = 8, Kerberos = 9, Msn = 7, Negotiate = 2, Ntlm = 3, Sicily = 5, } public partial class BerConversionException : System.DirectoryServices.Protocols.DirectoryException { public BerConversionException() { } protected BerConversionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public BerConversionException(string message) { } public BerConversionException(string message, System.Exception inner) { } } public static partial class BerConverter { public static object[] Decode(string format, byte[] value) { return default(object[]); } public static byte[] Encode(string format, params object[] value) { return default(byte[]); } } public partial class CompareRequest : System.DirectoryServices.Protocols.DirectoryRequest { public CompareRequest() { } public CompareRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttribute assertion) { } public CompareRequest(string distinguishedName, string attributeName, byte[] value) { } public CompareRequest(string distinguishedName, string attributeName, string value) { } public CompareRequest(string distinguishedName, string attributeName, System.Uri value) { } public System.DirectoryServices.Protocols.DirectoryAttribute Assertion { get { return default(System.DirectoryServices.Protocols.DirectoryAttribute); } } public string DistinguishedName { get { return default(string); } set { } } } public partial class CompareResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal CompareResponse() { } } public partial class CrossDomainMoveControl : System.DirectoryServices.Protocols.DirectoryControl { public CrossDomainMoveControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public CrossDomainMoveControl(string targetDomainController) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string TargetDomainController { get { return default(string); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class DeleteRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DeleteRequest() { } public DeleteRequest(string distinguishedName) { } public string DistinguishedName { get { return default(string); } set { } } } public partial class DeleteResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal DeleteResponse() { } } public enum DereferenceAlias { Always = 3, FindingBaseObject = 2, InSearching = 1, Never = 0, } public delegate void DereferenceConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection connectionToDereference); public partial class DirectoryAttribute : System.Collections.CollectionBase { public DirectoryAttribute() { } public DirectoryAttribute(string name, byte[] value) { } public DirectoryAttribute(string name, params object[] values) { } public DirectoryAttribute(string name, string value) { } public DirectoryAttribute(string name, System.Uri value) { } public object this[int index] { get { return default(object); } set { } } public string Name { get { return default(string); } set { } } public int Add(byte[] value) { return default(int); } public int Add(string value) { return default(int); } public int Add(System.Uri value) { return default(int); } public void AddRange(object[] values) { } public bool Contains(object value) { return default(bool); } public void CopyTo(object[] array, int index) { } public object[] GetValues(System.Type valuesType) { return default(object[]); } public int IndexOf(object value) { return default(int); } public void Insert(int index, byte[] value) { } public void Insert(int index, string value) { } public void Insert(int index, System.Uri value) { } protected override void OnValidate(object value) { } public void Remove(object value) { } } public partial class DirectoryAttributeCollection : System.Collections.CollectionBase { public DirectoryAttributeCollection() { } public System.DirectoryServices.Protocols.DirectoryAttribute this[int index] { get { return default(System.DirectoryServices.Protocols.DirectoryAttribute); } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttribute attribute) { return default(int); } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeCollection attributeCollection) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttribute value) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttribute value) { return default(int); } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttribute value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttribute value) { } } public partial class DirectoryAttributeModification : System.DirectoryServices.Protocols.DirectoryAttribute { public DirectoryAttributeModification() { } public System.DirectoryServices.Protocols.DirectoryAttributeOperation Operation { get { return default(System.DirectoryServices.Protocols.DirectoryAttributeOperation); } set { } } } public partial class DirectoryAttributeModificationCollection : System.Collections.CollectionBase { public DirectoryAttributeModificationCollection() { } public System.DirectoryServices.Protocols.DirectoryAttributeModification this[int index] { get { return default(System.DirectoryServices.Protocols.DirectoryAttributeModification); } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttributeModification attribute) { return default(int); } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModification[] attributes) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection attributeCollection) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttributeModification[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { return default(int); } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } } public enum DirectoryAttributeOperation { Add = 0, Delete = 1, Replace = 2, } public abstract partial class DirectoryConnection { protected DirectoryConnection() { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection); } } public virtual System.Net.NetworkCredential Credential { set { } } public virtual System.DirectoryServices.Protocols.DirectoryIdentifier Directory { get { return default(System.DirectoryServices.Protocols.DirectoryIdentifier); } } public virtual System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } } public abstract System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request); } public partial class DirectoryControl { public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { } public bool IsCritical { get { return default(bool); } set { } } public bool ServerSide { get { return default(bool); } set { } } public string Type { get { return default(string); } } public virtual byte[] GetValue() { return default(byte[]); } } public partial class DirectoryControlCollection : System.Collections.CollectionBase { public DirectoryControlCollection() { } public System.DirectoryServices.Protocols.DirectoryControl this[int index] { get { return default(System.DirectoryServices.Protocols.DirectoryControl); } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryControl control) { return default(int); } public void AddRange(System.DirectoryServices.Protocols.DirectoryControl[] controls) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryControlCollection controlCollection) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryControl value) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.DirectoryControl[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryControl value) { return default(int); } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryControl value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryControl value) { } } public partial class DirectoryException : System.Exception { public DirectoryException() { } protected DirectoryException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryException(string message) { } public DirectoryException(string message, System.Exception inner) { } } public abstract partial class DirectoryIdentifier { protected DirectoryIdentifier() { } } public partial class DirectoryNotificationControl : System.DirectoryServices.Protocols.DirectoryControl { public DirectoryNotificationControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public abstract partial class DirectoryOperation { protected DirectoryOperation() { } } public partial class DirectoryOperationException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public DirectoryOperationException() { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected DirectoryOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryOperationException(string message) { } public DirectoryOperationException(string message, System.Exception inner) { } public System.DirectoryServices.Protocols.DirectoryResponse Response { get { return default(System.DirectoryServices.Protocols.DirectoryResponse); } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public abstract partial class DirectoryRequest : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryRequest() { } public System.DirectoryServices.Protocols.DirectoryControlCollection Controls { get { return default(System.DirectoryServices.Protocols.DirectoryControlCollection); } } public string RequestId { get { return default(string); } set { } } } public abstract partial class DirectoryResponse : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryResponse() { } public virtual System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { return default(System.DirectoryServices.Protocols.DirectoryControl[]); } } public virtual string ErrorMessage { get { return default(string); } } public virtual string MatchedDN { get { return default(string); } } public virtual System.Uri[] Referral { get { return default(System.Uri[]); } } public string RequestId { get { return default(string); } } public virtual System.DirectoryServices.Protocols.ResultCode ResultCode { get { return default(System.DirectoryServices.Protocols.ResultCode); } } } [System.FlagsAttribute] public enum DirectorySynchronizationOptions : long { IncrementalValues = (long)2147483648, None = (long)0, ObjectSecurity = (long)1, ParentsFirst = (long)2048, PublicDataOnly = (long)8192, } public partial class DirSyncRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public DirSyncRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option, int attributeCount) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AttributeCount { get { return default(int); } set { } } public byte[] Cookie { get { return default(byte[]); } set { } } public System.DirectoryServices.Protocols.DirectorySynchronizationOptions Option { get { return default(System.DirectoryServices.Protocols.DirectorySynchronizationOptions); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class DirSyncResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal DirSyncResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { return default(byte[]); } } public bool MoreData { get { return default(bool); } } public int ResultSize { get { return default(int); } } } public partial class DomainScopeControl : System.DirectoryServices.Protocols.DirectoryControl { public DomainScopeControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class DsmlAuthRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DsmlAuthRequest() { } public DsmlAuthRequest(string principal) { } public string Principal { get { return default(string); } set { } } } public partial class ExtendedDNControl : System.DirectoryServices.Protocols.DirectoryControl { public ExtendedDNControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public ExtendedDNControl(System.DirectoryServices.Protocols.ExtendedDNFlag flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ExtendedDNFlag Flag { get { return default(System.DirectoryServices.Protocols.ExtendedDNFlag); } set { } } public override byte[] GetValue() { return default(byte[]); } } public enum ExtendedDNFlag { HexString = 0, StandardString = 1, } public partial class ExtendedRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ExtendedRequest() { } public ExtendedRequest(string requestName) { } public ExtendedRequest(string requestName, byte[] requestValue) { } public string RequestName { get { return default(string); } set { } } public byte[] RequestValue { get { return default(byte[]); } set { } } } public partial class ExtendedResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ExtendedResponse() { } public string ResponseName { get { return default(string); } } public byte[] ResponseValue { get { return default(byte[]); } } } public partial class LazyCommitControl : System.DirectoryServices.Protocols.DirectoryControl { public LazyCommitControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class LdapConnection : System.DirectoryServices.Protocols.DirectoryConnection, System.IDisposable { public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType) { } public LdapConnection(string server) { } public System.DirectoryServices.Protocols.AuthType AuthType { get { return default(System.DirectoryServices.Protocols.AuthType); } set { } } public bool AutoBind { get { return default(bool); } set { } } public override System.Net.NetworkCredential Credential { set { } } public System.DirectoryServices.Protocols.LdapSessionOptions SessionOptions { get { return default(System.DirectoryServices.Protocols.LdapSessionOptions); } } public override System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } } public void Abort(System.IAsyncResult asyncResult) { } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public void Bind() { } public void Bind(System.Net.NetworkCredential newCredential) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.DirectoryServices.Protocols.DirectoryResponse EndSendRequest(System.IAsyncResult asyncResult) { return default(System.DirectoryServices.Protocols.DirectoryResponse); } ~LdapConnection() { } public System.DirectoryServices.Protocols.PartialResultsCollection GetPartialResults(System.IAsyncResult asyncResult) { return default(System.DirectoryServices.Protocols.PartialResultsCollection); } public override System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request) { return default(System.DirectoryServices.Protocols.DirectoryResponse); } public System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout) { return default(System.DirectoryServices.Protocols.DirectoryResponse); } } public partial class LdapDirectoryIdentifier : System.DirectoryServices.Protocols.DirectoryIdentifier { public LdapDirectoryIdentifier(string server) { } public LdapDirectoryIdentifier(string server, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string server, int portNumber) { } public LdapDirectoryIdentifier(string server, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public bool Connectionless { get { return default(bool); } } public bool FullyQualifiedDnsHostName { get { return default(bool); } } public int PortNumber { get { return default(int); } } public string[] Servers { get { return default(string[]); } } } public partial class LdapException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public LdapException() { } public LdapException(int errorCode) { } public LdapException(int errorCode, string message) { } public LdapException(int errorCode, string message, System.Exception inner) { } public LdapException(int errorCode, string message, string serverErrorMessage) { } protected LdapException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public LdapException(string message) { } public LdapException(string message, System.Exception inner) { } public int ErrorCode { get { return default(int); } } public System.DirectoryServices.Protocols.PartialResultsCollection PartialResults { get { return default(System.DirectoryServices.Protocols.PartialResultsCollection); } } public string ServerErrorMessage { get { return default(string); } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class LdapSessionOptions { internal LdapSessionOptions() { } public bool AutoReconnect { get { return default(bool); } set { } } public string DomainName { get { return default(string); } set { } } public string HostName { get { return default(string); } set { } } public bool HostReachable { get { return default(bool); } } public System.DirectoryServices.Protocols.LocatorFlags LocatorFlag { get { return default(System.DirectoryServices.Protocols.LocatorFlags); } set { } } public System.TimeSpan PingKeepAliveTimeout { get { return default(System.TimeSpan); } set { } } public int PingLimit { get { return default(int); } set { } } public System.TimeSpan PingWaitTimeout { get { return default(System.TimeSpan); } set { } } public int ProtocolVersion { get { return default(int); } set { } } public System.DirectoryServices.Protocols.QueryClientCertificateCallback QueryClientCertificate { get { return default(System.DirectoryServices.Protocols.QueryClientCertificateCallback); } set { } } public System.DirectoryServices.Protocols.ReferralCallback ReferralCallback { get { return default(System.DirectoryServices.Protocols.ReferralCallback); } set { } } public System.DirectoryServices.Protocols.ReferralChasingOptions ReferralChasing { get { return default(System.DirectoryServices.Protocols.ReferralChasingOptions); } set { } } public int ReferralHopLimit { get { return default(int); } set { } } public bool RootDseCache { get { return default(bool); } set { } } public string SaslMethod { get { return default(string); } set { } } public bool Sealing { get { return default(bool); } set { } } public bool SecureSocketLayer { get { return default(bool); } set { } } public object SecurityContext { get { return default(object); } } public System.TimeSpan SendTimeout { get { return default(System.TimeSpan); } set { } } public bool Signing { get { return default(bool); } set { } } public System.DirectoryServices.Protocols.SecurityPackageContextConnectionInformation SslInformation { get { return default(System.DirectoryServices.Protocols.SecurityPackageContextConnectionInformation); } } public int SspiFlag { get { return default(int); } set { } } public bool TcpKeepAlive { get { return default(bool); } set { } } public System.DirectoryServices.Protocols.VerifyServerCertificateCallback VerifyServerCertificate { get { return default(System.DirectoryServices.Protocols.VerifyServerCertificateCallback); } set { } } public void FastConcurrentBind() { } public void StartTransportLayerSecurity(System.DirectoryServices.Protocols.DirectoryControlCollection controls) { } public void StopTransportLayerSecurity() { } } [System.FlagsAttribute] public enum LocatorFlags : long { AvoidSelf = (long)16384, DirectoryServicesPreferred = (long)32, DirectoryServicesRequired = (long)16, ForceRediscovery = (long)1, GCRequired = (long)64, GoodTimeServerPreferred = (long)8192, IPRequired = (long)512, IsDnsName = (long)131072, IsFlatName = (long)65536, KdcRequired = (long)1024, None = (long)0, OnlyLdapNeeded = (long)32768, PdcRequired = (long)128, ReturnDnsName = (long)1073741824, ReturnFlatName = (long)2147483648, TimeServerRequired = (long)2048, WriteableRequired = (long)4096, } public partial class ModifyDNRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyDNRequest() { } public ModifyDNRequest(string distinguishedName, string newParentDistinguishedName, string newName) { } public bool DeleteOldRdn { get { return default(bool); } set { } } public string DistinguishedName { get { return default(string); } set { } } public string NewName { get { return default(string); } set { } } public string NewParentDistinguishedName { get { return default(string); } set { } } } public partial class ModifyDNResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyDNResponse() { } } public partial class ModifyRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyRequest() { } public ModifyRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttributeModification[] modifications) { } public ModifyRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttributeOperation operation, string attributeName, params object[] values) { } public string DistinguishedName { get { return default(string); } set { } } public System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection Modifications { get { return default(System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection); } } } public partial class ModifyResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyResponse() { } } public delegate bool NotifyOfNewConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.DirectoryServices.Protocols.LdapConnection newConnection, System.Net.NetworkCredential credential, long currentUserToken, int errorCodeFromBind); public partial class PageResultRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public PageResultRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(int pageSize) : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { return default(byte[]); } set { } } public int PageSize { get { return default(int); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class PageResultResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal PageResultResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { return default(byte[]); } } public int TotalCount { get { return default(int); } } } public enum PartialResultProcessing { NoPartialResultSupport = 0, ReturnPartialResults = 1, ReturnPartialResultsAndNotifyCallback = 2, } public partial class PartialResultsCollection : System.Collections.ReadOnlyCollectionBase { internal PartialResultsCollection() { } public object this[int index] { get { return default(object); } } public bool Contains(object value) { return default(bool); } public void CopyTo(object[] values, int index) { } public int IndexOf(object value) { return default(int); } } public partial class PermissiveModifyControl : System.DirectoryServices.Protocols.DirectoryControl { public PermissiveModifyControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public delegate System.Security.Cryptography.X509Certificates.X509Certificate QueryClientCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, byte[][] trustedCAs); public delegate System.DirectoryServices.Protocols.LdapConnection QueryForConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, long currentUserToken); public partial class QuotaControl : System.DirectoryServices.Protocols.DirectoryControl { public QuotaControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public QuotaControl(System.Security.Principal.SecurityIdentifier querySid) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.Security.Principal.SecurityIdentifier QuerySid { get { return default(System.Security.Principal.SecurityIdentifier); } set { } } public override byte[] GetValue() { return default(byte[]); } } public sealed partial class ReferralCallback { public ReferralCallback() { } public System.DirectoryServices.Protocols.DereferenceConnectionCallback DereferenceConnection { get { return default(System.DirectoryServices.Protocols.DereferenceConnectionCallback); } set { } } public System.DirectoryServices.Protocols.NotifyOfNewConnectionCallback NotifyNewConnection { get { return default(System.DirectoryServices.Protocols.NotifyOfNewConnectionCallback); } set { } } public System.DirectoryServices.Protocols.QueryForConnectionCallback QueryForConnection { get { return default(System.DirectoryServices.Protocols.QueryForConnectionCallback); } set { } } } [System.FlagsAttribute] public enum ReferralChasingOptions { All = 96, External = 64, None = 0, Subordinate = 32, } public enum ResultCode { AdminLimitExceeded = 11, AffectsMultipleDsas = 71, AliasDereferencingProblem = 36, AliasProblem = 33, AttributeOrValueExists = 20, AuthMethodNotSupported = 7, Busy = 51, CompareFalse = 5, CompareTrue = 6, ConfidentialityRequired = 13, ConstraintViolation = 19, EntryAlreadyExists = 68, InappropriateAuthentication = 48, InappropriateMatching = 18, InsufficientAccessRights = 50, InvalidAttributeSyntax = 21, InvalidDNSyntax = 34, LoopDetect = 54, NamingViolation = 64, NoSuchAttribute = 16, NoSuchObject = 32, NotAllowedOnNonLeaf = 66, NotAllowedOnRdn = 67, ObjectClassModificationsProhibited = 69, ObjectClassViolation = 65, OffsetRangeError = 61, OperationsError = 1, Other = 80, ProtocolError = 2, Referral = 10, ReferralV2 = 9, ResultsTooLarge = 70, SaslBindInProgress = 14, SizeLimitExceeded = 4, SortControlMissing = 60, StrongAuthRequired = 8, Success = 0, TimeLimitExceeded = 3, Unavailable = 52, UnavailableCriticalExtension = 12, UndefinedAttributeType = 17, UnwillingToPerform = 53, VirtualListViewError = 76, } public enum SearchOption { DomainScope = 1, PhantomRoot = 2, } public partial class SearchOptionsControl : System.DirectoryServices.Protocols.DirectoryControl { public SearchOptionsControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption flags) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SearchOption SearchOption { get { return default(System.DirectoryServices.Protocols.SearchOption); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class SearchRequest : System.DirectoryServices.Protocols.DirectoryRequest { public SearchRequest() { } public SearchRequest(string distinguishedName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, params string[] attributeList) { } public System.DirectoryServices.Protocols.DereferenceAlias Aliases { get { return default(System.DirectoryServices.Protocols.DereferenceAlias); } set { } } public System.Collections.Specialized.StringCollection Attributes { get { return default(System.Collections.Specialized.StringCollection); } } public string DistinguishedName { get { return default(string); } set { } } public object Filter { get { return default(object); } set { } } public System.DirectoryServices.Protocols.SearchScope Scope { get { return default(System.DirectoryServices.Protocols.SearchScope); } set { } } public int SizeLimit { get { return default(int); } set { } } public System.TimeSpan TimeLimit { get { return default(System.TimeSpan); } set { } } public bool TypesOnly { get { return default(bool); } set { } } } public partial class SearchResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal SearchResponse() { } public override System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { return default(System.DirectoryServices.Protocols.DirectoryControl[]); } } public System.DirectoryServices.Protocols.SearchResultEntryCollection Entries { get { return default(System.DirectoryServices.Protocols.SearchResultEntryCollection); } } public override string ErrorMessage { get { return default(string); } } public override string MatchedDN { get { return default(string); } } public System.DirectoryServices.Protocols.SearchResultReferenceCollection References { get { return default(System.DirectoryServices.Protocols.SearchResultReferenceCollection); } } public override System.Uri[] Referral { get { return default(System.Uri[]); } } public override System.DirectoryServices.Protocols.ResultCode ResultCode { get { return default(System.DirectoryServices.Protocols.ResultCode); } } } public partial class SearchResultAttributeCollection : System.Collections.DictionaryBase { internal SearchResultAttributeCollection() { } public System.Collections.ICollection AttributeNames { get { return default(System.Collections.ICollection); } } public System.DirectoryServices.Protocols.DirectoryAttribute this[string attributeName] { get { return default(System.DirectoryServices.Protocols.DirectoryAttribute); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public bool Contains(string attributeName) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } } public partial class SearchResultEntry { internal SearchResultEntry() { } public System.DirectoryServices.Protocols.SearchResultAttributeCollection Attributes { get { return default(System.DirectoryServices.Protocols.SearchResultAttributeCollection); } } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { return default(System.DirectoryServices.Protocols.DirectoryControl[]); } } public string DistinguishedName { get { return default(string); } } } public partial class SearchResultEntryCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultEntryCollection() { } public System.DirectoryServices.Protocols.SearchResultEntry this[int index] { get { return default(System.DirectoryServices.Protocols.SearchResultEntry); } } public bool Contains(System.DirectoryServices.Protocols.SearchResultEntry value) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.SearchResultEntry[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultEntry value) { return default(int); } } public partial class SearchResultReference { internal SearchResultReference() { } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { return default(System.DirectoryServices.Protocols.DirectoryControl[]); } } public System.Uri[] Reference { get { return default(System.Uri[]); } } } public partial class SearchResultReferenceCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultReferenceCollection() { } public System.DirectoryServices.Protocols.SearchResultReference this[int index] { get { return default(System.DirectoryServices.Protocols.SearchResultReference); } } public bool Contains(System.DirectoryServices.Protocols.SearchResultReference value) { return default(bool); } public void CopyTo(System.DirectoryServices.Protocols.SearchResultReference[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultReference value) { return default(int); } } public enum SearchScope { Base = 0, OneLevel = 1, Subtree = 2, } public partial class SecurityDescriptorFlagControl : System.DirectoryServices.Protocols.DirectoryControl { public SecurityDescriptorFlagControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SecurityDescriptorFlagControl(System.DirectoryServices.Protocols.SecurityMasks masks) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SecurityMasks SecurityMasks { get { return default(System.DirectoryServices.Protocols.SecurityMasks); } set { } } public override byte[] GetValue() { return default(byte[]); } } [System.FlagsAttribute] public enum SecurityMasks { Dacl = 4, Group = 2, None = 0, Owner = 1, Sacl = 8, } public partial class SecurityPackageContextConnectionInformation { internal SecurityPackageContextConnectionInformation() { } public System.Security.Authentication.CipherAlgorithmType AlgorithmIdentifier { get { return default(System.Security.Authentication.CipherAlgorithmType); } } public int CipherStrength { get { return default(int); } } public int ExchangeStrength { get { return default(int); } } public System.Security.Authentication.HashAlgorithmType Hash { get { return default(System.Security.Authentication.HashAlgorithmType); } } public int HashStrength { get { return default(int); } } public int KeyExchangeAlgorithm { get { return default(int); } } public System.DirectoryServices.Protocols.SecurityProtocol Protocol { get { return default(System.DirectoryServices.Protocols.SecurityProtocol); } } } public enum SecurityProtocol { Pct1Client = 2, Pct1Server = 1, Ssl2Client = 8, Ssl2Server = 4, Ssl3Client = 32, Ssl3Server = 16, Tls1Client = 128, Tls1Server = 64, } public partial class ShowDeletedControl : System.DirectoryServices.Protocols.DirectoryControl { public ShowDeletedControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class SortKey { public SortKey() { } public SortKey(string attributeName, string matchingRule, bool reverseOrder) { } public string AttributeName { get { return default(string); } set { } } public string MatchingRule { get { return default(string); } set { } } public bool ReverseOrder { get { return default(bool); } set { } } } public partial class SortRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public SortRequestControl(params System.DirectoryServices.Protocols.SortKey[] sortKeys) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SortKey[] SortKeys { get { return default(System.DirectoryServices.Protocols.SortKey[]); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class SortResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal SortResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { return default(string); } } public System.DirectoryServices.Protocols.ResultCode Result { get { return default(System.DirectoryServices.Protocols.ResultCode); } } } public partial class TlsOperationException : System.DirectoryServices.Protocols.DirectoryOperationException { public TlsOperationException() { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected TlsOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TlsOperationException(string message) { } public TlsOperationException(string message, System.Exception inner) { } } public partial class TreeDeleteControl : System.DirectoryServices.Protocols.DirectoryControl { public TreeDeleteControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class VerifyNameControl : System.DirectoryServices.Protocols.DirectoryControl { public VerifyNameControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName, int flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int Flag { get { return default(int); } set { } } public string ServerName { get { return default(string); } set { } } public override byte[] GetValue() { return default(byte[]); } } public delegate bool VerifyServerCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, System.Security.Cryptography.X509Certificates.X509Certificate certificate); public partial class VlvRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public VlvRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, int offset) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, string target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AfterCount { get { return default(int); } set { } } public int BeforeCount { get { return default(int); } set { } } public byte[] ContextId { get { return default(byte[]); } set { } } public int EstimateCount { get { return default(int); } set { } } public int Offset { get { return default(int); } set { } } public byte[] Target { get { return default(byte[]); } set { } } public override byte[] GetValue() { return default(byte[]); } } public partial class VlvResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal VlvResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public int ContentCount { get { return default(int); } } public byte[] ContextId { get { return default(byte[]); } } public System.DirectoryServices.Protocols.ResultCode Result { get { return default(System.DirectoryServices.Protocols.ResultCode); } } public int TargetPosition { get { return default(int); } } } } 
// MetadataSource.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using ScriptSharp; using ScriptSharp.Importer.IL; namespace ScriptSharp.Importer { internal sealed class MetadataSource { private static readonly string CoreAssemblyName = "mscorlib"; private List<string> _assemblyPaths; private string _coreAssemblyPath; private Dictionary<string, AssemblyDefinition> _assemblyMap; private AssemblyDefinition _coreAssembly; public ICollection<string> Assemblies { get { return _assemblyPaths; } } public string CoreAssemblyPath { get { return _coreAssemblyPath; } } public AssemblyDefinition CoreAssemblyMetadata { get { return _coreAssembly; } } public AssemblyDefinition GetMetadata(string assembly) { return _assemblyMap[assembly]; } public bool LoadReferences(ICollection<string> references, IErrorHandler errorHandler) { bool hasLoadErrors = false; AssemblySet assemblySet = new AssemblySet(); foreach (string referencePath in references) { string assemblyFilePath = Path.GetFullPath(referencePath); if (File.Exists(assemblyFilePath) == false) { errorHandler.ReportError("The referenced assembly '" + referencePath + "' could not be located.", String.Empty); hasLoadErrors = true; continue; } string referenceName = Path.GetFileNameWithoutExtension(assemblyFilePath); if (assemblySet.IsReferenced(referenceName)) { errorHandler.ReportError("The referenced assembly '" + referencePath + "' is a duplicate reference.", String.Empty); hasLoadErrors = true; continue; } try { AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyFilePath); if (assembly == null) { errorHandler.ReportError("The referenced assembly '" + referencePath + "' could not be loaded as an assembly.", String.Empty); hasLoadErrors = true; continue; } if (referenceName.Equals(CoreAssemblyName, StringComparison.OrdinalIgnoreCase)) { if (_coreAssemblyPath != null) { errorHandler.ReportError("The core runtime assembly, mscorlib.dll must be referenced only once.", String.Empty); hasLoadErrors = true; continue; } else { _coreAssemblyPath = assemblyFilePath; _coreAssembly = assembly; } } else { assemblySet.AddAssembly(assemblyFilePath, referenceName, assembly); } } catch (Exception e) { Debug.Fail(e.ToString()); errorHandler.ReportError("The referenced assembly '" + referencePath + "' could not be loaded as an assembly.", String.Empty); hasLoadErrors = true; } } if (_coreAssembly == null) { errorHandler.ReportError("The 'mscorlib' assembly must be referenced.", String.Empty); hasLoadErrors = true; } else { if (VerifyScriptAssembly(_coreAssembly) == false) { errorHandler.ReportError("The assembly '" + _coreAssemblyPath + "' is not a valid script assembly.", String.Empty); hasLoadErrors = true; } } foreach (KeyValuePair<string, AssemblyDefinition> assemblyReference in assemblySet.Assemblies) { if (VerifyScriptAssembly(assemblyReference.Value) == false) { errorHandler.ReportError("The assembly '" + assemblyReference.Key + "' is not a valid script assembly.", String.Empty); hasLoadErrors = true; } } _assemblyMap = assemblySet.Assemblies; _assemblyPaths = assemblySet.GetAssemblyPaths(); return hasLoadErrors; } private bool VerifyScriptAssembly(AssemblyDefinition assembly) { foreach (CustomAttribute attribute in assembly.CustomAttributes) { if (String.CompareOrdinal(attribute.Constructor.DeclaringType.FullName, "System.ScriptAssemblyAttribute") == 0) { return true; } } return false; } private sealed class AssemblySet { private Dictionary<string, AssemblyDefinition> _assemblies; private HashSet<string> _assemblyNames; public AssemblySet() { _assemblies = new Dictionary<string, AssemblyDefinition>(StringComparer.Ordinal); _assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, AssemblyDefinition> Assemblies { get { return _assemblies; } } public void AddAssembly(string path, string referenceName, AssemblyDefinition assembly) { _assemblies[path] = assembly; _assemblyNames.Add(referenceName); } public List<string> GetAssemblyPaths() { // Perform a topological sort to get the list of assemblies in order // to cause loading of dependencies to happen before an assembly // that references them. List<AssemblyReference> references = new List<AssemblyReference>(); Dictionary<string, AssemblyReference> referenceMap = new Dictionary<string, AssemblyReference>(StringComparer.Ordinal); foreach (KeyValuePair<string, AssemblyDefinition> assembly in _assemblies) { AssemblyReference reference = new AssemblyReference(assembly.Key, assembly.Value); references.Add(reference); referenceMap[reference.FullName] = reference; } List<AssemblyReference> sortedReferences = new List<AssemblyReference>(); references.ForEach(r => VisitReference(r, referenceMap, sortedReferences)); return sortedReferences.Select(r => r.Path).ToList(); } public bool IsReferenced(string referenceName) { return _assemblyNames.Contains(referenceName); } private void VisitReference(AssemblyReference reference, Dictionary<string, AssemblyReference> referenceMap, List<AssemblyReference> referenceList) { if (reference.Visited) { return; } reference.Visit(); foreach (string dependencyName in reference.Dependencies) { AssemblyReference dependencyReference; if (referenceMap.TryGetValue(dependencyName, out dependencyReference)) { VisitReference(dependencyReference, referenceMap, referenceList); } } referenceList.Add(reference); } } private sealed class AssemblyReference { private string _path; private List<string> _dependencies; private AssemblyDefinition _assembly; private bool _visited; public AssemblyReference(string path, AssemblyDefinition assembly) { _path = path; _assembly = assembly; _dependencies = assembly.MainModule.AssemblyReferences.Select(a => a.FullName).ToList(); } public string FullName { get { return _assembly.FullName; } } public string Path { get { return _path; } } public IEnumerable<string> Dependencies { get { return _dependencies; } } public bool Visited { get { return _visited; } } public void Visit() { _visited = true; } } } }
/* * 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.Security.Cryptography; // for computing md5 hash using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType; using Ionic.Zlib; // You will need to uncomment these lines if you are adding a region module to some other assembly which does not already // specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans // the available DLLs //[assembly: Addin("MaterialsModule", "1.0")] //[assembly: AddinDependency("OpenSim", "0.8.1")] namespace OpenSim.Region.OptionalModules.Materials { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")] public class MaterialsModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "MaterialsModule"; } } public Type ReplaceableInterface { get { return null; } } IAssetCache m_cache; private Scene m_scene = null; private bool m_enabled = false; private int m_maxMaterialsPerTransaction = 50; public Dictionary<UUID, OSDMap> m_Materials = new Dictionary<UUID, OSDMap>(); public Dictionary<UUID, int> m_MaterialsRefCount = new Dictionary<UUID, int>(); private Dictionary<ulong, AssetBase> m_changes = new Dictionary<ulong, AssetBase>(); private Dictionary<ulong, double> m_changesTime = new Dictionary<ulong, double>(); public void Initialise(IConfigSource source) { m_enabled = true; // default is enabled IConfig config = source.Configs["Materials"]; if (config != null) { m_enabled = config.GetBoolean("enable_materials", m_enabled); m_maxMaterialsPerTransaction = config.GetInt("MaxMaterialsPerTransaction", m_maxMaterialsPerTransaction); } if (m_enabled) m_log.DebugFormat("[Materials]: Initialized"); } public void Close() { if (!m_enabled) return; } public void AddRegion(Scene scene) { if (!m_enabled) return; m_scene = scene; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene; m_scene.EventManager.OnBackup += EventManager_OnBackup; } private void EventManager_OnBackup(ISimulationDataService datastore, bool forcedBackup) { List<AssetBase> toStore; List<ulong> hashlist; lock (m_Materials) { if(m_changes.Count == 0) return; if(forcedBackup) { toStore = new List<AssetBase>(m_changes.Values); m_changes.Clear(); m_changesTime.Clear(); } else { toStore = new List<AssetBase>(); hashlist = new List<ulong>(); double storetime = Util.GetTimeStampMS() - 60000; foreach(KeyValuePair<ulong,double> kvp in m_changesTime) { if(kvp.Value < storetime) { toStore.Add(m_changes[kvp.Key]); hashlist.Add(kvp.Key); } } foreach(ulong u in hashlist) { m_changesTime.Remove(u); m_changes.Remove(u); } } if(toStore.Count > 0) Util.FireAndForget(delegate { foreach(AssetBase a in toStore) { a.Local = false; m_scene.AssetService.Store(a); } }); } } private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) { foreach (var part in obj.Parts) if (part != null) GetStoredMaterialsInPart(part); } private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps) { string capsBase = "/CAPS/" + caps.CapsObjectPath; IRequestHandler renderMaterialsPostHandler = new RestStreamHandler("POST", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsPostCap(request, agentID), "RenderMaterials", null); caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler); // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET // and POST handlers, (at least at the time this was originally written), so we first set up a POST // handler normally and then add a GET handler via MainServer IRequestHandler renderMaterialsGetHandler = new RestStreamHandler("GET", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsGetCap(request), "RenderMaterials", null); MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler); // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well IRequestHandler renderMaterialsPutHandler = new RestStreamHandler("PUT", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsPutCap(request, agentID), "RenderMaterials", null); MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler); } public void RemoveRegion(Scene scene) { if (!m_enabled) return; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; m_scene.EventManager.OnBackup -= EventManager_OnBackup; } public void RegionLoaded(Scene scene) { if (!m_enabled) return; m_cache = scene.RequestModuleInterface<IAssetCache>(); ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; } private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features) { features["MaxMaterialsPerTransaction"] = m_maxMaterialsPerTransaction; } /// <summary> /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'. /// </summary> /// <param name="part"></param> private void GetLegacyStoredMaterialsInPart(SceneObjectPart part) { if (part.DynAttrs == null) return; OSD OSMaterials = null; OSDArray matsArr = null; lock (part.DynAttrs) { if (part.DynAttrs.ContainsStore("OpenSim", "Materials")) { OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials"); if (materialsStore == null) return; materialsStore.TryGetValue("Materials", out OSMaterials); } if (OSMaterials != null && OSMaterials is OSDArray) matsArr = OSMaterials as OSDArray; else return; } if (matsArr == null) return; foreach (OSD elemOsd in matsArr) { if (elemOsd != null && elemOsd is OSDMap) { OSDMap matMap = elemOsd as OSDMap; if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material")) { try { lock (m_Materials) { UUID id = matMap["ID"].AsUUID(); if(m_Materials.ContainsKey(id)) m_MaterialsRefCount[id]++; else { m_Materials[id] = (OSDMap)matMap["Material"]; m_MaterialsRefCount[id] = 1; } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString()); } } } } } /// <summary> /// Find the materials used in the SOP, and add them to 'm_regionMaterials'. /// </summary> private void GetStoredMaterialsInPart(SceneObjectPart part) { if (part.Shape == null) return; var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length); if (te == null) return; GetLegacyStoredMaterialsInPart(part); if (te.DefaultTexture != null) GetStoredMaterialInFace(part, te.DefaultTexture); else m_log.WarnFormat( "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.", part.Name, part.ParentGroup.Name, m_scene.Name); foreach (Primitive.TextureEntryFace face in te.FaceTextures) { if (face != null) GetStoredMaterialInFace(part, face); } } /// <summary> /// Find the materials used in one Face, and add them to 'm_regionMaterials'. /// </summary> private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face) { UUID id = face.MaterialID; if (id == UUID.Zero) return; lock (m_Materials) { if (m_Materials.ContainsKey(id)) { m_MaterialsRefCount[id]++; return; } AssetBase matAsset = m_scene.AssetService.Get(id.ToString()); if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0 ) { //m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id); return; } byte[] data = matAsset.Data; OSDMap mat; try { mat = (OSDMap)OSDParser.DeserializeLLSDXml(data); } catch (Exception e) { m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message); return; } m_Materials[id] = mat; m_MaterialsRefCount[id] = 1; } } public string RenderMaterialsPostCap(string request, UUID agentID) { OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); OSDArray respArr = new OSDArray(); if (req.ContainsKey("Zipped")) { OSD osd = null; byte[] inBytes = req["Zipped"].AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDArray) { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); lock (m_Materials) { if (m_Materials.ContainsKey(id)) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["Material"] = m_Materials[id]; respArr.Add(matMap); } else { m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); // Theoretically we could try to load the material from the assets service, // but that shouldn't be necessary because the viewer should only request // materials that exist in a prim on the region, and all of these materials // are already stored in m_regionMaterials. } } } catch (Exception e) { m_log.Error("Error getting materials in response to viewer request", e); continue; } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); //return ""; } } resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); return response; } public string RenderMaterialsPutCap(string request, UUID agentID) { OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); HashSet<SceneObjectPart> parts = new HashSet<SceneObjectPart>(); if (req.ContainsKey("Zipped")) { OSD osd = null; byte[] inBytes = req["Zipped"].AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDMap) { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) { OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; if (matsOsd is OSDArray) { OSDArray matsArr = matsOsd as OSDArray; try { foreach (OSDMap matsMap in matsArr) { uint primLocalID = 0; try { primLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); continue; } SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); if (sop == null) { m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); continue; } if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) { m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); continue; } OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); continue; } UUID id; if (mat == null) { // This happens then the user removes a material from a prim id = UUID.Zero; } else { id = getNewID(mat); } int face = -1; UUID oldid = UUID.Zero; if (matsMap.ContainsKey("Face")) { face = matsMap["Face"].AsInteger(); Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face); oldid = faceEntry.MaterialID; faceEntry.MaterialID = id; } else { if (te.DefaultTexture == null) m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID); else { oldid = te.DefaultTexture.MaterialID; te.DefaultTexture.MaterialID = id; } } //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually sop.Shape.TextureEntry = te.GetBytes(); lock(m_Materials) { if(oldid != UUID.Zero && m_MaterialsRefCount.ContainsKey(oldid)) { m_MaterialsRefCount[oldid]--; if(m_MaterialsRefCount[oldid] <= 0) { m_Materials.Remove(oldid); m_MaterialsRefCount.Remove(oldid); m_cache.Expire(oldid.ToString()); } } if(id != UUID.Zero) { AssetBase asset = CacheMaterialAsAsset(id, agentID, mat, sop); if(asset != null) { ulong materialHash = (ulong)primLocalID << 32; if(face < 0) materialHash += 0xffffffff; else materialHash +=(ulong)face; m_changes[materialHash] = asset; m_changesTime[materialHash] = Util.GetTimeStampMS(); } } } if(!parts.Contains(sop)) parts.Add(sop); } foreach(SceneObjectPart sop in parts) { if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted) { sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.ScheduleFullUpdate(); sop.ParentGroup.HasGroupChanged = true; } } } catch (Exception e) { m_log.Warn("[Materials]: exception processing received material ", e); } } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); //return ""; } } resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); return response; } private UUID getNewID(OSDMap mat) { // ugly and done twice but keep compatibility for now Byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); using (var md5 = MD5.Create()) return new UUID(md5.ComputeHash(data), 0); } private AssetBase CacheMaterialAsAsset(UUID id, UUID agentID, OSDMap mat, SceneObjectPart sop) { AssetBase asset = null; lock (m_Materials) { if (!m_Materials.ContainsKey(id)) { m_Materials[id] = mat; m_MaterialsRefCount[id] = 1; byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); // This asset might exist already, but it's ok to try to store it again string name = "Material " + ChooseMaterialName(mat, sop); name = name.Substring(0, Math.Min(64, name.Length)).Trim(); asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString()); asset.Data = data; asset.Local = true; m_cache.Cache(asset); } else m_MaterialsRefCount[id]++; } return asset; } private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop) { UUID id; // Material UUID = hash of the material's data. // This makes materials deduplicate across the entire grid (but isn't otherwise required). byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); using (var md5 = MD5.Create()) id = new UUID(md5.ComputeHash(data), 0); lock (m_Materials) { if (!m_Materials.ContainsKey(id)) { m_Materials[id] = mat; m_MaterialsRefCount[id] = 1; // This asset might exist already, but it's ok to try to store it again string name = "Material " + ChooseMaterialName(mat, sop); name = name.Substring(0, Math.Min(64, name.Length)).Trim(); AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); } else m_MaterialsRefCount[id]++; } return id; } /// <summary> /// Use heuristics to choose a good name for the material. /// </summary> private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop) { UUID normMap = mat["NormMap"].AsUUID(); if (normMap != UUID.Zero) { AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString()); if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR")) return asset.Name; } UUID specMap = mat["SpecMap"].AsUUID(); if (specMap != UUID.Zero) { AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString()); if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR")) return asset.Name; } if (sop.Name != "Primitive") return sop.Name; if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive")) return sop.ParentGroup.Name; return ""; } public string RenderMaterialsGetCap(string request) { OSDMap resp = new OSDMap(); int matsCount = 0; OSDArray allOsd = new OSDArray(); lock (m_Materials) { foreach (KeyValuePair<UUID, OSDMap> kvp in m_Materials) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes()); matMap["Material"] = kvp.Value; allOsd.Add(matMap); matsCount++; } } resp["Zipped"] = ZCompressOSD(allOsd, false); return OSDParser.SerializeLLSDXmlString(resp); } private static string ZippedOsdBytesToString(byte[] bytes) { try { return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes)); } catch (Exception e) { return "ZippedOsdBytesToString caught an exception: " + e.ToString(); } } /// <summary> /// computes a UUID by hashing a OSD object /// </summary> /// <param name="osd"></param> /// <returns></returns> private static UUID HashOsd(OSD osd) { byte[] data = OSDParser.SerializeLLSDBinary(osd, false); using (var md5 = MD5.Create()) return new UUID(md5.ComputeHash(data), 0); } public static OSD ZCompressOSD(OSD inOsd, bool useHeader) { OSD osd = null; byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader); using (MemoryStream msSinkCompressed = new MemoryStream()) { using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed, Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true)) { zOut.Write(data, 0, data.Length); } msSinkCompressed.Seek(0L, SeekOrigin.Begin); osd = OSD.FromBinary(msSinkCompressed.ToArray()); } return osd; } public static OSD ZDecompressBytesToOsd(byte[] input) { OSD osd = null; using (MemoryStream msSinkUnCompressed = new MemoryStream()) { using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true)) { zOut.Write(input, 0, input.Length); } msSinkUnCompressed.Seek(0L, SeekOrigin.Begin); osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray()); } return osd; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Dns { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The DNS Management Client. /// </summary> public partial class DnsManagementClient : ServiceClient<DnsManagementClient>, IDnsManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Specifies the Azure subscription ID, which uniquely identifies the /// Microsoft Azure subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Specifies the API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IRecordSetsOperations. /// </summary> public virtual IRecordSetsOperations RecordSets { get; private set; } /// <summary> /// Gets the IZonesOperations. /// </summary> public virtual IZonesOperations Zones { get; private set; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DnsManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DnsManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DnsManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DnsManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DnsManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DnsManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DnsManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DnsManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { RecordSets = new RecordSetsOperations(this); Zones = new ZonesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-04-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// 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.Threading; using System.Collections.Generic; using System.Reflection; namespace System.Runtime.Serialization.Formatters.Binary { // This class contains information about an object. It is used so that // the rest of the Formatter routines can use a common interface for // a normal object, an ISerializable object, and a surrogate object internal sealed class WriteObjectInfo { internal int _objectInfoId; internal object _obj; internal Type _objectType; internal bool _isSi = false; internal bool _isNamed = false; internal bool _isArray = false; internal SerializationInfo _si = null; internal SerObjectInfoCache _cache = null; internal object[] _memberData = null; internal ISerializationSurrogate _serializationSurrogate = null; internal StreamingContext _context; internal SerObjectInfoInit _serObjectInfoInit = null; // Writing and Parsing information internal long _objectId; internal long _assemId; // Binder information private string _binderTypeName; private string _binderAssemblyString; internal WriteObjectInfo() { } internal void ObjectEnd() { PutObjectInfo(_serObjectInfoInit, this); } private void InternalInit() { _obj = null; _objectType = null; _isSi = false; _isNamed = false; _isArray = false; _si = null; _cache = null; _memberData = null; // Writing and Parsing information _objectId = 0; _assemId = 0; // Binder information _binderTypeName = null; _binderAssemblyString = null; } internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit); woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder); return woi; } // Write constructor internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { _context = context; _obj = obj; _serObjectInfoInit = serObjectInfoInit; _objectType = obj.GetType(); if (_objectType.IsArray) { _isArray = true; InitNoMembers(); return; } InvokeSerializationBinder(binder); objectWriter.ObjectManager.RegisterObject(obj); ISurrogateSelector surrogateSelectorTemp; if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null) { _si = new SerializationInfo(_objectType, converter); if (!_objectType.IsPrimitive) { _serializationSurrogate.GetObjectData(obj, _si, context); } InitSiWrite(); } else if (obj is ISerializable) { if (!_objectType.IsSerializable) { throw new SerializationException(SR.Format(SR.Serialization_NonSerType, _objectType.FullName, _objectType.Assembly.FullName)); } _si = new SerializationInfo(_objectType, converter); ((ISerializable)obj).GetObjectData(_si, context); InitSiWrite(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } else { InitMemberInfo(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } } internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit); woi.InitSerialize(objectType, surrogateSelector, context, serObjectInfoInit, converter, binder); return woi; } // Write Constructor used for array types or null members internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { _objectType = objectType; _context = context; _serObjectInfoInit = serObjectInfoInit; if (objectType.IsArray) { InitNoMembers(); return; } InvokeSerializationBinder(binder); ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { // surrogate does not have this problem since user has pass in through the BF's ctor _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); _isSi = true; } if (!_isSi) { InitMemberInfo(); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); } } private void InitSiWrite() { SerializationInfoEnumerator siEnum = null; _isSi = true; siEnum = _si.GetEnumerator(); int infoLength = 0; infoLength = _si.MemberCount; int count = infoLength; // For ISerializable cache cannot be saved because each object instance can have different values // BinaryWriter only puts the map on the wire if the ISerializable map cannot be reused. TypeInformation typeInformation = null; string fullTypeName = _si.FullTypeName; string assemblyString = _si.AssemblyName; bool hasTypeForwardedFrom = false; if (!_si.IsFullTypeNameSetExplicit) { typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); fullTypeName = typeInformation.FullTypeName; hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } if (!_si.IsAssemblyNameSetExplicit) { if (typeInformation == null) { typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); } assemblyString = typeInformation.AssemblyString; hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } _cache = new SerObjectInfoCache(fullTypeName, assemblyString, hasTypeForwardedFrom); _cache._memberNames = new string[count]; _cache._memberTypes = new Type[count]; _memberData = new object[count]; siEnum = _si.GetEnumerator(); for (int i = 0; siEnum.MoveNext(); i++) { _cache._memberNames[i] = siEnum.Name; _cache._memberTypes[i] = siEnum.ObjectType; _memberData[i] = siEnum.Value; } _isNamed = true; } private static void CheckTypeForwardedFrom(SerObjectInfoCache cache, Type objectType, string binderAssemblyString) { // nop } private void InitNoMembers() { if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerObjectInfoCache(_objectType); _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } } private void InitMemberInfo() { if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerObjectInfoCache(_objectType); _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context); int count = _cache._memberInfos.Length; _cache._memberNames = new string[count]; _cache._memberTypes = new Type[count]; // Calculate new arrays for (int i = 0; i < count; i++) { _cache._memberNames[i] = _cache._memberInfos[i].Name; _cache._memberTypes[i] = ((FieldInfo)_cache._memberInfos[i]).FieldType; } _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } if (_obj != null) { _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos); } _isNamed = true; } internal string GetTypeFullName() => _binderTypeName ?? _cache._fullTypeName; internal string GetAssemblyString() => _binderAssemblyString ?? _cache._assemblyString; private void InvokeSerializationBinder(SerializationBinder binder) => binder?.BindToName(_objectType, out _binderAssemblyString, out _binderTypeName); internal void GetMemberInfo(out string[] outMemberNames, out Type[] outMemberTypes, out object[] outMemberData) { outMemberNames = _cache._memberNames; outMemberTypes = _cache._memberTypes; outMemberData = _memberData; if (_isSi && !_isNamed) { throw new SerializationException(SR.Serialization_ISerializableMemberInfo); } } private static WriteObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit) { WriteObjectInfo objectInfo; if (!serObjectInfoInit._oiPool.IsEmpty()) { objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop(); objectInfo.InternalInit(); } else { objectInfo = new WriteObjectInfo(); objectInfo._objectInfoId = serObjectInfoInit._objectInfoIdCount++; } return objectInfo; } private static void PutObjectInfo(SerObjectInfoInit serObjectInfoInit, WriteObjectInfo objectInfo) => serObjectInfoInit._oiPool.Push(objectInfo); } internal sealed class ReadObjectInfo { internal int _objectInfoId; internal static int _readObjectInfoCounter; internal Type _objectType; internal ObjectManager _objectManager; internal int _count; internal bool _isSi = false; internal bool _isTyped = false; internal bool _isSimpleAssembly = false; internal SerObjectInfoCache _cache; internal string[] _wireMemberNames; internal Type[] _wireMemberTypes; private int _lastPosition = 0; internal ISerializationSurrogate _serializationSurrogate = null; internal StreamingContext _context; // Si Read internal List<Type> _memberTypesList; internal SerObjectInfoInit _serObjectInfoInit = null; internal IFormatterConverter _formatterConverter; internal ReadObjectInfo() { } internal void ObjectEnd() { } internal void PrepareForReuse() { _lastPosition = 0; } internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit); roi.Init(objectType, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly); return roi; } internal void Init(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { _objectType = objectType; _objectManager = objectManager; _context = context; _serObjectInfoInit = serObjectInfoInit; _formatterConverter = converter; _isSimpleAssembly = bSimpleAssembly; InitReadConstructor(objectType, surrogateSelector, context); } internal static ReadObjectInfo Create(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit); roi.Init(objectType, memberNames, memberTypes, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly); return roi; } internal void Init(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { _objectType = objectType; _objectManager = objectManager; _wireMemberNames = memberNames; _wireMemberTypes = memberTypes; _context = context; _serObjectInfoInit = serObjectInfoInit; _formatterConverter = converter; _isSimpleAssembly = bSimpleAssembly; if (memberTypes != null) { _isTyped = true; } if (objectType != null) { InitReadConstructor(objectType, surrogateSelector, context); } } private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context) { if (objectType.IsArray) { InitNoMembers(); return; } ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _isSi = true; } if (_isSi) { InitSiRead(); } else { InitMemberInfo(); } } private void InitSiRead() { if (_memberTypesList != null) { _memberTypesList = new List<Type>(20); } } private void InitNoMembers() { _cache = new SerObjectInfoCache(_objectType); } private void InitMemberInfo() { _cache = new SerObjectInfoCache(_objectType); _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context); _count = _cache._memberInfos.Length; _cache._memberNames = new string[_count]; _cache._memberTypes = new Type[_count]; // Calculate new arrays for (int i = 0; i < _count; i++) { _cache._memberNames[i] = _cache._memberInfos[i].Name; _cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]); } _isTyped = true; } // Get the memberInfo for a memberName internal MemberInfo GetMemberInfo(string name) { if (_cache == null) { return null; } if (_isSi) { throw new SerializationException(SR.Format(SR.Serialization_MemberInfo, _objectType + " " + name)); } if (_cache._memberInfos == null) { throw new SerializationException(SR.Format(SR.Serialization_NoMemberInfo, _objectType + " " + name)); } int position = Position(name); return position != -1 ? _cache._memberInfos[position] : null; } // Get the ObjectType for a memberName internal Type GetType(string name) { int position = Position(name); if (position == -1) { return null; } Type type = _isTyped ? _cache._memberTypes[position] : _memberTypesList[position]; if (type == null) { throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name)); } return type; } // Adds the value for a memberName internal void AddValue(string name, object value, ref SerializationInfo si, ref object[] memberData) { if (_isSi) { si.AddValue(name, value); } else { // If a member in the stream is not found, ignore it int position = Position(name); if (position != -1) { memberData[position] = value; } } } internal void InitDataStore(ref SerializationInfo si, ref object[] memberData) { if (_isSi) { if (si == null) { si = new SerializationInfo(_objectType, _formatterConverter); } } else { if (memberData == null && _cache != null) { memberData = new object[_cache._memberNames.Length]; } } } // Records an objectId in a member when the actual object for that member is not yet known internal void RecordFixup(long objectId, string name, long idRef) { if (_isSi) { _objectManager.RecordDelayedFixup(objectId, name, idRef); } else { int position = Position(name); if (position != -1) { _objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef); } } } // Fills in the values for an object internal void PopulateObjectMembers(object obj, object[] memberData) { if (!_isSi && memberData != null) { FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData); } } // Specifies the position in the memberNames array of this name private int Position(string name) { if (_cache == null) { return -1; } if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name)) { return _lastPosition; } else if ((++_lastPosition < _cache._memberNames.Length) && (_cache._memberNames[_lastPosition].Equals(name))) { return _lastPosition; } else { // Search for name for (int i = 0; i < _cache._memberNames.Length; i++) { if (_cache._memberNames[i].Equals(name)) { _lastPosition = i; return _lastPosition; } } _lastPosition = 0; return -1; } } // Return the member Types in order of memberNames internal Type[] GetMemberTypes(string[] inMemberNames, Type objectType) { if (_isSi) { throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, objectType)); } if (_cache == null) { return null; } if (_cache._memberTypes == null) { _cache._memberTypes = new Type[_count]; for (int i = 0; i < _count; i++) { _cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]); } } bool memberMissing = false; if (inMemberNames.Length < _cache._memberInfos.Length) { memberMissing = true; } Type[] outMemberTypes = new Type[_cache._memberInfos.Length]; bool isFound = false; for (int i = 0; i < _cache._memberInfos.Length; i++) { if (!memberMissing && inMemberNames[i].Equals(_cache._memberInfos[i].Name)) { outMemberTypes[i] = _cache._memberTypes[i]; } else { // MemberNames on wire in different order then memberInfos returned by reflection isFound = false; for (int j = 0; j < inMemberNames.Length; j++) { if (_cache._memberInfos[i].Name.Equals(inMemberNames[j])) { outMemberTypes[i] = _cache._memberTypes[i]; isFound = true; break; } } if (!isFound) { // A field on the type isn't found. See if the field has OptionalFieldAttribute. We only throw // when the assembly format is set appropriately. if (!_isSimpleAssembly && _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null) { throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName)); } } } } return outMemberTypes; } // Retrieves the member type from the MemberInfo internal Type GetMemberType(MemberInfo objMember) { if (objMember is FieldInfo) { return ((FieldInfo)objMember).FieldType; } throw new SerializationException(SR.Format(SR.Serialization_SerMemberInfo, objMember.GetType())); } private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit) { ReadObjectInfo roi = new ReadObjectInfo(); roi._objectInfoId = Interlocked.Increment(ref _readObjectInfoCounter); return roi; } } internal sealed class SerObjectInfoInit { internal readonly Dictionary<Type, SerObjectInfoCache> _seenBeforeTable = new Dictionary<Type, SerObjectInfoCache>(); internal int _objectInfoIdCount = 1; internal SerStack _oiPool = new SerStack("SerObjectInfo Pool"); } internal sealed class SerObjectInfoCache { internal readonly string _fullTypeName; internal readonly string _assemblyString; internal readonly bool _hasTypeForwardedFrom; internal MemberInfo[] _memberInfos; internal string[] _memberNames; internal Type[] _memberTypes; internal SerObjectInfoCache(string typeName, string assemblyName, bool hasTypeForwardedFrom) { _fullTypeName = typeName; _assemblyString = assemblyName; _hasTypeForwardedFrom = hasTypeForwardedFrom; } internal SerObjectInfoCache(Type type) { TypeInformation typeInformation = BinaryFormatter.GetTypeInformation(type); _fullTypeName = typeInformation.FullTypeName; _assemblyString = typeInformation.AssemblyString; _hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } } internal sealed class TypeInformation { internal TypeInformation(string fullTypeName, string assemblyString, bool hasTypeForwardedFrom) { FullTypeName = fullTypeName; AssemblyString = assemblyString; HasTypeForwardedFrom = hasTypeForwardedFrom; } internal string FullTypeName { get; } internal string AssemblyString { get; } internal bool HasTypeForwardedFrom { get; } } }
using System; using SharpVectors.Dom.Views; namespace SharpVectors.Dom.Events { /// <summary> /// Summary description for MouseEvent. /// </summary> public class MouseEvent : UiEvent , IMouseEvent { #region Private Fields private long screenX; private long screeny; private long clientX; private long clientY; private bool crtlKey; private bool shiftKey; private bool altKey; private bool metaKey; private ushort button; private IEventTarget relatedTarget; private bool altGraphKey; #endregion #region Constructors public MouseEvent() { } public MouseEvent( string eventType, bool bubbles, bool cancelable, IAbstractView view, long detail, long screenX, long screenY, long clientX, long clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, ushort button, IEventTarget relatedTarget) { InitMouseEvent( eventType, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget); } public MouseEvent( string namespaceUri, string eventType, bool bubbles, bool cancelable, IAbstractView view, long detail, long screenX, long screenY, long clientX, long clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, ushort button, IEventTarget relatedTarget, bool altGraphKey) { InitMouseEventNs( namespaceUri, eventType, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, altGraphKey); } public MouseEvent( EventType eventType, bool bubbles, bool cancelable, IAbstractView view, long detail, long screenX, long screenY, long clientX, long clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, ushort button, IEventTarget relatedTarget, bool altGraphKey) { InitMouseEventNs( eventType.NamespaceUri, eventType.Name, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, altGraphKey); } #endregion #region IMouseEvent interface #region Public Properties public long ScreenX { get { return screenX; } } public long ScreenY { get { return screeny; } } public long ClientX { get { return clientX; } } public long ClientY { get { return clientY; } } public bool CtrlKey { get { return crtlKey; } } public bool ShiftKey { get { return shiftKey; } } public bool AltKey { get { return altKey; } } public bool MetaKey { get { return metaKey; } } public ushort Button { get { return button; } } public IEventTarget RelatedTarget { get { return relatedTarget; } } public bool AltGraphKey { get { return altGraphKey; } } #endregion #region Public Methods public void InitMouseEvent( string eventType, bool bubbles, bool cancelable, IAbstractView view, long detail, long screenX, long screenY, long clientX, long clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, ushort button, IEventTarget relatedTarget) { InitUiEvent(eventType, bubbles, cancelable, view, detail); this.screenX = screenX; this.screeny = screeny; this.clientX = clientX; this.clientY = clientY; this.crtlKey = crtlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.button = button; this.relatedTarget = relatedTarget; this.altGraphKey = altGraphKey; } public void InitMouseEventNs( string namespaceUri, string eventType, bool bubbles, bool cancelable, IAbstractView view, long detail, long screenX, long screenY, long clientX, long clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, ushort button, IEventTarget relatedTarget, bool altGraphKey) { InitUiEventNs( namespaceUri, eventType, bubbles, cancelable, view, detail); this.screenX = screenX; this.screeny = screeny; this.clientX = clientX; this.clientY = clientY; this.crtlKey = crtlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.button = button; this.relatedTarget = relatedTarget; this.altGraphKey = altGraphKey; } #endregion #endregion } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// The BalloonPopupExtender control displays a popup which can contain any content. /// </summary> [ClientScriptResource("Sys.Extended.UI.BalloonPopupControlBehavior", Constants.BalloonPopupName)] [RequiredScript(typeof(PopupExtender))] [RequiredScript(typeof(CommonToolkitScripts))] [TargetControlType(typeof(WebControl))] [ClientCssResource(Constants.BalloonPopupName + ".Cloud")] [ClientCssResource(Constants.BalloonPopupName + ".Rectangle")] [Designer(typeof(BalloonPopupExtenderDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.BalloonPopupName + Constants.IconPostfix)] public class BalloonPopupExtender : DynamicPopulateExtenderControlBase { Animation _onHide; Animation _onShow; /// <summary> /// Extender control ID /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string ExtenderControlID { get { return GetPropertyValue("ExtenderControlID", String.Empty); } set { SetPropertyValue("ExtenderControlID", value); } } /// <summary> /// The ID of the control to display /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [DefaultValue("")] [ClientPropertyName("balloonPopupControlID")] public string BalloonPopupControlID { get { return GetPropertyValue("BalloonPopupControlID", String.Empty); } set { SetPropertyValue("BalloonPopupControlID", value); } } /// <summary> /// Optional setting specifying where the popup should be positioned relative to the target control /// </summary> /// <remarks> /// (TopRight, TopLeft, BottomRight, BottomLeft, Auto) Default value is Auto /// </remarks> [ExtenderControlProperty] [DefaultValue(BalloonPopupPosition.Auto)] [ClientPropertyName("balloonPopupPosition")] public BalloonPopupPosition Position { get; set; } /// <summary> /// Optional setting specifying the theme of balloon popup. /// Default value is Rectangle /// </summary> [ExtenderControlProperty] [DefaultValue(BalloonPopupStyle.Rectangle)] [ClientPropertyName("balloonPopupStyle")] public BalloonPopupStyle BalloonStyle { get; set; } /// <summary> /// Optional X (horizontal) offset for the popup window (relative to the target control). /// Default value is 0 /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetX")] public int OffsetX { get { return GetPropertyValue("OffsetX", 0); } set { SetPropertyValue("OffsetX", value); } } /// <summary> /// Optional Y (vertical) offset for the popup window (relative to the target control). /// Default value is 0 /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetY")] public int OffsetY { get { return GetPropertyValue("OffsetY", 0); } set { SetPropertyValue("OffsetY", value); } } /// <summary> /// The OnShow animation will be played each time the popup is displayed. /// The popup will be positioned correctly but hidden /// </summary> /// <remarks> /// The animation can use <HideAction Visible="true" /> to display the popup along with any other visual effects /// </remarks> [ExtenderControlProperty] [ClientPropertyName("onShow")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnShow { get { return GetAnimation(ref _onShow, "OnShow"); } set { SetAnimation(ref _onShow, "OnShow", value); } } /// <summary> /// The OnHide animation will be played each time the popup is hidden /// </summary> [ExtenderControlProperty] [ClientPropertyName("onHide")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnHide { get { return GetAnimation(ref _onHide, "OnHide"); } set { SetAnimation(ref _onHide, "OnHide", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onMouseOver event. Default value is false /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnMouseOver")] [DefaultValue(false)] public bool DisplayOnMouseOver { get { return GetPropertyValue("DisplayOnMouseOver", false); } set { SetPropertyValue("DisplayOnMouseOver", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onFocus event. Default value is false /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnFocus")] [DefaultValue(false)] public bool DisplayOnFocus { get { return GetPropertyValue("DisplayOnFocus", false); } set { SetPropertyValue("DisplayOnFocus", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onClick event. Default value is true /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnClick")] [DefaultValue(true)] public bool DisplayOnClick { get { return GetPropertyValue("DisplayOnClick", true); } set { SetPropertyValue("DisplayOnClick", value); } } /// <summary> /// Optional setting specifying the size of balloon popup. (Small, Medium and Large). Default value is Small /// </summary> [ExtenderControlProperty] [ClientPropertyName("balloonSize")] [DefaultValue(BalloonPopupSize.Small)] public BalloonPopupSize BalloonSize { get { return GetPropertyValue("BalloonSize", BalloonPopupSize.Small); } set { SetPropertyValue("BalloonSize", value); } } /// <summary> /// Optional setting specifying whether to display shadow of balloon popup or not /// </summary> [ExtenderControlProperty] [ClientPropertyName("useShadow")] [DefaultValue(true)] public bool UseShadow { get { return GetPropertyValue("UseShadow", true); } set { SetPropertyValue("UseShadow", value); } } /// <summary> /// This is required if user choose BalloonStyle to Custom. This specifies the url of custom css which will display custom theme /// </summary> [DefaultValue("")] public string CustomCssUrl { get; set; } /// <summary> /// Optional setting specifying whether to display scrollbar if contents are overflowing. /// Default value is Auto /// </summary> [DefaultValue(ScrollBars.Auto)] [Category("Behavior")] [ClientPropertyName("scrollBars")] [Description("Scroll bars behavior when content is overflow")] [ExtenderControlProperty] public ScrollBars ScrollBars { get { return GetPropertyValue("ScrollBars", ScrollBars.Auto); } set { SetPropertyValue("ScrollBars", value); } } /// <summary> /// This is required if user choose BalloonStyle to Custom. This specifies the name of the css class for the custom theme /// </summary> [ExtenderControlProperty] [ClientPropertyName("customClassName")] [DefaultValue("")] public string CustomClassName { get { return GetPropertyValue("CustomClassName", String.Empty); } set { SetPropertyValue("CustomClassName", value); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if(BalloonStyle == BalloonPopupStyle.Custom) { if(CustomCssUrl == String.Empty) throw new ArgumentException("Must pass CustomCssUrl value."); if(CustomClassName == String.Empty) throw new ArgumentException("Must pass CustomClassName value."); var isLinked = false; foreach(Control control in Page.Header.Controls) { if(control.ID == "customCssUrl") { isLinked = true; break; } } if(!isLinked) { var css = new HtmlLink(); css.Href = ResolveUrl(CustomCssUrl); css.Attributes["id"] = "customCssUrl"; css.Attributes["rel"] = "stylesheet"; css.Attributes["type"] = "text/css"; css.Attributes["media"] = "all"; Page.Header.Controls.Add(css); } } } } } #pragma warning restore 1591
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // 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.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Appearance { /// <summary> /// Enumeration values for CulturalAppearance (es.appear.cultural, Cultural Features Kind, /// section 4.3.5) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct CulturalAppearance { /// <summary> /// Describes the damaged appearance of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the damaged appearance of an entity")] public enum DamageValue : uint { /// <summary> /// No damage /// </summary> NoDamage = 0, /// <summary> /// Slight damage /// </summary> SlightDamage = 1, /// <summary> /// Moderate damage /// </summary> ModerateDamage = 2, /// <summary> /// Destroyed /// </summary> Destroyed = 3 } /// <summary> /// Describes status of smoke emanating from a Cultural Features object /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes status of smoke emanating from a Cultural Features object")] public enum SmokeValue : uint { /// <summary> /// Not smoking /// </summary> NotSmoking = 0, /// <summary> /// Smoke plume rising from the entity /// </summary> SmokePlumeRisingFromTheEntity = 1, /// <summary> /// null /// </summary> Unknown = 2 } /// <summary> /// Describes whether flames are rising from a Cultural Features object /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether flames are rising from a Cultural Features object")] public enum FlamingValue : uint { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Flames present /// </summary> FlamesPresent = 1 } /// <summary> /// Describes the frozen status of a Cultural Features object /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the frozen status of a Cultural Features object")] public enum FrozenStatusValue : uint { /// <summary> /// Not frozen /// </summary> NotFrozen = 0, /// <summary> /// Frozen (Frozen entities should not be dead-reckoned, i.e. should be displayed as fixed at the current location even if non-zero velocity, acceleration or rotation data received from the frozen entity) /// </summary> FrozenFrozenEntitiesShouldNotBeDeadReckonedIEShouldBeDisplayedAsFixedAtTheCurrentLocationEvenIfNonZeroVelocityAccelerationOrRotationDataReceivedFromTheFrozenEntity = 1 } /// <summary> /// Describes the Internal-Heat status /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the Internal-Heat status")] public enum InternalHeatStatusValue : uint { /// <summary> /// Internal-Heat off /// </summary> InternalHeatOff = 0, /// <summary> /// Internal-Heat on /// </summary> InternalHeatOn = 1 } /// <summary> /// Describes the state of a Cultural object /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of a Cultural object")] public enum StateValue : uint { /// <summary> /// Active /// </summary> Active = 0, /// <summary> /// Deactivated /// </summary> Deactivated = 1 } /// <summary> /// Describes whether Exterior Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Exterior Lights are on or off.")] public enum ExteriorLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes whether Interior Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Interior Lights are on or off.")] public enum InteriorLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes if the entity is Masked / Cloaked or Not /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes if the entity is Masked / Cloaked or Not")] public enum MaskedCloakedValue : uint { /// <summary> /// Not Masked / Not Cloaked /// </summary> NotMaskedNotCloaked = 0, /// <summary> /// Masked / Cloaked /// </summary> MaskedCloaked = 1 } private CulturalAppearance.DamageValue damage; private CulturalAppearance.SmokeValue smoke; private CulturalAppearance.FlamingValue flaming; private CulturalAppearance.FrozenStatusValue frozenStatus; private CulturalAppearance.InternalHeatStatusValue internalHeatStatus; private CulturalAppearance.StateValue state; private CulturalAppearance.ExteriorLightsValue exteriorLights; private CulturalAppearance.InteriorLightsValue interiorLights; private CulturalAppearance.MaskedCloakedValue maskedCloaked; /// <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 !=(CulturalAppearance left, CulturalAppearance 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 operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(CulturalAppearance left, CulturalAppearance right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> to <see cref="System.UInt32"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(CulturalAppearance obj) { return obj.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/>. /// </summary> /// <param name="value">The uint value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator CulturalAppearance(uint value) { return CulturalAppearance.FromUInt32(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static CulturalAppearance FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 4 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt32(BitConverter.ToUInt32(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance from the uint value. /// </summary> /// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance, represented by the uint value.</returns> public static CulturalAppearance FromUInt32(uint value) { CulturalAppearance ps = new CulturalAppearance(); uint mask1 = 0x0018; byte shift1 = 3; uint newValue1 = value & mask1 >> shift1; ps.Damage = (CulturalAppearance.DamageValue)newValue1; uint mask2 = 0x0060; byte shift2 = 5; uint newValue2 = value & mask2 >> shift2; ps.Smoke = (CulturalAppearance.SmokeValue)newValue2; uint mask4 = 0x8000; byte shift4 = 15; uint newValue4 = value & mask4 >> shift4; ps.Flaming = (CulturalAppearance.FlamingValue)newValue4; uint mask6 = 0x200000; byte shift6 = 21; uint newValue6 = value & mask6 >> shift6; ps.FrozenStatus = (CulturalAppearance.FrozenStatusValue)newValue6; uint mask7 = 0x400000; byte shift7 = 22; uint newValue7 = value & mask7 >> shift7; ps.InternalHeatStatus = (CulturalAppearance.InternalHeatStatusValue)newValue7; uint mask8 = 0x800000; byte shift8 = 23; uint newValue8 = value & mask8 >> shift8; ps.State = (CulturalAppearance.StateValue)newValue8; uint mask10 = 0x10000000; byte shift10 = 28; uint newValue10 = value & mask10 >> shift10; ps.ExteriorLights = (CulturalAppearance.ExteriorLightsValue)newValue10; uint mask11 = 0x20000000; byte shift11 = 29; uint newValue11 = value & mask11 >> shift11; ps.InteriorLights = (CulturalAppearance.InteriorLightsValue)newValue11; uint mask13 = 0x80000000; byte shift13 = 31; uint newValue13 = value & mask13 >> shift13; ps.MaskedCloaked = (CulturalAppearance.MaskedCloakedValue)newValue13; return ps; } /// <summary> /// Gets or sets the damage. /// </summary> /// <value>The damage.</value> public CulturalAppearance.DamageValue Damage { get { return this.damage; } set { this.damage = value; } } /// <summary> /// Gets or sets the smoke. /// </summary> /// <value>The smoke.</value> public CulturalAppearance.SmokeValue Smoke { get { return this.smoke; } set { this.smoke = value; } } /// <summary> /// Gets or sets the flaming. /// </summary> /// <value>The flaming.</value> public CulturalAppearance.FlamingValue Flaming { get { return this.flaming; } set { this.flaming = value; } } /// <summary> /// Gets or sets the frozenstatus. /// </summary> /// <value>The frozenstatus.</value> public CulturalAppearance.FrozenStatusValue FrozenStatus { get { return this.frozenStatus; } set { this.frozenStatus = value; } } /// <summary> /// Gets or sets the internalheatstatus. /// </summary> /// <value>The internalheatstatus.</value> public CulturalAppearance.InternalHeatStatusValue InternalHeatStatus { get { return this.internalHeatStatus; } set { this.internalHeatStatus = value; } } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public CulturalAppearance.StateValue State { get { return this.state; } set { this.state = value; } } /// <summary> /// Gets or sets the exteriorlights. /// </summary> /// <value>The exteriorlights.</value> public CulturalAppearance.ExteriorLightsValue ExteriorLights { get { return this.exteriorLights; } set { this.exteriorLights = value; } } /// <summary> /// Gets or sets the interiorlights. /// </summary> /// <value>The interiorlights.</value> public CulturalAppearance.InteriorLightsValue InteriorLights { get { return this.interiorLights; } set { this.interiorLights = value; } } /// <summary> /// Gets or sets the maskedcloaked. /// </summary> /// <value>The maskedcloaked.</value> public CulturalAppearance.MaskedCloakedValue MaskedCloaked { get { return this.maskedCloaked; } set { this.maskedCloaked = value; } } /// <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) { if (obj == null) { return false; } if (!(obj is CulturalAppearance)) { return false; } return this.Equals((CulturalAppearance)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(CulturalAppearance other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.Damage == other.Damage && this.Smoke == other.Smoke && this.Flaming == other.Flaming && this.FrozenStatus == other.FrozenStatus && this.InternalHeatStatus == other.InternalHeatStatus && this.State == other.State && this.ExteriorLights == other.ExteriorLights && this.InteriorLights == other.InteriorLights && this.MaskedCloaked == other.MaskedCloaked; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt32()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> to the uint value. /// </summary> /// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.CulturalAppearance"/> instance.</returns> public uint ToUInt32() { uint val = 0; val |= (uint)((uint)this.Damage << 3); val |= (uint)((uint)this.Smoke << 5); val |= (uint)((uint)this.Flaming << 15); val |= (uint)((uint)this.FrozenStatus << 21); val |= (uint)((uint)this.InternalHeatStatus << 22); val |= (uint)((uint)this.State << 23); val |= (uint)((uint)this.ExteriorLights << 28); val |= (uint)((uint)this.InteriorLights << 29); val |= (uint)((uint)this.MaskedCloaked << 31); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.Damage.GetHashCode(); hash = (hash * 29) + this.Smoke.GetHashCode(); hash = (hash * 29) + this.Flaming.GetHashCode(); hash = (hash * 29) + this.FrozenStatus.GetHashCode(); hash = (hash * 29) + this.InternalHeatStatus.GetHashCode(); hash = (hash * 29) + this.State.GetHashCode(); hash = (hash * 29) + this.ExteriorLights.GetHashCode(); hash = (hash * 29) + this.InteriorLights.GetHashCode(); hash = (hash * 29) + this.MaskedCloaked.GetHashCode(); } return hash; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security; using System.Text; using System.Threading; using System.Web; using ASC.Core; using ASC.Core.Common.Configuration; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.FederatedLogin; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.LoginProviders; using ASC.FederatedLogin.Profile; using ASC.Files.Core; using ASC.MessagingSystem; using ASC.Security.Cryptography; using ASC.Web.Core; using ASC.Web.Core.Files; using ASC.Web.Core.Users; using ASC.Web.Files.Classes; using ASC.Web.Files.Core; using ASC.Web.Files.HttpHandlers; using ASC.Web.Files.Resources; using ASC.Web.Files.Services.DocumentService; using ASC.Web.Studio.Core; using ASC.Web.Studio.Core.Users; using ASC.Web.Studio.UserControls.Common; using ASC.Web.Studio.Utility; using Newtonsoft.Json.Linq; using File = ASC.Files.Core.File; using MimeMapping = ASC.Common.Web.MimeMapping; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.Web.Files.ThirdPartyApp { public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider { public const string AppAttr = "gdrive"; public string Scopes { get { return ""; } } public string CodeUrl { get { return ""; } } public string AccessTokenUrl { get { return GoogleLoginProvider.Instance.AccessTokenUrl; } } public string RedirectUri { get { return this["googleDriveAppRedirectUrl"]; } } public string ClientID { get { return this["googleDriveAppClientId"]; } } public string ClientSecret { get { return this["googleDriveAppSecretKey"]; } } public bool IsEnabled { get { return !string.IsNullOrEmpty(ClientID) && !string.IsNullOrEmpty(ClientSecret); } } public GoogleDriveApp() { } public GoogleDriveApp(string name, int order, Dictionary<string, string> additional) : base(name, order, additional) { } public bool Request(HttpContext context) { switch ((context.Request[FilesLinkUtility.Action] ?? "").ToLower()) { case "stream": StreamFile(context); return true; case "convert": ConfirmConvertFile(context); return true; case "create": CreateFile(context); return true; } if (!string.IsNullOrEmpty(context.Request["code"])) { RequestCode(context); return true; } return false; } public string GetRefreshUrl() { return AccessTokenUrl; } public File GetFile(string fileId, out bool editable) { Global.Logger.Debug("GoogleDriveApp: get file " + fileId); fileId = ThirdPartySelector.GetFileId(fileId); var token = Token.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); editable = false; if (driveFile == null) return null; var jsonFile = JObject.Parse(driveFile); var file = new File { ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value<string>("id")), Title = Global.ReplaceInvalidCharsAndTruncate(GetCorrectTitle(jsonFile)), CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("createdTime")), ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modifiedTime")), ContentLength = Convert.ToInt64(jsonFile.Value<string>("size")), ModifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value<string>(), ProviderKey = "Google" }; var owners = jsonFile["owners"]; if (owners != null) { file.CreateByString = owners[0]["displayName"].Value<string>(); } editable = jsonFile["capabilities"]["canEdit"].Value<bool>(); return file; } public string GetFileStreamUrl(File file) { if (file == null) return string.Empty; var fileId = ThirdPartySelector.GetFileId(file.ID.ToString()); return GetFileStreamUrl(fileId); } private static string GetFileStreamUrl(string fileId) { Global.Logger.Debug("GoogleDriveApp: get file stream url " + fileId); var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath)); if (uriBuilder.Uri.IsLoopback) { uriBuilder.Host = Dns.GetHostName(); } var query = uriBuilder.Query; query += FilesLinkUtility.Action + "=stream&"; query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&"; query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&"; query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&"; query += ThirdPartySelector.AppAttr + "=" + AppAttr; return uriBuilder.Uri + "?" + query; } public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream) { Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + (stream == null ? " from - " + downloadUrl : " from stream")); fileId = ThirdPartySelector.GetFileId(fileId); var token = Token.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(driveFile); var currentType = GetCorrectExt(jsonFile); if (!fileType.Equals(currentType)) { try { if (stream != null) { downloadUrl = PathProvider.GetTempUrl(stream, fileType); downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl); } Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, null, null, false, out downloadUrl); stream = null; } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error convert", e); } } var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); request.Method = "PATCH"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = MimeMapping.GetMimeMapping(currentType); if (stream != null) { request.ContentLength = stream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = stream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } else { var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl); using (var downloadStream = new ResponseStream(downloadRequest.GetResponse())) { request.ContentLength = downloadStream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } } try { using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { string result = null; if (responseStream != null) { using (var readStream = new StreamReader(responseStream)) { result = readStream.ReadToEnd(); } } Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result); } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error save file stream", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } } private static void RequestCode(HttpContext context) { var state = context.Request["state"]; Global.Logger.Debug("GoogleDriveApp: state - " + state); if (string.IsNullOrEmpty(state)) { Global.Logger.Error("GoogleDriveApp: empty state"); throw new Exception("Empty state"); } var token = GetToken(context.Request["code"]); if (token == null) { Global.Logger.Error("GoogleDriveApp: token is null"); throw new SecurityException("Access token is null"); } var stateJson = JObject.Parse(state); var googleUserId = stateJson.Value<string>("userId"); if (SecurityContext.IsAuthenticated) { if (!CurrentUser(googleUserId)) { Global.Logger.Debug("GoogleDriveApp: logout for " + googleUserId); CookiesManager.ClearCookies(CookiesType.AuthKey); SecurityContext.Logout(); } } if (!SecurityContext.IsAuthenticated) { bool isNew; var userInfo = GetUserInfo(token, out isNew); if (userInfo == null) { Global.Logger.Error("GoogleDriveApp: UserInfo is null"); throw new Exception("Profile is null"); } var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID); CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey); MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialApp); if (isNew) { UserHelpTourHelper.IsNewUser = true; PersonalSettings.IsNewUser = true; PersonalSettings.IsNotActivated = true; } if (!string.IsNullOrEmpty(googleUserId) && !CurrentUser(googleUserId)) { AddLinker(googleUserId); } } Token.SaveToken(token); var action = stateJson.Value<string>("action"); switch (action) { case "create": var folderId = stateJson.Value<string>("folderId"); context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(folderId), true); return; case "open": var idsArray = stateJson.Value<JArray>("ids") ?? stateJson.Value<JArray>("exportIds"); if (idsArray == null) { Global.Logger.Error("GoogleDriveApp: ids is empty"); throw new Exception("File id is null"); } var fileId = idsArray.ToObject<List<string>>().FirstOrDefault(); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(driveFile); var ext = GetCorrectExt(jsonFile); if (FileUtility.ExtsMustConvert.Contains(ext) || GoogleLoginProvider.GoogleDriveExt.Contains(ext)) { Global.Logger.Debug("GoogleDriveApp: file must be converted"); if (FilesSettings.ConvertNotify) { context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId), true); return; } fileId = CreateConvertedFile(driveFile, token); } context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); return; } Global.Logger.Error("GoogleDriveApp: Action not identified"); throw new Exception("Action not identified"); } private static void StreamFile(HttpContext context) { try { var fileId = context.Request[FilesLinkUtility.FileId]; var auth = context.Request[FilesLinkUtility.AuthKey]; var userId = context.Request[CommonLinkUtility.ParamName_UserUserID]; Global.Logger.Debug("GoogleDriveApp: get file stream " + fileId); var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); Global.Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc); throw exc; } var token = Token.GetToken(AppAttr, userId); var driveFile = GetDriveFile(fileId, token); var jsonFile = JObject.Parse(driveFile); var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media"; if (string.IsNullOrEmpty(downloadUrl)) { Global.Logger.Error("GoogleDriveApp: downloadUrl is null"); throw new Exception("downloadUrl is null"); } Global.Logger.Debug("GoogleDriveApp: get file stream downloadUrl - " + downloadUrl); var request = (HttpWebRequest)WebRequest.Create(downloadUrl); request.Method = "GET"; request.Headers.Add("Authorization", "Bearer " + token); using (var response = request.GetResponse()) using (var stream = new ResponseStream(response)) { stream.CopyTo(context.Response.OutputStream); var contentLength = jsonFile.Value<string>("size"); Global.Logger.Debug("GoogleDriveApp: get file stream contentLength - " + contentLength); context.Response.AddHeader("Content-Length", contentLength); } } catch (Exception ex) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.Write(ex.Message); Global.Logger.Error("GoogleDriveApp: Error request " + context.Request.Url, ex); } try { context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); } catch (HttpException ex) { Global.Logger.Error("GoogleDriveApp StreamFile", ex); } } private static void ConfirmConvertFile(HttpContext context) { var fileId = context.Request[FilesLinkUtility.FileId]; Global.Logger.Debug("GoogleDriveApp: ConfirmConvertFile - " + fileId); var token = Token.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } fileId = CreateConvertedFile(driveFile, token); context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); } private static void CreateFile(HttpContext context) { var folderId = context.Request[FilesLinkUtility.FolderId]; var fileName = context.Request[FilesLinkUtility.FileTitle]; Global.Logger.Debug("GoogleDriveApp: CreateFile folderId - " + folderId + " fileName - " + fileName); var token = Token.GetToken(AppAttr); var culture = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).GetCulture(); var storeTemplate = Global.GetStoreTemplate(); var path = FileConstant.NewDocPath + culture + "/"; if (!storeTemplate.IsDirectory(path)) { path = FileConstant.NewDocPath + "en-US/"; } var ext = FileUtility.InternalExtension[FileUtility.GetFileTypeByFileName(fileName)]; path += "new" + ext; fileName = FileUtility.ReplaceFileExtension(fileName, ext); string driveFile; using (var content = storeTemplate.GetReadStream("", path)) { driveFile = CreateFile(content, fileName, folderId, token); } if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not created"); } var jsonFile = JObject.Parse(driveFile); var fileId = jsonFile.Value<string>("id"); context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); } private static Token GetToken(string code) { try { Global.Logger.Debug("GoogleDriveApp: GetAccessToken by code " + code); var token = OAuth20TokenHelper.GetAccessToken<GoogleDriveApp>(code); return new Token(token, AppAttr); } catch (Exception ex) { Global.Logger.Error(ex); } return null; } private static bool CurrentUser(string googleId) { var linker = new AccountLinker("webstudio"); var linkedProfiles = linker.GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.Google, googleId))); linkedProfiles = linkedProfiles.Concat(linker.GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.OpenId, googleId)))); Guid tmp; return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && tmp == SecurityContext.CurrentAccount.ID); } private static void AddLinker(string googleUserId) { Global.Logger.Debug("GoogleDriveApp: AddLinker " + googleUserId); var linker = new AccountLinker("webstudio"); linker.AddLink(SecurityContext.CurrentAccount.ID.ToString(), googleUserId, ProviderConstants.Google); } private static UserInfo GetUserInfo(Token token, out bool isNew) { isNew = false; if (token == null) { Global.Logger.Error("GoogleDriveApp: token is null"); throw new SecurityException("Access token is null"); } LoginProfile loginProfile = null; try { loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(token.ToString()); } catch (Exception ex) { Global.Logger.Error("GoogleDriveApp: userinfo request", ex); } if (loginProfile == null) { Global.Logger.Error("Error in userinfo request"); return null; } var userInfo = CoreContext.UserManager.GetUserByEmail(loginProfile.EMail); if (Equals(userInfo, Constants.LostUser)) { userInfo = LoginWithThirdParty.ProfileToUserInfo(loginProfile); var cultureName = loginProfile.Locale; if (string.IsNullOrEmpty(cultureName)) cultureName = Thread.CurrentThread.CurrentUICulture.Name; var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase)); if (cultureInfo != null) { userInfo.CultureName = cultureInfo.Name; } else { Global.Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName); } try { SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword()); } finally { SecurityContext.Logout(); } isNew = true; Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID); } return userInfo; } private static string GetDriveFile(string googleFileId, Token token) { if (token == null) { Global.Logger.Error("GoogleDriveApp: token is null"); throw new SecurityException("Access token is null"); } try { var requestUrl = GoogleLoginProvider.GoogleUrlFile + googleFileId + "?fields=" + HttpUtility.UrlEncode(GoogleLoginProvider.FilesFields); var resultResponse = RequestHelper.PerformRequest(requestUrl, headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } }); Global.Logger.Debug("GoogleDriveApp: file response - " + resultResponse); return resultResponse; } catch (Exception ex) { Global.Logger.Error("GoogleDriveApp: file request", ex); } return null; } private static string CreateFile(string contentUrl, string fileName, string folderId, Token token) { if (string.IsNullOrEmpty(contentUrl)) { Global.Logger.Error("GoogleDriveApp: downloadUrl is null"); throw new Exception("downloadUrl is null"); } Global.Logger.Debug("GoogleDriveApp: create from - " + contentUrl); var request = (HttpWebRequest)WebRequest.Create(contentUrl); using (var content = new ResponseStream(request.GetResponse())) { return CreateFile(content, fileName, folderId, token); } } private static string CreateFile(Stream content, string fileName, string folderId, Token token) { Global.Logger.Debug("GoogleDriveApp: create file"); var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "?uploadType=multipart"); using (var tmpStream = new MemoryStream()) { var boundary = DateTime.UtcNow.Ticks.ToString("x"); var folderdata = string.IsNullOrEmpty(folderId) ? "" : string.Format(",\"parents\":[\"{0}\"]", folderId); var metadata = string.Format("{{\"name\":\"{0}\"{1}}}", fileName, folderdata); var metadataPart = string.Format("\r\n--{0}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{1}", boundary, metadata); var bytes = Encoding.UTF8.GetBytes(metadataPart); tmpStream.Write(bytes, 0, bytes.Length); var mediaPartStart = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n", boundary, MimeMapping.GetMimeMapping(fileName)); bytes = Encoding.UTF8.GetBytes(mediaPartStart); tmpStream.Write(bytes, 0, bytes.Length); content.CopyTo(tmpStream); var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary); bytes = Encoding.UTF8.GetBytes(mediaPartEnd); tmpStream.Write(bytes, 0, bytes.Length); request.Method = "POST"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = "multipart/related; boundary=" + boundary; request.ContentLength = tmpStream.Length; Global.Logger.Debug("GoogleDriveApp: create file totalSize - " + tmpStream.Length); const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; tmpStream.Seek(0, SeekOrigin.Begin); while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } try { using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { string result = null; if (responseStream != null) { using (var readStream = new StreamReader(responseStream)) { result = readStream.ReadToEnd(); } } Global.Logger.Debug("GoogleDriveApp: create file response - " + result); return result; } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error create file", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } } return null; } private static string ConvertFile(string fileId, string fromExt) { Global.Logger.Debug("GoogleDriveApp: convert file"); var downloadUrl = GetFileStreamUrl(fileId); var toExt = FileUtility.GetInternalExtension(fromExt); try { Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, null, null, null, false, out downloadUrl); } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e); } return downloadUrl; } private static string CreateConvertedFile(string driveFile, Token token) { var jsonFile = JObject.Parse(driveFile); var fileName = GetCorrectTitle(jsonFile); var folderId = (string)jsonFile.SelectToken("parents[0]"); Global.Logger.Info("GoogleDriveApp: create copy - " + fileName); var ext = GetCorrectExt(jsonFile); var fileId = jsonFile.Value<string>("id"); if (GoogleLoginProvider.GoogleDriveExt.Contains(ext)) { var internalExt = FileUtility.GetGoogleDownloadableExtension(ext); fileName = FileUtility.ReplaceFileExtension(fileName, internalExt); var requiredMimeType = MimeMapping.GetMimeMapping(internalExt); var downloadUrl = GoogleLoginProvider.GoogleUrlFile + string.Format("{0}/export?mimeType={1}", fileId, HttpUtility.UrlEncode(requiredMimeType)); var request = (HttpWebRequest)WebRequest.Create(downloadUrl); request.Method = "GET"; request.Headers.Add("Authorization", "Bearer " + token); Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl); try { using (var fileStream = new ResponseStream(request.GetResponse())) { driveFile = CreateFile(fileStream, fileName, folderId, token); } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error download exportLink", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } } } else { var convertedUrl = ConvertFile(fileId, ext); if (string.IsNullOrEmpty(convertedUrl)) { Global.Logger.ErrorFormat("GoogleDriveApp: Error convertUrl. size {0}", FileSizeComment.FilesSizeToString(jsonFile.Value<int>("size"))); throw new Exception(FilesCommonResource.ErrorMassage_DocServiceException + " (convert)"); } var toExt = FileUtility.GetInternalExtension(fileName); fileName = FileUtility.ReplaceFileExtension(fileName, toExt); driveFile = CreateFile(convertedUrl, fileName, folderId, token); } jsonFile = JObject.Parse(driveFile); return jsonFile.Value<string>("id"); } private static string GetCorrectTitle(JToken jsonFile) { var title = jsonFile.Value<string>("name") ?? ""; var extTitle = FileUtility.GetFileExtension(title); var correctExt = GetCorrectExt(jsonFile); if (extTitle != correctExt) { title = title + correctExt; } return title; } private static string GetCorrectExt(JToken jsonFile) { var mimeType = (jsonFile.Value<string>("mimeType") ?? "").ToLower(); var ext = MimeMapping.GetExtention(mimeType); if (!GoogleLoginProvider.GoogleDriveExt.Contains(ext)) { var title = (jsonFile.Value<string>("name") ?? "").ToLower(); ext = FileUtility.GetFileExtension(title); if (MimeMapping.GetMimeMapping(ext) != mimeType) { var originalFilename = (jsonFile.Value<string>("originalFilename") ?? "").ToLower(); ext = FileUtility.GetFileExtension(originalFilename); if (MimeMapping.GetMimeMapping(ext) != mimeType) { ext = MimeMapping.GetExtention(mimeType); Global.Logger.Debug("GoogleDriveApp: Try GetCorrectExt - " + ext + " for - " + mimeType); } } } return ext; } } }
using System; using System.Data; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Reflection; using System.Collections.Specialized; using System.Xml; using Umbraco.Core.IO; using umbraco; using umbraco.cms.businesslogic.member; using System.Web.SessionState; namespace umbraco.presentation.umbracobase { // as of 4.10 the module has been replaced by Umbraco.Web.BaseRest.BaseRestHandler - stephan @zpqrtbnk [Obsolete("Has been replaced by BaseRestHandler.")] public class requestModule : IHttpModule { #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication httpApp) { //httpApp.PostAuthorizeRequest += new EventHandler(httpApp_PreRequestHandlerExecute); httpApp.PostAcquireRequestState += new EventHandler(httpApp_PostAcquireRequestState); httpApp.PostMapRequestHandler += new EventHandler(httpApp_PostMapRequestHandler); } void httpApp_PostMapRequestHandler(object sender, EventArgs e) { //remove extension and split the url HttpApplication httpApp = (HttpApplication)sender; string url = httpApp.Context.Request.RawUrl; string urlStart = IOHelper.ResolveUrl( SystemDirectories.Base ).TrimEnd('/').ToLower() + "/"; if (url.ToLower().StartsWith(urlStart)) { if (httpApp.Context.Handler is IReadOnlySessionState || httpApp.Context.Handler is IRequiresSessionState) { // no need to replace the current handler return; } // swap the current handler httpApp.Context.Handler = new MyHttpHandler(httpApp.Context.Handler); } } void httpApp_PostAcquireRequestState(object sender, EventArgs e) { HttpApplication httpApp = (HttpApplication)sender; //remove extension and split the url string url = httpApp.Context.Request.RawUrl; string urlStart = IOHelper.ResolveUrl(SystemDirectories.Base).TrimEnd('/').ToLower() + "/"; if (url.ToLower().StartsWith(urlStart)) { MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler; if (resourceHttpHandler != null) { // set the original handler back HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler; } string basedir = "/" + SystemDirectories.Base.TrimStart('~').Trim('/') + "/"; int indexOfBase = url.ToLower().IndexOf(basedir); url = url.Substring(indexOfBase); if (url.ToLower().Contains(".aspx")) url = url.Substring(0, url.IndexOf(".aspx")); if (url.ToLower().Contains("?")) url = url.Substring(0, url.IndexOf("?")); object[] urlArray = url.Split('/'); //There has to be minimum 4 parts in the url for this to work... /base/library/method/[parameter].aspx if (urlArray.Length >= 4) { string extensionAlias = urlArray[2].ToString(); string methodName = urlArray[3].ToString(); httpApp.Response.ContentType = "text/xml"; restExtension myExtension = new restExtension(extensionAlias, methodName); if (myExtension.isAllowed) { TrySetCulture(); string response = invokeMethod(myExtension, urlArray); // since return value is arbitrary (set by implementor), check length before checking for error if (response.Length >= 7) { if (response.Substring(0, 7) == "<error>") { httpApp.Response.StatusCode = 500; httpApp.Response.StatusDescription = "Internal Server Error"; } } httpApp.Response.Output.Write(response); } else { httpApp.Response.StatusCode = 500; httpApp.Response.StatusDescription = "Internal Server Error"; //Very static error msg... httpApp.Response.Output.Write("<error>Extension not found or permission denied</error>"); } //end the resposne httpApp.Response.End(); } } } private string invokeMethod(restExtension myExtension, object[] paras) { try { //So method is either not found or not valid... this should probably be moved... if (!myExtension.method.IsPublic || !myExtension.method.IsStatic) return "<error>Method has to be public and static</error>"; else //And if it is lets continue trying to invoke it... { //lets check if we have parameters enough in the url.. if (myExtension.method.GetParameters().Length > (paras.Length - 4)) //Too few return "<error>Not Enough parameters in url</error>"; else { //We have enough parameters... lets invoke.. //Create an instance of the type we need to invoke the method from. Object obj = Activator.CreateInstance(myExtension.type); Object response; //umbracoBase.baseBinder bBinder = new baseBinder(); if (myExtension.method.GetParameters().Length == 0) { //response = myMethod.method.Invoke(obj, BindingFlags.Public | BindingFlags.Instance, bBinder, null, System.Globalization.CultureInfo.CurrentCulture); response = myExtension.method.Invoke(obj, null); //Invoke with null as parameters as there are none } else { //We only need the parts of the url above the number 4 so we'll //recast those to objects and add them to the object[] //Getting the right lenght.. 4 is the magic number dum di dum.. object[] methodParams = new object[(paras.Length - 4)]; int i = 0; foreach (ParameterInfo pInfo in myExtension.method.GetParameters()) { Type myType = Type.GetType(pInfo.ParameterType.ToString()); methodParams[(i)] = Convert.ChangeType(paras[i + 4], myType); i++; } //Invoke with methodParams //response = myMethod.method.Invoke(obj, BindingFlags.Public | BindingFlags.Instance, bBinder, methodParams, System.Globalization.CultureInfo.CurrentCulture); response = myExtension.method.Invoke(obj, methodParams); } /*TODO - SOMETHING ALITTLE BETTER THEN ONLY CHECK FOR XPATHNODEITERATOR OR ELSE do ToString() */ if (response != null) { switch (myExtension.method.ReturnType.ToString()) { case "System.Xml.XPath.XPathNodeIterator": return ((System.Xml.XPath.XPathNodeIterator)response).Current.OuterXml; case "System.Xml.Linq.XDocument": return response.ToString(); case "System.Xml.XmlDocument": XmlDocument xmlDoc = (XmlDocument)response; StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); xmlDoc.WriteTo(xw); return sw.ToString(); default: string strResponse = ((string)response.ToString()); if (myExtension.returnXML) { //do a quick "is this html?" check... if it is add CDATA... if (strResponse.Contains("<") || strResponse.Contains(">")) strResponse = "<![CDATA[" + strResponse + "]]>"; return "<value>" + strResponse + "</value>"; } else { HttpContext.Current.Response.ContentType = "text/html"; return strResponse; } } } else { if (myExtension.returnXML) return "<error>Null value returned</error>"; else return string.Empty; } } } } catch (Exception ex) { //Overall exception handling... return "<error><![CDATA[MESSAGE:\n" + ex.Message + "\n\nSTACKTRACE:\n" + ex.StackTrace + "\n\nINNEREXCEPTION:\n" + ex.InnerException + "]]></error>"; } } private static void TrySetCulture() { string domain = HttpContext.Current.Request.Url.Host; //Host only if (TrySetCulture(domain)) return; domain = HttpContext.Current.Request.Url.Authority; //Host with port if (TrySetCulture(domain)) return; } private static bool TrySetCulture(string domain) { var uDomain = cms.businesslogic.web.Domain.GetDomain(domain); if (uDomain == null) return false; System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uDomain.Language.CultureAlias); return true; } } // a temp handler used to force the SessionStateModule to load session state public class MyHttpHandler : IHttpHandler, IRequiresSessionState { internal readonly IHttpHandler OriginalHandler; public MyHttpHandler(IHttpHandler originalHandler) { OriginalHandler = originalHandler; } public void ProcessRequest(HttpContext context) { // do not worry, ProcessRequest() will not be called, but let's be safe throw new InvalidOperationException("MyHttpHandler cannot process requests."); } public bool IsReusable { // IsReusable must be set to false since class has a member! get { return false; } } } } #endregion
using Facebook; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public sealed class FB : ScriptableObject { public static InitDelegate OnInitComplete; public static HideUnityDelegate OnHideUnity; private static IFacebook facebook; private static string authResponse; private static bool isInitCalled = false; private static string appId; private static bool cookie; private static bool logging; private static bool status; private static bool xfbml; private static bool frictionlessRequests; static IFacebook FacebookImpl { get { if (facebook == null) { throw new NullReferenceException("Facebook object is not yet loaded. Did you call FB.Init()?"); } return facebook; } } public static string AppId { get { // appId might be different from FBSettings.AppId // if using the programmatic version of FB.Init() return appId; } } public static string UserId { get { return (facebook != null) ? facebook.UserId : ""; } } public static string AccessToken { get { return (facebook != null) ? facebook.AccessToken : ""; } } public static DateTime AccessTokenExpiresAt { get { return (facebook != null) ? facebook.AccessTokenExpiresAt : DateTime.MinValue; } } public static bool IsLoggedIn { get { return (facebook != null) && facebook.IsLoggedIn; } } #region Init /** * This is the preferred way to call FB.Init(). It will take the facebook app id specified in your * "Facebook" => "Edit Settings" menu when it is called. * * onInitComplete - Delegate is called when FB.Init() finished initializing everything. * By passing in a delegate you can find out when you can safely call the other methods. */ public static void Init(InitDelegate onInitComplete, HideUnityDelegate onHideUnity = null, string authResponse = null) { Init( onInitComplete, FBSettings.AppId, FBSettings.Cookie, FBSettings.Logging, FBSettings.Status, FBSettings.Xfbml, FBSettings.FrictionlessRequests, onHideUnity, authResponse); } /** * If you need a more programmatic way to set the facebook app id and other setting call this function. * Useful for a build pipeline that requires no human input. */ public static void Init( InitDelegate onInitComplete, string appId, bool cookie = true, bool logging = true, bool status = true, bool xfbml = false, bool frictionlessRequests = true, HideUnityDelegate onHideUnity = null, string authResponse = null) { FB.appId = appId; FB.cookie = cookie; FB.logging = logging; FB.status = status; FB.xfbml = xfbml; FB.frictionlessRequests = frictionlessRequests; FB.authResponse = authResponse; FB.OnInitComplete = onInitComplete; FB.OnHideUnity = onHideUnity; if (!isInitCalled) { var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(typeof (IFacebook)); if (versionInfo == null) { FbDebug.Warn("Cannot find Facebook SDK Version"); } else { FbDebug.Info(String.Format("Using SDK {0}, Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion)); } #if UNITY_EDITOR FBComponentFactory.GetComponent<EditorFacebookLoader>(); #elif UNITY_WEBPLAYER FBComponentFactory.GetComponent<CanvasFacebookLoader>(); #elif UNITY_IOS FBComponentFactory.GetComponent<IOSFacebookLoader>(); #elif UNITY_ANDROID FBComponentFactory.GetComponent<AndroidFacebookLoader>(); #else throw new NotImplementedException("Facebook API does not yet support this platform"); #endif isInitCalled = true; return; } FbDebug.Warn("FB.Init() has already been called. You only need to call this once and only once."); // Init again if possible just in case something bad actually happened. if (FacebookImpl != null) { OnDllLoaded(); } } private static void OnDllLoaded() { var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(FacebookImpl.GetType()); if (versionInfo == null) { FbDebug.Warn("Finished loading Facebook dll, but could not find version info"); } else { FbDebug.Log(string.Format("Finished loading Facebook dll. Version {0} Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion)); } FacebookImpl.Init( OnInitComplete, appId, cookie, logging, status, xfbml, FBSettings.ChannelUrl, authResponse, frictionlessRequests, OnHideUnity ); } #endregion public static void Login(string scope = "", FacebookDelegate callback = null) { FacebookImpl.Login(scope, callback); } public static void Logout() { FacebookImpl.Logout(); } public static void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null) { FacebookImpl.AppRequest(message, to, filters, excludeIds, maxRecipients, data, title, callback); } public static void Feed( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { FacebookImpl.FeedRequest(toId, link, linkName, linkCaption, linkDescription, picture, mediaSource, actionName, actionLink, reference, properties, callback); } public static void API(string query, HttpMethod method, FacebookDelegate callback = null, Dictionary<string, string> formData = null) { FacebookImpl.API(query, method, formData, callback); } public static void API(string query, HttpMethod method, FacebookDelegate callback, WWWForm formData) { FacebookImpl.API(query, method, formData, callback); } public static void PublishInstall(FacebookDelegate callback = null) { FacebookImpl.PublishInstall(AppId, callback); } public static void GetDeepLink(FacebookDelegate callback) { FacebookImpl.GetDeepLink(callback); } #region App Events public sealed class AppEvents { // If the player has set the limitEventUsage flag to YES, your app will continue // to send this data to Facebook, but Facebook will not use the data to serve // targeted ads. Facebook may continue to use the information for other purposes, // including frequency capping, conversion events, estimating the number of unique // users, security and fraud detection, and debugging. public static bool LimitEventUsage { get { return (facebook != null) && facebook.LimitEventUsage; } set { facebook.LimitEventUsage = value; } } public static void LogEvent( string logEvent, float? valueToSum = null, Dictionary<string, object> parameters = null) { FacebookImpl.AppEventsLogEvent(logEvent, valueToSum, parameters); } public static void LogPurchase( float logPurchase, string currency = "USD", Dictionary<string, object> parameters = null) { FacebookImpl.AppEventsLogPurchase(logPurchase, currency, parameters); } } #endregion #region Canvas-Only Implemented Methods public sealed class Canvas { public static void Pay( string product, string action = "purchaseitem", int quantity = 1, int? quantityMin = null, int? quantityMax = null, string requestId = null, string pricepointId = null, string testCurrency = null, FacebookDelegate callback = null) { FacebookImpl.Pay(product, action, quantity, quantityMin, quantityMax, requestId, pricepointId, testCurrency, callback); } public static void SetResolution(int width, int height, bool fullscreen, int preferredRefreshRate = 0, params FBScreen.Layout[] layoutParams) { FBScreen.SetResolution(width, height, fullscreen, preferredRefreshRate, layoutParams); } public static void SetAspectRatio(int width, int height, params FBScreen.Layout[] layoutParams) { FBScreen.SetAspectRatio(width, height, layoutParams); } } #endregion #region Android-Only Implemented Methods public sealed class Android { public static string KeyHash { get { var androidFacebook = facebook as AndroidFacebook; return (androidFacebook != null) ? androidFacebook.KeyHash : ""; } } } #endregion #region Facebook Loader Class public abstract class RemoteFacebookLoader : MonoBehaviour { public delegate void LoadedDllCallback(IFacebook fb); private const string facebookNamespace = "Facebook."; private const int maxRetryLoadCount = 3; private static int retryLoadCount = 0; public static IEnumerator LoadFacebookClass(string className, LoadedDllCallback callback) { var url = string.Format(IntegratedPluginCanvasLocation.DllUrl, className); var www = new WWW(url); FbDebug.Log("loading dll: " + url); yield return www; if (www.error != null) { FbDebug.Error(www.error); if (retryLoadCount < maxRetryLoadCount) { ++retryLoadCount; #if UNITY_WEBPLAYER FBComponentFactory.AddComponent<CanvasFacebookLoader>(); #endif } www.Dispose(); yield break; } #if !UNITY_WINRT var assembly = Security.LoadAndVerifyAssembly(www.bytes); if (assembly == null) { FbDebug.Error("Could not securely load assembly from " + url); www.Dispose(); yield break; } var facebookClass = assembly.GetType(facebookNamespace + className); if (facebookClass == null) { FbDebug.Error(className + " not found in assembly!"); www.Dispose(); yield break; } // load the Facebook component into the gameobject // using the "as" cast so it'll null if it fails to cast, instead of exception var fb = typeof(FBComponentFactory) .GetMethod("GetComponent") .MakeGenericMethod(facebookClass) .Invoke(null, new object[] { IfNotExist.AddNew }) as IFacebook; if (fb == null) { FbDebug.Error(className + " couldn't be created."); www.Dispose(); yield break; } callback(fb); #endif www.Dispose(); } protected abstract string className { get; } IEnumerator Start() { var loader = LoadFacebookClass(className, OnDllLoaded); while (loader.MoveNext()) { yield return loader.Current; } Destroy(this); } private void OnDllLoaded(IFacebook fb) { FB.facebook = fb; FB.OnDllLoaded(); } } public abstract class CompiledFacebookLoader : MonoBehaviour { protected abstract IFacebook fb { get; } void Start() { FB.facebook = fb; FB.OnDllLoaded(); Destroy(this); } } #endregion }
//----------------------------------------------------------------------------- // <copyright file="DiagnosticTrace.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace System.Transactions.Diagnostics { /// <summary> /// Server side infrastructure file on the server for use /// by Indigo infrastructure classes /// /// DiagnosticTrace consists of static methods, properties and collections /// that can be accessed by Indigo infrastructure code to provide /// instrumentation. /// </summary> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Remoting.Messaging; using System.Security; using System.Text; using System.Threading; using System.Web; using System.Xml; using System.Xml.XPath; using System.ComponentModel; internal static class DiagnosticTrace { internal const string DefaultTraceListenerName = "Default"; static TraceSource traceSource = null; static bool tracingEnabled = true; static bool haveListeners = false; static Dictionary<int, string> traceEventTypeNames; static object localSyncObject = new object(); static int traceFailureCount = 0; static int traceFailureThreshold = 0; static SourceLevels level; static bool calledShutdown = false; static bool shouldCorrelate = false; static bool shouldTraceVerbose = false; static bool shouldTraceInformation = false; static bool shouldTraceWarning = false; static bool shouldTraceError = false; static bool shouldTraceCritical = false; internal static Guid EmptyGuid = Guid.Empty; static string AppDomainFriendlyName = null; const string subType = ""; const string version = "1"; const int traceFailureLogThreshold = 10; const string EventLogSourceName = ".NET Runtime"; const string TraceSourceName = "System.Transactions"; const string TraceRecordVersion = "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"; // System.Diagnostics.Process has a FullTrust link demand. We satisfy that FullTrust demand and do not leak the // Process object out of this call. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] static string ProcessName { get { string retval = null; using (Process process = Process.GetCurrentProcess()) { retval = process.ProcessName; } return retval; } } // System.Diagnostics.Process has a FullTrust link demand. We satisfy that FullTrust demand and do not leak the // Process object out of this call. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] static int ProcessId { get { int retval = -1; using (Process process = Process.GetCurrentProcess()) { retval = process.Id; } return retval; } } static TraceSource TraceSource { get { return DiagnosticTrace.traceSource; } set { DiagnosticTrace.traceSource = value; } } static Dictionary<int, string> TraceEventTypeNames { get { return DiagnosticTrace.traceEventTypeNames; } } static SourceLevels FixLevel(SourceLevels level) { //the bit fixing below is meant to keep the trace level legal even if somebody uses numbers in config if (((level & ~SourceLevels.Information) & SourceLevels.Verbose) != 0) { level |= SourceLevels.Verbose; } else if (((level & ~SourceLevels.Warning) & SourceLevels.Information) != 0) { level |= SourceLevels.Information; } else if (((level & ~SourceLevels.Error) & SourceLevels.Warning) != 0) { level |= SourceLevels.Warning; } if (((level & ~SourceLevels.Critical) & SourceLevels.Error) != 0) { level |= SourceLevels.Error; } if ((level & SourceLevels.Critical) != 0) { level |= SourceLevels.Critical; } return (level & ~SourceLevels.Warning) != 0 ? level | SourceLevels.ActivityTracing : level; } static void SetLevel(SourceLevels level) { SourceLevels fixedLevel = FixLevel(level); DiagnosticTrace.level = fixedLevel; if (DiagnosticTrace.TraceSource != null) { DiagnosticTrace.TraceSource.Switch.Level = fixedLevel; DiagnosticTrace.shouldCorrelate = DiagnosticTrace.ShouldTrace(TraceEventType.Transfer); DiagnosticTrace.shouldTraceVerbose = DiagnosticTrace.ShouldTrace(TraceEventType.Verbose); DiagnosticTrace.shouldTraceInformation = DiagnosticTrace.ShouldTrace(TraceEventType.Information); DiagnosticTrace.shouldTraceWarning = DiagnosticTrace.ShouldTrace(TraceEventType.Warning); DiagnosticTrace.shouldTraceError = DiagnosticTrace.ShouldTrace(TraceEventType.Error); DiagnosticTrace.shouldTraceCritical = DiagnosticTrace.ShouldTrace(TraceEventType.Critical); } } static void SetLevelThreadSafe(SourceLevels level) { if (DiagnosticTrace.TracingEnabled && level != DiagnosticTrace.Level) { lock (DiagnosticTrace.localSyncObject) { SetLevel(level); } } } internal static SourceLevels Level { //Do not call this property from Initialize! get { if (DiagnosticTrace.TraceSource != null && (DiagnosticTrace.TraceSource.Switch.Level != DiagnosticTrace.level)) { DiagnosticTrace.level = DiagnosticTrace.TraceSource.Switch.Level; } return DiagnosticTrace.level; } set { SetLevelThreadSafe(value); } } internal static bool HaveListeners { get { return DiagnosticTrace.haveListeners; } } internal static bool TracingEnabled { get { return DiagnosticTrace.tracingEnabled && DiagnosticTrace.traceSource != null; } } static DiagnosticTrace() { // We own the resource and it hasn't been filled in yet. //needed for logging events to event log DiagnosticTrace.AppDomainFriendlyName = AppDomain.CurrentDomain.FriendlyName; DiagnosticTrace.traceEventTypeNames = new Dictionary<int, string>(); // Initialize the values here to avoid bringing in unnecessary pages. // Address MB#20806 DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Critical] = "Critical"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Error] = "Error"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Warning] = "Warning"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Information] = "Information"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Verbose] = "Verbose"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Resume] = "Resume"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Start] = "Start"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Stop] = "Stop"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Suspend] = "Suspend"; DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Transfer] = "Transfer"; #if DEBUG // The following asserts are established to make sure that // the strings we have above continue to be correct. Any failures // should be discoverable during development time since this // code is in the main path. Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Critical], TraceEventType.Critical.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Error], TraceEventType.Error.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Warning], TraceEventType.Warning.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Information], TraceEventType.Information.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Verbose], TraceEventType.Verbose.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Resume], TraceEventType.Resume.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Start], TraceEventType.Start.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Stop], TraceEventType.Stop.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Suspend], TraceEventType.Suspend.ToString(), StringComparison.Ordinal)); Debug.Assert(string.Equals(DiagnosticTrace.traceEventTypeNames[(int)TraceEventType.Transfer], TraceEventType.Transfer.ToString(), StringComparison.Ordinal)); #endif DiagnosticTrace.TraceFailureThreshold = DiagnosticTrace.traceFailureLogThreshold; DiagnosticTrace.TraceFailureCount = DiagnosticTrace.TraceFailureThreshold + 1; try { DiagnosticTrace.traceSource = new TraceSource(DiagnosticTrace.TraceSourceName, SourceLevels.Critical); AppDomain currentDomain = AppDomain.CurrentDomain; if (DiagnosticTrace.TraceSource.Switch.ShouldTrace(TraceEventType.Critical)) { currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); } currentDomain.DomainUnload += new EventHandler(ExitOrUnloadEventHandler); currentDomain.ProcessExit += new EventHandler(ExitOrUnloadEventHandler); DiagnosticTrace.haveListeners = DiagnosticTrace.TraceSource.Listeners.Count > 0; DiagnosticTrace.SetLevel(DiagnosticTrace.TraceSource.Switch.Level); } catch (System.Configuration.ConfigurationErrorsException) { throw; } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch (Exception e) { if (DiagnosticTrace.TraceSource == null) { LogEvent(TraceEventType.Error, String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FailedToCreateTraceSource), e), true); } else { DiagnosticTrace.TraceSource = null; LogEvent(TraceEventType.Error, String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FailedToInitializeTraceSource), e), true); } } } internal static bool ShouldTrace(TraceEventType type) { return 0 != ((int)type & (int)DiagnosticTrace.Level) && (DiagnosticTrace.TraceSource != null) && (DiagnosticTrace.HaveListeners); } internal static bool ShouldCorrelate { get { return DiagnosticTrace.shouldCorrelate; } } internal static bool Critical { get { return DiagnosticTrace.shouldTraceCritical; } } internal static bool Error { get { return DiagnosticTrace.shouldTraceError; } } internal static bool Warning { get { return DiagnosticTrace.shouldTraceWarning; } } internal static bool Information { get { return DiagnosticTrace.shouldTraceInformation; } } internal static bool Verbose { get { return DiagnosticTrace.shouldTraceVerbose; } } static internal void TraceEvent(TraceEventType type, string code, string description) { DiagnosticTrace.TraceEvent(type, code, description, null, null, ref DiagnosticTrace.EmptyGuid, false, null); } static internal void TraceEvent(TraceEventType type, string code, string description, TraceRecord trace) { DiagnosticTrace.TraceEvent(type, code, description, trace, null, ref DiagnosticTrace.EmptyGuid, false, null); } static internal void TraceEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception) { DiagnosticTrace.TraceEvent(type, code, description, trace, exception, ref DiagnosticTrace.EmptyGuid, false, null); } static internal void TraceEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, ref Guid activityId, bool emitTransfer, object source) { #if DEBUG Debug.Assert(exception == null || type <= TraceEventType.Information); Debug.Assert(!string.IsNullOrEmpty(description), "All TraceCodes should have a description"); #endif if (DiagnosticTrace.ShouldTrace(type)) { using (Activity.CreateActivity(activityId, emitTransfer)) { XPathNavigator navigator = BuildTraceString(type, code, description, trace, exception, source); try { DiagnosticTrace.TraceSource.TraceData(type, 0, navigator); if (DiagnosticTrace.calledShutdown) { DiagnosticTrace.TraceSource.Flush(); } } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch (Exception e) { string traceString = SR.GetString(SR.TraceFailure, type.ToString(), code, description, source == null ? string.Empty : DiagnosticTrace.CreateSourceString(source)); LogTraceFailure(traceString, e); } } } } static internal void TraceAndLogEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, ref Guid activityId, object source) { bool shouldTrace = DiagnosticTrace.ShouldTrace(type); string traceString = null; try { LogEvent(type, code, description, trace, exception, source); if (shouldTrace) { DiagnosticTrace.TraceEvent(type, code, description, trace, exception, ref activityId, false, source); } } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch (Exception e) { LogTraceFailure(traceString, e); } } static internal void TraceTransfer(Guid newId) { Guid oldId = DiagnosticTrace.GetActivityId(); if (DiagnosticTrace.ShouldCorrelate && newId != oldId) { if (DiagnosticTrace.HaveListeners) { try { if (newId != oldId) { DiagnosticTrace.TraceSource.TraceTransfer(0, null, newId); } } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch (Exception e) { LogTraceFailure(null, e); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] static internal Guid GetActivityId() { object id = Trace.CorrelationManager.ActivityId; return id == null ? Guid.Empty : (Guid)id; } static internal void GetActivityId(ref Guid guid) { //If activity id propagation is disabled for performance, we return nothing avoiding CallContext access. if (DiagnosticTrace.ShouldCorrelate) { guid = DiagnosticTrace.GetActivityId(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] static internal void SetActivityId(Guid id) { Trace.CorrelationManager.ActivityId = id; } static string CreateSourceString(object source) { return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture); } static void LogEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, object source) { StringBuilder traceString = new StringBuilder(SR.GetString(SR.EventLogValue, DiagnosticTrace.ProcessName, DiagnosticTrace.ProcessId.ToString(CultureInfo.CurrentCulture), code, description)); if (source != null) { traceString.AppendLine(SR.GetString(SR.EventLogSourceValue, DiagnosticTrace.CreateSourceString(source))); } if (exception != null) { traceString.AppendLine(SR.GetString(SR.EventLogExceptionValue, exception.ToString())); } if (trace != null) { traceString.AppendLine(SR.GetString(SR.EventLogEventIdValue, trace.EventId)); traceString.AppendLine(SR.GetString(SR.EventLogTraceValue, trace.ToString())); } LogEvent(type, traceString.ToString(), false); } static internal void LogEvent(TraceEventType type, string message, bool addProcessInfo) { if (addProcessInfo) { message = String.Format(CultureInfo.CurrentCulture, "{0}: {1}\n{2}: {3}\n{4}", DiagnosticStrings.ProcessName, DiagnosticTrace.ProcessName, DiagnosticStrings.ProcessId, DiagnosticTrace.ProcessId, message); } LogEvent(type, message); } static internal void LogEvent(TraceEventType type, string message) { try { const int MaxEventLogLength = 8192; if (!string.IsNullOrEmpty(message) && message.Length >= MaxEventLogLength) { message = message.Substring(0, MaxEventLogLength - 1); } EventLog.WriteEntry(DiagnosticTrace.EventLogSourceName, message, EventLogEntryTypeFromEventType(type)); } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch { } } static string LookupSeverity(TraceEventType type) { int level = (int)type & (int)SourceLevels.Verbose; if (((int)type & ((int)TraceEventType.Start | (int)TraceEventType.Stop)) != 0) { level = (int)type; } else if (level == 0) { level = (int)TraceEventType.Verbose; } return DiagnosticTrace.TraceEventTypeNames[level]; } static int TraceFailureCount { get { return DiagnosticTrace.traceFailureCount; } set { DiagnosticTrace.traceFailureCount = value; } } static int TraceFailureThreshold { get { return DiagnosticTrace.traceFailureThreshold; } set { DiagnosticTrace.traceFailureThreshold = value; } } //log failure every traceFailureLogThreshold time, increase the threshold progressively static void LogTraceFailure(string traceString, Exception e) { if (e != null) { traceString = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FailedToTraceEvent), e, traceString != null ? traceString : ""); } lock (DiagnosticTrace.localSyncObject) { if (DiagnosticTrace.TraceFailureCount > DiagnosticTrace.TraceFailureThreshold) { DiagnosticTrace.TraceFailureCount = 1; DiagnosticTrace.TraceFailureThreshold *= 2; LogEvent(TraceEventType.Error, traceString, true); } else { DiagnosticTrace.TraceFailureCount++; } } } static void ShutdownTracing() { if (null != DiagnosticTrace.TraceSource) { try { if (DiagnosticTrace.Level != SourceLevels.Off) { if (DiagnosticTrace.Information) { Dictionary<string, string> values = new Dictionary<string, string>(3); values["AppDomain.FriendlyName"] = AppDomain.CurrentDomain.FriendlyName; values["ProcessName"] = DiagnosticTrace.ProcessName; values["ProcessId"] = DiagnosticTrace.ProcessId.ToString(CultureInfo.CurrentCulture); DiagnosticTrace.TraceEvent(TraceEventType.Information, DiagnosticTraceCode.AppDomainUnload, SR.GetString(SR.TraceCodeAppDomainUnloading), new DictionaryTraceRecord(values), null, ref DiagnosticTrace.EmptyGuid, false, null); } DiagnosticTrace.calledShutdown = true; DiagnosticTrace.TraceSource.Flush(); } } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (ThreadAbortException) { throw; } catch (Exception exception) { LogTraceFailure(null, exception); } } } static void ExitOrUnloadEventHandler(object sender, EventArgs e) { ShutdownTracing(); } static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception)args.ExceptionObject; TraceEvent(TraceEventType.Critical, DiagnosticTraceCode.UnhandledException, SR.GetString(SR.UnhandledException), null, e, ref DiagnosticTrace.EmptyGuid, false, null); ShutdownTracing(); } static XPathNavigator BuildTraceString(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, object source) { return DiagnosticTrace.BuildTraceString(new PlainXmlWriter(), type, code, description, trace, exception, source); } static XPathNavigator BuildTraceString(PlainXmlWriter xml, TraceEventType type, string code, string description, TraceRecord trace, Exception exception, object source) { xml.WriteStartElement(DiagnosticStrings.TraceRecordTag); xml.WriteAttributeString(DiagnosticStrings.NamespaceTag, DiagnosticTrace.TraceRecordVersion); xml.WriteAttributeString(DiagnosticStrings.SeverityTag, DiagnosticTrace.LookupSeverity(type)); xml.WriteElementString(DiagnosticStrings.TraceCodeTag, code); xml.WriteElementString(DiagnosticStrings.DescriptionTag, description); xml.WriteElementString(DiagnosticStrings.AppDomain, DiagnosticTrace.AppDomainFriendlyName); if (source != null) { xml.WriteElementString(DiagnosticStrings.SourceTag, DiagnosticTrace.CreateSourceString(source)); } if (trace != null) { xml.WriteStartElement(DiagnosticStrings.ExtendedDataTag); xml.WriteAttributeString(DiagnosticStrings.NamespaceTag, trace.EventId); trace.WriteTo(xml); xml.WriteEndElement(); } if (exception != null) { xml.WriteStartElement(DiagnosticStrings.ExceptionTag); DiagnosticTrace.AddExceptionToTraceString(xml, exception); xml.WriteEndElement(); } xml.WriteEndElement(); return xml.ToNavigator(); } static void AddExceptionToTraceString(XmlWriter xml, Exception exception) { xml.WriteElementString(DiagnosticStrings.ExceptionTypeTag, DiagnosticTrace.XmlEncode(exception.GetType().AssemblyQualifiedName)); xml.WriteElementString(DiagnosticStrings.MessageTag, DiagnosticTrace.XmlEncode(exception.Message)); xml.WriteElementString(DiagnosticStrings.StackTraceTag, DiagnosticTrace.XmlEncode(DiagnosticTrace.StackTraceString(exception))); xml.WriteElementString(DiagnosticStrings.ExceptionStringTag, DiagnosticTrace.XmlEncode(exception.ToString())); Win32Exception win32Exception = exception as Win32Exception; if (win32Exception != null) { xml.WriteElementString(DiagnosticStrings.NativeErrorCodeTag, win32Exception.NativeErrorCode.ToString("X", CultureInfo.InvariantCulture)); } if (exception.Data != null && exception.Data.Count > 0) { xml.WriteStartElement(DiagnosticStrings.DataItemsTag); foreach (object dataItem in exception.Data.Keys) { xml.WriteStartElement(DiagnosticStrings.DataTag); //Fix for Watson bug CSDMain 136718 - Add the null check incase the value is null. Only if both the key and value are non null, //write out the xml elements corresponding to them if (dataItem != null && exception.Data[dataItem] != null) { xml.WriteElementString(DiagnosticStrings.KeyTag, DiagnosticTrace.XmlEncode(dataItem.ToString())); xml.WriteElementString(DiagnosticStrings.ValueTag, DiagnosticTrace.XmlEncode(exception.Data[dataItem].ToString())); } xml.WriteEndElement(); } xml.WriteEndElement(); } if (exception.InnerException != null) { xml.WriteStartElement(DiagnosticStrings.InnerExceptionTag); DiagnosticTrace.AddExceptionToTraceString(xml, exception.InnerException); xml.WriteEndElement(); } } static string StackTraceString(Exception exception) { string retval = exception.StackTrace; if (string.IsNullOrEmpty(retval)) { // This means that the exception hasn't been thrown yet. We need to manufacture the stack then. StackTrace stackTrace = new StackTrace(true); System.Diagnostics.StackFrame[] stackFrames = stackTrace.GetFrames(); int numFramesToSkip = 0; foreach (System.Diagnostics.StackFrame stackFrame in stackFrames) { Type declaringType = stackFrame.GetMethod().DeclaringType; if (declaringType == typeof(DiagnosticTrace)) { ++numFramesToSkip; } else { break; } } stackTrace = new StackTrace(numFramesToSkip); retval = stackTrace.ToString(); } return retval; } //only used for exceptions, perf is not important static internal string XmlEncode(string text) { if (text == null) { return null; } int len = text.Length; StringBuilder encodedText = new StringBuilder(len + 8); //perf optimization, expecting no more than 2 > characters for (int i = 0; i < len; ++i) { char ch = text[i]; switch (ch) { case '<': encodedText.Append("&lt;"); break; case '>': encodedText.Append("&gt;"); break; case '&': encodedText.Append("&amp;"); break; default: encodedText.Append(ch); break; } } return encodedText.ToString(); } //<summary> // Converts incompatible serverity enumeration TraceEvetType into EventLogEntryType //</summary> static EventLogEntryType EventLogEntryTypeFromEventType(TraceEventType type) { EventLogEntryType retval = EventLogEntryType.Information; switch (type) { case TraceEventType.Critical: case TraceEventType.Error: retval = EventLogEntryType.Error; break; case TraceEventType.Warning: retval = EventLogEntryType.Warning; break; } return retval; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class CatchupPositionDecoder { public const ushort BLOCK_LENGTH = 20; public const ushort TEMPLATE_ID = 56; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private CatchupPositionDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public CatchupPositionDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public CatchupPositionDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LeadershipTermIdId() { return 1; } public static int LeadershipTermIdSinceVersion() { return 0; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LeadershipTermId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int LogPositionId() { return 2; } public static int LogPositionSinceVersion() { return 0; } public static int LogPositionEncodingOffset() { return 8; } public static int LogPositionEncodingLength() { return 8; } public static string LogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public long LogPosition() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int FollowerMemberIdId() { return 3; } public static int FollowerMemberIdSinceVersion() { return 0; } public static int FollowerMemberIdEncodingOffset() { return 16; } public static int FollowerMemberIdEncodingLength() { return 4; } public static string FollowerMemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int FollowerMemberIdNullValue() { return -2147483648; } public static int FollowerMemberIdMinValue() { return -2147483647; } public static int FollowerMemberIdMaxValue() { return 2147483647; } public int FollowerMemberId() { return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian); } public static int CatchupEndpointId() { return 4; } public static int CatchupEndpointSinceVersion() { return 0; } public static string CatchupEndpointCharacterEncoding() { return "US-ASCII"; } public static string CatchupEndpointMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int CatchupEndpointHeaderLength() { return 4; } public int CatchupEndpointLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetCatchupEndpoint(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetCatchupEndpoint(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string CatchupEndpoint() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[CatchupPosition](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeadershipTermId="); builder.Append(LeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogPosition="); builder.Append(LogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='followerMemberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("FollowerMemberId="); builder.Append(FollowerMemberId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='catchupEndpoint', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CatchupEndpoint="); builder.Append(CatchupEndpoint()); Limit(originalLimit); return builder; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Abp.Configuration; using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using Abp.Extensions; using Abp.MultiTenancy; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Represents a user. /// </summary> [Table("AbpUsers")] public class AbpUser<TTenant, TUser> : FullAuditedEntity<long, TUser>, IUser<long>, IMayHaveTenant<TTenant, TUser>, IPassivable where TTenant : AbpTenant<TTenant, TUser> where TUser : AbpUser<TTenant, TUser> { /// <summary> /// UserName of the admin. /// admin can not be deleted and UserName of the admin can not be changed. /// </summary> public const string AdminUserName = "admin"; /// <summary> /// Maximum length of the <see cref="Name"/> property. /// </summary> public const int MaxNameLength = 32; /// <summary> /// Maximum length of the <see cref="Surname"/> property. /// </summary> public const int MaxSurnameLength = 32; /// <summary> /// Maximum length of the <see cref="UserName"/> property. /// </summary> public const int MaxUserNameLength = 32; /// <summary> /// Maximum length of the <see cref="Password"/> property. /// </summary> public const int MaxPasswordLength = 128; /// <summary> /// Maximum length of the <see cref="Password"/> without hashed. /// </summary> public const int MaxPlainPasswordLength = 32; /// <summary> /// Maximum length of the <see cref="EmailAddress"/> property. /// </summary> public const int MaxEmailAddressLength = 256; /// <summary> /// Maximum length of the <see cref="EmailConfirmationCode"/> property. /// </summary> public const int MaxEmailConfirmationCodeLength = 128; /// <summary> /// Maximum length of the <see cref="PasswordResetCode"/> property. /// </summary> public const int MaxPasswordResetCodeLength = 128; /// <summary> /// Maximum length of the <see cref="AuthenticationSource"/> property. /// </summary> public const int MaxAuthenticationSourceLength = 64; /// <summary> /// Tenant of this user. /// </summary> [ForeignKey("TenantId")] public virtual TTenant Tenant { get; set; } /// <summary> /// Tenant Id of this user. /// </summary> public virtual int? TenantId { get; set; } /// <summary> /// Authorization source name. /// It's set to external authentication source name if created by an external source. /// Default: null. /// </summary> [MaxLength(MaxAuthenticationSourceLength)] public virtual string AuthenticationSource { get; set; } /// <summary> /// Name of the user. /// </summary> [Required] [StringLength(MaxNameLength)] public virtual string Name { get; set; } /// <summary> /// Surname of the user. /// </summary> [Required] [StringLength(MaxSurnameLength)] public virtual string Surname { get; set; } /// <summary> /// User name. /// User name must be unique for it's tenant. /// </summary> [Required] [StringLength(MaxUserNameLength)] public virtual string UserName { get; set; } /// <summary> /// Password of the user. /// </summary> [Required] [StringLength(MaxPasswordLength)] public virtual string Password { get; set; } /// <summary> /// Email address of the user. /// Email address must be unique for it's tenant. /// </summary> [Required] [StringLength(MaxEmailAddressLength)] public virtual string EmailAddress { get; set; } /// <summary> /// Is the <see cref="EmailAddress"/> confirmed. /// </summary> public virtual bool IsEmailConfirmed { get; set; } /// <summary> /// Confirmation code for email. /// </summary> [StringLength(MaxEmailConfirmationCodeLength)] public virtual string EmailConfirmationCode { get; set; } /// <summary> /// Reset code for password. /// It's not valid if it's null. /// It's for one usage and must be set to null after reset. /// </summary> [StringLength(MaxPasswordResetCodeLength)] public virtual string PasswordResetCode { get; set; } /// <summary> /// The last time this user entered to the system. /// </summary> public virtual DateTime? LastLoginTime { get; set; } /// <summary> /// Is this user active? /// If as user is not active, he/she can not use the application. /// </summary> public virtual bool IsActive { get; set; } /// <summary> /// Login definitions for this user. /// </summary> [ForeignKey("UserId")] public virtual ICollection<UserLogin> Logins { get; set; } /// <summary> /// Role definitions for this user. /// </summary> [ForeignKey("UserId")] public virtual ICollection<UserRole> Roles { get; set; } /// <summary> /// Permission definitions for this user. /// </summary> [ForeignKey("UserId")] public virtual ICollection<UserPermissionSetting> Permissions { get; set; } /// <summary> /// Settings for this user. /// </summary> [ForeignKey("UserId")] public virtual ICollection<Setting> Settings { get; set; } public AbpUser() { IsActive = true; } public virtual void SetNewPasswordResetCode() { PasswordResetCode = Guid.NewGuid().ToString("N").Truncate(MaxPasswordResetCodeLength); } public virtual void SetNewEmailConfirmationCode() { EmailConfirmationCode = Guid.NewGuid().ToString("N").Truncate(MaxEmailConfirmationCodeLength); } public override string ToString() { return string.Format("[User {0}] {1}", Id, UserName); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // QueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This is the abstract base class for all query operators in the system. It /// implements the ParallelQuery{T} type so that it can be bound as the source /// of parallel queries and so that it can be returned as the result of parallel query /// operations. Not much is in here, although it does serve as the "entry point" for /// opening all query operators: it will lazily analyze and cache a plan the first /// time the tree is opened, and will open the tree upon calls to GetEnumerator. /// /// Notes: /// This class implements ParallelQuery so that any parallel query operator /// can bind to the parallel query provider overloads. This allows us to string /// together operators w/out the user always specifying AsParallel, e.g. /// Select(Where(..., ...), ...), and so forth. /// </summary> /// <typeparam name="TOutput"></typeparam> internal abstract class QueryOperator<TOutput> : ParallelQuery<TOutput> { protected bool _outputOrdered; internal QueryOperator(QuerySettings settings) : this(false, settings) { } internal QueryOperator(bool isOrdered, QuerySettings settings) : base(settings) { _outputOrdered = isOrdered; } //--------------------------------------------------------------------------------------- // Opening the query operator will do whatever is necessary to begin enumerating its // results. This includes in some cases actually introducing parallelism, enumerating // other query operators, and so on. This is abstract and left to the specific concrete // operator classes to implement. // // Arguments: // settings - various flags and settings to control query execution // preferStriping - flag representing whether the caller prefers striped partitioning // over range partitioning // // Return Values: // Either a single enumerator, or a partition (for partition parallelism). // internal abstract QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping); //--------------------------------------------------------------------------------------- // The GetEnumerator method is the standard IEnumerable mechanism for walking the // contents of a query. Note that GetEnumerator is only ever called on the root node: // we then proceed by calling Open on all of the subsequent query nodes. // // Arguments: // usePipelining - whether the returned enumerator will pipeline (i.e. return // control to the caller when the query is spawned) or not // (i.e. use the calling thread to execute the query). Note // that there are some conditions during which this hint will // be ignored -- currently, that happens only if a sort is // found anywhere in the query graph. // suppressOrderPreservation - whether to shut order preservation off, regardless // of the contents of the query // // Return Value: // An enumerator that retrieves elements from the query output. // // Notes: // The default mode of execution is to pipeline the query execution with respect // to the GetEnumerator caller (aka the consumer). An overload is available // that can be used to override the default with an explicit choice. // public override IEnumerator<TOutput> GetEnumerator() { // Buffering is unspecified and order preservation is not suppressed. return GetEnumerator(null, false); } public IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions) { // Pass through the value supplied for pipelining, and do not suppress // order preservation by default. return GetEnumerator(mergeOptions, false); } //--------------------------------------------------------------------------------------- // Is the output of this operator ordered? // internal bool OutputOrdered { get { return _outputOrdered; } } internal virtual IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation) { // Return a dummy enumerator that will call back GetOpenedEnumerator() on 'this' QueryOperator // the first time the user calls MoveNext(). We do this to prevent executing the query if user // never calls MoveNext(). return new QueryOpeningEnumerator<TOutput>(this, mergeOptions, suppressOrderPreservation); } //--------------------------------------------------------------------------------------- // The GetOpenedEnumerator method return an enumerator that walks the contents of a query. // The enumerator will be "opened", which means that PLINQ will start executing the query // immediately, even before the user calls MoveNext() for the first time. // internal IEnumerator<TOutput> GetOpenedEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrder, bool forEffect, QuerySettings querySettings) { // If the top-level enumerator forces a premature merge, run the query sequentially. if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism) { IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken); return ExceptionAggregator.WrapEnumerable(opSequential, querySettings.CancellationState).GetEnumerator(); } QueryResults<TOutput> queryResults = GetQueryResults(querySettings); if (mergeOptions == null) { mergeOptions = querySettings.MergeOptions; } Debug.Assert(mergeOptions != null); // Top-level preemptive cancellation test. // This handles situations where cancellation has occured before execution commences // The handling for in-execution occurs in QueryTaskGroupState.QueryEnd() if (querySettings.CancellationState.MergedCancellationToken.IsCancellationRequested) { if (querySettings.CancellationState.ExternalCancellationToken.IsCancellationRequested) throw new OperationCanceledException(querySettings.CancellationState.ExternalCancellationToken); else throw new OperationCanceledException(); } bool orderedMerge = OutputOrdered && !suppressOrder; PartitionedStreamMerger<TOutput> merger = new PartitionedStreamMerger<TOutput>(forEffect, mergeOptions.GetValueOrDefault(), querySettings.TaskScheduler, orderedMerge, querySettings.CancellationState, querySettings.QueryId); queryResults.GivePartitionedStream(merger); // hook up the data flow between the operator-executors, starting from the merger. if (forEffect) { return null; } return merger.MergeExecutor.GetEnumerator(); } // This method is called only once on the 'head operator' which is the last specified operator in the query // This method then recursively uses Open() to prepare itself and the other enumerators. private QueryResults<TOutput> GetQueryResults(QuerySettings querySettings) { TraceHelpers.TraceInfo("[timing]: {0}: starting execution - QueryOperator<>::GetQueryResults", DateTime.Now.Ticks); // All mandatory query settings must be specified Debug.Assert(querySettings.TaskScheduler != null); Debug.Assert(querySettings.DegreeOfParallelism.HasValue); Debug.Assert(querySettings.ExecutionMode.HasValue); // Now just open the query tree's root operator, supplying a specific DOP return Open(querySettings, false); } //--------------------------------------------------------------------------------------- // Executes the query and returns the results in an array. // internal TOutput[] ExecuteAndGetResultsAsArray() { QuerySettings querySettings = SpecifiedQuerySettings .WithPerExecutionSettings() .WithDefaults(); QueryLifecycle.LogicalQueryExecutionBegin(querySettings.QueryId); try { if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism) { IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken); IEnumerable<TOutput> opSequentialWithCancelChecks = CancellableEnumerable.Wrap(opSequential, querySettings.CancellationState.ExternalCancellationToken); return ExceptionAggregator.WrapEnumerable(opSequentialWithCancelChecks, querySettings.CancellationState).ToArray(); } QueryResults<TOutput> results = GetQueryResults(querySettings); // Top-level preemptive cancellation test. // This handles situations where cancellation has occured before execution commences // The handling for in-execution occurs in QueryTaskGroupState.QueryEnd() if (querySettings.CancellationState.MergedCancellationToken.IsCancellationRequested) { if (querySettings.CancellationState.ExternalCancellationToken.IsCancellationRequested) throw new OperationCanceledException(querySettings.CancellationState.ExternalCancellationToken); else throw new OperationCanceledException(); } if (results.IsIndexible && OutputOrdered) { // The special array-based merge performs better if the output is ordered, because // it does not have to pay for ordering. In the unordered case, we it appears that // the stop-and-go merge performs a little better. ArrayMergeHelper<TOutput> merger = new ArrayMergeHelper<TOutput>(SpecifiedQuerySettings, results); merger.Execute(); TOutput[] output = merger.GetResultsAsArray(); querySettings.CleanStateAtQueryEnd(); return output; } else { PartitionedStreamMerger<TOutput> merger = new PartitionedStreamMerger<TOutput>(false, ParallelMergeOptions.FullyBuffered, querySettings.TaskScheduler, OutputOrdered, querySettings.CancellationState, querySettings.QueryId); results.GivePartitionedStream(merger); TOutput[] output = merger.MergeExecutor.GetResultsAsArray(); querySettings.CleanStateAtQueryEnd(); return output; } } finally { QueryLifecycle.LogicalQueryExecutionEnd(querySettings.QueryId); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // // Note that iterating the returned enumerable will not wrap exceptions AggregateException. // Before this enumerable is returned to the user, we must wrap it with an // ExceptionAggregator. // internal abstract IEnumerable<TOutput> AsSequentialQuery(CancellationToken token); //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge. // internal abstract bool LimitsParallelism { get; } //--------------------------------------------------------------------------------------- // The state of the order index of the results returned by this operator. // internal abstract OrdinalIndexState OrdinalIndexState { get; } //--------------------------------------------------------------------------------------- // A helper method that executes the query rooted at the openedChild operator, and returns // the results as ListQueryResults<TSource>. // internal static ListQueryResults<TOutput> ExecuteAndCollectResults<TKey>( PartitionedStream<TOutput, TKey> openedChild, int partitionCount, bool outputOrdered, bool useStriping, QuerySettings settings) { TaskScheduler taskScheduler = settings.TaskScheduler; MergeExecutor<TOutput> executor = MergeExecutor<TOutput>.Execute<TKey>( openedChild, false, ParallelMergeOptions.FullyBuffered, taskScheduler, outputOrdered, settings.CancellationState, settings.QueryId); return new ListQueryResults<TOutput>(executor.GetResultsAsArray(), partitionCount, useStriping); } //--------------------------------------------------------------------------------------- // Returns a QueryOperator<T> for any IEnumerable<T> data source. This will just do a // cast and return a reference to the same data source if the source is another query // operator, but will lazily allocate a scan operation and return that otherwise. // // Arguments: // source - any enumerable data source to be wrapped // // Return Value: // A query operator. // internal static QueryOperator<TOutput> AsQueryOperator(IEnumerable<TOutput> source) { Debug.Assert(source != null); // Just try casting the data source to a query operator, in the case that // our child is just another query operator. QueryOperator<TOutput> sourceAsOperator = source as QueryOperator<TOutput>; if (sourceAsOperator == null) { OrderedParallelQuery<TOutput> orderedQuery = source as OrderedParallelQuery<TOutput>; if (orderedQuery != null) { // We have to handle OrderedParallelQuery<T> specially. In all other cases, // ParallelQuery *is* the QueryOperator<T>. But, OrderedParallelQuery<T> // is not QueryOperator<T>, it only has a reference to one. Ideally, we // would want SortQueryOperator<T> to inherit from OrderedParallelQuery<T>, // but that conflicts with other constraints on our class hierarchy. sourceAsOperator = (QueryOperator<TOutput>)orderedQuery.SortOperator; } else { // If the cast failed, then the data source is a real piece of data. We // just construct a new scan operator on top of it. sourceAsOperator = new ScanQueryOperator<TOutput>(source); } } Debug.Assert(sourceAsOperator != null); return sourceAsOperator; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmBlockTest { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmBlockTest() : base() { Resize += frmBlockTest_Resize; Load += frmBlockTest_Load; KeyPress += frmBlockTest_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); Form_Initialize_Renamed(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public Microsoft.VisualBasic.PowerPacks.Printing.PrintForm PrintForm1; public System.Windows.Forms.Label lblTotalOP; public System.Windows.Forms.Label lblTotalLP; public System.Windows.Forms.Label lblTotalO; public System.Windows.Forms.Label _lblTotal_17; public System.Windows.Forms.Label lblTotalL; public System.Windows.Forms.Label _lblTotal_16; public System.Windows.Forms.Label lblTotalH; public System.Windows.Forms.Label _lblTotal_15; public System.Windows.Forms.Label lblTotalG; public System.Windows.Forms.Label _lblTotal_14; public System.Windows.Forms.Label _lblTotal_13; public System.Windows.Forms.Label lblTotalQ; public System.Windows.Forms.Label _lblTotal_12; public System.Windows.Forms.Label lblTotalF; public System.Windows.Forms.Label lblP; public System.Windows.Forms.Label _lblTotal_11; public System.Windows.Forms.Panel picTotal; public System.Windows.Forms.TextBox _txtEdit_0; private System.Windows.Forms.Button withEventsField_cmdLoadNext; public System.Windows.Forms.Button cmdLoadNext { get { return withEventsField_cmdLoadNext; } set { if (withEventsField_cmdLoadNext != null) { withEventsField_cmdLoadNext.Click -= cmdLoadNext_Click; } withEventsField_cmdLoadNext = value; if (withEventsField_cmdLoadNext != null) { withEventsField_cmdLoadNext.Click += cmdLoadNext_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtR; public System.Windows.Forms.TextBox txtR { get { return withEventsField_txtR; } set { if (withEventsField_txtR != null) { withEventsField_txtR.Enter -= txtR_Enter; withEventsField_txtR.KeyPress -= txtR_KeyPress; withEventsField_txtR.Leave -= txtR_Leave; } withEventsField_txtR = value; if (withEventsField_txtR != null) { withEventsField_txtR.Enter += txtR_Enter; withEventsField_txtR.KeyPress += txtR_KeyPress; withEventsField_txtR.Leave += txtR_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtZ; public System.Windows.Forms.TextBox txtZ { get { return withEventsField_txtZ; } set { if (withEventsField_txtZ != null) { withEventsField_txtZ.Enter -= txtZ_Enter; withEventsField_txtZ.KeyPress -= txtZ_KeyPress; withEventsField_txtZ.Leave -= txtZ_Leave; } withEventsField_txtZ = value; if (withEventsField_txtZ != null) { withEventsField_txtZ.Enter += txtZ_Enter; withEventsField_txtZ.KeyPress += txtZ_KeyPress; withEventsField_txtZ.Leave += txtZ_Leave; } } } private System.Windows.Forms.Button withEventsField_cmdTotal; public System.Windows.Forms.Button cmdTotal { get { return withEventsField_cmdTotal; } set { if (withEventsField_cmdTotal != null) { withEventsField_cmdTotal.Click -= cmdTotal_Click; } withEventsField_cmdTotal = value; if (withEventsField_cmdTotal != null) { withEventsField_cmdTotal.Click += cmdTotal_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtReqGP; public System.Windows.Forms.TextBox txtReqGP { get { return withEventsField_txtReqGP; } set { if (withEventsField_txtReqGP != null) { withEventsField_txtReqGP.Enter -= txtReqGP_Enter; } withEventsField_txtReqGP = value; if (withEventsField_txtReqGP != null) { withEventsField_txtReqGP.Enter += txtReqGP_Enter; } } } private System.Windows.Forms.TextBox withEventsField_txtVAT; public System.Windows.Forms.TextBox txtVAT { get { return withEventsField_txtVAT; } set { if (withEventsField_txtVAT != null) { withEventsField_txtVAT.Enter -= txtVAT_Enter; } withEventsField_txtVAT = value; if (withEventsField_txtVAT != null) { withEventsField_txtVAT.Enter += txtVAT_Enter; } } } public System.Windows.Forms.Label lblQuantity; public System.Windows.Forms.Label _lbl_8; public System.Windows.Forms.Label lblBrokenPack; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label lblContentExclusive; public System.Windows.Forms.Label lblContentInclusives; public System.Windows.Forms.Label lblDepositExclusives; public System.Windows.Forms.Label lblA; public System.Windows.Forms.Label lblB; public System.Windows.Forms.Label lblC; public System.Windows.Forms.Label _lblTotal_0; public System.Windows.Forms.Label _lblTotal_1; public System.Windows.Forms.Label _lblTotal_2; public System.Windows.Forms.Label _lblTotal_3; public System.Windows.Forms.Label _lblTotal_4; public System.Windows.Forms.Label _lblTotal_5; public System.Windows.Forms.Label lblX; public System.Windows.Forms.Label lblGP_Y; public System.Windows.Forms.Label lblB_Z; public System.Windows.Forms.Label _lblTotal_6; public System.Windows.Forms.Label _lblTotal_7; public System.Windows.Forms.Label _lblTotal_8; public System.Windows.Forms.Label _lblTotal_9; public System.Windows.Forms.Label _lblTotal_10; public System.Windows.Forms.GroupBox frmTotals; public System.Windows.Forms.TextBox _txtEdit_1; public System.Windows.Forms.TextBox _txtEdit_2; private System.Windows.Forms.Button withEventsField_cmdReg; public System.Windows.Forms.Button cmdReg { get { return withEventsField_cmdReg; } set { if (withEventsField_cmdReg != null) { withEventsField_cmdReg.Click -= cmdReg_Click; } withEventsField_cmdReg = value; if (withEventsField_cmdReg != null) { withEventsField_cmdReg.Click += cmdReg_Click; } } } private System.Windows.Forms.Button withEventsField_cmdProc; public System.Windows.Forms.Button cmdProc { get { return withEventsField_cmdProc; } set { if (withEventsField_cmdProc != null) { withEventsField_cmdProc.Click -= cmdProc_Click; } withEventsField_cmdProc = value; if (withEventsField_cmdProc != null) { withEventsField_cmdProc.Click += cmdProc_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Panel Picture2; private myDataGridView withEventsField_gridItem; public myDataGridView gridItem { get { return withEventsField_gridItem; } set { if (withEventsField_gridItem != null) { withEventsField_gridItem.Enter -= gridItem_EnterCell; withEventsField_gridItem.Enter -= gridItem_Enter; withEventsField_gridItem.KeyPress -= gridItem_KeyPress; withEventsField_gridItem.Leave -= gridItem_LeaveCell; } withEventsField_gridItem = value; if (withEventsField_gridItem != null) { withEventsField_gridItem.Enter += gridItem_EnterCell; withEventsField_gridItem.Enter += gridItem_Enter; withEventsField_gridItem.KeyPress += gridItem_KeyPress; withEventsField_gridItem.Leave += gridItem_LeaveCell; } } } //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblTotal As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtEdit As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmBlockTest)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.PrintForm1 = new Microsoft.VisualBasic.PowerPacks.Printing.PrintForm(this); this.picTotal = new System.Windows.Forms.Panel(); this.lblTotalOP = new System.Windows.Forms.Label(); this.lblTotalLP = new System.Windows.Forms.Label(); this.lblTotalO = new System.Windows.Forms.Label(); this._lblTotal_17 = new System.Windows.Forms.Label(); this.lblTotalL = new System.Windows.Forms.Label(); this._lblTotal_16 = new System.Windows.Forms.Label(); this.lblTotalH = new System.Windows.Forms.Label(); this._lblTotal_15 = new System.Windows.Forms.Label(); this.lblTotalG = new System.Windows.Forms.Label(); this._lblTotal_14 = new System.Windows.Forms.Label(); this._lblTotal_13 = new System.Windows.Forms.Label(); this.lblTotalQ = new System.Windows.Forms.Label(); this._lblTotal_12 = new System.Windows.Forms.Label(); this.lblTotalF = new System.Windows.Forms.Label(); this.lblP = new System.Windows.Forms.Label(); this._lblTotal_11 = new System.Windows.Forms.Label(); this._txtEdit_0 = new System.Windows.Forms.TextBox(); this.frmTotals = new System.Windows.Forms.GroupBox(); this.cmdLoadNext = new System.Windows.Forms.Button(); this.txtR = new System.Windows.Forms.TextBox(); this.txtZ = new System.Windows.Forms.TextBox(); this.cmdTotal = new System.Windows.Forms.Button(); this.txtReqGP = new System.Windows.Forms.TextBox(); this.txtVAT = new System.Windows.Forms.TextBox(); this.lblQuantity = new System.Windows.Forms.Label(); this._lbl_8 = new System.Windows.Forms.Label(); this.lblBrokenPack = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this.lblContentExclusive = new System.Windows.Forms.Label(); this.lblContentInclusives = new System.Windows.Forms.Label(); this.lblDepositExclusives = new System.Windows.Forms.Label(); this.lblA = new System.Windows.Forms.Label(); this.lblB = new System.Windows.Forms.Label(); this.lblC = new System.Windows.Forms.Label(); this._lblTotal_0 = new System.Windows.Forms.Label(); this._lblTotal_1 = new System.Windows.Forms.Label(); this._lblTotal_2 = new System.Windows.Forms.Label(); this._lblTotal_3 = new System.Windows.Forms.Label(); this._lblTotal_4 = new System.Windows.Forms.Label(); this._lblTotal_5 = new System.Windows.Forms.Label(); this.lblX = new System.Windows.Forms.Label(); this.lblGP_Y = new System.Windows.Forms.Label(); this.lblB_Z = new System.Windows.Forms.Label(); this._lblTotal_6 = new System.Windows.Forms.Label(); this._lblTotal_7 = new System.Windows.Forms.Label(); this._lblTotal_8 = new System.Windows.Forms.Label(); this._lblTotal_9 = new System.Windows.Forms.Label(); this._lblTotal_10 = new System.Windows.Forms.Label(); this._txtEdit_1 = new System.Windows.Forms.TextBox(); this._txtEdit_2 = new System.Windows.Forms.TextBox(); this.Picture2 = new System.Windows.Forms.Panel(); this.cmdReg = new System.Windows.Forms.Button(); this.cmdProc = new System.Windows.Forms.Button(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.gridItem = new myDataGridView(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblTotal = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.txtEdit = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) this.picTotal.SuspendLayout(); this.frmTotals.SuspendLayout(); this.Picture2.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.gridItem).BeginInit(); //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblTotal, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtEdit, System.ComponentModel.ISupportInitialize).BeginInit() this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.Text = "4MEAT Block Tester"; this.ClientSize = new System.Drawing.Size(1016, 707); this.Location = new System.Drawing.Point(4, 23); this.ControlBox = false; this.KeyPreview = true; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; this.Enabled = true; this.MaximizeBox = true; this.MinimizeBox = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.Name = "frmBlockTest"; this.picTotal.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.picTotal.ForeColor = System.Drawing.SystemColors.WindowText; this.picTotal.Size = new System.Drawing.Size(997, 49); this.picTotal.Location = new System.Drawing.Point(8, 576); this.picTotal.TabIndex = 37; this.picTotal.Dock = System.Windows.Forms.DockStyle.None; this.picTotal.CausesValidation = true; this.picTotal.Enabled = true; this.picTotal.Cursor = System.Windows.Forms.Cursors.Default; this.picTotal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picTotal.TabStop = true; this.picTotal.Visible = true; this.picTotal.BorderStyle = System.Windows.Forms.BorderStyle.None; this.picTotal.Name = "picTotal"; this.lblTotalOP.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalOP.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalOP.Text = "0.00"; this.lblTotalOP.Size = new System.Drawing.Size(65, 16); this.lblTotalOP.Location = new System.Drawing.Point(928, 16); this.lblTotalOP.TabIndex = 54; this.lblTotalOP.Enabled = true; this.lblTotalOP.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalOP.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalOP.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalOP.UseMnemonic = true; this.lblTotalOP.Visible = true; this.lblTotalOP.AutoSize = false; this.lblTotalOP.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalOP.Name = "lblTotalOP"; this.lblTotalLP.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalLP.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalLP.Text = "0.00"; this.lblTotalLP.Size = new System.Drawing.Size(65, 16); this.lblTotalLP.Location = new System.Drawing.Point(728, 16); this.lblTotalLP.TabIndex = 53; this.lblTotalLP.Enabled = true; this.lblTotalLP.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalLP.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalLP.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalLP.UseMnemonic = true; this.lblTotalLP.Visible = true; this.lblTotalLP.AutoSize = false; this.lblTotalLP.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalLP.Name = "lblTotalLP"; this.lblTotalO.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalO.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalO.Text = "0.00"; this.lblTotalO.Size = new System.Drawing.Size(65, 16); this.lblTotalO.Location = new System.Drawing.Point(928, 0); this.lblTotalO.TabIndex = 51; this.lblTotalO.Enabled = true; this.lblTotalO.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalO.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalO.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalO.UseMnemonic = true; this.lblTotalO.Visible = true; this.lblTotalO.AutoSize = false; this.lblTotalO.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalO.Name = "lblTotalO"; this._lblTotal_17.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_17.BackColor = System.Drawing.Color.Transparent; this._lblTotal_17.Text = "O :"; this._lblTotal_17.Size = new System.Drawing.Size(35, 16); this._lblTotal_17.Location = new System.Drawing.Point(944, 32); this._lblTotal_17.TabIndex = 50; this._lblTotal_17.Enabled = true; this._lblTotal_17.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_17.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_17.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_17.UseMnemonic = true; this._lblTotal_17.Visible = true; this._lblTotal_17.AutoSize = false; this._lblTotal_17.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_17.Name = "_lblTotal_17"; this.lblTotalL.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalL.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalL.Text = "0.00"; this.lblTotalL.Size = new System.Drawing.Size(65, 16); this.lblTotalL.Location = new System.Drawing.Point(728, 0); this.lblTotalL.TabIndex = 49; this.lblTotalL.Enabled = true; this.lblTotalL.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalL.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalL.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalL.UseMnemonic = true; this.lblTotalL.Visible = true; this.lblTotalL.AutoSize = false; this.lblTotalL.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalL.Name = "lblTotalL"; this._lblTotal_16.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_16.BackColor = System.Drawing.Color.Transparent; this._lblTotal_16.Text = "L :"; this._lblTotal_16.Size = new System.Drawing.Size(35, 16); this._lblTotal_16.Location = new System.Drawing.Point(736, 32); this._lblTotal_16.TabIndex = 48; this._lblTotal_16.Enabled = true; this._lblTotal_16.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_16.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_16.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_16.UseMnemonic = true; this._lblTotal_16.Visible = true; this._lblTotal_16.AutoSize = false; this._lblTotal_16.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_16.Name = "_lblTotal_16"; this.lblTotalH.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalH.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalH.Text = "0.00"; this.lblTotalH.Size = new System.Drawing.Size(65, 16); this.lblTotalH.Location = new System.Drawing.Point(462, 0); this.lblTotalH.TabIndex = 47; this.lblTotalH.Enabled = true; this.lblTotalH.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalH.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalH.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalH.UseMnemonic = true; this.lblTotalH.Visible = true; this.lblTotalH.AutoSize = false; this.lblTotalH.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalH.Name = "lblTotalH"; this._lblTotal_15.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_15.BackColor = System.Drawing.Color.Transparent; this._lblTotal_15.Text = "H :"; this._lblTotal_15.Size = new System.Drawing.Size(27, 16); this._lblTotal_15.Location = new System.Drawing.Point(480, 16); this._lblTotal_15.TabIndex = 46; this._lblTotal_15.Enabled = true; this._lblTotal_15.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_15.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_15.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_15.UseMnemonic = true; this._lblTotal_15.Visible = true; this._lblTotal_15.AutoSize = false; this._lblTotal_15.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_15.Name = "_lblTotal_15"; this.lblTotalG.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalG.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalG.Text = "0.00"; this.lblTotalG.Size = new System.Drawing.Size(65, 16); this.lblTotalG.Location = new System.Drawing.Point(392, 0); this.lblTotalG.TabIndex = 45; this.lblTotalG.Enabled = true; this.lblTotalG.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalG.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalG.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalG.UseMnemonic = true; this.lblTotalG.Visible = true; this.lblTotalG.AutoSize = false; this.lblTotalG.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalG.Name = "lblTotalG"; this._lblTotal_14.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_14.BackColor = System.Drawing.Color.Transparent; this._lblTotal_14.Text = "G :"; this._lblTotal_14.Size = new System.Drawing.Size(27, 16); this._lblTotal_14.Location = new System.Drawing.Point(408, 16); this._lblTotal_14.TabIndex = 44; this._lblTotal_14.Enabled = true; this._lblTotal_14.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_14.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_14.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_14.UseMnemonic = true; this._lblTotal_14.Visible = true; this._lblTotal_14.AutoSize = false; this._lblTotal_14.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_14.Name = "_lblTotal_14"; this._lblTotal_13.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_13.BackColor = System.Drawing.Color.Transparent; this._lblTotal_13.Text = "Q :"; this._lblTotal_13.Size = new System.Drawing.Size(35, 16); this._lblTotal_13.Location = new System.Drawing.Point(536, 16); this._lblTotal_13.TabIndex = 43; this._lblTotal_13.Enabled = true; this._lblTotal_13.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_13.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_13.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_13.UseMnemonic = true; this._lblTotal_13.Visible = true; this._lblTotal_13.AutoSize = false; this._lblTotal_13.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_13.Name = "_lblTotal_13"; this.lblTotalQ.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalQ.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalQ.Text = "0.00"; this.lblTotalQ.Size = new System.Drawing.Size(65, 16); this.lblTotalQ.Location = new System.Drawing.Point(528, 0); this.lblTotalQ.TabIndex = 42; this.lblTotalQ.Enabled = true; this.lblTotalQ.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalQ.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalQ.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalQ.UseMnemonic = true; this.lblTotalQ.Visible = true; this.lblTotalQ.AutoSize = false; this.lblTotalQ.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalQ.Name = "lblTotalQ"; this._lblTotal_12.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_12.BackColor = System.Drawing.Color.Transparent; this._lblTotal_12.Text = "F :"; this._lblTotal_12.Size = new System.Drawing.Size(27, 16); this._lblTotal_12.Location = new System.Drawing.Point(344, 16); this._lblTotal_12.TabIndex = 41; this._lblTotal_12.Enabled = true; this._lblTotal_12.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_12.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_12.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_12.UseMnemonic = true; this._lblTotal_12.Visible = true; this._lblTotal_12.AutoSize = false; this._lblTotal_12.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_12.Name = "_lblTotal_12"; this.lblTotalF.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblTotalF.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblTotalF.Text = "0.00"; this.lblTotalF.Size = new System.Drawing.Size(65, 16); this.lblTotalF.Location = new System.Drawing.Point(323, 0); this.lblTotalF.TabIndex = 40; this.lblTotalF.Enabled = true; this.lblTotalF.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTotalF.Cursor = System.Windows.Forms.Cursors.Default; this.lblTotalF.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblTotalF.UseMnemonic = true; this.lblTotalF.Visible = true; this.lblTotalF.AutoSize = false; this.lblTotalF.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblTotalF.Name = "lblTotalF"; this.lblP.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblP.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblP.Text = "0.00"; this.lblP.Size = new System.Drawing.Size(65, 16); this.lblP.Location = new System.Drawing.Point(192, 0); this.lblP.TabIndex = 39; this.lblP.Enabled = true; this.lblP.ForeColor = System.Drawing.SystemColors.ControlText; this.lblP.Cursor = System.Windows.Forms.Cursors.Default; this.lblP.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblP.UseMnemonic = true; this.lblP.Visible = true; this.lblP.AutoSize = false; this.lblP.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblP.Name = "lblP"; this._lblTotal_11.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_11.BackColor = System.Drawing.Color.Transparent; this._lblTotal_11.Text = "Weight after Cutting & W.Loss - P :"; this._lblTotal_11.Size = new System.Drawing.Size(187, 16); this._lblTotal_11.Location = new System.Drawing.Point(0, 0); this._lblTotal_11.TabIndex = 38; this._lblTotal_11.Enabled = true; this._lblTotal_11.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_11.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_11.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_11.UseMnemonic = true; this._lblTotal_11.Visible = true; this._lblTotal_11.AutoSize = false; this._lblTotal_11.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_11.Name = "_lblTotal_11"; this._txtEdit_0.AutoSize = false; this._txtEdit_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_0.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_0.Size = new System.Drawing.Size(55, 16); this._txtEdit_0.Location = new System.Drawing.Point(391, 546); this._txtEdit_0.MaxLength = 8; this._txtEdit_0.TabIndex = 36; this._txtEdit_0.Tag = "0"; this._txtEdit_0.Text = "0"; this._txtEdit_0.Visible = false; this._txtEdit_0.AcceptsReturn = true; this._txtEdit_0.CausesValidation = true; this._txtEdit_0.Enabled = true; this._txtEdit_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_0.HideSelection = true; this._txtEdit_0.ReadOnly = false; this._txtEdit_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_0.Multiline = false; this._txtEdit_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_0.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_0.TabStop = true; this._txtEdit_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_0.Name = "_txtEdit_0"; this.frmTotals.Text = " Genral Information "; this.frmTotals.Size = new System.Drawing.Size(889, 137); this.frmTotals.Location = new System.Drawing.Point(3, 56); this.frmTotals.TabIndex = 10; this.frmTotals.BackColor = System.Drawing.SystemColors.Control; this.frmTotals.Enabled = true; this.frmTotals.ForeColor = System.Drawing.SystemColors.ControlText; this.frmTotals.RightToLeft = System.Windows.Forms.RightToLeft.No; this.frmTotals.Visible = true; this.frmTotals.Padding = new System.Windows.Forms.Padding(0); this.frmTotals.Name = "frmTotals"; this.cmdLoadNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdLoadNext.Text = "Next"; this.cmdLoadNext.Size = new System.Drawing.Size(99, 40); this.cmdLoadNext.Location = new System.Drawing.Point(776, 40); this.cmdLoadNext.TabIndex = 56; this.cmdLoadNext.TabStop = false; this.cmdLoadNext.Visible = false; this.cmdLoadNext.BackColor = System.Drawing.SystemColors.Control; this.cmdLoadNext.CausesValidation = true; this.cmdLoadNext.Enabled = true; this.cmdLoadNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdLoadNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdLoadNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdLoadNext.Name = "cmdLoadNext"; this.txtR.AutoSize = false; this.txtR.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtR.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.txtR.Size = new System.Drawing.Size(234, 19); this.txtR.Location = new System.Drawing.Point(215, 36); this.txtR.TabIndex = 0; this.txtR.Text = "0.00"; this.txtR.AcceptsReturn = true; this.txtR.CausesValidation = true; this.txtR.Enabled = true; this.txtR.ForeColor = System.Drawing.SystemColors.WindowText; this.txtR.HideSelection = true; this.txtR.ReadOnly = false; this.txtR.MaxLength = 0; this.txtR.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtR.Multiline = false; this.txtR.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtR.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtR.TabStop = true; this.txtR.Visible = true; this.txtR.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtR.Name = "txtR"; this.txtZ.AutoSize = false; this.txtZ.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtZ.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.txtZ.Size = new System.Drawing.Size(234, 19); this.txtZ.Location = new System.Drawing.Point(215, 56); this.txtZ.TabIndex = 1; this.txtZ.Text = "0.00"; this.txtZ.AcceptsReturn = true; this.txtZ.CausesValidation = true; this.txtZ.Enabled = true; this.txtZ.ForeColor = System.Drawing.SystemColors.WindowText; this.txtZ.HideSelection = true; this.txtZ.ReadOnly = false; this.txtZ.MaxLength = 0; this.txtZ.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtZ.Multiline = false; this.txtZ.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtZ.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtZ.TabStop = true; this.txtZ.Visible = true; this.txtZ.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtZ.Name = "txtZ"; this.cmdTotal.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdTotal.Text = "Calculate"; this.cmdTotal.Size = new System.Drawing.Size(99, 40); this.cmdTotal.Location = new System.Drawing.Point(776, 88); this.cmdTotal.TabIndex = 11; this.cmdTotal.TabStop = false; this.cmdTotal.BackColor = System.Drawing.SystemColors.Control; this.cmdTotal.CausesValidation = true; this.cmdTotal.Enabled = true; this.cmdTotal.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdTotal.Cursor = System.Windows.Forms.Cursors.Default; this.cmdTotal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdTotal.Name = "cmdTotal"; this.txtReqGP.AutoSize = false; this.txtReqGP.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtReqGP.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.txtReqGP.Size = new System.Drawing.Size(120, 19); this.txtReqGP.Location = new System.Drawing.Point(616, 36); this.txtReqGP.TabIndex = 2; this.txtReqGP.Text = "0.00"; this.txtReqGP.AcceptsReturn = true; this.txtReqGP.CausesValidation = true; this.txtReqGP.Enabled = true; this.txtReqGP.ForeColor = System.Drawing.SystemColors.WindowText; this.txtReqGP.HideSelection = true; this.txtReqGP.ReadOnly = false; this.txtReqGP.MaxLength = 0; this.txtReqGP.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtReqGP.Multiline = false; this.txtReqGP.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtReqGP.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtReqGP.TabStop = true; this.txtReqGP.Visible = true; this.txtReqGP.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtReqGP.Name = "txtReqGP"; this.txtVAT.AutoSize = false; this.txtVAT.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtVAT.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.txtVAT.Size = new System.Drawing.Size(120, 19); this.txtVAT.Location = new System.Drawing.Point(616, 92); this.txtVAT.TabIndex = 3; this.txtVAT.Text = "0.00"; this.txtVAT.AcceptsReturn = true; this.txtVAT.CausesValidation = true; this.txtVAT.Enabled = true; this.txtVAT.ForeColor = System.Drawing.SystemColors.WindowText; this.txtVAT.HideSelection = true; this.txtVAT.ReadOnly = false; this.txtVAT.MaxLength = 0; this.txtVAT.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtVAT.Multiline = false; this.txtVAT.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtVAT.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtVAT.TabStop = true; this.txtVAT.Visible = true; this.txtVAT.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtVAT.Name = "txtVAT"; this.lblQuantity.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblQuantity.Text = "lblQuantity"; this.lblQuantity.Size = new System.Drawing.Size(64, 17); this.lblQuantity.Location = new System.Drawing.Point(673, 195); this.lblQuantity.TabIndex = 35; this.lblQuantity.BackColor = System.Drawing.SystemColors.Control; this.lblQuantity.Enabled = true; this.lblQuantity.ForeColor = System.Drawing.SystemColors.ControlText; this.lblQuantity.Cursor = System.Windows.Forms.Cursors.Default; this.lblQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblQuantity.UseMnemonic = true; this.lblQuantity.Visible = true; this.lblQuantity.AutoSize = false; this.lblQuantity.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblQuantity.Name = "lblQuantity"; this._lbl_8.Text = "No Of Cases"; this._lbl_8.Size = new System.Drawing.Size(60, 13); this._lbl_8.Location = new System.Drawing.Point(673, 183); this._lbl_8.TabIndex = 34; this._lbl_8.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_8.BackColor = System.Drawing.Color.Transparent; this._lbl_8.Enabled = true; this._lbl_8.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_8.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_8.UseMnemonic = true; this._lbl_8.Visible = true; this._lbl_8.AutoSize = true; this._lbl_8.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_8.Name = "_lbl_8"; this.lblBrokenPack.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblBrokenPack.Text = "lblQuantity"; this.lblBrokenPack.Size = new System.Drawing.Size(64, 17); this.lblBrokenPack.Location = new System.Drawing.Point(745, 195); this.lblBrokenPack.TabIndex = 33; this.lblBrokenPack.BackColor = System.Drawing.SystemColors.Control; this.lblBrokenPack.Enabled = true; this.lblBrokenPack.ForeColor = System.Drawing.SystemColors.ControlText; this.lblBrokenPack.Cursor = System.Windows.Forms.Cursors.Default; this.lblBrokenPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblBrokenPack.UseMnemonic = true; this.lblBrokenPack.Visible = true; this.lblBrokenPack.AutoSize = false; this.lblBrokenPack.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblBrokenPack.Name = "lblBrokenPack"; this._lbl_2.Text = "Broken Packs"; this._lbl_2.Size = new System.Drawing.Size(67, 13); this._lbl_2.Location = new System.Drawing.Point(742, 183); this._lbl_2.TabIndex = 32; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = true; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this.lblContentExclusive.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblContentExclusive.BackColor = System.Drawing.Color.FromArgb(128, 128, 255); this.lblContentExclusive.Text = "person name"; this.lblContentExclusive.Size = new System.Drawing.Size(234, 16); this.lblContentExclusive.Location = new System.Drawing.Point(215, 20); this.lblContentExclusive.TabIndex = 31; this.lblContentExclusive.Enabled = true; this.lblContentExclusive.ForeColor = System.Drawing.SystemColors.ControlText; this.lblContentExclusive.Cursor = System.Windows.Forms.Cursors.Default; this.lblContentExclusive.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblContentExclusive.UseMnemonic = true; this.lblContentExclusive.Visible = true; this.lblContentExclusive.AutoSize = false; this.lblContentExclusive.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblContentExclusive.Name = "lblContentExclusive"; this.lblContentInclusives.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblContentInclusives.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.lblContentInclusives.Text = "0.00"; this.lblContentInclusives.Size = new System.Drawing.Size(233, 16); this.lblContentInclusives.Location = new System.Drawing.Point(840, 32); this.lblContentInclusives.TabIndex = 30; this.lblContentInclusives.Visible = false; this.lblContentInclusives.Enabled = true; this.lblContentInclusives.ForeColor = System.Drawing.SystemColors.ControlText; this.lblContentInclusives.Cursor = System.Windows.Forms.Cursors.Default; this.lblContentInclusives.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblContentInclusives.UseMnemonic = true; this.lblContentInclusives.AutoSize = false; this.lblContentInclusives.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblContentInclusives.Name = "lblContentInclusives"; this.lblDepositExclusives.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblDepositExclusives.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.lblDepositExclusives.Text = "0.00"; this.lblDepositExclusives.Size = new System.Drawing.Size(233, 16); this.lblDepositExclusives.Location = new System.Drawing.Point(840, 16); this.lblDepositExclusives.TabIndex = 29; this.lblDepositExclusives.Visible = false; this.lblDepositExclusives.Enabled = true; this.lblDepositExclusives.ForeColor = System.Drawing.SystemColors.ControlText; this.lblDepositExclusives.Cursor = System.Windows.Forms.Cursors.Default; this.lblDepositExclusives.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblDepositExclusives.UseMnemonic = true; this.lblDepositExclusives.AutoSize = false; this.lblDepositExclusives.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblDepositExclusives.Name = "lblDepositExclusives"; this.lblA.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblA.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblA.Text = "0.00"; this.lblA.Size = new System.Drawing.Size(234, 16); this.lblA.Location = new System.Drawing.Point(215, 74); this.lblA.TabIndex = 28; this.lblA.Enabled = true; this.lblA.ForeColor = System.Drawing.SystemColors.ControlText; this.lblA.Cursor = System.Windows.Forms.Cursors.Default; this.lblA.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblA.UseMnemonic = true; this.lblA.Visible = true; this.lblA.AutoSize = false; this.lblA.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblA.Name = "lblA"; this.lblB.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblB.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblB.Text = "0.00"; this.lblB.Size = new System.Drawing.Size(234, 16); this.lblB.Location = new System.Drawing.Point(215, 92); this.lblB.TabIndex = 27; this.lblB.Enabled = true; this.lblB.ForeColor = System.Drawing.SystemColors.ControlText; this.lblB.Cursor = System.Windows.Forms.Cursors.Default; this.lblB.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblB.UseMnemonic = true; this.lblB.Visible = true; this.lblB.AutoSize = false; this.lblB.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblB.Name = "lblB"; this.lblC.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblC.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblC.Text = "0.00"; this.lblC.Size = new System.Drawing.Size(234, 16); this.lblC.Location = new System.Drawing.Point(215, 110); this.lblC.TabIndex = 26; this.lblC.Enabled = true; this.lblC.ForeColor = System.Drawing.SystemColors.ControlText; this.lblC.Cursor = System.Windows.Forms.Cursors.Default; this.lblC.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblC.UseMnemonic = true; this.lblC.Visible = true; this.lblC.AutoSize = false; this.lblC.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblC.Name = "lblC"; this._lblTotal_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_0.BackColor = System.Drawing.Color.Transparent; this._lblTotal_0.Text = "Person Cutting :"; this._lblTotal_0.Size = new System.Drawing.Size(203, 16); this._lblTotal_0.Location = new System.Drawing.Point(0, 20); this._lblTotal_0.TabIndex = 25; this._lblTotal_0.Enabled = true; this._lblTotal_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_0.UseMnemonic = true; this._lblTotal_0.Visible = true; this._lblTotal_0.AutoSize = false; this._lblTotal_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_0.Name = "_lblTotal_0"; this._lblTotal_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_1.BackColor = System.Drawing.Color.Transparent; this._lblTotal_1.Text = "Price Per Kg :"; this._lblTotal_1.Size = new System.Drawing.Size(203, 16); this._lblTotal_1.Location = new System.Drawing.Point(2, 38); this._lblTotal_1.TabIndex = 24; this._lblTotal_1.Enabled = true; this._lblTotal_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_1.UseMnemonic = true; this._lblTotal_1.Visible = true; this._lblTotal_1.AutoSize = false; this._lblTotal_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_1.Name = "_lblTotal_1"; this._lblTotal_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_2.BackColor = System.Drawing.Color.Transparent; this._lblTotal_2.Text = "Weight of Carcass :"; this._lblTotal_2.Size = new System.Drawing.Size(203, 16); this._lblTotal_2.Location = new System.Drawing.Point(2, 56); this._lblTotal_2.TabIndex = 23; this._lblTotal_2.Enabled = true; this._lblTotal_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_2.UseMnemonic = true; this._lblTotal_2.Visible = true; this._lblTotal_2.AutoSize = false; this._lblTotal_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_2.Name = "_lblTotal_2"; this._lblTotal_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_3.BackColor = System.Drawing.Color.Transparent; this._lblTotal_3.Text = "Cost of Carcass :"; this._lblTotal_3.Size = new System.Drawing.Size(203, 16); this._lblTotal_3.Location = new System.Drawing.Point(2, 74); this._lblTotal_3.TabIndex = 22; this._lblTotal_3.Enabled = true; this._lblTotal_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_3.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_3.UseMnemonic = true; this._lblTotal_3.Visible = true; this._lblTotal_3.AutoSize = false; this._lblTotal_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_3.Name = "_lblTotal_3"; this._lblTotal_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_4.BackColor = System.Drawing.Color.Transparent; this._lblTotal_4.Text = "Weight Loss & Cutting Loss :"; this._lblTotal_4.Size = new System.Drawing.Size(203, 16); this._lblTotal_4.Location = new System.Drawing.Point(2, 92); this._lblTotal_4.TabIndex = 21; this._lblTotal_4.Enabled = true; this._lblTotal_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_4.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_4.UseMnemonic = true; this._lblTotal_4.Visible = true; this._lblTotal_4.AutoSize = false; this._lblTotal_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_4.Name = "_lblTotal_4"; this._lblTotal_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_5.BackColor = System.Drawing.Color.Transparent; this._lblTotal_5.Text = "Effective Price per Kg after loss :"; this._lblTotal_5.Size = new System.Drawing.Size(203, 16); this._lblTotal_5.Location = new System.Drawing.Point(2, 110); this._lblTotal_5.TabIndex = 20; this._lblTotal_5.Enabled = true; this._lblTotal_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_5.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_5.UseMnemonic = true; this._lblTotal_5.Visible = true; this._lblTotal_5.AutoSize = false; this._lblTotal_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_5.Name = "_lblTotal_5"; this.lblX.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblX.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblX.Text = "0.00"; this.lblX.Size = new System.Drawing.Size(120, 16); this.lblX.Location = new System.Drawing.Point(616, 110); this.lblX.TabIndex = 19; this.lblX.Enabled = true; this.lblX.ForeColor = System.Drawing.SystemColors.ControlText; this.lblX.Cursor = System.Windows.Forms.Cursors.Default; this.lblX.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblX.UseMnemonic = true; this.lblX.Visible = true; this.lblX.AutoSize = false; this.lblX.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblX.Name = "lblX"; this.lblGP_Y.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblGP_Y.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblGP_Y.Text = "0.00"; this.lblGP_Y.Size = new System.Drawing.Size(120, 16); this.lblGP_Y.Location = new System.Drawing.Point(616, 56); this.lblGP_Y.TabIndex = 18; this.lblGP_Y.Enabled = true; this.lblGP_Y.ForeColor = System.Drawing.SystemColors.ControlText; this.lblGP_Y.Cursor = System.Windows.Forms.Cursors.Default; this.lblGP_Y.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblGP_Y.UseMnemonic = true; this.lblGP_Y.Visible = true; this.lblGP_Y.AutoSize = false; this.lblGP_Y.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblGP_Y.Name = "lblGP_Y"; this.lblB_Z.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblB_Z.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblB_Z.Text = "0.00"; this.lblB_Z.Size = new System.Drawing.Size(120, 16); this.lblB_Z.Location = new System.Drawing.Point(616, 74); this.lblB_Z.TabIndex = 17; this.lblB_Z.Enabled = true; this.lblB_Z.ForeColor = System.Drawing.SystemColors.ControlText; this.lblB_Z.Cursor = System.Windows.Forms.Cursors.Default; this.lblB_Z.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblB_Z.UseMnemonic = true; this.lblB_Z.Visible = true; this.lblB_Z.AutoSize = false; this.lblB_Z.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblB_Z.Name = "lblB_Z"; this._lblTotal_6.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_6.BackColor = System.Drawing.Color.Transparent; this._lblTotal_6.Text = "X - VAT+1 :"; this._lblTotal_6.Size = new System.Drawing.Size(133, 16); this._lblTotal_6.Location = new System.Drawing.Point(472, 110); this._lblTotal_6.TabIndex = 16; this._lblTotal_6.Enabled = true; this._lblTotal_6.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_6.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_6.UseMnemonic = true; this._lblTotal_6.Visible = true; this._lblTotal_6.AutoSize = false; this._lblTotal_6.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_6.Name = "_lblTotal_6"; this._lblTotal_7.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_7.BackColor = System.Drawing.Color.Transparent; this._lblTotal_7.Text = "VAT :"; this._lblTotal_7.Size = new System.Drawing.Size(133, 16); this._lblTotal_7.Location = new System.Drawing.Point(472, 92); this._lblTotal_7.TabIndex = 15; this._lblTotal_7.Enabled = true; this._lblTotal_7.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_7.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_7.UseMnemonic = true; this._lblTotal_7.Visible = true; this._lblTotal_7.AutoSize = false; this._lblTotal_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_7.Name = "_lblTotal_7"; this._lblTotal_8.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_8.BackColor = System.Drawing.Color.Transparent; this._lblTotal_8.Text = "B/Z :"; this._lblTotal_8.Size = new System.Drawing.Size(133, 16); this._lblTotal_8.Location = new System.Drawing.Point(472, 74); this._lblTotal_8.TabIndex = 14; this._lblTotal_8.Enabled = true; this._lblTotal_8.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_8.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_8.UseMnemonic = true; this._lblTotal_8.Visible = true; this._lblTotal_8.AutoSize = false; this._lblTotal_8.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_8.Name = "_lblTotal_8"; this._lblTotal_9.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_9.BackColor = System.Drawing.Color.Transparent; this._lblTotal_9.Text = "(1 - GP%) :"; this._lblTotal_9.Size = new System.Drawing.Size(133, 16); this._lblTotal_9.Location = new System.Drawing.Point(472, 56); this._lblTotal_9.TabIndex = 13; this._lblTotal_9.Enabled = true; this._lblTotal_9.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_9.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_9.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_9.UseMnemonic = true; this._lblTotal_9.Visible = true; this._lblTotal_9.AutoSize = false; this._lblTotal_9.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_9.Name = "_lblTotal_9"; this._lblTotal_10.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblTotal_10.BackColor = System.Drawing.Color.Transparent; this._lblTotal_10.Text = "Required GP :"; this._lblTotal_10.Size = new System.Drawing.Size(133, 16); this._lblTotal_10.Location = new System.Drawing.Point(472, 38); this._lblTotal_10.TabIndex = 12; this._lblTotal_10.Enabled = true; this._lblTotal_10.ForeColor = System.Drawing.SystemColors.ControlText; this._lblTotal_10.Cursor = System.Windows.Forms.Cursors.Default; this._lblTotal_10.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblTotal_10.UseMnemonic = true; this._lblTotal_10.Visible = true; this._lblTotal_10.AutoSize = false; this._lblTotal_10.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblTotal_10.Name = "_lblTotal_10"; this._txtEdit_1.AutoSize = false; this._txtEdit_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_1.Size = new System.Drawing.Size(55, 16); this._txtEdit_1.Location = new System.Drawing.Point(350, 583); this._txtEdit_1.MaxLength = 10; this._txtEdit_1.TabIndex = 9; this._txtEdit_1.Tag = "0"; this._txtEdit_1.Text = "0"; this._txtEdit_1.Visible = false; this._txtEdit_1.AcceptsReturn = true; this._txtEdit_1.CausesValidation = true; this._txtEdit_1.Enabled = true; this._txtEdit_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_1.HideSelection = true; this._txtEdit_1.ReadOnly = false; this._txtEdit_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_1.Multiline = false; this._txtEdit_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_1.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_1.TabStop = true; this._txtEdit_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_1.Name = "_txtEdit_1"; this._txtEdit_2.AutoSize = false; this._txtEdit_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtEdit_2.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._txtEdit_2.Size = new System.Drawing.Size(55, 16); this._txtEdit_2.Location = new System.Drawing.Point(422, 583); this._txtEdit_2.MaxLength = 10; this._txtEdit_2.TabIndex = 8; this._txtEdit_2.Tag = "0"; this._txtEdit_2.Text = "0"; this._txtEdit_2.Visible = false; this._txtEdit_2.AcceptsReturn = true; this._txtEdit_2.CausesValidation = true; this._txtEdit_2.Enabled = true; this._txtEdit_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtEdit_2.HideSelection = true; this._txtEdit_2.ReadOnly = false; this._txtEdit_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtEdit_2.Multiline = false; this._txtEdit_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtEdit_2.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtEdit_2.TabStop = true; this._txtEdit_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._txtEdit_2.Name = "_txtEdit_2"; this.Picture2.Dock = System.Windows.Forms.DockStyle.Top; this.Picture2.BackColor = System.Drawing.Color.Blue; this.Picture2.Size = new System.Drawing.Size(1016, 49); this.Picture2.Location = new System.Drawing.Point(0, 0); this.Picture2.TabIndex = 5; this.Picture2.TabStop = false; this.Picture2.CausesValidation = true; this.Picture2.Enabled = true; this.Picture2.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture2.Cursor = System.Windows.Forms.Cursors.Default; this.Picture2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture2.Visible = true; this.Picture2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture2.Name = "Picture2"; this.cmdReg.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdReg.Text = "&Register 4MEAT"; this.cmdReg.Size = new System.Drawing.Size(115, 40); this.cmdReg.Location = new System.Drawing.Point(352, 3); this.cmdReg.TabIndex = 55; this.cmdReg.TabStop = false; this.cmdReg.Visible = false; this.cmdReg.BackColor = System.Drawing.SystemColors.Control; this.cmdReg.CausesValidation = true; this.cmdReg.Enabled = true; this.cmdReg.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdReg.Cursor = System.Windows.Forms.Cursors.Default; this.cmdReg.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdReg.Name = "cmdReg"; this.cmdProc.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdProc.Text = "&Process"; this.cmdProc.Size = new System.Drawing.Size(67, 40); this.cmdProc.Location = new System.Drawing.Point(168, 3); this.cmdProc.TabIndex = 52; this.cmdProc.TabStop = false; this.cmdProc.BackColor = System.Drawing.SystemColors.Control; this.cmdProc.CausesValidation = true; this.cmdProc.Enabled = true; this.cmdProc.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdProc.Cursor = System.Windows.Forms.Cursors.Default; this.cmdProc.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdProc.Name = "cmdProc"; this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrint.Text = "P&rint"; this.cmdPrint.Size = new System.Drawing.Size(67, 40); this.cmdPrint.Location = new System.Drawing.Point(88, 3); this.cmdPrint.TabIndex = 7; this.cmdPrint.TabStop = false; this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.CausesValidation = true; this.cmdPrint.Enabled = true; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Name = "cmdPrint"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(67, 40); this.cmdExit.Location = new System.Drawing.Point(7, 3); this.cmdExit.TabIndex = 6; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; //gridItem.OcxState = CType(resources.GetObject("gridItem.OcxState"), System.Windows.Forms.AxHost.State) this.gridItem.Size = new System.Drawing.Size(901, 359); this.gridItem.Location = new System.Drawing.Point(3, 200); this.gridItem.TabIndex = 4; this.gridItem.Name = "gridItem"; this.Controls.Add(picTotal); this.Controls.Add(_txtEdit_0); this.Controls.Add(frmTotals); this.Controls.Add(_txtEdit_1); this.Controls.Add(_txtEdit_2); this.Controls.Add(Picture2); this.Controls.Add(gridItem); this.picTotal.Controls.Add(lblTotalOP); this.picTotal.Controls.Add(lblTotalLP); this.picTotal.Controls.Add(lblTotalO); this.picTotal.Controls.Add(_lblTotal_17); this.picTotal.Controls.Add(lblTotalL); this.picTotal.Controls.Add(_lblTotal_16); this.picTotal.Controls.Add(lblTotalH); this.picTotal.Controls.Add(_lblTotal_15); this.picTotal.Controls.Add(lblTotalG); this.picTotal.Controls.Add(_lblTotal_14); this.picTotal.Controls.Add(_lblTotal_13); this.picTotal.Controls.Add(lblTotalQ); this.picTotal.Controls.Add(_lblTotal_12); this.picTotal.Controls.Add(lblTotalF); this.picTotal.Controls.Add(lblP); this.picTotal.Controls.Add(_lblTotal_11); this.frmTotals.Controls.Add(cmdLoadNext); this.frmTotals.Controls.Add(txtR); this.frmTotals.Controls.Add(txtZ); this.frmTotals.Controls.Add(cmdTotal); this.frmTotals.Controls.Add(txtReqGP); this.frmTotals.Controls.Add(txtVAT); this.frmTotals.Controls.Add(lblQuantity); this.frmTotals.Controls.Add(_lbl_8); this.frmTotals.Controls.Add(lblBrokenPack); this.frmTotals.Controls.Add(_lbl_2); this.frmTotals.Controls.Add(lblContentExclusive); this.frmTotals.Controls.Add(lblContentInclusives); this.frmTotals.Controls.Add(lblDepositExclusives); this.frmTotals.Controls.Add(lblA); this.frmTotals.Controls.Add(lblB); this.frmTotals.Controls.Add(lblC); this.frmTotals.Controls.Add(_lblTotal_0); this.frmTotals.Controls.Add(_lblTotal_1); this.frmTotals.Controls.Add(_lblTotal_2); this.frmTotals.Controls.Add(_lblTotal_3); this.frmTotals.Controls.Add(_lblTotal_4); this.frmTotals.Controls.Add(_lblTotal_5); this.frmTotals.Controls.Add(lblX); this.frmTotals.Controls.Add(lblGP_Y); this.frmTotals.Controls.Add(lblB_Z); this.frmTotals.Controls.Add(_lblTotal_6); this.frmTotals.Controls.Add(_lblTotal_7); this.frmTotals.Controls.Add(_lblTotal_8); this.frmTotals.Controls.Add(_lblTotal_9); this.frmTotals.Controls.Add(_lblTotal_10); this.Picture2.Controls.Add(cmdReg); this.Picture2.Controls.Add(cmdProc); this.Picture2.Controls.Add(cmdPrint); this.Picture2.Controls.Add(cmdExit); //Me.lbl.SetIndex(_lbl_8, CType(8, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //Me.lblTotal.SetIndex(_lblTotal_17, CType(17, Short)) //Me.lblTotal.SetIndex(_lblTotal_16, CType(16, Short)) //Me.lblTotal.SetIndex(_lblTotal_15, CType(15, Short)) //Me.lblTotal.SetIndex(_lblTotal_14, CType(14, Short)) //Me.lblTotal.SetIndex(_lblTotal_13, CType(13, Short)) //Me.lblTotal.SetIndex(_lblTotal_12, CType(12, Short)) //Me.lblTotal.SetIndex(_lblTotal_11, CType(11, Short)) //Me.lblTotal.SetIndex(_lblTotal_0, CType(0, Short)) //Me.lblTotal.SetIndex(_lblTotal_1, CType(1, Short)) //Me.lblTotal.SetIndex(_lblTotal_2, CType(2, Short)) //Me.lblTotal.SetIndex(_lblTotal_3, CType(3, Short)) //Me.lblTotal.SetIndex(_lblTotal_4, CType(4, Short)) //Me.lblTotal.SetIndex(_lblTotal_5, CType(5, Short)) //Me.lblTotal.SetIndex(_lblTotal_6, CType(6, Short)) //Me.lblTotal.SetIndex(_lblTotal_7, CType(7, Short)) //Me.lblTotal.SetIndex(_lblTotal_8, CType(8, Short)) //Me.lblTotal.SetIndex(_lblTotal_9, CType(9, Short)) //Me.lblTotal.SetIndex(_lblTotal_10, CType(10, Short)) //Me.txtEdit.SetIndex(_txtEdit_0, CType(0, Short)) //Me.txtEdit.SetIndex(_txtEdit_1, CType(1, Short)) //Me.txtEdit.SetIndex(_txtEdit_2, CType(2, Short)) //CType(Me.txtEdit, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblTotal, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() ((System.ComponentModel.ISupportInitialize)this.gridItem).EndInit(); this.picTotal.ResumeLayout(false); this.frmTotals.ResumeLayout(false); this.Picture2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType { internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private SyntaxNode GetNamespaceOrTypeNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n)) .FirstOrDefault(); } private SyntaxNode GetNamespaceNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n)) .FirstOrDefault(); } internal INamedTypeSymbol LookupTypeSymbol() { return (INamedTypeSymbol)LookupSymbol(); } protected override object GetExtenderNames() { return CodeModelService.GetTypeExtenderNames(); } protected override object GetExtender(string name) { return CodeModelService.GetTypeExtender(name, this); } public override object Parent { get { var containingNamespaceOrType = GetNamespaceOrTypeNode(); return containingNamespaceOrType != null ? (object)FileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType) : this.FileCodeModel; } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey), (ICodeElements)this.Members); } } public EnvDTE.CodeElements Bases { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateDataTypeKind, value); } } public EnvDTE.CodeElements DerivedTypes { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements ImplementedInterfaces { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true); } } public EnvDTE.CodeElements Members { get { return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey); } } public EnvDTE.CodeNamespace Namespace { get { var namespaceNode = GetNamespaceNode(); return namespaceNode != null ? FileCodeModel.CreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode) : null; } } /// <returns>True if the current type inherits from or equals the type described by the /// given full name.</returns> /// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks> public bool get_IsDerivedFrom(string fullName) { var currentType = LookupTypeSymbol(); if (currentType == null) { return false; } var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName); if (baseType == null) { return false; } return currentType.InheritsFromOrEquals(baseType); } public override bool IsCodeType { get { return true; } } public void RemoveMember(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.ElementIsNotValid, "element"); } codeElement.Delete(); } public EnvDTE.CodeElement AddBase(object @base, object position) { return FileCodeModel.EnsureEditor(() => { FileCodeModel.AddBase(LookupNode(), @base, position); var codeElements = this.Bases as ICodeElements; EnvDTE.CodeElement element; var hr = codeElements.Item(1, out element); if (ErrorHandler.Succeeded(hr)) { return element; } return null; }); } public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) { return FileCodeModel.EnsureEditor(() => { var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position); var codeElements = this.ImplementedInterfaces as ICodeElements; EnvDTE.CodeElement element; var hr = codeElements.Item(name, out element); if (ErrorHandler.Succeeded(hr)) { return element as EnvDTE.CodeInterface; } return null; }); } public void RemoveBase(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveBase(LookupNode(), element); }); } public void RemoveInterface(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveImplementedInterface(LookupNode(), element); }); } } }
// 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. /*============================================================ ** ** ** ** Implementation details of CLR Contracts. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool _assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { if (_assertingMustUseRewriter) System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); _assertingMustUseRewriter = true; // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; if (caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; String simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null); _assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind)); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endregion FailureBehavior } public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS #endif public void SetUnwind() { _unwind = true; } } [Serializable] [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { readonly ContractFailureKind _Kind; readonly string _UserMessage; readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; this._Kind = kind; this._UserMessage = userMessage; this._Condition = condition; } private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _Kind = (ContractFailureKind)info.GetInt32("Kind"); _UserMessage = info.GetString("UserMessage"); _Condition = info.GetString("Condition"); } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _Kind); info.AddValue("UserMessage", _UserMessage); info.AddValue("Condition", _Condition); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent; private static readonly Object lockObject = new Object(); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); lock (lockObject) { contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS #endif remove { lock (lockObject) { contractFailedEvent -= value; } } } /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind)); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... ContractFailedEventArgs eventArgs = null; // In case of OOM. #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent; if (contractFailedEventLocal != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } } finally { if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); } // May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. // Optional info like string for collapsed text vs. expanded text. String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind)); const int numStackFramesToSkip = 2; // To make stack traces easier to read System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetResourceNameForFailure(ContractFailureKind failureKind) { String resourceName = null; switch (failureKind) { case ContractFailureKind.Assert: resourceName = "AssertionFailed"; break; case ContractFailureKind.Assume: resourceName = "AssumptionFailed"; break; case ContractFailureKind.Precondition: resourceName = "PreconditionFailed"; break; case ContractFailureKind.Postcondition: resourceName = "PostconditionFailed"; break; case ContractFailureKind.Invariant: resourceName = "InvariantFailed"; break; case ContractFailureKind.PostconditionOnException: resourceName = "PostconditionOnExceptionFailed"; break; default: Contract.Assume(false, "Unreachable code"); resourceName = "AssumptionFailed"; break; } return resourceName; } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { String resourceName = GetResourceNameForFailure(failureKind); // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage; if (!String.IsNullOrEmpty(conditionText)) { resourceName += "_Cnd"; failureMessage = Environment.GetResourceString(resourceName, conditionText); } else { failureMessage = Environment.GetResourceString(resourceName); } // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } } } // namespace System.Runtime.CompilerServices
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GroupDrivesCollectionRequest. /// </summary> public partial class GroupDrivesCollectionRequest : BaseRequest, IGroupDrivesCollectionRequest { /// <summary> /// Constructs a new GroupDrivesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GroupDrivesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Drive to the collection via POST. /// </summary> /// <param name="drive">The Drive to add.</param> /// <returns>The created Drive.</returns> public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive) { return this.AddAsync(drive, CancellationToken.None); } /// <summary> /// Adds the specified Drive to the collection via POST. /// </summary> /// <param name="drive">The Drive to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Drive.</returns> public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Drive>(drive, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGroupDrivesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGroupDrivesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GroupDrivesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Expand(Expression<Func<Drive, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Select(Expression<Func<Drive, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGroupDrivesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
//----------------------------------------------------------------------------- // <copyright file="DropboxClient.common.cs" company="Dropbox Inc"> // Copyright (c) Dropbox Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace Dropbox.Api { using System; using System.Net.Http; /// <summary> /// The class which contains all configurations for Dropbox client. /// </summary> public sealed class DropboxClientConfig { /// <summary> /// Initializes a new instance of the <see cref="DropboxClientConfig"/> class. /// </summary> public DropboxClientConfig() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="DropboxClientConfig"/> class. /// </summary> /// <param name="userAgent">The user agent to use when making requests.</param> public DropboxClientConfig(string userAgent) : this(userAgent, 4) { } /// <summary> /// Initializes a new instance of the <see cref="DropboxClientConfig"/> class. /// </summary> /// <param name="userAgent">The user agent to use when making requests.</param> /// <param name="maxRetriesOnError">The max number retries on error.</param> public DropboxClientConfig(string userAgent, int maxRetriesOnError) : this(userAgent, maxRetriesOnError, null) { } /// <summary> /// Initializes a new instance of the <see cref="DropboxClientConfig"/> class. /// </summary> /// <param name="userAgent">The user agent to use when making requests.</param> /// <param name="maxRetriesOnError">The max number retries on error.</param> /// <param name="httpClient">The custom http client.</param> internal DropboxClientConfig(string userAgent, int maxRetriesOnError, HttpClient httpClient) { this.UserAgent = userAgent; this.MaxRetriesOnError = maxRetriesOnError; this.HttpClient = httpClient; } /// <summary> /// Gets or sets the max number retries on error. Default value is 4. /// </summary> public int MaxRetriesOnError { get; set; } /// <summary> /// Gets or sets the user agent to use when making requests. /// </summary> /// <remarks> /// This value helps Dropbox to identify requests coming from your application. /// We recommend that you use the format <c>"AppName/Version"</c>; if a value is supplied, the string /// <c>"/OfficialDropboxDotNetV2SDK/__version__"</c> is appended to the user agent. /// </remarks> public string UserAgent { get; set; } /// <summary> /// Gets or sets the custom http client. If not set, a default http client will be created. /// </summary> public HttpClient HttpClient { get; set; } } /// <summary> /// The client which contains endpoints which perform user-level actions. /// </summary> public sealed partial class DropboxClient : IDisposable { /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> public DropboxClient(string oauth2AccessToken) : this(oauth2AccessToken, new DropboxClientConfig()) { } /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> /// <param name="userAgent">The user agent to use when making requests.</param> [Obsolete("This constructor is deprecated, please use DropboxClientConfig instead.")] public DropboxClient(string oauth2AccessToken, string userAgent) : this(oauth2AccessToken, new DropboxClientConfig(userAgent)) { } /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> /// <param name="config">The <see cref="DropboxClientConfig"/>.</param> public DropboxClient(string oauth2AccessToken, DropboxClientConfig config) : this(new DropboxRequestHandlerOptions(oauth2AccessToken, config.MaxRetriesOnError, config.UserAgent, httpClient: config.HttpClient)) { if (oauth2AccessToken == null) { throw new ArgumentNullException("oauth2AccessToken"); } } /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxClient"/> class. /// </summary> /// <param name="options">The request handler options.</param> /// <param name="selectUser">The member id of the selected user. If provided together with /// a team access token, actions will be performed on this this user's Dropbox.</param> internal DropboxClient(DropboxRequestHandlerOptions options, string selectUser = null) { this.InitializeRoutes(new DropboxRequestHandler(options, selectUser)); } /// <summary> /// Dummy dispose method. /// </summary> public void Dispose() { } } /// <summary> /// The client which contains endpoints which perform team-level actions. /// </summary> public sealed partial class DropboxTeamClient { /// <summary> /// The request handler options. /// </summary> private readonly DropboxRequestHandlerOptions options; /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxTeamClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> public DropboxTeamClient(string oauth2AccessToken) : this(oauth2AccessToken, new DropboxClientConfig()) { } /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxTeamClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> /// <param name="userAgent">The user agent to use when making requests.</param> [Obsolete("This constructor is deprecated, please use DropboxClientConfig instead.")] public DropboxTeamClient(string oauth2AccessToken, string userAgent) : this(oauth2AccessToken, new DropboxClientConfig(userAgent)) { } /// <summary> /// Initializes a new instance of the <see cref="T:Dropbox.Api.DropboxTeamClient"/> class. /// </summary> /// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param> /// <param name="config">The <see cref="DropboxClientConfig"/>.</param> public DropboxTeamClient(string oauth2AccessToken, DropboxClientConfig config) { if (oauth2AccessToken == null) { throw new ArgumentNullException("oauth2AccessToken"); } this.options = new DropboxRequestHandlerOptions(oauth2AccessToken, config.MaxRetriesOnError, config.UserAgent, httpClient: config.HttpClient); this.InitializeRoutes(new DropboxRequestHandler(this.options)); } /// <summary> /// Convert the team client to a user client which can perform action on the given team member's Dropbox. /// </summary> /// <param name="memberId">The member id of a user who is in the team.</param> /// <returns>The <see cref="DropboxClient"/></returns> public DropboxClient AsMember(string memberId) { return new DropboxClient(this.options, memberId); } } /// <summary> /// General HTTP exception /// </summary> public class HttpException : Exception { /// <summary> /// Initializes a new instance of the <see cref="HttpException"/> class. /// </summary> /// <param name="statusCode">The status code.</param> /// <param name="message">The message.</param> /// <param name="uri">The request uri.</param> /// <param name="inner">The inner.</param> internal HttpException(int statusCode, string message = null, Uri uri = null, Exception inner = null) : base(message, inner) { this.StatusCode = statusCode; this.RequestUri = uri; } /// <summary> /// Gets the HTTP status code that prompted this exception /// </summary> /// <value> /// The status code. /// </value> public int StatusCode { get; private set; } /// <summary> /// Gets the URI for the request that prompted this exception. /// </summary> /// <value> /// The request URI. /// </value> public Uri RequestUri { get; private set; } } /// <summary> /// An HTTP exception that is caused by the server reporting a bad request. /// </summary> public class BadInputException : HttpException { /// <summary> /// Initializes a new instance of the <see cref="BadInputException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="uri">The request URI.</param> internal BadInputException(string message, Uri uri = null) : base(400, message, uri) { } } /// <summary> /// An HTTP exception that is caused by the server reporting an authentication problem. /// </summary> public partial class AuthException { /// <summary> /// Initializes a new instance of the <see cref="AuthException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="uri">The request URI</param> [Obsolete("This constructor will be removed soon.")] public AuthException(string message, Uri uri = null) : base(null, message) { this.StatusCode = 401; this.RequestUri = uri; } /// <summary> /// Gets the HTTP status code that prompted this exception /// </summary> /// <value> /// The status code. /// </value> [Obsolete("This field will be removed soon.")] public int StatusCode { get; private set; } /// <summary> /// Gets the URI for the request that prompted this exception. /// </summary> /// <value> /// The request URI. /// </value> [Obsolete("This field will be removed soon.")] public Uri RequestUri { get; private set; } } /// <summary> /// An HTTP Exception that will cause a retry due to transient failure. The SDK will perform /// a certain number of retries which is configurable in <see cref="DropboxClient"/>. If the client /// still gets this exception, it's up to the client to decide whether to continue retrying or not. /// </summary> public class RetryException : HttpException { /// <summary> /// Initializes a new instance of the <see cref="RetryException"/> class. /// </summary> /// <param name="statusCode">The status code.</param> /// <param name="message">The message.</param> /// <param name="uri">The request URI.</param> /// <param name="inner">The inner.</param> internal RetryException(int statusCode, string message = null, Uri uri = null, Exception inner = null) : base(statusCode, message, uri, inner) { } /// <summary> /// Gets a value indicating whether this error represents a rate limiting response from the server. /// </summary> /// <value> /// <c>true</c> if this response is a rate limit; otherwise, <c>false</c>. /// </value> [Obsolete("This field will be removed soon. Please catch RateLimitException separately.")] public virtual bool IsRateLimit { get { return false; } } } /// <summary> /// An HTTP Exception that will cause a retry due to rate limiting. The SDK will not do auto-retry for /// this type of exception. The client should do proper backoff based on the value of /// <see cref="RateLimitException.RetryAfter"/> field. /// </summary> public class RateLimitException : RetryException { /// <summary> /// Initializes a new instance of the <see cref="RateLimitException"/> class. /// </summary> /// <param name="retryAfter">The time in second which the client should retry after.</param> /// <param name="message">The message.</param> /// <param name="uri">The request URI.</param> /// <param name="inner">The inner.</param> internal RateLimitException(int retryAfter, string message = null, Uri uri = null, Exception inner = null) : base(429, message, uri, inner) { this.RetryAfter = retryAfter; } /// <summary> /// Gets the value in second which the client should backoff and retry after. /// </summary> public int RetryAfter { get; private set; } /// <summary> /// Gets a value indicating whether this error represents a rate limiting response from the server. /// </summary> /// <value> /// <c>true</c> if this response is a rate limit; otherwise, <c>false</c>. /// </value> [Obsolete("This field will be removed soon.")] public override bool IsRateLimit { get { return true; } } } }
using System; using System.Linq; using UnityEditor; using UnityEngine; using System.Collections.Generic; using PrefabEvolution; using Object = UnityEngine.Object; [CustomEditor(typeof(PEPrefabScript), true)] class PEPrefabScriptEditor : Editor { private PETreeNode rootNode; private PEAutoDict<Object, bool> expandedDict = new PEAutoDict<Object, bool>(false); PETreeNode Add(GameObject go, PETreeNode parent, bool includeChildren = true) { var isExpanded = expandedDict[go]; var node = new PETreeNode(isExpanded) { content = new GUIContent(go.name, PEResources.icon), UserData = go }; parent.children.Add(node); node.OnExpandChanged += expanded => expandedDict[go] = expanded; var pi = go.GetComponent<PEPrefabScript>(); if (pi) { var isRoot = PrefabUtility.FindPrefabRoot(pi.gameObject) == pi.Prefab || PrefabUtility.GetPrefabParent(pi.gameObject) == pi.Prefab; if (isRoot) { node.color = Color.green; node.content.text += " (Root)"; } else { node.color = Color.yellow; node.content.text += " (Nested)"; } } if (prefabScript.Modifications.TransformParentChanges.Any(npo => npo.child == go.transform)) { node.color = Color.cyan; node.content.text += " (Parent Changed)"; } else if (prefabScript.Modifications.NonPrefabObjects.Any(c => c.child == go.transform)) { node.color = Color.yellow; node.content.text += " (New)"; } if (!includeChildren) return node; foreach (var property in GetProperties(go)) { Add(property, node); } foreach (Component component in go.GetComponents<Component>()) { Add(component, node); } foreach (Transform transform in go.transform) { var nd = Add(transform.gameObject, node); if (nd.children.Count == 0 && nd.color == Color.white) node.children.Remove(nd); } foreach (var obj in GetRemovedObjects(go, prefabScript)) { PETreeNode nd = null; var component = obj as Component; if (component != null) { nd = Add(component, node, false); } else { var gameObject = obj as GameObject; if (gameObject != null) { nd = Add(gameObject, node, false); } } if (nd != null) { nd.color = Color.red; nd.content.text += " (Removed)"; } } return node; } PETreeNode Add(SerializedProperty property, PETreeNode parent) { var node = new PETreeNode.PropertyNode { UserData = property }; parent.children.Add(node); return node; } PETreeNode Add(Component component, PETreeNode parent, bool includeChildren = true) { var isNewComponent = prefabScript.Modifications.NonPrefabComponents.Any(c => c.child == component) && !(component is PEPrefabScript); if (!isNewComponent && !includeChildren) return null; var isExpanded = expandedDict[component]; var node = new PETreeNode(isExpanded) { content = new GUIContent(component.GetType().Name, EditorGUIUtility.ObjectContent(component, component.GetType()).image), UserData = component }; node.OnExpandChanged += expanded => expandedDict[component] = expanded; if (isNewComponent) { node.content.text += " (New)"; node.color = Color.yellow; } else { var propertiesOverrides = GetProperties(component).ToArray(); if (propertiesOverrides.Length == 0) return null; foreach (var property in propertiesOverrides) { Add(property, node); } } parent.children.Add(node); return node; } IEnumerable<SerializedProperty> GetProperties(Object obj) { var modifications = serializedObject.FindProperty("Modifications.Modificated"); modifications.Next(true); for (var i = 0; i < modifications.arraySize; i++) { var property = modifications.GetArrayElementAtIndex(i); if (property.FindPropertyRelative("Object").objectReferenceValue == obj) yield return property; } } void OnEnable() { this.exposedPropertiesEditor = new PEExposedPropertiesEditor(this.targets.OfType<PEPrefabScript>().ToArray()); rootNode = new PETreeNode(false) { content = new GUIContent("Modifications") }; rootNode.children.Add(new PETreeNode()); Action<bool> d = obj => { if (obj) { prefabScript.BuildModifications(); UpdateTree(); prefabScript.OnBuildModifications += UpdateTree; } else { prefabScript.OnBuildModifications -= UpdateTree; } }; rootNode.OnExpandChanged += d; } void OnDisable() { this.prefabScript.OnBuildModifications -= UpdateTree; } void UpdateTree() { serializedObject.Update(); rootNode = new PETreeNode(rootNode.Expanded) { content = new GUIContent("Modifications") }; Add(prefabScript.gameObject, rootNode); } static IEnumerable<Object> GetRemovedObjects(Object go, PEPrefabScript prefabInstance) { foreach (var liif in prefabInstance.Modifications.RemovedObjects) { var instanceObj = prefabInstance.GetDiffWith().Links[liif]; if (instanceObj == null) continue; var removedGO = instanceObj.InstanceTarget as GameObject; var removedComponent = instanceObj.InstanceTarget as Component; if (removedComponent is PEPrefabScript) continue; var remoteParent = (removedGO != null) ? (removedGO.transform.parent == null ? removedGO.transform.gameObject : removedGO.transform.parent.gameObject) : (removedComponent != null ? removedComponent.gameObject : null); var localLink = prefabInstance.Links[prefabInstance.GetDiffWith().Links[remoteParent]]; if (localLink == null) continue; var localParent = localLink.InstanceTarget; if (localParent == go) yield return instanceObj.InstanceTarget; } } internal PEPrefabScript prefabScript { get { return this.target as PEPrefabScript; } } static internal void DrawView(PEPrefabScript script) { GUILayout.Space(3); var icon = EditorGUIUtility.ObjectContent(null, typeof(GameObject)); GUILayout.BeginHorizontal(); if (!string.IsNullOrEmpty(script.ParentPrefabGUID)) { var c = GUI.backgroundColor; if (!script.ParentPrefab) GUI.backgroundColor = Color.red; var content = new GUIContent(script.ParentPrefab ? script.ParentPrefab.name : "Missing:" + script.ParentPrefabGUID, icon.image); GUILayout.Label("Parent:", GUILayout.Width(50)); if (GUILayout.Button(content, EditorStyles.miniButton, GUILayout.Height(16), GUILayout.MinWidth(0))) EditorGUIUtility.PingObject(script.ParentPrefab); GUI.backgroundColor = c; } if (!string.IsNullOrEmpty(script.PrefabGUID)) { var c = GUI.backgroundColor; if (!script.Prefab) GUI.backgroundColor = Color.red; var content = new GUIContent(script.Prefab ? script.Prefab.name : "Missing:" + script.PrefabGUID, icon.image); GUILayout.Label("Prefab:", GUILayout.Width(50)); if (GUILayout.Button(content, EditorStyles.miniButton, GUILayout.Height(16), GUILayout.MinWidth(0))) EditorGUIUtility.PingObject(script.Prefab); GUI.backgroundColor = c; } GUILayout.EndHorizontal(); GUILayout.Space(1); DrawCommands(script); EditorGUIUtility.labelWidth = 150; } private PEExposedPropertiesEditor exposedPropertiesEditor; public override void OnInspectorGUI() { var script = prefabScript; if (!PEPrefs.DrawOnHeader) { DrawView(script); exposedPropertiesEditor.Draw(); } if ((script.hideFlags & HideFlags.NotEditable) != HideFlags.NotEditable) { DrawDefault(); if (rootNode != null) rootNode.Draw(); } } static void DrawCommands(PEPrefabScript prefabScript) { var e = GUI.enabled; GUI.enabled = true; if (GUILayout.Button("Menu", EditorStyles.miniButton)) { var menu = new GenericMenu(); PEUtils.BuildMenu(menu, prefabScript, PrefabUtility.GetPrefabParent(prefabScript.gameObject) == prefabScript.Prefab); menu.ShowAsContext(); } GUI.enabled = e; } void DrawDefault() { var obj = serializedObject; EditorGUI.BeginChangeCheck(); obj.Update(); SerializedProperty iterator = obj.GetIterator(); bool enterChildren = true; while (iterator.NextVisible(enterChildren)) { if (iterator.name != "m_Script" && iterator.name != "Modifications" && iterator.name != "PrefabGUID" && iterator.name != "ParentPrefabGUID") EditorGUILayout.PropertyField(iterator, true); enterChildren = false; } obj.ApplyModifiedProperties(); EditorGUI.EndChangeCheck(); } } //}
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace liquicode.AppTools { public static partial class DataStructures { public partial class GenericNode<T> { //------------------------------------------------- public class NodeNotification { public enum NotificationStatus { Pending = 0, Completed = 1 } public NotificationStatus Status = NotificationStatus.Pending; public GenericNode<T> Node = null; public NodeNotification( NotificationStatus Status_in, GenericNode<T> Node_in ) { this.Status = Status_in; this.Node = Node_in; } } //------------------------------------------------- public interface INodeNotificationListener { void Notify( NodeNotification Notification_in ); } //------------------------------------------------- public class NodeUpdateNotification : NodeNotification { public NodeUpdateNotification( NotificationStatus Status_in, GenericNode<T> Node_in ) : base( Status_in, Node_in ) { } } //------------------------------------------------- public class NodeClearChildrenNotification : NodeNotification { public NodeClearChildrenNotification( NotificationStatus Status_in, GenericNode<T> Node_in ) : base( Status_in, Node_in ) { } } //------------------------------------------------- public class NodeChildNotification : NodeNotification { public GenericNode<T> ChildNode = null; public int ChildIndex = -1; public NodeChildNotification( NotificationStatus Status_in, GenericNode<T> Node_in, GenericNode<T> ChildNode_in, int ChildIndex_in ) : base( Status_in, Node_in ) { this.ChildNode = ChildNode_in; this.ChildIndex = ChildIndex_in; } } //------------------------------------------------- public class NodeAddChildNotification : NodeChildNotification { public NodeAddChildNotification( NotificationStatus Status_in, GenericNode<T> Node_in, GenericNode<T> ChildNode_in, int ChildIndex_in ) : base( Status_in, Node_in, ChildNode_in, ChildIndex_in ) { } } //------------------------------------------------- public class NodeRemoveChildNotification : NodeChildNotification { public NodeRemoveChildNotification( NotificationStatus Status_in, GenericNode<T> Node_in, GenericNode<T> ChildNode_in, int ChildIndex_in ) : base( Status_in, Node_in, ChildNode_in, ChildIndex_in ) { } } //------------------------------------------------- public class NodeNotificationBroadcaster : NodeNotification, INodeNotificationListener { public ArrayList Listeners = new ArrayList(); public NodeNotificationBroadcaster() : base( NotificationStatus.Pending, null ) { } public void Notify( NodeNotification Notification_in ) { foreach( INodeNotificationListener listener in this.Listeners ) { listener.Notify( Notification_in ); } return; } } //------------------------------------------------- public void Notify( NodeNotification Notification_in ) { // Notify on this node. if( (this._Listener != null) ) { this._Listener.Notify( Notification_in ); return; } if( Notification_in is NodeUpdateNotification ) { this.Fire_NodeUpdate( new NodeUpdate_EventArgs( (NodeUpdateNotification)Notification_in ) ); } else if( Notification_in is NodeClearChildrenNotification ) { this.Fire_NodeClearChildren( new NodeClearChildren_EventArgs( (NodeClearChildrenNotification)Notification_in ) ); } else if( Notification_in is NodeAddChildNotification ) { this.Fire_NodeAddChild( new NodeAddChild_EventArgs( (NodeAddChildNotification)Notification_in ) ); } else if( Notification_in is NodeRemoveChildNotification ) { this.Fire_NodeRemoveChild( new NodeRemoveChild_EventArgs( (NodeRemoveChildNotification)Notification_in ) ); } // Propogate notification upwards GenericNode<T> parent = this.ParentNode; if( (parent != null) ) { parent.Notify( Notification_in ); } return; } //------------------------------------------------- public void NotifyUpdate( NodeNotification.NotificationStatus Status_in ) { this.Notify( new NodeNotification( Status_in, this ) ); } //===================================================================== public class NodeUpdate_EventArgs : EventArgs { public NodeUpdateNotification Notification = null; public NodeUpdate_EventArgs( NodeUpdateNotification Notification ) { this.Notification = Notification; return; } } public delegate void NodeUpdate_EventHandler( object sender, NodeUpdate_EventArgs e ); public event NodeUpdate_EventHandler Event_NodeUpdate = null; public virtual void Fire_NodeUpdate( NodeUpdate_EventArgs e ) { if( this.Event_NodeUpdate == null ) { return; } this.Event_NodeUpdate( this, e ); return; } //===================================================================== public class NodeClearChildren_EventArgs : EventArgs { public NodeClearChildrenNotification Notification = null; public NodeClearChildren_EventArgs( NodeClearChildrenNotification Notification ) { this.Notification = Notification; return; } } public delegate void NodeClearChildren_EventHandler( object sender, NodeClearChildren_EventArgs e ); public event NodeClearChildren_EventHandler Event_NodeClearChildren = null; public virtual void Fire_NodeClearChildren( NodeClearChildren_EventArgs e ) { if( this.Event_NodeClearChildren == null ) { return; } this.Event_NodeClearChildren( this, e ); return; } //===================================================================== public class NodeAddChild_EventArgs : EventArgs { public NodeAddChildNotification Notification = null; public NodeAddChild_EventArgs( NodeAddChildNotification Notification ) { this.Notification = Notification; return; } } public delegate void NodeAddChild_EventHandler( object sender, NodeAddChild_EventArgs e ); public event NodeAddChild_EventHandler Event_NodeAddChild = null; public virtual void Fire_NodeAddChild( NodeAddChild_EventArgs e ) { if( this.Event_NodeAddChild == null ) { return; } this.Event_NodeAddChild( this, e ); return; } //===================================================================== public class NodeRemoveChild_EventArgs : EventArgs { public NodeRemoveChildNotification Notification = null; public NodeRemoveChild_EventArgs( NodeRemoveChildNotification Notification ) { this.Notification = Notification; return; } } public delegate void NodeRemoveChild_EventHandler( object sender, NodeRemoveChild_EventArgs e ); public event NodeRemoveChild_EventHandler Event_NodeRemoveChild = null; public virtual void Fire_NodeRemoveChild( NodeRemoveChild_EventArgs e ) { if( this.Event_NodeRemoveChild == null ) { return; } this.Event_NodeRemoveChild( this, e ); return; } } } }
/* * 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. * * Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. * All rights reserved. */ using System; using System.Runtime.InteropServices; namespace ZooKeeperNet.IO { /// <summary> /// Equivalent of System.BitConverter, but with either endianness. /// </summary> public abstract class EndianBitConverter { #region Endianness of this converter /// <summary> /// Indicates the byte order ("endianess") in which data is converted using this class. /// </summary> /// <remarks> /// Different computer architectures store data using different byte orders. "Big-endian" /// means the most significant byte is on the left end of a word. "Little-endian" means the /// most significant byte is on the right end of a word. /// </remarks> /// <returns>true if this converter is little-endian, false otherwise.</returns> public abstract bool IsLittleEndian(); /// <summary> /// Indicates the byte order ("endianess") in which data is converted using this class. /// </summary> public abstract Endianness Endianness { get; } #endregion #region Factory properties static LittleEndianBitConverter little = new LittleEndianBitConverter(); /// <summary> /// Returns a little-endian bit converter instance. The same instance is /// always returned. /// </summary> public static LittleEndianBitConverter Little { get { return little; } } static BigEndianBitConverter big = new BigEndianBitConverter(); /// <summary> /// Returns a big-endian bit converter instance. The same instance is /// always returned. /// </summary> public static BigEndianBitConverter Big { get { return big; } } #endregion #region Double/primitive conversions /// <summary> /// Converts the specified double-precision floating point number to a /// 64-bit signed integer. Note: the endianness of this converter does not /// affect the returned value. /// </summary> /// <param name="value">The number to convert. </param> /// <returns>A 64-bit signed integer whose value is equivalent to value.</returns> public long DoubleToInt64Bits(double value) { return BitConverter.DoubleToInt64Bits(value); } /// <summary> /// Converts the specified 64-bit signed integer to a double-precision /// floating point number. Note: the endianness of this converter does not /// affect the returned value. /// </summary> /// <param name="value">The number to convert. </param> /// <returns>A double-precision floating point number whose value is equivalent to value.</returns> public double Int64BitsToDouble (long value) { return BitConverter.Int64BitsToDouble(value); } /// <summary> /// Converts the specified single-precision floating point number to a /// 32-bit signed integer. Note: the endianness of this converter does not /// affect the returned value. /// </summary> /// <param name="value">The number to convert. </param> /// <returns>A 32-bit signed integer whose value is equivalent to value.</returns> public int SingleToInt32Bits(float value) { return new Int32SingleUnion(value).AsInt32; } /// <summary> /// Converts the specified 32-bit signed integer to a single-precision floating point /// number. Note: the endianness of this converter does not /// affect the returned value. /// </summary> /// <param name="value">The number to convert. </param> /// <returns>A single-precision floating point number whose value is equivalent to value.</returns> public float Int32BitsToSingle (int value) { return new Int32SingleUnion(value).AsSingle; } #endregion #region To(PrimitiveType) conversions /// <summary> /// Returns a Boolean value converted from one byte at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>true if the byte at startIndex in value is nonzero; otherwise, false.</returns> public bool ToBoolean (byte[] value, int startIndex) { CheckByteArgument(value, startIndex, 1); return BitConverter.ToBoolean(value, startIndex); } /// <summary> /// Returns a Unicode character converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A character formed by two bytes beginning at startIndex.</returns> public char ToChar (byte[] value, int startIndex) { return unchecked((char) (CheckedFromBytes(value, startIndex, 2))); } /// <summary> /// Returns a double-precision floating point number converted from eight bytes /// at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A double precision floating point number formed by eight bytes beginning at startIndex.</returns> public double ToDouble (byte[] value, int startIndex) { return Int64BitsToDouble(ToInt64(value, startIndex)); } /// <summary> /// Returns a single-precision floating point number converted from four bytes /// at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A single precision floating point number formed by four bytes beginning at startIndex.</returns> public float ToSingle (byte[] value, int startIndex) { return Int32BitsToSingle(ToInt32(value, startIndex)); } /// <summary> /// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 16-bit signed integer formed by two bytes beginning at startIndex.</returns> public short ToInt16 (byte[] value, int startIndex) { return unchecked((short) (CheckedFromBytes(value, startIndex, 2))); } /// <summary> /// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 32-bit signed integer formed by four bytes beginning at startIndex.</returns> public int ToInt32 (byte[] value, int startIndex) { return unchecked((int) (CheckedFromBytes(value, startIndex, 4))); } /// <summary> /// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 64-bit signed integer formed by eight bytes beginning at startIndex.</returns> public long ToInt64 (byte[] value, int startIndex) { return CheckedFromBytes(value, startIndex, 8); } /// <summary> /// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns> public ushort ToUInt16 (byte[] value, int startIndex) { return unchecked((ushort) (CheckedFromBytes(value, startIndex, 2))); } /// <summary> /// Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 32-bit unsigned integer formed by four bytes beginning at startIndex.</returns> public uint ToUInt32 (byte[] value, int startIndex) { return unchecked((uint) (CheckedFromBytes(value, startIndex, 4))); } /// <summary> /// Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A 64-bit unsigned integer formed by eight bytes beginning at startIndex.</returns> public ulong ToUInt64 (byte[] value, int startIndex) { return unchecked((ulong) (CheckedFromBytes(value, startIndex, 8))); } /// <summary> /// Checks the given argument for validity. /// </summary> /// <param name="value">The byte array passed in</param> /// <param name="startIndex">The start index passed in</param> /// <param name="bytesRequired">The number of bytes required</param> /// <exception cref="ArgumentNullException">value is a null reference</exception> /// <exception cref="ArgumentOutOfRangeException"> /// startIndex is less than zero or greater than the length of value minus bytesRequired. /// </exception> static void CheckByteArgument(byte[] value, int startIndex, int bytesRequired) { if (value==null) { throw new ArgumentNullException("value"); } if (startIndex < 0 || startIndex > value.Length-bytesRequired) { throw new ArgumentOutOfRangeException("startIndex"); } } /// <summary> /// Checks the arguments for validity before calling FromBytes /// (which can therefore assume the arguments are valid). /// </summary> /// <param name="value">The bytes to convert after checking</param> /// <param name="startIndex">The index of the first byte to convert</param> /// <param name="bytesToConvert">The number of bytes to convert</param> /// <returns></returns> long CheckedFromBytes(byte[] value, int startIndex, int bytesToConvert) { CheckByteArgument(value, startIndex, bytesToConvert); return FromBytes(value, startIndex, bytesToConvert); } /// <summary> /// Convert the given number of bytes from the given array, from the given start /// position, into a long, using the bytes as the least significant part of the long. /// By the time this is called, the arguments have been checked for validity. /// </summary> /// <param name="value">The bytes to convert</param> /// <param name="startIndex">The index of the first byte to convert</param> /// <param name="bytesToConvert">The number of bytes to use in the conversion</param> /// <returns>The converted number</returns> protected abstract long FromBytes(byte[] value, int startIndex, int bytesToConvert); #endregion #region ToString conversions /// <summary> /// Returns a String converted from the elements of a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <remarks>All the elements of value are converted.</remarks> /// <returns> /// A String of hexadecimal pairs separated by hyphens, where each pair /// represents the corresponding element in value; for example, "7F-2C-4A". /// </returns> public static string ToString(byte[] value) { return BitConverter.ToString(value); } /// <summary> /// Returns a String converted from the elements of a byte array starting at a specified array position. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <remarks>The elements from array position startIndex to the end of the array are converted.</remarks> /// <returns> /// A String of hexadecimal pairs separated by hyphens, where each pair /// represents the corresponding element in value; for example, "7F-2C-4A". /// </returns> public static string ToString(byte[] value, int startIndex) { return BitConverter.ToString(value, startIndex); } /// <summary> /// Returns a String converted from a specified number of bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <param name="length">The number of bytes to convert.</param> /// <remarks>The length elements from array position startIndex are converted.</remarks> /// <returns> /// A String of hexadecimal pairs separated by hyphens, where each pair /// represents the corresponding element in value; for example, "7F-2C-4A". /// </returns> public static string ToString(byte[] value, int startIndex, int length) { return BitConverter.ToString(value, startIndex, length); } #endregion #region Decimal conversions /// <summary> /// Returns a decimal value converted from sixteen bytes /// at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A decimal formed by sixteen bytes beginning at startIndex.</returns> public decimal ToDecimal (byte[] value, int startIndex) { // HACK: This always assumes four parts, each in their own endianness, // starting with the first part at the start of the byte array. // On the other hand, there's no real format specified... int[] parts = new int[4]; for (int i=0; i < 4; i++) { parts[i] = ToInt32(value, startIndex+i*4); } return new Decimal(parts); } /// <summary> /// Returns the specified decimal value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 16.</returns> public byte[] GetBytes(decimal value) { byte[] bytes = new byte[16]; int[] parts = decimal.GetBits(value); for (int i=0; i < 4; i++) { CopyBytesImpl(parts[i], 4, bytes, i*4); } return bytes; } /// <summary> /// Copies the specified decimal value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">A character to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(decimal value, byte[] buffer, int index) { int[] parts = decimal.GetBits(value); for (int i=0; i < 4; i++) { CopyBytesImpl(parts[i], 4, buffer, i*4+index); } } #endregion #region GetBytes conversions /// <summary> /// Returns an array with the given number of bytes formed /// from the least significant bytes of the specified value. /// This is used to implement the other GetBytes methods. /// </summary> /// <param name="value">The value to get bytes for</param> /// <param name="bytes">The number of significant bytes to return</param> byte[] GetBytes(long value, int bytes) { byte[] buffer = new byte[bytes]; CopyBytes(value, bytes, buffer, 0); return buffer; } /// <summary> /// Returns the specified Boolean value as an array of bytes. /// </summary> /// <param name="value">A Boolean value.</param> /// <returns>An array of bytes with length 1.</returns> public byte[] GetBytes(bool value) { return BitConverter.GetBytes(value); } /// <summary> /// Returns the specified Unicode character value as an array of bytes. /// </summary> /// <param name="value">A character to convert.</param> /// <returns>An array of bytes with length 2.</returns> public byte[] GetBytes(char value) { return GetBytes(value, 2); } /// <summary> /// Returns the specified double-precision floating point value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> public byte[] GetBytes(double value) { return GetBytes(DoubleToInt64Bits(value), 8); } /// <summary> /// Returns the specified 16-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 2.</returns> public byte[] GetBytes(short value) { return GetBytes(value, 2); } /// <summary> /// Returns the specified 32-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> public byte[] GetBytes(int value) { return GetBytes(value, 4); } /// <summary> /// Returns the specified 64-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> public byte[] GetBytes(long value) { return GetBytes(value, 8); } /// <summary> /// Returns the specified single-precision floating point value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> public byte[] GetBytes(float value) { return GetBytes(SingleToInt32Bits(value), 4); } /// <summary> /// Returns the specified 16-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 2.</returns> public byte[] GetBytes(ushort value) { return GetBytes(value, 2); } /// <summary> /// Returns the specified 32-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> public byte[] GetBytes(uint value) { return GetBytes(value, 4); } /// <summary> /// Returns the specified 64-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> public byte[] GetBytes(ulong value) { return GetBytes(unchecked((long)value), 8); } #endregion #region CopyBytes conversions /// <summary> /// Copies the given number of bytes from the least-specific /// end of the specified value into the specified byte array, beginning /// at the specified index. /// This is used to implement the other CopyBytes methods. /// </summary> /// <param name="value">The value to copy bytes for</param> /// <param name="bytes">The number of significant bytes to copy</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> void CopyBytes(long value, int bytes, byte[] buffer, int index) { if (buffer==null) { throw new ArgumentNullException("buffer", "Byte array must not be null"); } if (buffer.Length < index+bytes) { throw new ArgumentOutOfRangeException("Buffer not big enough for value"); } CopyBytesImpl(value, bytes, buffer, index); } /// <summary> /// Copies the given number of bytes from the least-specific /// end of the specified value into the specified byte array, beginning /// at the specified index. /// This must be implemented in concrete derived classes, but the implementation /// may assume that the value will fit into the buffer. /// </summary> /// <param name="value">The value to copy bytes for</param> /// <param name="bytes">The number of significant bytes to copy</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> protected abstract void CopyBytesImpl(long value, int bytes, byte[] buffer, int index); /// <summary> /// Copies the specified Boolean value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">A Boolean value.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(bool value, byte[] buffer, int index) { CopyBytes(value ? 1 : 0, 1, buffer, index); } /// <summary> /// Copies the specified Unicode character value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">A character to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(char value, byte[] buffer, int index) { CopyBytes(value, 2, buffer, index); } /// <summary> /// Copies the specified double-precision floating point value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(double value, byte[] buffer, int index) { CopyBytes(DoubleToInt64Bits(value), 8, buffer, index); } /// <summary> /// Copies the specified 16-bit signed integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(short value, byte[] buffer, int index) { CopyBytes(value, 2, buffer, index); } /// <summary> /// Copies the specified 32-bit signed integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(int value, byte[] buffer, int index) { CopyBytes(value, 4, buffer, index); } /// <summary> /// Copies the specified 64-bit signed integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(long value, byte[] buffer, int index) { CopyBytes(value, 8, buffer, index); } /// <summary> /// Copies the specified single-precision floating point value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(float value, byte[] buffer, int index) { CopyBytes(SingleToInt32Bits(value), 4, buffer, index); } /// <summary> /// Copies the specified 16-bit unsigned integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(ushort value, byte[] buffer, int index) { CopyBytes(value, 2, buffer, index); } /// <summary> /// Copies the specified 32-bit unsigned integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(uint value, byte[] buffer, int index) { CopyBytes(value, 4, buffer, index); } /// <summary> /// Copies the specified 64-bit unsigned integer value into the specified byte array, /// beginning at the specified index. /// </summary> /// <param name="value">The number to convert.</param> /// <param name="buffer">The byte array to copy the bytes into</param> /// <param name="index">The first index into the array to copy the bytes into</param> public void CopyBytes(ulong value, byte[] buffer, int index) { CopyBytes(unchecked((long)value), 8, buffer, index); } #endregion #region Private struct used for Single/Int32 conversions /// <summary> /// Union used solely for the equivalent of DoubleToInt64Bits and vice versa. /// </summary> [StructLayout(LayoutKind.Explicit)] struct Int32SingleUnion { /// <summary> /// Int32 version of the value. /// </summary> [FieldOffset(0)] int i; /// <summary> /// Single version of the value. /// </summary> [FieldOffset(0)] float f; /// <summary> /// Creates an instance representing the given integer. /// </summary> /// <param name="i">The integer value of the new instance.</param> internal Int32SingleUnion(int i) { this.f = 0; // Just to keep the compiler happy this.i = i; } /// <summary> /// Creates an instance representing the given floating point number. /// </summary> /// <param name="f">The floating point value of the new instance.</param> internal Int32SingleUnion(float f) { this.i = 0; // Just to keep the compiler happy this.f = f; } /// <summary> /// Returns the value of the instance as an integer. /// </summary> internal int AsInt32 { get { return i; } } /// <summary> /// Returns the value of the instance as a floating point number. /// </summary> internal float AsSingle { get { return f; } } } #endregion } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony.unity3d.ui.ucore { public class LoadScreenUCore : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject { public LoadScreenUCore(global::haxe.lang.EmptyObject empty) : base() { unchecked { } #line default } public LoadScreenUCore() : base() { unchecked { #line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.fastLoad = false; #line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.loader = new global::pony.Loader(new global::haxe.lang.Null<int>(1, true), new global::haxe.lang.Null<int>(100, true)); global::pony.unity3d.ui.LoadScreen.lastLoader = this.loader; } #line default } public static object __hx_createEmpty() { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return new global::pony.unity3d.ui.ucore.LoadScreenUCore(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static object __hx_create(global::Array arr) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return new global::pony.unity3d.ui.ucore.LoadScreenUCore(); } #line default } public bool fastLoad; public global::UnityEngine.Texture background; public global::UnityEngine.Texture main; public global::UnityEngine.GameObject bgTextureObject; public global::UnityEngine.GameObject mainTextureObject; public global::UnityEngine.GameObject up; public global::pony.unity3d.ui.ProgressBar progress; public global::pony.Loader loader; public virtual void Start() { unchecked { #line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.fastLoad = false; #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" global::pony.unity3d.Fixed2dCamera._set_visible(false); #line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (( this.background != default(global::UnityEngine.Texture) )) { this.bgTextureObject = new global::UnityEngine.GameObject(global::haxe.lang.Runtime.toString("GUITexture LoadScreen Background")); global::UnityEngine.GUITexture guiTextureObject = ((global::UnityEngine.GUITexture) (this.bgTextureObject.AddComponent(global::haxe.lang.Runtime.toString("GUITexture"))) ); guiTextureObject.texture = this.background; this.bgTextureObject.transform.position = new global::UnityEngine.Vector3(((float) (0.5) ), ((float) (0.5) ), ((float) (100) )); } #line 80 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (( this.main != default(global::UnityEngine.Texture) )) { this.mainTextureObject = new global::UnityEngine.GameObject(global::haxe.lang.Runtime.toString("GUITexture LoadScreen Main")); global::UnityEngine.GUITexture mguiTextureObject = ((global::UnityEngine.GUITexture) (this.mainTextureObject.AddComponent(global::haxe.lang.Runtime.toString("GUITexture"))) ); mguiTextureObject.texture = this.main; mguiTextureObject.transform.localScale = new global::UnityEngine.Vector3(((float) (0) ), ((float) (0) )); mguiTextureObject.pixelInset = new global::UnityEngine.Rect(( - (this.main.width) / 2 ), ( - (this.main.height) / 2 ), ((float) (this.main.width) ), ((float) (this.main.height) )); this.mainTextureObject.transform.position = new global::UnityEngine.Vector3(((float) (0.5) ), ((float) (0.5) ), ((float) (101) )); } #line 89 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (( this.progress != default(global::pony.unity3d.ui.ProgressBar) )) { object __temp_stmt659 = default(object); #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this.progress) ), global::haxe.lang.Runtime.toString("set"), ((int) (5741474) ))) ), 1); #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" __temp_stmt659 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false); } #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.loader.progress.@add(__temp_stmt659, default(global::haxe.lang.Null<int>)); } #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" int priority = 0; #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object listener = default(object); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object f1 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("end"), ((int) (5047259) ))) ), 0); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" listener = global::pony.events._Listener.Listener_Impl_._fromFunction(f1, false); } #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object __temp_stmt660 = default(object); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object f2 = global::haxe.lang.Runtime.getField(listener, "f", 102, true); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object this1 = default(object); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object __temp_getvar234 = f2; #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" double __temp_ret235 = ((double) (global::haxe.lang.Runtime.getField_f(__temp_getvar234, "used", 1303220797, true)) ); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object __temp_expr661 = ((object) (global::haxe.lang.Runtime.setField(__temp_getvar234, "used", 1303220797, ( __temp_ret235 + 1.0 ))) ); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" double __temp_expr662 = __temp_ret235; } #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" bool __temp_odecl657 = ((bool) (global::haxe.lang.Runtime.getField(listener, "event", 1975830554, true)) ); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" bool __temp_odecl658 = ((bool) (global::haxe.lang.Runtime.getField(listener, "ignoreReturn", 98429794, true)) ); #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this1 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 98429794, 373703110, 1247723251, 1975830554}), new global::Array<object>(new object[]{f2, __temp_odecl658, true, default(global::pony.events.Event), __temp_odecl657}), new global::Array<int>(new int[]{1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (1) ), ((double) (0) )})); } #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" __temp_stmt660 = this1; } #line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.loader.complite.@add(((object) (__temp_stmt660) ), new global::haxe.lang.Null<int>(priority, true)); } this.loader.init(new global::haxe.lang.Null<bool>(this.fastLoad, true)); } #line default } public virtual void end() { unchecked { #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" global::pony.unity3d.Fixed2dCamera._set_visible(true); if (( this.bgTextureObject != default(global::UnityEngine.GameObject) )) { #line 98 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" global::UnityEngine.Object.Destroy(((global::UnityEngine.Object) (this.bgTextureObject) )); } if (( this.mainTextureObject != default(global::UnityEngine.GameObject) )) { #line 99 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" global::UnityEngine.Object.Destroy(((global::UnityEngine.Object) (this.mainTextureObject) )); } if (( this.progress != default(global::pony.unity3d.ui.ProgressBar) )) { object __temp_stmt663 = default(object); #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" { #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this.progress) ), global::haxe.lang.Runtime.toString("set"), ((int) (5741474) ))) ), 1); #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" __temp_stmt663 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false); } #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.loader.progress.@remove(__temp_stmt663); global::UnityEngine.Object.Destroy(((global::UnityEngine.Object) (this.progress.gameObject) )); } #line 104 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (( this.up != default(global::UnityEngine.GameObject) )) { #line 104 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" global::UnityEngine.Object.Destroy(((global::UnityEngine.Object) (this.up) )); } } #line default } public virtual bool __hx_deleteField(string field, int hash) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return false; } #line default } public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (isCheck) { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return global::haxe.lang.Runtime.undefined; } else { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (throwErrors) { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" throw global::haxe.lang.HaxeException.wrap("Field not found."); } else { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return default(object); } } } #line default } public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" if (throwErrors) { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type."); } else { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return default(double); } } #line default } public virtual object __hx_lookupSetField(string field, int hash, object @value) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing."); } #line default } public virtual double __hx_lookupSetField_f(string field, int hash, double @value) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type."); } #line default } public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" switch (hash) { default: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.__hx_lookupSetField_f(field, hash, @value); } } } #line default } public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" switch (hash) { case 1575675685: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.hideFlags = ((global::UnityEngine.HideFlags) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 1224700491: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.name = global::haxe.lang.Runtime.toString(@value); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 5790298: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.tag = global::haxe.lang.Runtime.toString(@value); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 373703110: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.active = ((bool) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 2117141633: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.enabled = ((bool) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 896046654: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.useGUILayout = ((bool) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 1483687955: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.loader = ((global::pony.Loader) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 103479213: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.progress = ((global::pony.unity3d.ui.ProgressBar) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 26203: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.up = ((global::UnityEngine.GameObject) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 1829108225: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.mainTextureObject = ((global::UnityEngine.GameObject) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 1280791797: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.bgTextureObject = ((global::UnityEngine.GameObject) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 1213610041: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.main = ((global::UnityEngine.Texture) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 639472622: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.background = ((global::UnityEngine.Texture) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } case 64095970: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.fastLoad = ((bool) (@value) ); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return @value; } default: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.__hx_lookupSetField(field, hash, @value); } } } #line default } public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" switch (hash) { case 1826409040: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) ); } case 304123084: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) ); } case 276486854: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) ); } case 295397041: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) ); } case 1955029599: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) ); } case 1575675685: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.hideFlags; } case 1224700491: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.name; } case 294420221: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) ); } case 139469119: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) ); } case 967979664: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) ); } case 2122408236: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) ); } case 1328964235: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) ); } case 1723652455: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) ); } case 89600725: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) ); } case 2134927590: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) ); } case 5790298: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.tag; } case 373703110: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.active; } case 1471506513: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.gameObject; } case 1751728597: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.particleSystem; } case 524620744: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.particleEmitter; } case 964013983: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.hingeJoint; } case 1238753076: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.collider; } case 674101152: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.guiTexture; } case 262266241: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.guiElement; } case 1515196979: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.networkView; } case 801759432: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.guiText; } case 662730966: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.audio; } case 853263683: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.renderer; } case 1431885287: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.constantForce; } case 1261760260: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.animation; } case 1962709206: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.light; } case 931940005: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.camera; } case 1895479501: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.rigidbody; } case 1167273324: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.transform; } case 2117141633: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.enabled; } case 2084823382: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) ); } case 1856815770: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) ); } case 832859768: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) ); } case 987108662: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) ); } case 602588383: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) ); } case 1641152943: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) ); } case 1416948632: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) ); } case 757431474: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) ); } case 896046654: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.useGUILayout; } case 5047259: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("end"), ((int) (5047259) ))) ); } case 389604418: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) ); } case 1483687955: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.loader; } case 103479213: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.progress; } case 26203: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.up; } case 1829108225: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.mainTextureObject; } case 1280791797: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.bgTextureObject; } case 1213610041: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.main; } case 639472622: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.background; } case 64095970: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.fastLoad; } default: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.__hx_lookupField(field, hash, throwErrors, isCheck); } } } #line default } public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" switch (hash) { default: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return this.__hx_lookupField_f(field, hash, throwErrors); } } } #line default } public virtual object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" switch (hash) { case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return global::haxe.lang.Runtime.slowCallField(this, field, dynargs); } case 5047259: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.end(); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" break; } case 389604418: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" this.Start(); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" break; } default: { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs); } } #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" return default(object); } #line default } public virtual void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("hideFlags"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("name"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("tag"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("active"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("gameObject"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("particleSystem"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("particleEmitter"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("hingeJoint"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("collider"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("guiTexture"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("guiElement"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("networkView"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("guiText"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("audio"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("renderer"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("constantForce"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("animation"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("light"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("camera"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("rigidbody"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("transform"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("enabled"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("useGUILayout"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("loader"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("progress"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("up"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("mainTextureObject"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("bgTextureObject"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("main"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("background"); #line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/ucore/LoadScreenUCore.hx" baseArr.push("fastLoad"); } #line default } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; #if !NETCF using System.Runtime.Serialization; using System.Xml; #endif namespace log4net.Util { /// <summary> /// String keyed object map. /// </summary> /// <remarks> /// <para> /// While this collection is serializable only member /// objects that are serializable will /// be serialized along with this collection. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if NETCF public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, IDictionary #else [Serializable] public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary #endif { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class. /// </para> /// </remarks> public PropertiesDictionary() { } /// <summary> /// Constructor /// </summary> /// <param name="propertiesDictionary">properties to copy</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class. /// </para> /// </remarks> public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) : base(propertiesDictionary) { } #endregion Public Instance Constructors #region Private Instance Constructors #if !(NETCF || NETSTANDARD1_3) /// <summary> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class /// with serialized data. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> /// <remarks> /// <para> /// Because this class is sealed the serialization constructor is private. /// </para> /// </remarks> private PropertiesDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the value of the property with the specified key. /// </summary> /// <value> /// The value of the property with the specified key. /// </value> /// <param name="key">The key of the property to get or set.</param> /// <remarks> /// <para> /// The property value will only be serialized if it is serializable. /// If it cannot be serialized it will be silently ignored if /// a serialization operation is performed. /// </para> /// </remarks> override public object this[string key] { get { return InnerHashtable[key]; } set { InnerHashtable[key] = value; } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Remove the entry with the specified key from this dictionary /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Remove the entry with the specified key from this dictionary /// </para> /// </remarks> public void Remove(string key) { InnerHashtable.Remove(key); } #endregion Public Instance Methods #region Implementation of IDictionary /// <summary> /// See <see cref="IDictionary.GetEnumerator"/> /// </summary> /// <returns>an enumerator</returns> /// <remarks> /// <para> /// Returns a <see cref="IDictionaryEnumerator"/> over the contest of this collection. /// </para> /// </remarks> IDictionaryEnumerator IDictionary.GetEnumerator() { return InnerHashtable.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary.Remove"/> /// </summary> /// <param name="key">the key to remove</param> /// <remarks> /// <para> /// Remove the entry with the specified key from this dictionary /// </para> /// </remarks> void IDictionary.Remove(object key) { InnerHashtable.Remove(key); } /// <summary> /// See <see cref="IDictionary.Contains"/> /// </summary> /// <param name="key">the key to lookup in the collection</param> /// <returns><c>true</c> if the collection contains the specified key</returns> /// <remarks> /// <para> /// Test if this collection contains a specified key. /// </para> /// </remarks> bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } /// <summary> /// Remove all properties from the properties collection /// </summary> /// <remarks> /// <para> /// Remove all properties from the properties collection /// </para> /// </remarks> public override void Clear() { InnerHashtable.Clear(); } /// <summary> /// See <see cref="IDictionary.Add"/> /// </summary> /// <param name="key">the key</param> /// <param name="value">the value to store for the key</param> /// <remarks> /// <para> /// Store a value for the specified <see cref="String"/> <paramref name="key"/>. /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the <paramref name="key"/> is not a string</exception> void IDictionary.Add(object key, object value) { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } InnerHashtable.Add(key, value); } /// <summary> /// See <see cref="IDictionary.IsReadOnly"/> /// </summary> /// <value> /// <c>false</c> /// </value> /// <remarks> /// <para> /// This collection is modifiable. This property always /// returns <c>false</c>. /// </para> /// </remarks> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IDictionary.this"/> /// </summary> /// <value> /// The value for the key specified. /// </value> /// <remarks> /// <para> /// Get or set a value for the specified <see cref="String"/> <paramref name="key"/>. /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the <paramref name="key"/> is not a string</exception> object IDictionary.this[object key] { get { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } return InnerHashtable[key]; } set { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } InnerHashtable[key] = value; } } /// <summary> /// See <see cref="IDictionary.Values"/> /// </summary> ICollection IDictionary.Values { get { return InnerHashtable.Values; } } /// <summary> /// See <see cref="IDictionary.Keys"/> /// </summary> ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } /// <summary> /// See <see cref="IDictionary.IsFixedSize"/> /// </summary> bool IDictionary.IsFixedSize { get { return false; } } #endregion #region Implementation of ICollection /// <summary> /// See <see cref="ICollection.CopyTo"/> /// </summary> /// <param name="array"></param> /// <param name="index"></param> void ICollection.CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } /// <summary> /// See <see cref="ICollection.IsSynchronized"/> /// </summary> bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } /// <summary> /// See <see cref="ICollection.SyncRoot"/> /// </summary> object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } #endregion #region Implementation of IEnumerable /// <summary> /// See <see cref="IEnumerable.GetEnumerator"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)InnerHashtable).GetEnumerator(); } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindAccess { /// <summary> /// Strongly-typed collection for the Shipper class. /// </summary> [Serializable] public partial class ShipperCollection : ActiveList<Shipper, ShipperCollection> { public ShipperCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ShipperCollection</returns> public ShipperCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Shipper o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Shippers table. /// </summary> [Serializable] public partial class Shipper : ActiveRecord<Shipper>, IActiveRecord { #region .ctors and Default Settings public Shipper() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Shipper(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Shipper(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Shipper(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Shippers", TableType.Table, DataService.GetInstance("NorthwindAccess")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarShipperID = new TableSchema.TableColumn(schema); colvarShipperID.ColumnName = "ShipperID"; colvarShipperID.DataType = DbType.Int32; colvarShipperID.MaxLength = 0; colvarShipperID.AutoIncrement = true; colvarShipperID.IsNullable = false; colvarShipperID.IsPrimaryKey = true; colvarShipperID.IsForeignKey = false; colvarShipperID.IsReadOnly = false; colvarShipperID.DefaultSetting = @""; colvarShipperID.ForeignKeyTableName = ""; schema.Columns.Add(colvarShipperID); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; colvarCompanyName.DefaultSetting = @""; colvarCompanyName.ForeignKeyTableName = ""; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema); colvarPhone.ColumnName = "Phone"; colvarPhone.DataType = DbType.String; colvarPhone.MaxLength = 24; colvarPhone.AutoIncrement = false; colvarPhone.IsNullable = true; colvarPhone.IsPrimaryKey = false; colvarPhone.IsForeignKey = false; colvarPhone.IsReadOnly = false; colvarPhone.DefaultSetting = @""; colvarPhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhone); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindAccess"].AddSchema("Shippers",schema); } } #endregion #region Props [XmlAttribute("ShipperID")] [Bindable(true)] public int ShipperID { get { return GetColumnValue<int>(Columns.ShipperID); } set { SetColumnValue(Columns.ShipperID, value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>(Columns.CompanyName); } set { SetColumnValue(Columns.CompanyName, value); } } [XmlAttribute("Phone")] [Bindable(true)] public string Phone { get { return GetColumnValue<string>(Columns.Phone); } set { SetColumnValue(Columns.Phone, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public NorthwindAccess.OrderCollection Orders() { return new NorthwindAccess.OrderCollection().Where(Order.Columns.ShipVia, ShipperID).Load(); } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCompanyName,string varPhone) { Shipper item = new Shipper(); item.CompanyName = varCompanyName; item.Phone = varPhone; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varShipperID,string varCompanyName,string varPhone) { Shipper item = new Shipper(); item.ShipperID = varShipperID; item.CompanyName = varCompanyName; item.Phone = varPhone; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn ShipperIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CompanyNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn PhoneColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string ShipperID = @"ShipperID"; public static string CompanyName = @"CompanyName"; public static string Phone = @"Phone"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
using FakeItEasy; using FakeItEasy.Configuration; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using Sharpify; using Sharpify.Models; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace Sharpify.Tests { // our test top-level resource public class Robot : ShopifyResourceModel { private string _RobotType; public string RobotType { get { return _RobotType; } set { SetProperty(ref _RobotType, value); } } private string _Manufacturer; public string Manufacturer { get { return _Manufacturer; } set { SetProperty(ref _Manufacturer, value); } } private IHasMany<Part> _Parts; public IHasMany<Part> Parts { get { return _Parts; } set { SetProperty(ref _Parts, value); } } private IList<Inspection> _Inspections; public IList<Inspection> Inspections { get { return _Inspections; } set { SetProperty(ref _Inspections, value); } } private IHasOne<Brain> _Brain; public IHasOne<Brain> Brain { get { return _Brain; } set { SetProperty(ref _Brain, value); } } private IHasOne<Laser> _Laser; [Inlinable] public IHasOne<Laser> Laser { get { return _Laser; } set { SetProperty(ref _Laser, value); } } private SpecialAction _Explode; public SpecialAction Explode { get { return _Explode; } set { SetProperty(ref _Explode, value); } } } public class DeepNestedHasAInline : ShopifyResourceModel { } public class Brain : ShopifyResourceModel { private int _SynapseCount; public int SynapseCount { get { return _SynapseCount; } set { SetProperty(ref _SynapseCount, value); } } private IHasOne<DeepNestedHasAInline> _DeepNested; public IHasOne<DeepNestedHasAInline> DeepNested { get { return _DeepNested; } set { SetProperty(ref _DeepNested, value); } } } public class Laser : ShopifyResourceModel { } // our test subresource public class Part : ShopifyResourceModel, IFullMutable { private string _Sku; public string Sku { get { return _Sku; } set { SetProperty(ref _Sku, value); } } } // our inlined resource public class Inspection { public DateTime InspectedAt { get; set; } public String Inspector { get; set; } } [TestFixture] public class RestResourceTest { public RestResourceTest () { } public IShopifyAPIContext Shopify { get; set; } public RestResource<Robot> Robots { get; set; } public RestResource<Brain> Brains { get; set; } /// <summary> /// SubResources would normally be created dynamically /// and set as "proxies" as the collections backing subresource /// lists on a given model object. We make one manually here. /// </summary> public IHasMany<Part> CalculonsParts { get; set; } public Robot Calculon { get; set; } [SetUp] public void BeforeEach() { Shopify = A.Fake<IShopifyAPIContext>(); A.CallTo(() => Shopify.AdminPath()).Returns("/admin"); A.CallTo(() => Shopify.GetRequestContentType()).Returns(new MediaTypeHeaderValue("application/json")); Robots = new RestResource<Robot>(Shopify); Brains = new RestResource<Brain>(Shopify); Calculon = new Robot() { Id = 42 }; CalculonsParts = new SubResource<Part>(Robots, Calculon); } [Test] public void ShouldGenerateCorrectBasePath() { Assert.AreEqual("/admin/robots", Robots.Path()); } [Test] public void ShouldAmalgamateQueryParametersWithWhere() { var rrNexus = Robots.Where("robot_type", "nexus"); var rrNexusParameters = rrNexus.FullParameters(); Assert.AreEqual("nexus", rrNexusParameters["robot_type"]); var rrNexusByTyrell = rrNexus.Where("manufacturer", "tyrell"); var rrNexusByTyrellParameters = rrNexusByTyrell.FullParameters(); Assert.AreEqual("nexus", rrNexusByTyrellParameters["robot_type"]); Assert.AreEqual("tyrell", rrNexusByTyrellParameters["manufacturer"]); } [Test] public void ShouldAmalgamateQueryParmaetersWithWhereByMemberExpressions() { var rrNexus = Robots.Where(r => r.RobotType, "nexus"); var rrNexusParameters = rrNexus.FullParameters(); Assert.AreEqual("nexus", rrNexusParameters["RobotType"]); } public static Task<T> TaskForResult<T>(T input) { var tcs = new TaskCompletionSource<T>(); tcs.SetResult(input); return tcs.Task; } [Test] public void ShouldFetchAListOfAllMatchedModels() { var callRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots", EmptyQueryParametersExpectation(), null)); callRawExpectation.Returns(TaskForResult<string>("json text!")); var translationExpectation = A.CallTo(() => Shopify.TranslateObject<List<Robot>>("robots", "json text!")); translationExpectation.Returns(new List<Robot>() { new Robot() { Id = 8889 } } ); var answer = Robots.AsListUnpaginated(); answer.Wait(); callRawExpectation.MustHaveHappened(); translationExpectation.MustHaveHappened(); Assert.AreEqual(1, answer.Result.Count); Assert.NotNull(answer.Result[0].Parts); Assert.AreEqual("/admin/robots/8889/parts", answer.Result[0].Parts.Path()); } [Test] public void ShouldBuildSubResourcePaths() { Assert.AreEqual("/admin/robots/42/parts", CalculonsParts.Path()); Assert.AreEqual("/admin/robots/42/parts/67", CalculonsParts.InstancePath(67)); } private MediaTypeHeaderValue JsonFormatExpectation() { return A<MediaTypeHeaderValue>.That.Matches(mt => mt.ToString() == "application/json"); } private String JsonContentsExpectation(Func<object, bool> predicate) { return A<String>.That.Matches(json => predicate(JsonConvert.DeserializeObject(json))); } private NameValueCollection EmptyQueryParametersExpectation() { return A<NameValueCollection>.That.Matches(nvc => nvc.Keys.Count == 0); } private NameValueCollection PageNumberQueryParameterExpectation(int pageNumber) { return A<NameValueCollection>.That.Matches(nvc => nvc.Get("page") == pageNumber.ToString()); } [Test] public void ShouldFetchARecord() { var callRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots/89", EmptyQueryParametersExpectation(), null)); callRawExpectation.Returns(TaskForResult<string>("robot #89's json")); var translationExpectation = A.CallTo(() => Shopify.TranslateObject<Robot>("robot", "robot #89's json")); var translatedRobot = new Robot { Id = 89 }; // // TODO: .Get will start setting translationExpectation.Returns(translatedRobot); var answer = Robots.Find(89); answer.Wait(); Assert.AreSame(answer.Result, translatedRobot); // check for the Parts subresource object Assert.AreEqual("/admin/robots/89/parts", answer.Result.Parts.Path()); callRawExpectation.MustHaveHappened(); translationExpectation.MustHaveHappened(); } [Test] public void ShouldCreateASubResourceRecord() { var partToPost = new Part() { Sku = "0xdeadbeef" }; var translationExpectation = A.CallTo(() => Shopify.ObjectTranslate<Part>("part", partToPost)); translationExpectation.Returns("PART 988 JSON"); var postRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Post, JsonFormatExpectation(), "/admin/robots/42/parts", null, "PART 988 JSON")); postRawExpectation.Returns(TaskForResult<string>("PART 988 REAL JSON")); var resultTranslationExpectation = A.CallTo(() => Shopify.TranslateObject<Part>("part", "PART 988 REAL JSON")); // it got the id of 90 on the server var resultantPart = new Part() { Id = 90 }; resultTranslationExpectation.Returns(resultantPart); var answer = CalculonsParts.Create<Part>(partToPost); answer.Wait(); translationExpectation.MustHaveHappened(); postRawExpectation.MustHaveHappened(); resultTranslationExpectation.MustHaveHappened(); Assert.AreSame(resultantPart, answer.Result); } [Test] public void ShouldUpdateASubResourceRecord() { var partToPost = new Part() { Id = 9777 }; var translationExpectation = A.CallTo(() => Shopify.ObjectTranslate<Part>("part", partToPost)); translationExpectation.Returns("PART 988 JSON"); var putRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Put, JsonFormatExpectation(), "/admin/robots/42/parts/9777", null, "PART 988 JSON")); putRawExpectation.Returns(TaskForResult<string>("")); var answer = CalculonsParts.Update<Part>(partToPost); answer.Wait(); translationExpectation.MustHaveHappened(); putRawExpectation.MustHaveHappened(); } [Test] public void ShouldDeleteASubResourceRecord() { var partToPost = new Part() { Id = 83 }; partToPost.SetExisting(); var deleteRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Delete, JsonFormatExpectation(), "/admin/robots/42/parts/83", null, null)); deleteRawExpectation.Returns(TaskForResult<string>("")); var answer = CalculonsParts.Delete<Part>(partToPost); answer.Wait(); deleteRawExpectation.MustHaveHappened(); } [Test] public void ShouldFetchASubResourceRecord() { var callRawExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots/42/parts/69", EmptyQueryParametersExpectation(), null)); callRawExpectation.Returns(TaskForResult<string>("robot #42's part #69 json")); var translationExpectation = A.CallTo(() => Shopify.TranslateObject<Part>("part", "robot #42's part #69 json")); var translatedPart = new Part { Id = 69 }; translationExpectation.Returns(translatedPart); var answer = CalculonsParts.Find(69); answer.Wait(); Assert.AreSame(translatedPart, answer.Result); } [Test] public void ShouldReplaceInstanceSubResourceForHasOnePlaceholder() { var getRobotExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots/420", EmptyQueryParametersExpectation(), null)); getRobotExpectation.Returns(TaskForResult<string>("Robot #420's json")); // Robot #42 has Brain #56 var translationExpectation = A.CallTo(() => Shopify.TranslateObject<Robot>("robot", "Robot #420's json")); var translatedRobot = new Robot { Id = 420, Brain = new HasOneDeserializationPlaceholder<Brain>(56) }; translationExpectation.Returns(translatedRobot); var answer = Robots.Find(420); answer.Wait(); getRobotExpectation.MustHaveHappened(); translationExpectation.MustHaveHappened(); Assert.IsInstanceOf<SingleInstanceSubResource<Brain>>(answer.Result.Brain); Assert.AreEqual(56, answer.Result.Brain.Id); } [Test] public void ShouldReplaceInstanceSubResourceForHasOnePlaceholdersWithinAHasOneInline() { // if we receive a has one inline, we need to be sure that the post-processing also // happens for the resourcemodels deserialized inside a HasOneInline<> var getRobotExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots/420", EmptyQueryParametersExpectation(), null)); getRobotExpectation.Returns(TaskForResult<string>("Robot #420's json")); // Robot #42 has Brain #56 var translationExpectation = A.CallTo(() => Shopify.TranslateObject<Robot>("robot", "Robot #420's json")); var translatedBrain = new Brain { Id = 747, DeepNested = new HasOneDeserializationPlaceholder<DeepNestedHasAInline>(8010)}; var translatedRobot = new Robot { Id = 420, Brain = new HasOneInline<Brain>(translatedBrain) }; translationExpectation.Returns(translatedRobot); var answer = Robots.Find(420); answer.Wait(1000); getRobotExpectation.MustHaveHappened(); translationExpectation.MustHaveHappened(); Assert.IsInstanceOf<HasOneInline<Brain>>(answer.Result.Brain); var hasOneBrain = (HasOneInline<Brain>)(answer.Result.Brain); var brain = hasOneBrain.Get(); brain.Wait(1000); Assert.IsInstanceOf<SingleInstanceSubResource<DeepNestedHasAInline>>(brain.Result.DeepNested); Assert.AreEqual(8010, brain.Result.DeepNested.Id); } // inlined has ones are directly handled by JsonDataTranslator, and thus are not mediated by // by RestResource. [Test] public void ShouldSetHasOneIdOnOwnedModel() { // dev user stories for has_one: // -- fetching from a host model object you already have // -- setting a new instance on -- one that has been already saved // -- one that has not been saved (ie., has no ID); // -- setting a new var r = new Robot() { Id = 67 }; r.Brain = new SingleInstanceSubResource<Brain>(Shopify, new Brain() { Id = 89 }); } [Test] public void ShouldFetchCount() { var getRobotCountExpectation = A.CallTo(() => Shopify.CallRaw(HttpMethod.Get, JsonFormatExpectation(), "/admin/robots/count", EmptyQueryParametersExpectation(), null)); getRobotCountExpectation.Returns(TaskForResult<string>("robots count json")); var translationExpectation = A.CallTo(() => Shopify.TranslateObject<int>("count", "robots count json")); translationExpectation.Returns(34969); var answer = Robots.Count(); answer.Wait(); Assert.AreEqual(34969, answer.Result); } [Test] public void ShouldCallActionsByProperty() { Robots.CallAction(Calculon, () => Calculon.Explode); A.CallTo(() => Shopify.CallRaw(HttpMethod.Post, JsonFormatExpectation(), "/admin/robots/42/explode", EmptyQueryParametersExpectation(), null)).MustHaveHappened(); } [Test] public void ShouldSetHasOneAsIdByDefault() { var brain = new Brain() { Id = 38 }; Robots.Has<Brain>(Calculon, (calculon) => calculon.Brain, brain); Assert.IsInstanceOf<SingleInstanceSubResource<Brain>>(Calculon.Brain); } [Test] public void ShouldSetHasOneInlineByDefault() { var laser = new Laser() { Id = 32 }; Robots.Has<Laser>(Calculon, (calculon) => calculon.Laser, laser); Assert.IsInstanceOf<HasOneInline<Laser>>(Calculon.Laser); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion namespace FluentValidation.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Resources; using Results; using Validators; /// <summary> /// Defines a rule associated with a property. /// </summary> public class PropertyRule : IValidationRule { readonly List<IPropertyValidator> validators = new List<IPropertyValidator>(); Func<CascadeMode> cascadeModeThunk = () => ValidatorOptions.CascadeMode; string propertyDisplayName; string propertyName; /// <summary> /// Property associated with this rule. /// </summary> public MemberInfo Member { get; private set; } /// <summary> /// Function that can be invoked to retrieve the value of the property. /// </summary> public Func<object, object> PropertyFunc { get; private set; } /// <summary> /// Expression that was used to create the rule. /// </summary> public LambdaExpression Expression { get; private set; } /// <summary> /// String source that can be used to retrieve the display name (if null, falls back to the property name) /// </summary> public IStringSource DisplayName { get; set; } /// <summary> /// Rule set that this rule belongs to (if specified) /// </summary> public string RuleSet { get; set; } /// <summary> /// Function that will be invoked if any of the validators associated with this rule fail. /// </summary> public Action<object> OnFailure { get; set; } /// <summary> /// The current validator being configured by this rule. /// </summary> public IPropertyValidator CurrentValidator { get; private set; } /// <summary> /// Type of the property being validated /// </summary> public Type TypeToValidate { get; private set; } /// <summary> /// Cascade mode for this rule. /// </summary> public CascadeMode CascadeMode { get { return cascadeModeThunk(); } set { cascadeModeThunk = () => value; } } /// <summary> /// Validators associated with this rule. /// </summary> public IEnumerable<IPropertyValidator> Validators { get { return validators; } } /// <summary> /// Creates a new property rule. /// </summary> /// <param name="member">Property</param> /// <param name="propertyFunc">Function to get the property value</param> /// <param name="expression">Lambda expression used to create the rule</param> /// <param name="cascadeModeThunk">Function to get the cascade mode.</param> /// <param name="typeToValidate">Type to validate</param> /// <param name="containerType">Container type that owns the property</param> public PropertyRule(MemberInfo member, Func<object, object> propertyFunc, LambdaExpression expression, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) { Member = member; PropertyFunc = propertyFunc; Expression = expression; OnFailure = x => { }; TypeToValidate = typeToValidate; this.cascadeModeThunk = cascadeModeThunk; DependentRules = new List<IValidationRule>(); PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression); DisplayName = new LazyStringSource(() => ValidatorOptions.DisplayNameResolver(containerType, member, expression)); } /// <summary> /// Creates a new property rule from a lambda expression. /// </summary> public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression) { return Create(expression, () => ValidatorOptions.CascadeMode); } /// <summary> /// Creates a new property rule from a lambda expression. /// </summary> public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression, Func<CascadeMode> cascadeModeThunk) { var member = expression.GetMember(); var compiled = expression.Compile(); return new PropertyRule(member, compiled.CoerceToNonGeneric(), expression, cascadeModeThunk, typeof(TProperty), typeof(T)); } /// <summary> /// Adds a validator to the rule. /// </summary> public void AddValidator(IPropertyValidator validator) { CurrentValidator = validator; validators.Add(validator); } /// <summary> /// Replaces a validator in this rule. Used to wrap validators. /// </summary> public void ReplaceValidator(IPropertyValidator original, IPropertyValidator newValidator) { var index = validators.IndexOf(original); if (index > -1) { validators[index] = newValidator; if (ReferenceEquals(CurrentValidator, original)) { CurrentValidator = newValidator; } } } /// <summary> /// Remove a validator in this rule. /// </summary> public void RemoveValidator(IPropertyValidator original) { if (ReferenceEquals(CurrentValidator, original)) { CurrentValidator = validators.LastOrDefault(x => x != original); } validators.Remove(original); } /// <summary> /// Clear all validators from this rule. /// </summary> public void ClearValidators() { CurrentValidator = null; validators.Clear(); } /// <summary> /// Returns the property name for the property being validated. /// Returns null if it is not a property being validated (eg a method call) /// </summary> public string PropertyName { get { return propertyName; } set { propertyName = value; propertyDisplayName = propertyName.SplitPascalCase(); } } /// <summary> /// Allows custom creation of an error message /// </summary> public Func<PropertyValidatorContext, string> MessageBuilder { get; set; } /// <summary> /// Dependent rules /// </summary> public List<IValidationRule> DependentRules { get; private set; } /// <summary> /// Display name for the property. /// </summary> public string GetDisplayName() { string result = null; if (DisplayName != null) { result = DisplayName.GetString(); } if (result == null) { result = propertyDisplayName; } return result; } /// <summary> /// Performs validation using a validation context and returns a collection of Validation Failures. /// </summary> /// <param name="context">Validation Context</param> /// <returns>A collection of validation failures</returns> public virtual IEnumerable<ValidationFailure> Validate(ValidationContext context) { string displayName = GetDisplayName(); if (PropertyName == null && displayName == null) { //No name has been specified. Assume this is a model-level rule, so we should use empty string instead. displayName = string.Empty; } // Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator) string propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName); // Ensure that this rule is allowed to run. // The validatselector has the opportunity to veto this before any of the validators execute. if (!context.Selector.CanExecute(this, propertyName, context)) { yield break; } var cascade = cascadeModeThunk(); bool hasAnyFailure = false; // Invoke each validator and collect its results. foreach (var validator in validators) { var results = InvokePropertyValidator(context, validator, propertyName); bool hasFailure = false; foreach (var result in results) { hasAnyFailure = true; hasFailure = true; yield return result; } // If there has been at least one failure, and our CascadeMode has been set to StopOnFirst // then don't continue to the next rule if (cascade == FluentValidation.CascadeMode.StopOnFirstFailure && hasFailure) { break; } } if (hasAnyFailure) { // Callback if there has been at least one property validator failed. OnFailure(context.InstanceToValidate); } else { foreach (var dependentRule in DependentRules) { foreach (var failure in dependentRule.Validate(context)) { yield return failure; } } } } /// <summary> /// Performs asynchronous validation using a validation context and returns a collection of Validation Failures. /// </summary> /// <param name="context">Validation Context</param> /// <returns>A collection of validation failures</returns> public Task<IEnumerable<ValidationFailure>> ValidateAsync(ValidationContext context, CancellationToken cancellation) { try { var displayName = GetDisplayName(); if (PropertyName == null && displayName == null) { //No name has been specified. Assume this is a model-level rule, so we should use empty string instead. displayName = string.Empty; } // Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator) var propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName); // Ensure that this rule is allowed to run. // The validatselector has the opportunity to veto this before any of the validators execute. if (!context.Selector.CanExecute(this, propertyName, context)) { return TaskHelpers.FromResult(Enumerable.Empty<ValidationFailure>()); } var cascade = cascadeModeThunk(); var failures = new List<ValidationFailure>(); var fastExit = false; // Firstly, invoke all syncronous validators and collect their results. foreach (var validator in validators.Where(v => !v.IsAsync)) { if (cancellation.IsCancellationRequested) { return TaskHelpers.Canceled<IEnumerable<ValidationFailure>>(); } var results = InvokePropertyValidator(context, validator, propertyName); failures.AddRange(results); // If there has been at least one failure, and our CascadeMode has been set to StopOnFirst // then don't continue to the next rule if (fastExit = (cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0)) { break; } } var asyncValidators = validators.Where(v => v.IsAsync).ToList(); //if there's no async validators or StopOnFirstFailure triggered then we exit if (asyncValidators.Count == 0 || fastExit) { if (failures.Count > 0) { // Callback if there has been at least one property validator failed. OnFailure(context.InstanceToValidate); } return TaskHelpers.FromResult(failures.AsEnumerable()); } //Then call asyncronous validators in non-blocking way var validations = asyncValidators // .Select(v => v.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation) .Select(v => InvokePropertyValidatorAsync(context, v, propertyName, cancellation) //this is thread safe because tasks are launched sequencially .Then(fs => failures.AddRange(fs), runSynchronously: true) ); return TaskHelpers.Iterate( validations, breakCondition: _ => cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0, cancellationToken: cancellation ).Then(() => { if (failures.Count > 0) { OnFailure(context.InstanceToValidate); } return failures.AsEnumerable(); }, runSynchronously: true ); } catch (Exception ex) { return TaskHelpers.FromError<IEnumerable<ValidationFailure>>(ex); } } protected virtual Task<IEnumerable<ValidationFailure>> InvokePropertyValidatorAsync(ValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation) { return validator.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation); } /// <summary> /// Invokes a property validator using the specified validation context. /// </summary> protected virtual IEnumerable<ValidationFailure> InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, string propertyName) { var propertyContext = new PropertyValidatorContext(context, this, propertyName); return validator.Validate(propertyContext); } public void ApplyCondition(Func<object, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. if (applyConditionTo == ApplyConditionTo.AllValidators) { foreach (var validator in Validators.ToList()) { var wrappedValidator = new DelegatingValidator(predicate, validator); ReplaceValidator(validator, wrappedValidator); } } else { var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator); ReplaceValidator(CurrentValidator, wrappedValidator); } } public void ApplyAsyncCondition(Func<object, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. if (applyConditionTo == ApplyConditionTo.AllValidators) { foreach (var validator in Validators.ToList()) { var wrappedValidator = new DelegatingValidator(predicate, validator); ReplaceValidator(validator, wrappedValidator); } } else { var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator); ReplaceValidator(CurrentValidator, wrappedValidator); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.OpenXml4Net.OPC; using System.IO; using System.Xml.Serialization; using System.Xml; public class XWPFSettings : POIXMLDocumentPart { private CT_Settings ctSettings; public XWPFSettings(PackagePart part) : base(part) { } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] public XWPFSettings(PackagePart part, PackageRelationship rel) : this(part) { } public XWPFSettings() : base() { ctSettings = new CT_Settings(); } internal override void OnDocumentRead() { base.OnDocumentRead(); ReadFrom(GetPackagePart().GetInputStream()); } /** * In the zoom tag inside Settings.xml file <br/> * it Sets the value of zoom * @return percentage as an integer of zoom level */ public long GetZoomPercent() { CT_Zoom zoom = ctSettings.zoom; if (!ctSettings.IsSetZoom()) { zoom = ctSettings.AddNewZoom(); } else { zoom = ctSettings.zoom; } return long.Parse(zoom.percent); } /// <summary> /// Set zoom. In the zoom tag inside settings.xml file it sets the value of zoom /// </summary> /// <param name="zoomPercent"></param> /// <example> /// sample snippet from Settings.xml /// /// &lt;w:zoom w:percent="50" /&gt; /// </example> public void SetZoomPercent(long zoomPercent) { if (!ctSettings.IsSetZoom()) { ctSettings.AddNewZoom(); } CT_Zoom zoom = ctSettings.zoom; zoom.percent = zoomPercent.ToString(); } /** * Verifies the documentProtection tag inside settings.xml file <br/> * if the protection is enforced (w:enforcement="1") <br/> * <p/> * <br/> * sample snippet from settings.xml * <pre> * &lt;w:settings ... &gt; * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt; * </pre> * * @return true if documentProtection is enforced with option any */ public bool IsEnforcedWith() { CT_DocProtect ctDocProtect = ctSettings.documentProtection; if (ctDocProtect == null) { return false; } return ctDocProtect.enforcement.Equals(ST_OnOff.on); } /** * Verifies the documentProtection tag inside Settings.xml file <br/> * if the protection is enforced (w:enforcement="1") <br/> * and if the kind of protection Equals to passed (STDocProtect.Enum editValue) <br/> * * <br/> * sample snippet from Settings.xml * <pre> * &lt;w:settings ... &gt; * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt; * </pre> * * @return true if documentProtection is enforced with option ReadOnly */ public bool IsEnforcedWith(ST_DocProtect editValue) { CT_DocProtect ctDocProtect = ctSettings.documentProtection; if (ctDocProtect == null) { return false; } return ctDocProtect.enforcement.Equals(ST_OnOff.on) && ctDocProtect.edit.Equals(editValue); } /** * Enforces the protection with the option specified by passed editValue.<br/> * <br/> * In the documentProtection tag inside Settings.xml file <br/> * it Sets the value of enforcement to "1" (w:enforcement="1") <br/> * and the value of edit to the passed editValue (w:edit="[passed editValue]")<br/> * <br/> * sample snippet from Settings.xml * <pre> * &lt;w:settings ... &gt; * &lt;w:documentProtection w:edit=&quot;[passed editValue]&quot; w:enforcement=&quot;1&quot;/&gt; * </pre> */ public void SetEnforcementEditValue(ST_DocProtect editValue) { SafeGetDocumentProtection().enforcement = (ST_OnOff.on); SafeGetDocumentProtection().edit = (editValue); } /** * Removes protection enforcement.<br/> * In the documentProtection tag inside Settings.xml file <br/> * it Sets the value of enforcement to "0" (w:enforcement="0") <br/> */ public void RemoveEnforcement() { SafeGetDocumentProtection().enforcement = (ST_OnOff.off); } /** * Enforces fields update on document open (in Word). * In the settings.xml file <br/> * sets the updateSettings value to true (w:updateSettings w:val="true") * * NOTICES: * <ul> * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" * (if "Update automatic links at open" is enabled)</li> * <li>Flag is removed after saving with changes in Word </li> * </ul> */ public void SetUpdateFields() { CT_OnOff onOff = new CT_OnOff(); onOff.val = true; ctSettings.updateFields=(onOff); } public bool IsUpdateFields() { return ctSettings.IsSetUpdateFields() && ctSettings.updateFields.val == true; } /** * get or set revision tracking */ public bool IsTrackRevisions { get { return ctSettings.IsSetTrackRevisions(); } set { if (value) { if (!ctSettings.IsSetTrackRevisions()) { ctSettings.AddNewTrackRevisions(); } } else { if (ctSettings.IsSetTrackRevisions()) { ctSettings.UnsetTrackRevisions(); } } } } protected internal override void Commit() { if (ctSettings == null) { throw new InvalidOperationException("Unable to write out settings that were never read in!"); } /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.SaveSyntheticDocumentElement=(new QName(CTSettings.type.Name.NamespaceURI, "settings")); Dictionary<String, String> map = new Dictionary<String, String>(); map.Put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); xmlOptions.SaveSuggestedPrefixes=(map);*/ //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] { // new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")}); PackagePart part = GetPackagePart(); using (Stream out1 = part.GetOutputStream()) { SettingsDocument sd = new SettingsDocument(ctSettings); sd.Save(out1); } } private CT_DocProtect SafeGetDocumentProtection() { CT_DocProtect documentProtection = ctSettings.documentProtection; if (documentProtection == null) { documentProtection = new CT_DocProtect(); ctSettings.documentProtection = (documentProtection); } return ctSettings.documentProtection; } private void ReadFrom(Stream inputStream) { try { XmlDocument xmldoc = ConvertStreamToXml(inputStream); ctSettings = SettingsDocument.Parse(xmldoc,NamespaceManager).Settings; } catch (Exception e) { throw new Exception("SettingsDocument parse failed", e); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using log4net; namespace NetGore { /// <summary> /// Base class for a handler of Say commands. /// </summary> /// <typeparam name="T">The type of the object that the commands are coming from (the user).</typeparam> /// <typeparam name="U">The type of <see cref="SayCommandAttribute"/>.</typeparam> public abstract class SayHandlerBase<T, U> where T : class where U : SayCommandAttribute { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly SayHandlerStringCommandParser _parser; readonly ISayCommands<T> _sayCommands; /// <summary> /// Initializes a new instance of the <see cref="SayHandlerBase{T,U}"/> class. /// </summary> /// <param name="sayCommands">The object containing the Say commands.</param> protected SayHandlerBase(ISayCommands<T> sayCommands) { _sayCommands = sayCommands; _parser = new SayHandlerStringCommandParser(this, sayCommands.GetType()); } /// <summary> /// Gets if the given <paramref name="user"/> is allowed to invoke the given command. /// </summary> /// <param name="user">The user invoking the command.</param> /// <param name="commandData">The information about the command to be invoked.</param> /// <returns>True if the command can be invoked; otherwise false.</returns> protected virtual bool AllowInvokeCommand(T user, StringCommandParserCommandData<U> commandData) { return true; } /// <summary> /// Gets the message to display when the user is not allowed to invoke a command. /// </summary> /// <param name="user">The user invoking the command.</param> /// <param name="commandData">The information about the command to be invoked.</param> /// <returns>The message to display to the <paramref name="user"/>, or null or empty to display nothing.</returns> protected virtual string GetCommandNotAllowedMessage(T user, StringCommandParserCommandData<U> commandData) { return "You are not allowed to do that."; } /// <summary> /// Handles a command from a <paramref name="user"/>. /// </summary> /// <param name="user">The user.</param> /// <param name="text">The command string.</param> void HandleCommand(T user, string text) { // Remove the command symbol from the text text = RemoveCommandSymbol(text); // Parse string output; lock (_sayCommands) { _sayCommands.User = user; _parser.TryParse(_sayCommands, text, out output); } string orginalMessage = "/" + text; // Handle the output if (!string.IsNullOrEmpty(output)) HandleCommandOutput(user, output, orginalMessage); } /// <summary> /// When overridden in the derived class, handles the output from a command. /// </summary> /// <param name="user">The user that the command came from.</param> /// <param name="text">The output text from the command. Will not be null or empty.</param> /// <param name="orginalMessage">The orginal message that was inititally input.</param> protected abstract void HandleCommandOutput(T user, string text, string orginalMessage); /// <summary> /// When overridden in the derived class, handles text that was not a command. /// </summary> /// <param name="user">The user the <paramref name="text"/> came from.</param> /// <param name="text">The text that wasn't a command.</param> protected abstract void HandleNonCommand(T user, string text); /// <summary> /// Checks if a Say string is formatted to be a command. /// </summary> /// <param name="text">String to check.</param> /// <returns>True if a command, else false.</returns> protected virtual bool IsCommand(string text) { // Must be at least 2 characters long to be a command if (text.Length < 2) return false; // Check for a command character on the first character switch (text[0]) { case '/': case '\\': return true; default: return false; } } /// <summary> /// Checks if a string is a valid Say string. /// </summary> /// <param name="text">String to check.</param> /// <returns>True if a valid Say string, else false.</returns> protected virtual bool IsValidSayString(string text) { // Check if empty if (string.IsNullOrEmpty(text)) return false; // Check each character in the string to make sure they are valid foreach (var letter in text) { // Only allow chars >= 32, and non-control chars if (letter < 32 || char.IsControl(letter)) return false; } return true; } /// <summary> /// Processes a string of text. /// </summary> /// <param name="user">User that the <paramref name="text"/> came from.</param> /// <param name="text">Text to process.</param> /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception> public void Process(T user, string text) { if (user == null) throw new ArgumentNullException("user"); if (log.IsInfoEnabled) log.InfoFormat("Processing Say string from User `{0}`: {1}", user, text); // Check for an invalid string if (!IsValidSayString(text)) { const string errmsg = "Invalid Say string from User `{0}`: {1}"; Debug.Fail(string.Format(errmsg, user, text)); if (log.IsErrorEnabled) log.ErrorFormat(errmsg, user, text); return; } // Check if a command if (IsCommand(text)) { HandleCommand(user, text); return; } // Not a command, so just do a normal, to-area chat HandleNonCommand(user, text); } /// <summary> /// Removes the command symbol from the <paramref name="text"/>. /// </summary> /// <param name="text">The string to remove the command symbol from.</param> /// <returns>The <paramref name="text"/> without the command symbol.</returns> protected virtual string RemoveCommandSymbol(string text) { return text.Substring(1); } sealed class SayHandlerStringCommandParser : StringCommandParser<U> { readonly SayHandlerBase<T, U> _sayHandlerBase; public SayHandlerStringCommandParser(SayHandlerBase<T, U> sayHandlerBase, params Type[] types) : base((IEnumerable<Type>)types) { _sayHandlerBase = sayHandlerBase; } /// <summary> /// When overridden in the derived class, gets if the <paramref name="binder"/> is allowed to invoke the method /// defined by the given <see cref="StringCommandParserCommandData{T}"/> using the given set of <paramref name="args"/>. /// </summary> /// <param name="binder">The object to invoke the method on. If the method handling the command is static, /// this is ignored and can be null.</param> /// <param name="cmdData">The <see cref="StringCommandParserCommandData{T}"/> /// containing the method to invoke and the corresponding attribute /// that is attached to it.</param> /// <param name="args">The casted arguments to use to invoke the method.</param> /// <returns></returns> protected override bool AllowInvokeMethod(object binder, StringCommandParserCommandData<U> cmdData, object[] args) { var sayCommands = binder as ISayCommands<T>; if (sayCommands == null) { const string errmsg = "Was expecting the binder `{0}` to be type ISayCommands<T>, but was `{1}`."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, binder, binder != null ? binder.GetType().ToString() : "NULL"); Debug.Fail(string.Format(errmsg, binder, binder != null ? binder.GetType().ToString() : "NULL")); return false; } return _sayHandlerBase.AllowInvokeCommand(sayCommands.User, cmdData); } /// <summary> /// Handles when a command with the valid parameters was found, but <see cref="StringCommandParser{T}.AllowInvokeMethod"/> /// returned false for the given <see cref="binder"/>. /// </summary> /// <param name="binder">The object to invoke the method on. If the method handling the command is static, /// this is ignored and can be null.</param> /// <param name="cd">The <see cref="StringCommandParserCommandData{T}"/> for the command that the /// <paramref name="binder"/> was rejected from /// invoking.</param> /// <param name="args">Arguments used to invoke the command. Can be null.</param> /// <returns>A string containing a message about why the command failed to be handled.</returns> protected override string HandleCommandInvokeDenied(object binder, StringCommandParserCommandData<U> cd, string[] args) { var sayCommands = binder as ISayCommands<T>; if (sayCommands == null) { const string errmsg = "Was expecting the binder `{0}` to be type ISayCommands<T>, but was `{1}`."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, binder, binder != null ? binder.GetType().ToString() : "NULL"); Debug.Fail(string.Format(errmsg, binder, binder != null ? binder.GetType().ToString() : "NULL")); return string.Empty; } return _sayHandlerBase.GetCommandNotAllowedMessage(sayCommands.User, cd); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.RecommendationEngine.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedPredictionApiKeyRegistryClientTest { [xunit::FactAttribute] public void CreatePredictionApiKeyRegistrationRequestObject() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration response = client.CreatePredictionApiKeyRegistration(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePredictionApiKeyRegistrationRequestObjectAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictionApiKeyRegistration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration responseCallSettings = await client.CreatePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PredictionApiKeyRegistration responseCancellationToken = await client.CreatePredictionApiKeyRegistrationAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePredictionApiKeyRegistration() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration response = client.CreatePredictionApiKeyRegistration(request.Parent, request.PredictionApiKeyRegistration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePredictionApiKeyRegistrationAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictionApiKeyRegistration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration responseCallSettings = await client.CreatePredictionApiKeyRegistrationAsync(request.Parent, request.PredictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PredictionApiKeyRegistration responseCancellationToken = await client.CreatePredictionApiKeyRegistrationAsync(request.Parent, request.PredictionApiKeyRegistration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePredictionApiKeyRegistrationResourceNames() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration response = client.CreatePredictionApiKeyRegistration(request.ParentAsEventStoreName, request.PredictionApiKeyRegistration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePredictionApiKeyRegistrationResourceNamesAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), PredictionApiKeyRegistration = new PredictionApiKeyRegistration(), }; PredictionApiKeyRegistration expectedResponse = new PredictionApiKeyRegistration { ApiKey = "api_key30288039", }; mockGrpcClient.Setup(x => x.CreatePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PredictionApiKeyRegistration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); PredictionApiKeyRegistration responseCallSettings = await client.CreatePredictionApiKeyRegistrationAsync(request.ParentAsEventStoreName, request.PredictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PredictionApiKeyRegistration responseCancellationToken = await client.CreatePredictionApiKeyRegistrationAsync(request.ParentAsEventStoreName, request.PredictionApiKeyRegistration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePredictionApiKeyRegistrationRequestObject() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); client.DeletePredictionApiKeyRegistration(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePredictionApiKeyRegistrationRequestObjectAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); await client.DeletePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePredictionApiKeyRegistrationAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePredictionApiKeyRegistration() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); client.DeletePredictionApiKeyRegistration(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePredictionApiKeyRegistrationAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); await client.DeletePredictionApiKeyRegistrationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePredictionApiKeyRegistrationAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePredictionApiKeyRegistrationResourceNames() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); client.DeletePredictionApiKeyRegistration(request.PredictionApiKeyRegistrationName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePredictionApiKeyRegistrationResourceNamesAsync() { moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient> mockGrpcClient = new moq::Mock<PredictionApiKeyRegistry.PredictionApiKeyRegistryClient>(moq::MockBehavior.Strict); DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePredictionApiKeyRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PredictionApiKeyRegistryClient client = new PredictionApiKeyRegistryClientImpl(mockGrpcClient.Object, null); await client.DeletePredictionApiKeyRegistrationAsync(request.PredictionApiKeyRegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePredictionApiKeyRegistrationAsync(request.PredictionApiKeyRegistrationName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using System.Xml; using System.Xml.Serialization; using System.Reflection; using System.Net; namespace Raccoom.Xml.Rss { /// <summary>RssImage is an optional sub-element of channel, which contains three required and three optional sub-elements.</summary> [System.Runtime.InteropServices.ComVisible(true), System.Runtime.InteropServices.Guid("026FF54F-96DF-4879-A355-880832C49A2C")] [System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)] [System.Runtime.InteropServices.ProgId("Raccoom.RssImage")] [Serializable] [System.Xml.Serialization.XmlTypeAttribute("image")] [System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] public class RssImage : ComponentModel.SyndicationObjectBase, IRssImage { #region fields /// <summary>Title</summary> private string _title; /// <summary>Url</summary> private string _url; /// <summary>Link</summary> private string _link; /// <summary>Description</summary> private string _description; /// <summary>Width</summary> private int _width; /// <summary>Height</summary> private int _height; #endregion #region constructors /// <summary>Initializes a new instance with default values</summary> public RssImage () { } #endregion #region public interface public override bool Specified { get { return HeightSpecified || WidthSpecified || !string.IsNullOrEmpty(Title) || !string.IsNullOrEmpty(Url) || !string.IsNullOrEmpty(Link); } } /// <summary>Describes the image, it's used in the ALT attribute of the HTML img tag when the channel is rendered in HTML. </summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("Describes the image, it's used in the ALT attribute of the HTML img tag when the channel is rendered in HTML. ")] [System.Xml.Serialization.XmlElementAttribute("title")] public string Title { get { return _title; } set { bool changed = !object.Equals(_title, value); _title = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Title)); } } // end Title /// <summary>The URL of a GIF, JPEG or PNG image. </summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("The URL of a GIF, JPEG or PNG image. ")] [System.Xml.Serialization.XmlElementAttribute("url")] public string Url { get { return _url; } set { bool changed = !object.Equals(_url, value); _url = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Url)); } } // end Url /// <summary>the URL of the site, when the channel is rendered, the image is a link to the site.</summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("the URL of the site, when the channel is rendered, the image is a link to the site.")] [System.Xml.Serialization.XmlElementAttribute("link")] public string Link { get { return _link; } set { bool changed = !object.Equals(_link, value); _link = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Link)); } } // end Link /// <summary>Contains text that is included in the TITLE attribute of the link formed around the image in the HTML rendering.</summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("Contains text that is included in the TITLE attribute of the link formed around the image in the HTML rendering.")] [System.Xml.Serialization.XmlElementAttribute("description")] public string Description { get { return _description; } set { bool changed = !object.Equals(_description, value); _description = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Description)); } } // end Description /// <summary>Maximum value for width is 144, default value is 88.</summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("Maximum value for width is 144, default value is 88."),System.ComponentModel.DefaultValue(88)] [System.Xml.Serialization.XmlElementAttribute("width")] public int Width { get { return _width; } set { bool changed = !object.Equals(_width, value); _width = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Width)); } } // end Width /// <summary> /// Instructs the XmlSerializer whether or not to generate the XML element /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] [System.ComponentModel.Browsable(false), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public bool WidthSpecified { get { return _width>0; } set { /* do nothing */ } } /// <summary>Maximum value for height is 400, default value is 31.</summary> [System.ComponentModel.Category("RssImage"), System.ComponentModel.Description("Maximum value for height is 400, default value is 31."),System.ComponentModel.DefaultValue(31)] [System.Xml.Serialization.XmlElementAttribute("height")] public int Height { get { return _height; } set { bool changed = !object.Equals(_height, value); _height = value; if(changed) OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(Fields.Height)); } } // end Height /// <summary> /// Instructs the XmlSerializer whether or not to generate the XML element /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] [System.ComponentModel.Browsable(false), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public bool HeightSpecified { get { return _height>0; } set { /* do nothing */ } } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>The friendly name</returns> public override string ToString () { return this.Description; } #endregion #region protected interface #endregion #region nested classes /// <summary> /// public writeable class properties /// </summary> internal struct Fields { public const string Title = "Title"; public const string Url = "Url"; public const string Link = "Link"; public const string Description = "Description"; public const string Width = "Width"; public const string Height = "Height"; } #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 System.Globalization; using System.Linq; using NUnit.Framework; using QuantConnect.Logging; using QuantConnect.Securities.Option.StrategyMatcher; using static QuantConnect.Securities.Option.StrategyMatcher.OptionPositionCollection; using static QuantConnect.Securities.Option.StrategyMatcher.OptionStrategyDefinitions; using static QuantConnect.Tests.Common.Securities.Options.StrategyMatcher.Option; namespace QuantConnect.Tests.Common.Securities.Options.StrategyMatcher { [TestFixture] public class OptionStrategyDefinitionTests { [Test] [TestCaseSource(nameof(TestCases))] public void Run(TestCase test) { var result = test.Definition.Match(test.Positions).ToList(); foreach (var match in result) { Log.Trace(string.Join(";", match.Legs.Select(leg => String(leg.Position)))); } test.AssertMatch(result); } [Test] public void CoveredCall_MatchesMultipleTimes_ForEachUniqueShortCallContract() { // CoveredCall // 0: +1 underlying lot // 1: -1 Call // so we should match // (4U, -4C100) // (3U, -3C110) // (5U, -5C120) // (9U, -9C130) // (20U, -20C140) // OptionStrategyDefinition.Match produces ALL possible matches var positions = Empty.AddRange(Position(Underlying, +20), Position(Call[100], -4), Position(Put[105], -4), Position(Call[105], +4), Position(Put[110], +4), Position(Call[110], -3), Position(Put[115], -3), Position(Call[115], +3), Position(Put[120], +3), Position(Call[120], -5), Position(Put[125], -5), Position(Call[125], +5), Position(Put[130], +5), Position(Call[130], -9), Position(Put[135], -9), Position(Call[140], -21), Position(Put[145], -21) ); // force lower strikes to be evaluated first to provide determinism for this test var options = OptionStrategyMatcherOptions.ForDefinitions(CoveredCall) .WithPositionEnumerator(new FunctionalOptionPositionCollectionEnumerator( pos => pos.OrderBy(p => p.IsUnderlying ? 0 : p.Strike) )); var matches = CoveredCall.Match(options, positions).ToList(); Assert.AreEqual(5, matches.Count); Assert.AreEqual(1, matches.Count(m => m.Multiplier == 4)); Assert.AreEqual(1, matches.Count(m => m.Multiplier == 3)); Assert.AreEqual(1, matches.Count(m => m.Multiplier == 5)); Assert.AreEqual(1, matches.Count(m => m.Multiplier == 9)); Assert.AreEqual(1, matches.Count(m => m.Multiplier == 20)); } [Test] public void DoubleCountPositionsMatchingSamePositionMultipleTimesInDifferentMatches() { // this test aims to verify that we can match the same definition multiple times if positions allows // 1: -C110 +C105 // 0: -C110 +C100 // 2: -C115 +C105 // 3: -C115 +C100 var positions = Empty.AddRange( Position(Call[100], -1), Position(Call[105], -1), Position(Call[110]), Position(Call[115]) ); var matches = BearCallSpread.Match(positions).ToList(); Assert.AreEqual(4, matches.Count); Assert.AreEqual(1, matches.Count(m => m.Legs[1].Position.Strike == 110 && m.Legs[0].Position.Strike == 105)); Assert.AreEqual(1, matches.Count(m => m.Legs[1].Position.Strike == 110 && m.Legs[0].Position.Strike == 100)); Assert.AreEqual(1, matches.Count(m => m.Legs[1].Position.Strike == 115 && m.Legs[0].Position.Strike == 105)); Assert.AreEqual(1, matches.Count(m => m.Legs[1].Position.Strike == 115 && m.Legs[0].Position.Strike == 100)); } [Test] public void ResultingPositionsAreCorrectNoUnderlying() { var positions = Empty.AddRange( Position(Call[100], 10), Position(Call[110], -20), Position(Call[120], 10) ); var matches = ButterflyCall.Match(positions).ToList(); Assert.AreEqual(1, matches.Count); Assert.AreEqual(3, matches[0].Legs.Count); Assert.AreEqual(1, matches[0].Legs.Count(m => m.Position.Strike == 100 && m.Position.Quantity == 10)); Assert.AreEqual(1, matches[0].Legs.Count(m => m.Position.Strike == 110 && m.Position.Quantity == -20)); Assert.AreEqual(1, matches[0].Legs.Count(m => m.Position.Strike == 120 && m.Position.Quantity == 10)); // Now let add some extra option contracts which shouldn't match since they aren't enough positions = positions.Add(Position(Call[100], 5)); positions = positions.Add(Position(Call[110], -5)); matches = ButterflyCall.Match(positions).ToList(); Assert.AreEqual(1, matches.Count); Assert.AreEqual(3, matches[0].Legs.Count); // assert the strategy size respects the matching multiplier var strategy = matches[0].CreateStrategy(); Assert.AreEqual(1, strategy.OptionLegs.Count(m => m.Strike == 100 && m.Quantity == 10)); Assert.AreEqual(1, strategy.OptionLegs.Count(m => m.Strike == 110 && m.Quantity == -20)); Assert.AreEqual(1, strategy.OptionLegs.Count(m => m.Strike == 120 && m.Quantity == 10)); // assert the remaining positions are the expected ones positions = matches[0].RemoveFrom(positions); Assert.AreEqual(2, positions.Count); Assert.AreEqual(1, positions.Count(m => m.Strike == 100 && m.Quantity == 5)); Assert.AreEqual(1, positions.Count(m => m.Strike == 110 && m.Quantity == -5)); } [Test] public void ResultingPositionsAreCorrectWithUnderlying() { var positions = Empty.AddRange( Position(Call[100], -5), // should match 4 covered calls new OptionPosition(Underlying, 4) ); var matches = CoveredCall.Match(positions).ToList(); Assert.AreEqual(1, matches.Count); // underlying isn't included yet Assert.AreEqual(1, matches[0].Legs.Count); Assert.AreEqual(1, matches[0].Legs.Count(m => m.Position.Strike == 100 && m.Position.Quantity == -5)); var strategy = matches[0].CreateStrategy(); Assert.AreEqual(1, strategy.OptionLegs.Count); Assert.AreEqual(1, strategy.UnderlyingLegs.Count); Assert.AreEqual(1, strategy.OptionLegs.Count(m => m.Strike == 100 && m.Quantity == -4)); Assert.AreEqual(1, strategy.UnderlyingLegs.Count(m => m.Quantity == 4)); // assert the remaining positions are the expected ones positions = matches[0].RemoveFrom(positions); Assert.AreEqual(1, positions.Count); Assert.AreEqual(1, positions.Count(m => !m.IsUnderlying && m.Strike == 100 && m.Quantity == -1)); } private static string String(OptionPosition position) { var sign = position.Quantity > 0 ? "+" : ""; var s = position.Symbol; var symbol = s.HasUnderlying ? $"{s.Underlying.Value}:{s.ID.OptionRight}@{s.ID.StrikePrice}:{s.ID.Date:MM-dd}" : s.Value; return $"{sign}{position.Quantity} {symbol}"; } public static TestCaseData[] TestCases { get { return new[] { TestCase.ExactPosition(CoveredCall, Position(Call[100], -1), new OptionPosition(Underlying, +100) ), TestCase.ExactPosition(CoveredPut, Position(Put[100], -1), new OptionPosition(Underlying, -100) ), TestCase.ExactPosition(BearCallSpread, Position(Call[110], +1), Position(Call[100], -1)), TestCase.ExactPosition(BearCallSpread, Position(Call[100], -1), Position(Call[110], +1)), TestCase.ExactPosition(BearPutSpread, Position( Put[110], +1), Position( Put[100], -1)), TestCase.ExactPosition(BearPutSpread, Position( Put[100], -1), Position( Put[110], +1)), TestCase.ExactPosition(BullCallSpread, Position(Call[110], -1), Position(Call[100], +1)), TestCase.ExactPosition(BullCallSpread, Position(Call[100], +1), Position(Call[110], -1)), TestCase.ExactPosition(BullPutSpread, Position( Put[110], -1), Position( Put[100], +1)), TestCase.ExactPosition(BullPutSpread, Position( Put[100], +1), Position( Put[110], -1)), TestCase.ExactPosition(Straddle, Position(Call[100], +1), Position( Put[100], +1)), TestCase.ExactPosition(Straddle, Position( Put[100], +1), Position(Call[100], +1)), TestCase.ExactPosition(ButterflyCall, Position(Call[100], +1), Position(Call[105], -2), Position(Call[110], +1)), TestCase.ExactPosition(ButterflyCall, Position(Call[105], -2), Position(Call[100], +1), Position(Call[110], +1)), TestCase.ExactPosition(ButterflyCall, Position(Call[110], +1), Position(Call[105], -2), Position(Call[100], +1)), TestCase.ExactPosition(ShortButterflyCall, Position(Call[110], -1), Position(Call[105], +2), Position(Call[100], -1)), TestCase.ExactPosition(ButterflyPut, Position( Put[100], +1), Position( Put[105], -2), Position( Put[110], +1)), TestCase.ExactPosition(ButterflyPut, Position( Put[105], -2), Position( Put[100], +1), Position( Put[110], +1)), TestCase.ExactPosition(ButterflyPut, Position( Put[110], +1), Position( Put[105], -2), Position( Put[100], +1)), TestCase.ExactPosition(ShortButterflyPut, Position( Put[110], -1), Position( Put[105], +2), Position( Put[100], -1)), TestCase.ExactPosition(CallCalendarSpread, Position(Call[100, 1], +1), Position(Call[100, 0], -1)), TestCase.ExactPosition(CallCalendarSpread, Position(Call[100, 0], -1), Position(Call[100, 1], +1)), TestCase.ExactPosition(PutCalendarSpread, Position( Put[100, 1], +1), Position( Put[100, 0], -1)), TestCase.ExactPosition(PutCalendarSpread, Position( Put[100, 0], -1), Position( Put[100, 1], +1)), TestCase.ExactPosition(IronCondor, Position( Put[100, 0], +1), Position(Put[105, 0], -1), Position(Call[110, 0], -1), Position(Call[120, 0], +1)) }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray(); } } // aim for perfect match, extra quantity in position, extra symbol position, no match/missing leg public class TestCase { private static readonly Dictionary<string, int> NameCounts = new Dictionary<string, int>(); public string Name { get; } public OptionStrategyDefinition Definition { get; } public OptionPositionCollection Positions { get; } public IReadOnlyList<OptionPosition> Extra { get; } public IReadOnlyList<OptionPosition> Missing { get; } public IReadOnlyDictionary<string, int> ExpectedMatches { get; } public OptionStrategyMatcher CreateMatcher() => new OptionStrategyMatcher(new OptionStrategyMatcherOptions( new[] {Definition}, new List<int> {100, 100, 100, 100} )); private readonly string _methodName; private TestCase( string methodName, OptionStrategyDefinition definition, IReadOnlyList<OptionPosition> positions, IReadOnlyList<OptionPosition> extra, IReadOnlyList<OptionPosition> missing ) { _methodName = methodName; Extra = extra; Missing = missing; Definition = definition; Positions = FromPositions(positions); var suffix = positions.Select(p => { var quantity = p.Quantity.ToString(CultureInfo.InvariantCulture); if (p.Quantity > 0) { quantity = $"+{quantity}"; } if (p.IsUnderlying) { return $"{quantity}{p.Symbol.Value}"; } return $"{quantity}{p.Right.ToString()[0]}@{p.Strike}"; }); Name = $"{definition.Name}:{methodName}({string.Join(", ", suffix)})"; //int count; //if (NameCounts.TryGetValue(Name, out count)) //{ // // test runner doesn't like duplicate names -- ensure uniqueness by counting instances of names // count++; //} //NameCounts[Name] = count; //Name = $"{Name} ({count})"; ExpectedMatches = new Dictionary<string, int> { {nameof(ExactPosition), 1}, {nameof(ExtraQuantity), 1}, {nameof(ExtraPosition), 1}, {nameof(MissingPosition), 0} }; } public void AssertMatch(List<OptionStrategyDefinitionMatch> matches) { switch (_methodName) { case nameof(ExactPosition): Assert.AreEqual(ExpectedMatches[_methodName], matches.Count); Assert.AreEqual(Definition, matches[0].Definition); break; case nameof(ExtraQuantity): Assert.AreEqual(ExpectedMatches[_methodName], matches.Count); Assert.AreEqual(Definition, matches[0].Definition); break; case nameof(ExtraPosition): Assert.AreEqual(ExpectedMatches[_methodName], matches.Count); Assert.AreEqual(Definition, matches[0].Definition); break; case nameof(MissingPosition): Assert.AreEqual(0, matches.Count); break; default: Assert.Fail("Failed to perform assertion."); break; } } public override string ToString() { return Name; } public static TestCase ExactPosition(OptionStrategyDefinition definition, params OptionPosition[] positions) { return new TestCase(nameof(ExactPosition), definition, positions, Array.Empty<OptionPosition>(), Array.Empty<OptionPosition>()); } public static TestCase ExtraQuantity(OptionStrategyDefinition definition, params OptionPosition[] positions) { // add 1 to the first position var extra = positions[0].WithQuantity(1); var pos = positions.Select((p, i) => i == 0 ? p + extra : p).ToList(); return new TestCase(nameof(ExtraQuantity), definition, pos, new[] {extra}, Array.Empty<OptionPosition>()); } public static TestCase ExtraPosition(OptionStrategyDefinition definition, params OptionPosition[] positions) { // add a random position w/ the same underlying var maxStrike = positions.Where(p => p.Symbol.HasUnderlying).Max(p => p.Strike); var extra = new OptionPosition(positions[0].Symbol.WithStrike(maxStrike + 5m), 1); var pos = positions.Concat(new[] {extra}).ToList(); return new TestCase(nameof(ExtraPosition), definition, pos, new[] {extra}, Array.Empty<OptionPosition>()); } public static TestCase MissingPosition(OptionStrategyDefinition definition, OptionPosition missing, params OptionPosition[] positions) { return new TestCase(nameof(MissingPosition), definition, positions, Array.Empty<OptionPosition>(), new []{missing}); } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.IO; using log4net; using FluorineFx.Messaging.Api; using FluorineFx.Messaging.Api.Stream; using FluorineFx.Util; namespace FluorineFx.Messaging.Rtmp.Stream.Codec { class ScreenVideo : IVideoStreamCodec { /// <summary> /// ScreenVideo video codec constant. /// </summary> static string CodecName = "ScreenVideo"; /// <summary> /// FLV codec screen marker constant. /// </summary> public const byte FLV_CODEC_SCREEN = 0x03; /// <summary> /// Block data. /// </summary> private byte[] _blockData; /// <summary> /// Block size. /// </summary> private int[] _blockSize; /// <summary> /// Video width. /// </summary> private int _width; /// <summary> /// Video height. /// </summary> private int _height; /// <summary> /// Width info. /// </summary> private int _widthInfo; /// <summary> /// Height info. /// </summary> private int _heightInfo; /// <summary> /// Block width. /// </summary> private int _blockWidth; /// <summary> /// Block height. /// </summary> private int _blockHeight; /// <summary> /// Number of blocks. /// </summary> private int _blockCount; /// <summary> /// Block data size. /// </summary> private int _blockDataSize; /// <summary> /// Total block data size. /// </summary> private int _totalBlockDataSize; public ScreenVideo() { Reset(); } #region IVideoStreamCodec Members public string Name { get { return ScreenVideo.CodecName; } } public void Reset() { _blockData = null; _blockSize = null; _width = 0; _height = 0; _widthInfo = 0; _heightInfo = 0; _blockWidth = 0; _blockHeight = 0; _blockCount = 0; _blockDataSize = 0; _totalBlockDataSize = 0; } public bool CanDropFrames { get { return false; } } public bool CanHandleData(ByteBuffer data) { if (data.Limit == 0) return false;// Empty buffer byte first = data.Get(); bool result = ((first & 0x0f) == VideoCodec.ScreenVideo.Id); data.Rewind(); return result; } public bool AddData(ByteBuffer data) { if (data.Limit == 0) return false;// Empty buffer if (!CanHandleData(data)) return false; data.Get(); UpdateSize(data); int idx = 0; int pos = 0; byte[] tmpData = new byte[_blockDataSize]; int countBlocks = _blockCount; while (data.Remaining > 0 && countBlocks > 0) { short size = data.GetShort(); countBlocks--; if (size == 0) { // Block has not been modified idx += 1; pos += _blockDataSize; continue; } // Store new block data _blockSize[idx] = size; data.Read(tmpData, 0, size); Array.Copy(tmpData, 0, _blockData, pos, size); idx += 1; pos += _blockDataSize; } data.Rewind(); return true; } public ByteBuffer GetKeyframe() { ByteBuffer result = ByteBuffer.Allocate(1024); result.AutoExpand = true; // Header result.Put((byte)(VideoCodec.FLV_FRAME_KEY | VideoCodec.ScreenVideo.Id)); // Frame size result.PutShort((short)_widthInfo); result.PutShort((short)_heightInfo); // Get compressed blocks byte[] tmpData = new byte[_blockDataSize]; int pos = 0; for (int idx = 0; idx < _blockCount; idx++) { int size = _blockSize[idx]; if (size == 0) { // This should not happen: no data for this block return null; } result.PutShort((short)size); Array.Copy(_blockData, pos, tmpData, 0, size); result.Put(tmpData, 0, size); pos += _blockDataSize; } result.Rewind(); return result; } public ByteBuffer GetDecoderConfiguration() { return null; } #endregion /// <summary> /// This uses the same algorithm as "compressBound" from zlib. /// </summary> /// <param name="size"></param> /// <returns></returns> private int GetMaxCompressedSize(int size) { return size + (size >> 12) + (size >> 14) + 11; } /// <summary> /// Update total block size. /// </summary> /// <param name="data"></param> private void UpdateSize(ByteBuffer data) { _widthInfo = data.GetShort(); _heightInfo = data.GetShort(); // extract width and height of the frame _width = _widthInfo & 0xfff; _height = _heightInfo & 0xfff; // calculate size of blocks _blockWidth = _widthInfo & 0xf000; _blockWidth = (_blockWidth >> 12) + 1; _blockWidth <<= 4; _blockHeight = _heightInfo & 0xf000; _blockHeight = (_blockHeight >> 12) + 1; _blockHeight <<= 4; int xblocks = _width / _blockWidth; if ((_width % _blockWidth) != 0) { // partial block xblocks += 1; } int yblocks = _height / _blockHeight; if ((_height % _blockHeight) != 0) { // partial block yblocks += 1; } _blockCount = xblocks * yblocks; int blockSize = GetMaxCompressedSize(_blockWidth * _blockHeight * 3); int totalBlockSize = blockSize * _blockCount; if (_totalBlockDataSize != totalBlockSize) { //log.Debug("Allocating memory for {} compressed blocks.", this.blockCount); _blockDataSize = blockSize; _totalBlockDataSize = totalBlockSize; _blockData = new byte[blockSize * _blockCount]; _blockSize = new int[blockSize * _blockCount]; // Reset the sizes to zero for (int idx = 0; idx < _blockCount; idx++) { _blockSize[idx] = 0; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using System.Net; using Umbraco.Core; using Umbraco.Core.Auditing; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.IO; namespace umbraco.cms.businesslogic.packager.repositories { [Obsolete("This should not be used and will be removed in future Umbraco versions")] public class Repository : DisposableObject { public string Guid { get; private set; } public string Name { get; private set; } public string RepositoryUrl { get; private set; } public string WebserviceUrl { get; private set; } public RepositoryWebservice Webservice { get { var repo = new RepositoryWebservice(WebserviceUrl); return repo; } } public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc) { string packageName = package.Name; string packageGuid = package.PackageGuid; string description = package.Readme; string packageFile = package.PackagePath; System.IO.FileStream fs1 = null; try { byte[] pack = new byte[0]; fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read); pack = new byte[fs1.Length]; fs1.Read(pack, 0, (int) fs1.Length); fs1.Close(); fs1 = null; byte[] thumb = new byte[0]; //todo upload thumbnail... return Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description); } catch (Exception ex) { LogHelper.Error<Repository>("An error occurred in SubmitPackage", ex); return SubmitStatus.Error; } } public static List<Repository> getAll() { var repositories = new List<Repository>(); foreach (var r in UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories) { var repository = new Repository { Guid = r.Id.ToString(), Name = r.Name }; repository.RepositoryUrl = r.RepositoryUrl; repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + r.WebServiceUrl.Trim('/'); if (r.HasCustomWebServiceUrl) { string wsUrl = r.WebServiceUrl; if (wsUrl.Contains("://")) { repository.WebserviceUrl = r.WebServiceUrl; } else { repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); } } repositories.Add(repository); } return repositories; } public static Repository getByGuid(string repositoryGuid) { Guid id; if (System.Guid.TryParse(repositoryGuid, out id) == false) { throw new FormatException("The repositoryGuid is not a valid GUID"); } var found = UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories.FirstOrDefault(x => x.Id == id); if (found == null) { return null; } var repository = new Repository { Guid = found.Id.ToString(), Name = found.Name }; repository.RepositoryUrl = found.RepositoryUrl; repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + found.WebServiceUrl.Trim('/'); if (found.HasCustomWebServiceUrl) { string wsUrl = found.WebServiceUrl; if (wsUrl.Contains("://")) { repository.WebserviceUrl = found.WebServiceUrl; } else { repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); } } return repository; } //shortcut method to download pack from repo and place it on the server... public string fetch(string packageGuid) { return fetch(packageGuid, string.Empty); } public string fetch(string packageGuid, int userId) { // log Audit.Add(AuditTypes.PackagerInstall, string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), userId, -1); return fetch(packageGuid); } /// <summary> /// Used to get the correct package file from the repo for the current umbraco version /// </summary> /// <param name="packageGuid"></param> /// <param name="userId"></param> /// <param name="currentUmbracoVersion"></param> /// <returns></returns> public string GetPackageFile(string packageGuid, int userId, System.Version currentUmbracoVersion) { // log Audit.Add(AuditTypes.PackagerInstall, string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), userId, -1); var fileByteArray = Webservice.GetPackageFile(packageGuid, currentUmbracoVersion.ToString(3)); //successfull if (fileByteArray.Length > 0) { // Check for package directory if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) { fs1.Write(fileByteArray, 0, fileByteArray.Length); fs1.Close(); return "packages\\" + packageGuid + ".umb"; } } return ""; } public bool HasConnection() { string strServer = this.RepositoryUrl; try { HttpWebRequest reqFP = (HttpWebRequest) HttpWebRequest.Create(strServer); HttpWebResponse rspFP = (HttpWebResponse) reqFP.GetResponse(); if (HttpStatusCode.OK == rspFP.StatusCode) { // HTTP = 200 - Internet connection available, server online rspFP.Close(); return true; } else { // Other status - Server or connection not available rspFP.Close(); return false; } } catch (WebException) { // Exception - connection not available return false; } } /// <summary> /// This goes and fetches the Byte array for the package from OUR, but it's pretty strange /// </summary> /// <param name="packageGuid"> /// The package ID for the package file to be returned /// </param> /// <param name="key"> /// This is a strange Umbraco version parameter - but it's not really an umbraco version, it's a special/odd version format like Version41 /// but it's actually not used for the 7.5+ package installs so it's obsolete/unused. /// </param> /// <returns></returns> public string fetch(string packageGuid, string key) { byte[] fileByteArray = new byte[0]; if (key == string.Empty) { //SD: this is odd, not sure why it returns a different package depending on the legacy xml schema but I'll leave it for now if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) fileByteArray = Webservice.fetchPackage(packageGuid); else { fileByteArray = Webservice.fetchPackageByVersion(packageGuid, Version.Version41); } } else { fileByteArray = Webservice.fetchProtectedPackage(packageGuid, key); } //successfull if (fileByteArray.Length > 0) { // Check for package directory if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) { fs1.Write(fileByteArray, 0, fileByteArray.Length); fs1.Close(); return "packages\\" + packageGuid + ".umb"; } } // log return ""; } /// <summary> /// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic. /// </summary> protected override void DisposeResources() { Webservice.Dispose(); } } }
#if !(NETCF_1_0 || SILVERLIGHT) using System; using System.Security.Cryptography; using SystemX509 = System.Security.Cryptography.X509Certificates; using ChainUtils.BouncyCastle.Asn1.Pkcs; using ChainUtils.BouncyCastle.Asn1.X509; using ChainUtils.BouncyCastle.Crypto; using ChainUtils.BouncyCastle.Crypto.Parameters; using ChainUtils.BouncyCastle.Math; using ChainUtils.BouncyCastle.Utilities; namespace ChainUtils.BouncyCastle.Security { /// <summary> /// A class containing methods to interface the BouncyCastle world to the .NET Crypto world. /// </summary> public sealed class DotNetUtilities { private DotNetUtilities() { } /// <summary> /// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure. /// </summary> /// <param name="x509Struct"></param> /// <returns>A System.Security.Cryptography.X509Certificate.</returns> public static SystemX509.X509Certificate ToX509Certificate( X509CertificateStructure x509Struct) { return new SystemX509.X509Certificate(x509Struct.GetDerEncoded()); } public static AsymmetricCipherKeyPair GetDsaKeyPair( DSA dsa) { return GetDsaKeyPair(dsa.ExportParameters(true)); } public static AsymmetricCipherKeyPair GetDsaKeyPair( DSAParameters dp) { DsaValidationParameters validationParameters = (dp.Seed != null) ? new DsaValidationParameters(dp.Seed, dp.Counter) : null; DsaParameters parameters = new DsaParameters( new BigInteger(1, dp.P), new BigInteger(1, dp.Q), new BigInteger(1, dp.G), validationParameters); DsaPublicKeyParameters pubKey = new DsaPublicKeyParameters( new BigInteger(1, dp.Y), parameters); DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters( new BigInteger(1, dp.X), parameters); return new AsymmetricCipherKeyPair(pubKey, privKey); } public static DsaPublicKeyParameters GetDsaPublicKey( DSA dsa) { return GetDsaPublicKey(dsa.ExportParameters(false)); } public static DsaPublicKeyParameters GetDsaPublicKey( DSAParameters dp) { DsaValidationParameters validationParameters = (dp.Seed != null) ? new DsaValidationParameters(dp.Seed, dp.Counter) : null; DsaParameters parameters = new DsaParameters( new BigInteger(1, dp.P), new BigInteger(1, dp.Q), new BigInteger(1, dp.G), validationParameters); return new DsaPublicKeyParameters( new BigInteger(1, dp.Y), parameters); } public static AsymmetricCipherKeyPair GetRsaKeyPair( RSA rsa) { return GetRsaKeyPair(rsa.ExportParameters(true)); } public static AsymmetricCipherKeyPair GetRsaKeyPair( RSAParameters rp) { BigInteger modulus = new BigInteger(1, rp.Modulus); BigInteger pubExp = new BigInteger(1, rp.Exponent); RsaKeyParameters pubKey = new RsaKeyParameters( false, modulus, pubExp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( modulus, pubExp, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), new BigInteger(1, rp.DP), new BigInteger(1, rp.DQ), new BigInteger(1, rp.InverseQ)); return new AsymmetricCipherKeyPair(pubKey, privKey); } public static RsaKeyParameters GetRsaPublicKey( RSA rsa) { return GetRsaPublicKey(rsa.ExportParameters(false)); } public static RsaKeyParameters GetRsaPublicKey( RSAParameters rp) { return new RsaKeyParameters( false, new BigInteger(1, rp.Modulus), new BigInteger(1, rp.Exponent)); } public static AsymmetricCipherKeyPair GetKeyPair(AsymmetricAlgorithm privateKey) { if (privateKey is DSA) { return GetDsaKeyPair((DSA)privateKey); } if (privateKey is RSA) { return GetRsaKeyPair((RSA)privateKey); } throw new ArgumentException("Unsupported algorithm specified", "privateKey"); } public static RSA ToRSA(RsaKeyParameters rsaKey) { // TODO This appears to not work for private keys (when no CRT info) return CreateRSAProvider(ToRSAParameters(rsaKey)); } public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey) { return CreateRSAProvider(ToRSAParameters(privKey)); } public static RSA ToRSA(RsaPrivateKeyStructure privKey) { return CreateRSAProvider(ToRSAParameters(privKey)); } public static RSAParameters ToRSAParameters(RsaKeyParameters rsaKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = rsaKey.Modulus.ToByteArrayUnsigned(); if (rsaKey.IsPrivate) rp.D = ConvertRSAParametersField(rsaKey.Exponent, rp.Modulus.Length); else rp.Exponent = rsaKey.Exponent.ToByteArrayUnsigned(); return rp; } public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = privKey.Modulus.ToByteArrayUnsigned(); rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned(); rp.P = privKey.P.ToByteArrayUnsigned(); rp.Q = privKey.Q.ToByteArrayUnsigned(); rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length); rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length); rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length); rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length); return rp; } public static RSAParameters ToRSAParameters(RsaPrivateKeyStructure privKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = privKey.Modulus.ToByteArrayUnsigned(); rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned(); rp.P = privKey.Prime1.ToByteArrayUnsigned(); rp.Q = privKey.Prime2.ToByteArrayUnsigned(); rp.D = ConvertRSAParametersField(privKey.PrivateExponent, rp.Modulus.Length); rp.DP = ConvertRSAParametersField(privKey.Exponent1, rp.P.Length); rp.DQ = ConvertRSAParametersField(privKey.Exponent2, rp.Q.Length); rp.InverseQ = ConvertRSAParametersField(privKey.Coefficient, rp.Q.Length); return rp; } // TODO Move functionality to more general class private static byte[] ConvertRSAParametersField(BigInteger n, int size) { byte[] bs = n.ToByteArrayUnsigned(); if (bs.Length == size) return bs; if (bs.Length > size) throw new ArgumentException("Specified size too small", "size"); byte[] padded = new byte[size]; Array.Copy(bs, 0, padded, size - bs.Length, bs.Length); return padded; } private static RSA CreateRSAProvider(RSAParameters rp) { RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(); rsaCsp.ImportParameters(rp); return rsaCsp; } } } #endif
using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Streams; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.TestingHost; using TestExtensions; using TestGrainInterfaces; using Tests.GeoClusterTests; using Xunit; using Xunit.Abstractions; using Orleans.Hosting; namespace UnitTests.GeoClusterTests { [TestCategory("GeoCluster")] public class MultiClusterRegistrationTests : TestingClusterHost { private string[] ClusterNames; private ClientWrapper[][] Clients; private IEnumerable<KeyValuePair<string, ClientWrapper>> EnumerateClients() { for (int i = 0; i < ClusterNames.Length; i++) foreach (var c in Clients[i]) yield return new KeyValuePair<string, ClientWrapper>(ClusterNames[i], c); } public MultiClusterRegistrationTests(ITestOutputHelper output) : base(output) { } [SkippableFact] public async Task TwoClusterBattery() { await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2)); var testtasks = new List<Task>(); testtasks.Add(RunWithTimeout("Deact", 20000, Deact)); testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls)); testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls)); testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls)); testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification)); testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification)); foreach (var t in testtasks) await t; } [SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/4265"), TestCategory("Functional")] public async Task ThreeClusterBattery() { await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 2)); var testtasks = new List<Task>(); testtasks.Add(RunWithTimeout("Deact", 20000, Deact)); testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls)); testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls)); testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls)); testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification)); testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification)); foreach (var t in testtasks) await t; } [SkippableFact] public async Task FourClusterBattery() { await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 1, 1)); var testtasks = new List<Task>(); for (int i = 0; i < 20; i++) { testtasks.Add(RunWithTimeout("Deact", 20000, Deact)); testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls)); testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls)); testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls)); testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification)); testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification)); } foreach (var t in testtasks) await t; } private Task StartClustersAndClients(params short[] silos) { return StartClustersAndClients(null, null, silos); } public class SiloConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddSimpleMessageStreamProvider("SMSProvider"); } } private Task StartClustersAndClients(Action<ClusterConfiguration> config_customizer, Action<ClientConfiguration> clientconfig_customizer, params short[] silos) { WriteLog("Creating clusters and clients..."); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); // use a random global service id for testing purposes var globalserviceid = Guid.NewGuid(); random = new Random(); System.Threading.ThreadPool.SetMaxThreads(8, 8); // configuration for cluster Action<ClusterConfiguration> addtracing = (ClusterConfiguration c) => { config_customizer?.Invoke(c); }; // Create clusters and clients ClusterNames = new string[silos.Length]; Clients = new ClientWrapper[silos.Length][]; for (int i = 0; i < silos.Length; i++) { var numsilos = silos[i]; var clustername = ClusterNames[i] = ((char)('A' + i)).ToString(); var c = Clients[i] = new ClientWrapper[numsilos]; NewGeoCluster<SiloConfigurator>(globalserviceid, clustername, silos[i], addtracing); // create one client per silo Parallel.For(0, numsilos, paralleloptions, (j) => c[j] = this.NewClient(clustername, j, ClientWrapper.Factory, null, clientBuilder => clientBuilder.AddSimpleMessageStreamProvider("SMSProvider"))); } WriteLog("Clusters and clients are ready (elapsed = {0})", stopwatch.Elapsed); // wait for configuration to stabilize WaitForLivenessToStabilizeAsync().WaitWithThrow(TimeSpan.FromMinutes(1)); Clients[0][0].InjectClusterConfiguration(ClusterNames); WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1)); stopwatch.Stop(); WriteLog("Multicluster is ready (elapsed = {0}).", stopwatch.Elapsed); return Task.CompletedTask; } Random random; public class ClientWrapper : ClientWrapperBase { public static readonly Func<string, int, string, Action<ClientConfiguration>, Action<IClientBuilder>, ClientWrapper> Factory = (name, gwPort, clusterId, configUpdater, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, configUpdater, clientConfigurator); public ClientWrapper(string name, int gatewayport, string clusterId, Action<ClientConfiguration> configCustomizer, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, configCustomizer, clientConfigurator) { this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0); } public int CallGrain(int i) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); this.Client.Logger().Info("Call Grain {0}", grainRef); Task<int> toWait = grainRef.SayHelloAsync(); toWait.Wait(); return toWait.GetResult(); } public string GetRuntimeId(int i) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); this.Client.Logger().Info("GetRuntimeId {0}", grainRef); Task<string> toWait = grainRef.GetRuntimeId(); toWait.Wait(); return toWait.GetResult(); } public void Deactivate(int i) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); this.Client.Logger().Info("Deactivate {0}", grainRef); Task toWait = grainRef.Deactivate(); toWait.GetResult(); } public void EnableStreamNotifications(int i) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); this.Client.Logger().Info("EnableStreamNotifications {0}", grainRef); Task toWait = grainRef.EnableStreamNotifications(); toWait.GetResult(); } // observer-based notification public void Subscribe(int i, IClusterTestListener listener) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); this.Client.Logger().Info("Create Listener object {0}", grainRef); listeners.Add(listener); var obj = this.GrainFactory.CreateObjectReference<IClusterTestListener>(listener).Result; listeners.Add(obj); this.Client.Logger().Info("Subscribe {0}", grainRef); Task toWait = grainRef.Subscribe(obj); toWait.GetResult(); } List<IClusterTestListener> listeners = new List<IClusterTestListener>(); // keep them from being GCed // stream-based notification public void SubscribeStream(int i, IAsyncObserver<int> listener) { IStreamProvider streamProvider = this.Client.GetStreamProvider("SMSProvider"); Guid guid = new Guid(i, 0, 0, new byte[8]); IAsyncStream<int> stream = streamProvider.GetStream<int>(guid, "notificationtest"); handle = stream.SubscribeAsync(listener).GetResult(); } StreamSubscriptionHandle<int> handle; public void InjectClusterConfiguration(params string[] clusters) { systemManagement.InjectMultiClusterConfiguration(clusters).Wait(); } IManagementGrain systemManagement; public string GetGrainRef(int i) { return this.GrainFactory.GetGrain<IClusterTestGrain>(i).ToString(); } } public class ClusterTestListener : MarshalByRefObject, IClusterTestListener, IAsyncObserver<int> { public ClusterTestListener(Action<int> oncall) { this.oncall = oncall; } private Action<int> oncall; public void GotHello(int number) { count++; oncall(number); } public Task OnNextAsync(int item, StreamSequenceToken token = null) { GotHello(item); return Task.CompletedTask; } public Task OnCompletedAsync() { throw new NotImplementedException(); } public Task OnErrorAsync(Exception ex) { throw new NotImplementedException(); } public int count; } private int Next() { lock (random) return random.Next(); } private async Task SequentialCalls() { await Task.Yield(); var x = Next(); var gref = Clients[0][0].GetGrainRef(x); var list = EnumerateClients().ToList(); // one call to each silo, in parallel foreach (var c in list) c.Value.CallGrain(x); // total number of increments should match AssertEqual(list.Count() + 1, Clients[0][0].CallGrain(x), gref); } private async Task ParallelCalls() { await Task.Yield(); var x = Next(); var gref = Clients[0][0].GetGrainRef(x); var list = EnumerateClients().ToList(); // one call to each silo, in parallel Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x)); // total number of increments should match AssertEqual(list.Count + 1, Clients[0][0].CallGrain(x), gref); } private async Task ManyParallelCalls() { await Task.Yield(); var x = Next(); var gref = Clients[0][0].GetGrainRef(x); // pick just one client per cluster, use it multiple times var clients = Clients.Select(a => a[0]).ToList(); // concurrently increment (numupdates) times, distributed over the clients Parallel.For(0, 20, paralleloptions, i => clients[i % clients.Count].CallGrain(x)); // total number of increments should match AssertEqual(21, Clients[0][0].CallGrain(x), gref); } private async Task Deact() { var x = Next(); var gref = Clients[0][0].GetGrainRef(x); // put into cluster A var id = Clients[0][0].GetRuntimeId(x); WriteLog("Grain {0} at {1}", gref, id); Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id); // ensure presence in all caches var list = EnumerateClients().ToList(); Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x)); Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x)); AssertEqual(2* list.Count() + 1, Clients[0][0].CallGrain(x), gref); WriteLog("Grain {0} deactivating.", gref); //deactivate Clients[0][0].Deactivate(x); // wait for deactivation to complete await Task.Delay(5000); WriteLog("Grain {0} reactivating.", gref); // activate anew in cluster B var val = Clients[1][0].CallGrain(x); AssertEqual(1, val, gref); var newid = Clients[1][0].GetRuntimeId(x); WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]); Assert.Contains(Clusters[ClusterNames[1]].Silos, silo => silo.SiloAddress.ToString() == newid); WriteLog("Grain {0} Check that other clusters find new activation.", gref); for (int i = 2; i < Clusters.Count; i++) { var idd = Clients[i][0].GetRuntimeId(x); WriteLog("{2} sees Grain {0} at {1}", gref, idd, ClusterNames[i]); AssertEqual(newid, idd, gref); } } private async Task ObserverBasedClientNotification() { var x = Next(); var gref = Clients[0][0].GetGrainRef(x); Clients[0][0].GetRuntimeId(x); WriteLog("{0} created grain", gref); var listeners = new List<ClusterTestListener>(); var promises = new List<Task<int>>(); // create an observer on each client Parallel.For(0, Clients.Length, paralleloptions, i => { for (int jj = 0; jj < Clients[i].Length; jj++) { int j = jj; var promise = new TaskCompletionSource<int>(); var listener = new ClusterTestListener((num) => { WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref); promise.TrySetResult(num); }); promises.Add(promise.Task); listeners.Add(listener); Clients[i][j].Subscribe(x, listener); WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref); } }); // call the grain Clients[0][0].CallGrain(x); await Task.WhenAll(promises); var sortedresults = promises.Select(p => p.Result).OrderBy(num => num).ToArray(); // each client should get its own notification for (int i = 0; i < sortedresults.Length; i++) AssertEqual(sortedresults[i], i, gref); } private async Task StreamBasedClientNotification() { var x = Next(); var gref = Clients[0][0].GetGrainRef(x); Clients[0][0].EnableStreamNotifications(x); WriteLog("{0} created grain", gref); var listeners = new List<ClusterTestListener>(); var promises = new List<Task<int>>(); // create an observer on each client Parallel.For(0, Clients.Length, paralleloptions, i => { for (int jj = 0; jj < Clients[i].Length; jj++) { int j = jj; var promise = new TaskCompletionSource<int>(); var listener = new ClusterTestListener((num) => { WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref); promise.TrySetResult(num); }); promises.Add(promise.Task); listeners.Add(listener); Clients[i][j].SubscribeStream(x, listener); WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref); } }); // call the grain Clients[0][0].CallGrain(x); await Task.WhenAll(promises); // each client should get same value foreach (var p in promises) AssertEqual(1, p.Result, gref); } [SkippableFact, TestCategory("Functional")] public async Task BlockedDeact() { await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => { Action<ClusterConfiguration> c = (cc) => { cc.Globals.DirectoryLazyDeregistrationDelay = TimeSpan.FromSeconds(5); }; return StartClustersAndClients(c, null, 1, 1); }); await RunWithTimeout("BlockedDeact", 10 * 1000, async () => { var x = Next(); var gref = Clients[0][0].GetGrainRef(x); // put into cluster A and access from cluster B var id = Clients[0][0].GetRuntimeId(x); WriteLog("Grain {0} at {1}", gref, id); Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id); var id2 = Clients[1][0].GetRuntimeId(x); AssertEqual(id2, id, gref); // deactivate grain in cluster A, but block deactivation message to cluster B WriteLog("Grain {0} deactivating.", gref); BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]); Clients[0][0].Deactivate(x); await Task.Delay(5000); UnblockAllClusterCommunication(ClusterNames[0]); // reactivate in cluster B. This should cause unregistration to be sent WriteLog("Grain {0} reactivating.", gref); // activate anew in cluster B var val = Clients[1][0].CallGrain(x); AssertEqual(1, val, gref); var newid = Clients[1][0].GetRuntimeId(x); WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]); Assert.True(Clusters[ClusterNames[1]].Silos.First().SiloAddress.ToString() == newid); }); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NUnit.Framework; using TestCases.SS.UserModel; using NPOI.SS.UserModel; using NPOI.OpenXmlFormats.Spreadsheet; using System; using NPOI.XSSF.Model; using NPOI.SS.Util; using NPOI.SS; using TestCases.HSSF; using System.Text; namespace NPOI.XSSF.UserModel { /** * @author Yegor Kozlov */ [TestFixture] public class TestXSSFCell : BaseTestXCell { public TestXSSFCell() : base(XSSFITestDataProvider.instance) { } /** * Bug 47026: trouble changing cell type when workbook doesn't contain * Shared String Table */ [Test] public void Test47026_1() { IWorkbook source = _testDataProvider.OpenSampleWorkbook("47026.xlsm"); ISheet sheet = source.GetSheetAt(0); IRow row = sheet.GetRow(0); ICell cell = row.GetCell(0); cell.SetCellType(CellType.String); cell.SetCellValue("456"); } [Test] public void Test47026_2() { IWorkbook source = _testDataProvider.OpenSampleWorkbook("47026.xlsm"); ISheet sheet = source.GetSheetAt(0); IRow row = sheet.GetRow(0); ICell cell = row.GetCell(0); cell.SetCellFormula(null); cell.SetCellValue("456"); } /** * Test that we can read inline strings that are expressed directly in the cell defInition * instead of implementing the shared string table. * * Some programs, for example, Microsoft Excel Driver for .xlsx insert inline string * instead of using the shared string table. See bug 47206 */ [Test] public void TestInlineString() { XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("xlsx-jdbc.xlsx"); XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0); XSSFRow row = (XSSFRow)sheet.GetRow(1); XSSFCell cell_0 = (XSSFCell)row.GetCell(0); Assert.AreEqual(ST_CellType.inlineStr, cell_0.GetCTCell().t); Assert.IsTrue(cell_0.GetCTCell().IsSetIs()); Assert.AreEqual(cell_0.StringCellValue, "A Very large string in column 1 AAAAAAAAAAAAAAAAAAAAA"); XSSFCell cell_1 = (XSSFCell)row.GetCell(1); Assert.AreEqual(ST_CellType.inlineStr, cell_1.GetCTCell().t); Assert.IsTrue(cell_1.GetCTCell().IsSetIs()); Assert.AreEqual(cell_1.StringCellValue, "foo"); XSSFCell cell_2 = (XSSFCell)row.GetCell(2); Assert.AreEqual(ST_CellType.inlineStr, cell_2.GetCTCell().t); Assert.IsTrue(cell_2.GetCTCell().IsSetIs()); Assert.AreEqual(row.GetCell(2).StringCellValue, "bar"); } /** * Bug 47278 - xsi:nil attribute for <t> tag caused Excel 2007 to fail to open workbook */ [Test] public void Test47278() { XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.CreateWorkbook(); XSSFSheet sheet = (XSSFSheet)wb.CreateSheet(); IRow row = sheet.CreateRow(0); SharedStringsTable sst = wb.GetSharedStringSource(); Assert.AreEqual(0, sst.Count); //case 1. cell.SetCellValue(new XSSFRichTextString((String)null)); ICell cell_0 = row.CreateCell(0); XSSFRichTextString str = new XSSFRichTextString((String)null); Assert.IsNull(str.String); cell_0.SetCellValue(str); Assert.AreEqual(0, sst.Count); Assert.AreEqual(CellType.Blank, cell_0.CellType); //case 2. cell.SetCellValue((String)null); ICell cell_1 = row.CreateCell(1); cell_1.SetCellValue((String)null); Assert.AreEqual(0, sst.Count); Assert.AreEqual(CellType.Blank, cell_1.CellType); } [Test] public void TestFormulaString() { XSSFWorkbook wb = new XSSFWorkbook(); XSSFCell cell = (XSSFCell)wb.CreateSheet().CreateRow(0).CreateCell(0); CT_Cell ctCell = cell.GetCTCell(); //low-level bean holding cell's xml cell.SetCellFormula("A2"); Assert.AreEqual(CellType.Formula, cell.CellType); Assert.AreEqual(cell.CellFormula, "A2"); //the value is not Set and cell's type='N' which means blank Assert.AreEqual(ST_CellType.n, ctCell.t); //set cached formula value cell.SetCellValue("t='str'"); //we are still of 'formula' type Assert.AreEqual(CellType.Formula, cell.CellType); Assert.AreEqual(cell.CellFormula, "A2"); //cached formula value is Set and cell's type='STR' Assert.AreEqual(ST_CellType.str, ctCell.t); Assert.AreEqual(cell.StringCellValue, "t='str'"); //now remove the formula, the cached formula result remains cell.SetCellFormula(null); Assert.AreEqual(CellType.String, cell.CellType); Assert.AreEqual(ST_CellType.str, ctCell.t); //the line below failed prior to fix of Bug #47889 Assert.AreEqual(cell.StringCellValue, "t='str'"); //revert to a blank cell cell.SetCellValue((String)null); Assert.AreEqual(CellType.Blank, cell.CellType); Assert.AreEqual(ST_CellType.n, ctCell.t); Assert.AreEqual(cell.StringCellValue, ""); } /** * Bug 47889: problems when calling XSSFCell.StringCellValue on a workbook Created in Gnumeric */ [Test] public void Test47889() { XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("47889.xlsx"); ISheet sh = wb.GetSheetAt(0); ICell cell; //try a string cell cell = sh.GetRow(0).GetCell(0); Assert.AreEqual(CellType.String, cell.CellType); Assert.AreEqual(cell.StringCellValue, "a"); Assert.AreEqual(cell.ToString(), "a"); //Gnumeric produces spreadsheets without styles //make sure we return null for that instead of throwing OutOfBounds Assert.AreEqual(null, cell.CellStyle); //try a numeric cell cell = sh.GetRow(1).GetCell(0); Assert.AreEqual(CellType.Numeric, cell.CellType); Assert.AreEqual(1.0, cell.NumericCellValue); Assert.AreEqual(cell.ToString(), "1"); //Gnumeric produces spreadsheets without styles //make sure we return null for that instead of throwing OutOfBounds Assert.AreEqual(null, cell.CellStyle); } [Test] public void TestIsMergedCell() { XSSFWorkbook wb = new XSSFWorkbook(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(5); ICell cell5 = row.CreateCell(5); ICell cell6 = row.CreateCell(6); ICell cell8 = row.CreateCell(8); Assert.IsFalse(cell5.IsMergedCell); Assert.IsFalse(cell6.IsMergedCell); Assert.IsFalse(cell8.IsMergedCell); sheet.AddMergedRegion(new SS.Util.CellRangeAddress(5, 6, 5, 6)); //region with 4 cells Assert.IsTrue(cell5.IsMergedCell); Assert.IsTrue(cell6.IsMergedCell); Assert.IsFalse(cell8.IsMergedCell); } [Test] public void TestMissingRAttribute() { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)wb.CreateSheet(); XSSFRow row = (XSSFRow)sheet.CreateRow(0); XSSFCell a1 = (XSSFCell)row.CreateCell(0); a1.SetCellValue("A1"); XSSFCell a2 = (XSSFCell)row.CreateCell(1); a2.SetCellValue("B1"); XSSFCell a4 = (XSSFCell)row.CreateCell(4); a4.SetCellValue("E1"); XSSFCell a6 = (XSSFCell)row.CreateCell(5); a6.SetCellValue("F1"); assertCellsWithMissingR(row); a2.GetCTCell().unsetR(); a6.GetCTCell().unsetR(); assertCellsWithMissingR(row); wb = (XSSFWorkbook)_testDataProvider.WriteOutAndReadBack(wb); row = (XSSFRow)wb.GetSheetAt(0).GetRow(0); assertCellsWithMissingR(row); } private void assertCellsWithMissingR(XSSFRow row) { XSSFCell a1 = (XSSFCell)row.GetCell(0); Assert.IsNotNull(a1); XSSFCell a2 = (XSSFCell)row.GetCell(1); Assert.IsNotNull(a2); XSSFCell a5 = (XSSFCell)row.GetCell(4); Assert.IsNotNull(a5); XSSFCell a6 = (XSSFCell)row.GetCell(5); Assert.IsNotNull(a6); Assert.AreEqual(6, row.LastCellNum); Assert.AreEqual(4, row.PhysicalNumberOfCells); Assert.AreEqual(a1.StringCellValue, "A1"); Assert.AreEqual(a2.StringCellValue, "B1"); Assert.AreEqual(a5.StringCellValue, "E1"); Assert.AreEqual(a6.StringCellValue, "F1"); // even if R attribute is not set, // POI is able to re-construct it from column and row indexes Assert.AreEqual(a1.GetReference(), "A1"); Assert.AreEqual(a2.GetReference(), "B1"); Assert.AreEqual(a5.GetReference(), "E1"); Assert.AreEqual(a6.GetReference(), "F1"); } [Test] public void TestMissingRAttributeBug54288() { // workbook with cells missing the R attribute XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("54288.xlsx"); // same workbook re-saved in Excel 2010, the R attribute is updated for every cell with the right value. XSSFWorkbook wbRef = (XSSFWorkbook)_testDataProvider.OpenSampleWorkbook("54288-ref.xlsx"); XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0); XSSFSheet sheetRef = (XSSFSheet)wbRef.GetSheetAt(0); Assert.AreEqual(sheetRef.PhysicalNumberOfRows, sheet.PhysicalNumberOfRows); // Test idea: iterate over cells in the reference worksheet, they all have the R attribute set. // For each cell from the reference sheet find the corresponding cell in the problematic file (with missing R) // and assert that POI reads them equally: DataFormatter formater = new DataFormatter(); foreach (IRow r in sheetRef) { XSSFRow rowRef = (XSSFRow)r; XSSFRow row = (XSSFRow)sheet.GetRow(rowRef.RowNum); Assert.AreEqual(rowRef.PhysicalNumberOfCells, row.PhysicalNumberOfCells, "number of cells in row[" + row.RowNum + "]"); foreach (ICell c in rowRef.Cells) { XSSFCell cellRef = (XSSFCell)c; XSSFCell cell = (XSSFCell)row.GetCell(cellRef.ColumnIndex); Assert.AreEqual(cellRef.ColumnIndex, cell.ColumnIndex); Assert.AreEqual(cellRef.GetReference(), cell.GetReference()); if (!cell.GetCTCell().IsSetR()) { Assert.IsTrue(cellRef.GetCTCell().IsSetR(), "R must e set in cellRef"); String valRef = formater.FormatCellValue(cellRef); String val = formater.FormatCellValue(cell); Assert.AreEqual(valRef, val); } } } } [Test] public void Test56170() { IWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56170.xlsx"); XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0); IWorkbook wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); ICell cell; // add some contents to table so that the table will need expansion IRow row = sheet.GetRow(0); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell = row.CreateCell(0); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell.SetCellValue("demo1"); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell = row.CreateCell(1); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell.SetCellValue("demo2"); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell = row.CreateCell(2); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); cell.SetCellValue("demo3"); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); row = sheet.GetRow(1); cell = row.CreateCell(0); cell.SetCellValue("demo1"); cell = row.CreateCell(1); cell.SetCellValue("demo2"); cell = row.CreateCell(2); cell.SetCellValue("demo3"); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); // expand table XSSFTable table = sheet.GetTables()[0]; CellReference startRef = table.GetStartCellReference(); CellReference endRef = table.GetEndCellReference(); table.GetCTTable().@ref = (new CellRangeAddress(startRef.Row, 1, startRef.Col, endRef.Col).FormatAsString()); wbRead = XSSFTestDataSamples.WriteOutAndReadBack(wb); Assert.IsNotNull(wbRead); /*FileOutputStream stream = new FileOutputStream("c:\\temp\\output.xlsx"); workbook.Write(stream); stream.Close();*/ } [Test] public void Test56170Reproduce() { IWorkbook wb = new XSSFWorkbook(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); // by creating Cells out of order we trigger the handling in onDocumentWrite() ICell cell1 = row.CreateCell(1); ICell cell2 = row.CreateCell(0); validateRow(row); validateRow(row); // once again with removing one cell row.RemoveCell(cell1); validateRow(row); // once again with removing one cell row.RemoveCell(cell1); // now check again validateRow(row); // once again with removing one cell row.RemoveCell(cell2); // now check again validateRow(row); } private void validateRow(IRow row) { // trigger bug with CArray handling ((XSSFRow)row).OnDocumentWrite(); foreach (ICell cell in row) { cell.ToString(); } } [Test] public void TestBug56644ReturnNull() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56644.xlsx"); try { wb.MissingCellPolicy = (MissingCellPolicy.RETURN_BLANK_AS_NULL); ISheet sheet = wb.GetSheet("samplelist"); IRow row = sheet.GetRow(20); row.CreateCell(2); } finally { wb.Close(); } } [Test] public void TestBug56644ReturnBlank() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56644.xlsx"); try { wb.MissingCellPolicy = (MissingCellPolicy.RETURN_NULL_AND_BLANK); ISheet sheet = wb.GetSheet("samplelist"); IRow row = sheet.GetRow(20); row.CreateCell(2); } finally { wb.Close(); } } [Test] public void TestBug56644CreateBlank() { XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("56644.xlsx"); try { wb.MissingCellPolicy = (MissingCellPolicy.CREATE_NULL_AS_BLANK); ISheet sheet = wb.GetSheet("samplelist"); IRow row = sheet.GetRow(20); row.CreateCell(2); } finally { wb.Close(); } } [Test] public void TestEncodingbeloAscii() { StringBuilder sb = new StringBuilder(); // test all possible characters for (int i = 0; i < char.MaxValue; i++) { sb.Append((char)i); } String strAll = sb.ToString(); // process in chunks as we have a limit on size of column now int pos = 0; while (pos < strAll.Length) { String str = strAll.Substring(pos, Math.Min(strAll.Length, pos + SpreadsheetVersion.EXCEL2007.MaxTextLength)- pos); IWorkbook wb = HSSFITestDataProvider.Instance.CreateWorkbook(); ICell cell = wb.CreateSheet().CreateRow(0).CreateCell(0); IWorkbook xwb = XSSFITestDataProvider.instance.CreateWorkbook(); ICell xCell = xwb.CreateSheet().CreateRow(0).CreateCell(0); //IWorkbook swb = SXSSFITestDataProvider.instance.CreateWorkbook(); //ICell sCell = swb.CreateSheet().CreateRow(0).CreateCell(0); cell.SetCellValue(str); Assert.AreEqual(str, cell.StringCellValue); xCell.SetCellValue(str); Assert.AreEqual(str, xCell.StringCellValue); //sCell.SetCellValue(str); //Assert.AreEqual(str, sCell.StringCellValue); IWorkbook wbBack = HSSFITestDataProvider.Instance.WriteOutAndReadBack(wb); IWorkbook xwbBack = XSSFITestDataProvider.instance.WriteOutAndReadBack(xwb); //IWorkbook swbBack = SXSSFITestDataProvider.instance.WriteOutAndReadBack(swb); cell = wbBack.GetSheetAt(0).CreateRow(0).CreateCell(0); xCell = xwbBack.GetSheetAt(0).CreateRow(0).CreateCell(0); //sCell = swbBack.GetSheetAt(0).CreateRow(0).CreateCell(0); Assert.AreEqual(cell.StringCellValue, xCell.StringCellValue); //Assert.AreEqual(cell.StringCellValue, sCell.StringCellValue); pos += SpreadsheetVersion.EXCEL97.MaxTextLength; } } } }
// Copyright 2014 Mario Guggenberger <mg@protyposis.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. using OpenSource.UPnP; namespace LocalAudioBroadcast { /// <summary> /// Transparent DeviceSide UPnP Service /// </summary> public class DvConnectionManager : IUPnPService { // Place your declarations above this line #region AutoGenerated Code Section [Do NOT Modify, unless you know what you're doing] //{{{{{ Begin Code Block private _DvConnectionManager _S; public static string URN = "urn:schemas-upnp-org:service:ConnectionManager:1"; public double VERSION { get { return(double.Parse(_S.GetUPnPService().Version)); } } public enum Enum_A_ARG_TYPE_Direction { INPUT, OUTPUT, } public Enum_A_ARG_TYPE_Direction A_ARG_TYPE_Direction { set { string v = ""; switch(value) { case Enum_A_ARG_TYPE_Direction.INPUT: v = "Input"; break; case Enum_A_ARG_TYPE_Direction.OUTPUT: v = "Output"; break; } _S.SetStateVariable("A_ARG_TYPE_Direction",v); } get { Enum_A_ARG_TYPE_Direction RetVal = 0; string v = (string)_S.GetStateVariable("A_ARG_TYPE_Direction"); switch(v) { case "Input": RetVal = Enum_A_ARG_TYPE_Direction.INPUT; break; case "Output": RetVal = Enum_A_ARG_TYPE_Direction.OUTPUT; break; } return(RetVal); } } public enum Enum_A_ARG_TYPE_ConnectionStatus { OK, CONTENTFORMATMISMATCH, INSUFFICIENTBANDWIDTH, UNRELIABLECHANNEL, UNKNOWN, } public Enum_A_ARG_TYPE_ConnectionStatus A_ARG_TYPE_ConnectionStatus { set { string v = ""; switch(value) { case Enum_A_ARG_TYPE_ConnectionStatus.OK: v = "OK"; break; case Enum_A_ARG_TYPE_ConnectionStatus.CONTENTFORMATMISMATCH: v = "ContentFormatMismatch"; break; case Enum_A_ARG_TYPE_ConnectionStatus.INSUFFICIENTBANDWIDTH: v = "InsufficientBandwidth"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNRELIABLECHANNEL: v = "UnreliableChannel"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNKNOWN: v = "Unknown"; break; } _S.SetStateVariable("A_ARG_TYPE_ConnectionStatus",v); } get { Enum_A_ARG_TYPE_ConnectionStatus RetVal = 0; string v = (string)_S.GetStateVariable("A_ARG_TYPE_ConnectionStatus"); switch(v) { case "OK": RetVal = Enum_A_ARG_TYPE_ConnectionStatus.OK; break; case "ContentFormatMismatch": RetVal = Enum_A_ARG_TYPE_ConnectionStatus.CONTENTFORMATMISMATCH; break; case "InsufficientBandwidth": RetVal = Enum_A_ARG_TYPE_ConnectionStatus.INSUFFICIENTBANDWIDTH; break; case "UnreliableChannel": RetVal = Enum_A_ARG_TYPE_ConnectionStatus.UNRELIABLECHANNEL; break; case "Unknown": RetVal = Enum_A_ARG_TYPE_ConnectionStatus.UNKNOWN; break; } return(RetVal); } } static public string Enum_A_ARG_TYPE_Direction_ToString(Enum_A_ARG_TYPE_Direction en) { string RetVal = ""; switch(en) { case Enum_A_ARG_TYPE_Direction.INPUT: RetVal = "Input"; break; case Enum_A_ARG_TYPE_Direction.OUTPUT: RetVal = "Output"; break; } return(RetVal); } static public string[] Values_A_ARG_TYPE_Direction { get { string[] RetVal = new string[2]{"Output","Input"}; return(RetVal); } } static public string Enum_A_ARG_TYPE_ConnectionStatus_ToString(Enum_A_ARG_TYPE_ConnectionStatus en) { string RetVal = ""; switch(en) { case Enum_A_ARG_TYPE_ConnectionStatus.OK: RetVal = "OK"; break; case Enum_A_ARG_TYPE_ConnectionStatus.CONTENTFORMATMISMATCH: RetVal = "ContentFormatMismatch"; break; case Enum_A_ARG_TYPE_ConnectionStatus.INSUFFICIENTBANDWIDTH: RetVal = "InsufficientBandwidth"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNRELIABLECHANNEL: RetVal = "UnreliableChannel"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNKNOWN: RetVal = "Unknown"; break; } return(RetVal); } static public string[] Values_A_ARG_TYPE_ConnectionStatus { get { string[] RetVal = new string[5]{"Unknown","UnreliableChannel","InsufficientBandwidth","ContentFormatMismatch","OK"}; return(RetVal); } } public delegate void OnStateVariableModifiedHandler(DvConnectionManager sender); public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_ConnectionStatus; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_ConnectionID; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_AVTransportID; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_RcsID; public event OnStateVariableModifiedHandler OnStateVariableModified_SourceProtocolInfo; public event OnStateVariableModifiedHandler OnStateVariableModified_SinkProtocolInfo; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_ProtocolInfo; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_ConnectionManager; public event OnStateVariableModifiedHandler OnStateVariableModified_A_ARG_TYPE_Direction; public event OnStateVariableModifiedHandler OnStateVariableModified_CurrentConnectionIDs; public System.Int32 A_ARG_TYPE_ConnectionID { get { return((System.Int32)_S.GetStateVariable("A_ARG_TYPE_ConnectionID")); } set { _S.SetStateVariable("A_ARG_TYPE_ConnectionID", value); } } public System.Int32 A_ARG_TYPE_AVTransportID { get { return((System.Int32)_S.GetStateVariable("A_ARG_TYPE_AVTransportID")); } set { _S.SetStateVariable("A_ARG_TYPE_AVTransportID", value); } } public System.Int32 A_ARG_TYPE_RcsID { get { return((System.Int32)_S.GetStateVariable("A_ARG_TYPE_RcsID")); } set { _S.SetStateVariable("A_ARG_TYPE_RcsID", value); } } public System.String Evented_SourceProtocolInfo { get { return((System.String)_S.GetStateVariable("SourceProtocolInfo")); } set { _S.SetStateVariable("SourceProtocolInfo", value); } } public System.String Evented_SinkProtocolInfo { get { return((System.String)_S.GetStateVariable("SinkProtocolInfo")); } set { _S.SetStateVariable("SinkProtocolInfo", value); } } public System.String A_ARG_TYPE_ProtocolInfo { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_ProtocolInfo")); } set { _S.SetStateVariable("A_ARG_TYPE_ProtocolInfo", value); } } public System.String A_ARG_TYPE_ConnectionManager { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_ConnectionManager")); } set { _S.SetStateVariable("A_ARG_TYPE_ConnectionManager", value); } } public System.String Evented_CurrentConnectionIDs { get { return((System.String)_S.GetStateVariable("CurrentConnectionIDs")); } set { _S.SetStateVariable("CurrentConnectionIDs", value); } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_ConnectionStatus { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_ConnectionStatus { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_ConnectionID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_ConnectionID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_AVTransportID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_AVTransportID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_RcsID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_RcsID { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_SourceProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo")).Accumulator = value; } } public double ModerationDuration_SourceProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_SinkProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo")).Accumulator = value; } } public double ModerationDuration_SinkProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_ProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_ProtocolInfo { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_ConnectionManager { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_ConnectionManager { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_A_ARG_TYPE_Direction { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction")).Accumulator = value; } } public double ModerationDuration_A_ARG_TYPE_Direction { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction")).ModerationPeriod = value; } } public UPnPModeratedStateVariable.IAccumulator Accumulator_CurrentConnectionIDs { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs")).Accumulator); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs")).Accumulator = value; } } public double ModerationDuration_CurrentConnectionIDs { get { return(((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs")).ModerationPeriod); } set { ((UPnPModeratedStateVariable)_S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs")).ModerationPeriod = value; } } public delegate void Delegate_GetCurrentConnectionIDs(out System.String ConnectionIDs); public delegate void Delegate_GetCurrentConnectionInfo(System.Int32 ConnectionID, out System.Int32 RcsID, out System.Int32 AVTransportID, out System.String ProtocolInfo, out System.String PeerConnectionManager, out System.Int32 PeerConnectionID, out DvConnectionManager.Enum_A_ARG_TYPE_Direction Direction, out DvConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus Status); public delegate void Delegate_GetProtocolInfo(out System.String Source, out System.String Sink); public Delegate_GetCurrentConnectionIDs External_GetCurrentConnectionIDs = null; public Delegate_GetCurrentConnectionInfo External_GetCurrentConnectionInfo = null; public Delegate_GetProtocolInfo External_GetProtocolInfo = null; public void RemoveStateVariable_A_ARG_TYPE_ConnectionStatus() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus")); } public void RemoveStateVariable_A_ARG_TYPE_ConnectionID() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID")); } public void RemoveStateVariable_A_ARG_TYPE_AVTransportID() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID")); } public void RemoveStateVariable_A_ARG_TYPE_RcsID() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID")); } public void RemoveStateVariable_SourceProtocolInfo() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo")); } public void RemoveStateVariable_SinkProtocolInfo() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo")); } public void RemoveStateVariable_A_ARG_TYPE_ProtocolInfo() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo")); } public void RemoveStateVariable_A_ARG_TYPE_ConnectionManager() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager")); } public void RemoveStateVariable_A_ARG_TYPE_Direction() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction")); } public void RemoveStateVariable_CurrentConnectionIDs() { _S.GetUPnPService().RemoveStateVariable(_S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs")); } public void RemoveAction_GetCurrentConnectionIDs() { _S.GetUPnPService().RemoveMethod("GetCurrentConnectionIDs"); } public void RemoveAction_GetCurrentConnectionInfo() { _S.GetUPnPService().RemoveMethod("GetCurrentConnectionInfo"); } public void RemoveAction_GetProtocolInfo() { _S.GetUPnPService().RemoveMethod("GetProtocolInfo"); } public System.Net.IPEndPoint GetCaller() { return(_S.GetUPnPService().GetCaller()); } public System.Net.IPEndPoint GetReceiver() { return(_S.GetUPnPService().GetReceiver()); } private class _DvConnectionManager { private DvConnectionManager Outer = null; private UPnPService S; internal _DvConnectionManager(DvConnectionManager n) { Outer = n; S = BuildUPnPService(); } public UPnPService GetUPnPService() { return(S); } public void SetStateVariable(string VarName, object VarValue) { S.SetStateVariable(VarName,VarValue); } public object GetStateVariable(string VarName) { return(S.GetStateVariable(VarName)); } protected UPnPService BuildUPnPService() { UPnPStateVariable[] RetVal = new UPnPStateVariable[10]; RetVal[0] = new UPnPModeratedStateVariable("A_ARG_TYPE_ConnectionStatus", typeof(System.String), false); RetVal[0].AllowedStringValues = new string[5]{"OK", "ContentFormatMismatch", "InsufficientBandwidth", "UnreliableChannel", "Unknown"}; RetVal[0].AddAssociation("GetCurrentConnectionInfo", "Status"); RetVal[1] = new UPnPModeratedStateVariable("A_ARG_TYPE_ConnectionID", typeof(System.Int32), false); RetVal[1].AddAssociation("GetCurrentConnectionInfo", "ConnectionID"); RetVal[1].AddAssociation("GetCurrentConnectionInfo", "PeerConnectionID"); RetVal[2] = new UPnPModeratedStateVariable("A_ARG_TYPE_AVTransportID", typeof(System.Int32), false); RetVal[2].AddAssociation("GetCurrentConnectionInfo", "AVTransportID"); RetVal[3] = new UPnPModeratedStateVariable("A_ARG_TYPE_RcsID", typeof(System.Int32), false); RetVal[3].AddAssociation("GetCurrentConnectionInfo", "RcsID"); RetVal[4] = new UPnPModeratedStateVariable("SourceProtocolInfo", typeof(System.String), true); RetVal[4].AddAssociation("GetProtocolInfo", "Source"); RetVal[5] = new UPnPModeratedStateVariable("SinkProtocolInfo", typeof(System.String), true); RetVal[5].AddAssociation("GetProtocolInfo", "Sink"); RetVal[6] = new UPnPModeratedStateVariable("A_ARG_TYPE_ProtocolInfo", typeof(System.String), false); RetVal[6].AddAssociation("GetCurrentConnectionInfo", "ProtocolInfo"); RetVal[7] = new UPnPModeratedStateVariable("A_ARG_TYPE_ConnectionManager", typeof(System.String), false); RetVal[7].AddAssociation("GetCurrentConnectionInfo", "PeerConnectionManager"); RetVal[8] = new UPnPModeratedStateVariable("A_ARG_TYPE_Direction", typeof(System.String), false); RetVal[8].AllowedStringValues = new string[2]{"Input", "Output"}; RetVal[8].AddAssociation("GetCurrentConnectionInfo", "Direction"); RetVal[9] = new UPnPModeratedStateVariable("CurrentConnectionIDs", typeof(System.String), true); RetVal[9].AddAssociation("GetCurrentConnectionIDs", "ConnectionIDs"); UPnPService S = new UPnPService(1, "urn:upnp-org:serviceId:ConnectionManager", URN, true, this); for(int i=0;i<RetVal.Length;++i) { S.AddStateVariable(RetVal[i]); } S.AddMethod("GetCurrentConnectionIDs"); S.AddMethod("GetCurrentConnectionInfo"); S.AddMethod("GetProtocolInfo"); return(S); } public void GetCurrentConnectionIDs(out System.String ConnectionIDs) { if (Outer.External_GetCurrentConnectionIDs != null) { Outer.External_GetCurrentConnectionIDs(out ConnectionIDs); } else { Sink_GetCurrentConnectionIDs(out ConnectionIDs); } } public void GetCurrentConnectionInfo(System.Int32 ConnectionID, out System.Int32 RcsID, out System.Int32 AVTransportID, out System.String ProtocolInfo, out System.String PeerConnectionManager, out System.Int32 PeerConnectionID, out System.String Direction, out System.String Status) { Enum_A_ARG_TYPE_Direction e_Direction; Enum_A_ARG_TYPE_ConnectionStatus e_Status; if (Outer.External_GetCurrentConnectionInfo != null) { Outer.External_GetCurrentConnectionInfo(ConnectionID, out RcsID, out AVTransportID, out ProtocolInfo, out PeerConnectionManager, out PeerConnectionID, out e_Direction, out e_Status); } else { Sink_GetCurrentConnectionInfo(ConnectionID, out RcsID, out AVTransportID, out ProtocolInfo, out PeerConnectionManager, out PeerConnectionID, out e_Direction, out e_Status); } switch(e_Direction) { case Enum_A_ARG_TYPE_Direction.INPUT: Direction = "Input"; break; case Enum_A_ARG_TYPE_Direction.OUTPUT: Direction = "Output"; break; default: Direction = ""; break; } switch(e_Status) { case Enum_A_ARG_TYPE_ConnectionStatus.OK: Status = "OK"; break; case Enum_A_ARG_TYPE_ConnectionStatus.CONTENTFORMATMISMATCH: Status = "ContentFormatMismatch"; break; case Enum_A_ARG_TYPE_ConnectionStatus.INSUFFICIENTBANDWIDTH: Status = "InsufficientBandwidth"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNRELIABLECHANNEL: Status = "UnreliableChannel"; break; case Enum_A_ARG_TYPE_ConnectionStatus.UNKNOWN: Status = "Unknown"; break; default: Status = ""; break; } } public void GetProtocolInfo(out System.String Source, out System.String Sink) { if (Outer.External_GetProtocolInfo != null) { Outer.External_GetProtocolInfo(out Source, out Sink); } else { Sink_GetProtocolInfo(out Source, out Sink); } } public Delegate_GetCurrentConnectionIDs Sink_GetCurrentConnectionIDs; public Delegate_GetCurrentConnectionInfo Sink_GetCurrentConnectionInfo; public Delegate_GetProtocolInfo Sink_GetProtocolInfo; } public DvConnectionManager() { _S = new _DvConnectionManager(this); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionStatus").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_ConnectionStatus); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionID").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_ConnectionID); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_AVTransportID").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_AVTransportID); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_RcsID").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_RcsID); _S.GetUPnPService().GetStateVariableObject("SourceProtocolInfo").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_SourceProtocolInfo); _S.GetUPnPService().GetStateVariableObject("SinkProtocolInfo").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_SinkProtocolInfo); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ProtocolInfo").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_ProtocolInfo); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_ConnectionManager").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_ConnectionManager); _S.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Direction").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_A_ARG_TYPE_Direction); _S.GetUPnPService().GetStateVariableObject("CurrentConnectionIDs").OnModified += new UPnPStateVariable.ModifiedHandler(OnModifiedSink_CurrentConnectionIDs); _S.Sink_GetCurrentConnectionIDs = new Delegate_GetCurrentConnectionIDs(GetCurrentConnectionIDs); _S.Sink_GetCurrentConnectionInfo = new Delegate_GetCurrentConnectionInfo(GetCurrentConnectionInfo); _S.Sink_GetProtocolInfo = new Delegate_GetProtocolInfo(GetProtocolInfo); } public DvConnectionManager(string ID):this() { _S.GetUPnPService().ServiceID = ID; } public UPnPService GetUPnPService() { return(_S.GetUPnPService()); } private void OnModifiedSink_A_ARG_TYPE_ConnectionStatus(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_ConnectionStatus != null) OnStateVariableModified_A_ARG_TYPE_ConnectionStatus(this); } private void OnModifiedSink_A_ARG_TYPE_ConnectionID(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_ConnectionID != null) OnStateVariableModified_A_ARG_TYPE_ConnectionID(this); } private void OnModifiedSink_A_ARG_TYPE_AVTransportID(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_AVTransportID != null) OnStateVariableModified_A_ARG_TYPE_AVTransportID(this); } private void OnModifiedSink_A_ARG_TYPE_RcsID(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_RcsID != null) OnStateVariableModified_A_ARG_TYPE_RcsID(this); } private void OnModifiedSink_SourceProtocolInfo(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_SourceProtocolInfo != null) OnStateVariableModified_SourceProtocolInfo(this); } private void OnModifiedSink_SinkProtocolInfo(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_SinkProtocolInfo != null) OnStateVariableModified_SinkProtocolInfo(this); } private void OnModifiedSink_A_ARG_TYPE_ProtocolInfo(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_ProtocolInfo != null) OnStateVariableModified_A_ARG_TYPE_ProtocolInfo(this); } private void OnModifiedSink_A_ARG_TYPE_ConnectionManager(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_ConnectionManager != null) OnStateVariableModified_A_ARG_TYPE_ConnectionManager(this); } private void OnModifiedSink_A_ARG_TYPE_Direction(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_A_ARG_TYPE_Direction != null) OnStateVariableModified_A_ARG_TYPE_Direction(this); } private void OnModifiedSink_CurrentConnectionIDs(UPnPStateVariable sender, object NewValue) { if (OnStateVariableModified_CurrentConnectionIDs != null) OnStateVariableModified_CurrentConnectionIDs(this); } //}}}}} End of Code Block #endregion /// <summary> /// Action: GetCurrentConnectionIDs /// </summary> /// <param name="ConnectionIDs">Associated State Variable: CurrentConnectionIDs</param> public void GetCurrentConnectionIDs(out System.String ConnectionIDs) { //ToDo: Add Your implementation here, and remove exception throw(new UPnPCustomException(800,"This method has not been completely implemented...")); } /// <summary> /// Action: GetCurrentConnectionInfo /// </summary> /// <param name="ConnectionID">Associated State Variable: A_ARG_TYPE_ConnectionID</param> /// <param name="RcsID">Associated State Variable: A_ARG_TYPE_RcsID</param> /// <param name="AVTransportID">Associated State Variable: A_ARG_TYPE_AVTransportID</param> /// <param name="ProtocolInfo">Associated State Variable: A_ARG_TYPE_ProtocolInfo</param> /// <param name="PeerConnectionManager">Associated State Variable: A_ARG_TYPE_ConnectionManager</param> /// <param name="PeerConnectionID">Associated State Variable: A_ARG_TYPE_ConnectionID</param> /// <param name="Direction">Associated State Variable: A_ARG_TYPE_Direction</param> /// <param name="Status">Associated State Variable: A_ARG_TYPE_ConnectionStatus</param> public void GetCurrentConnectionInfo(System.Int32 ConnectionID, out System.Int32 RcsID, out System.Int32 AVTransportID, out System.String ProtocolInfo, out System.String PeerConnectionManager, out System.Int32 PeerConnectionID, out Enum_A_ARG_TYPE_Direction Direction, out Enum_A_ARG_TYPE_ConnectionStatus Status) { //ToDo: Add Your implementation here, and remove exception throw(new UPnPCustomException(800,"This method has not been completely implemented...")); } /// <summary> /// Action: GetProtocolInfo /// </summary> /// <param name="Source">Associated State Variable: SourceProtocolInfo</param> /// <param name="Sink">Associated State Variable: SinkProtocolInfo</param> public void GetProtocolInfo(out System.String Source, out System.String Sink) { //ToDo: Add Your implementation here, and remove exception throw(new UPnPCustomException(800,"This method has not been completely implemented...")); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AngularUI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using Bloom.Api; using Bloom.Book; using Bloom.TeamCollection; using Bloom.MiscUI; using Bloom.web; using Bloom.web.controllers; using Gecko; using MarkdownDeep; using SIL.IO; namespace Bloom.CollectionTab { /// <summary> /// this is an un-editable preview of a book in the library; either vernacular or template /// </summary> public partial class LibraryBookView : UserControl { private readonly BookSelection _bookSelection; //private readonly SendReceiver _sendReceiver; private readonly CreateFromSourceBookCommand _createFromSourceBookCommand; private readonly EditBookCommand _editBookCommand; private Shell _shell; private bool _reshowPending = false; private bool _visible; private BloomWebSocketServer _webSocketServer; public TeamCollectionManager TeamCollectionMgr { get; internal set; } public delegate LibraryBookView Factory();//autofac uses this public LibraryBookView(BookSelection bookSelection, //SendReceiver sendReceiver, CreateFromSourceBookCommand createFromSourceBookCommand, EditBookCommand editBookCommand, SelectedTabChangedEvent selectedTabChangedEvent, SelectedTabAboutToChangeEvent selectedTabAboutToChangeEvent, BloomWebSocketServer webSocketServer, LocalizationChangedEvent localizationChangedEvent) { InitializeComponent(); _bookSelection = bookSelection; //_sendReceiver = sendReceiver; _createFromSourceBookCommand = createFromSourceBookCommand; _editBookCommand = editBookCommand; _webSocketServer = webSocketServer; if (!Bloom.CLI.UploadCommand.IsUploading) bookSelection.SelectionChanged += OnBookSelectionChanged; selectedTabAboutToChangeEvent.Subscribe(c => { if (!(c.To is ReactCollectionTabView)) { // We're becoming invisible. Stop any work in progress to generate a preview // (thus allowing other browsers, like the ones in the Edit view, to navigate // to their destinations.) HidePreview(); } }); selectedTabChangedEvent.Subscribe(c => { var wasVisible = _visible; _visible = c.To is ReactCollectionTabView; if (_reshowPending || wasVisible != _visible) { ShowBook(); } }); _reactBookPreviewControl.SetLocalizationChangedEvent(localizationChangedEvent); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); LoadBook(); } private void UpdateTitleBar() { if (this.ParentForm != null) { _shell = (Shell)this.ParentForm; } if (_shell != null) { _shell.SetWindowText((_bookSelection.CurrentSelection == null) ? null : _bookSelection.CurrentSelection.NameBestForUserDisplay); } } void OnBookSelectionChanged(object sender, BookSelectionChangedEventArgs args) { try { // If we just created this book and are right about to switch to edit mode, // we don't need to update the preview. Not doing so prevents situations where // the page expires before we display it properly (somehow...BL-4856) and // also just saves time. LoadBook(!args.AboutToEdit); UpdateTitleBar(); } catch (Exception error) { var msg = L10NSharp.LocalizationManager.GetString("Errors.ErrorSelecting", "There was a problem selecting the book. Restarting Bloom may fix the problem. If not, please report the problem to us."); SIL.Reporting.ErrorReport.NotifyUserOfProblem(error, msg); } } private void LoadBook(bool updatePreview = true) { ShowBook(updatePreview); if (_bookSelection.CurrentSelection != null) { _bookSelection.CurrentSelection.ContentsChanged += new EventHandler(CurrentSelection_ContentsChanged); } } void CurrentSelection_ContentsChanged(object sender, EventArgs e) { if(_visible) ShowBook(); else { _reshowPending = true; } UpdateTitleBar(); } private object _pendingPreviewProps; private void ShowBook(bool updatePreview = true) { if (IsDisposed) return; // typically because we're using the new collection tab, but unfortunately hooked this event up when constructed. if (_bookSelection.CurrentSelection == null || !_visible) { HidePreview(); } else { Debug.WriteLine("LibraryBookView.ShowBook() currentselection ok"); _readmeBrowser.Visible = false; _splitContainerForPreviewAndAboutBrowsers.Visible = true; if (updatePreview && !TroubleShooterDialog.SuppressBookPreview) { var previewDom = _bookSelection.CurrentSelection.GetPreviewHtmlFileForWholeBook(); XmlHtmlConverter.MakeXmlishTagsSafeForInterpretationAsHtml(previewDom.RawDom); var fakeTempFile = BloomServer.MakeSimulatedPageFileInBookFolder(previewDom, setAsCurrentPageForDebugging: false, source: BloomServer.SimulatedPageFileSource.Preview); Application.Idle += UpdatePreview; _pendingPreviewProps = new { initialBookPreviewUrl = fakeTempFile.Key }; // need this for initial selection // We need this for changing selection's book info display if team collection. _webSocketServer.SendEvent("bookContent", "reload"); _reactBookPreviewControl.Visible = true; RecordAndCleanupFakeFiles(fakeTempFile); } _splitContainerForPreviewAndAboutBrowsers.Panel2Collapsed = true; if (_bookSelection.CurrentSelection.HasAboutBookInformationToShow) { if (RobustFile.Exists(_bookSelection.CurrentSelection.AboutBookHtmlPath)) { _splitContainerForPreviewAndAboutBrowsers.Panel2Collapsed = false; _readmeBrowser.Navigate(_bookSelection.CurrentSelection.AboutBookHtmlPath.ToLocalhost(), false); _readmeBrowser.Visible = true; } else if (RobustFile.Exists(_bookSelection.CurrentSelection.AboutBookMdPath)) { _splitContainerForPreviewAndAboutBrowsers.Panel2Collapsed = false; var md = new Markdown(); var contents = RobustFile.ReadAllText(_bookSelection.CurrentSelection.AboutBookMdPath); _readmeBrowser.NavigateRawHtml( string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", md.Transform(contents))); _readmeBrowser.Visible = true; } } _reshowPending = false; } } private void UpdatePreview(object sender, EventArgs e) { Application.Idle -= UpdatePreview; _reactBookPreviewControl.Props = _pendingPreviewProps; } SimulatedPageFile _previousPageFile; /// <summary> /// Remember the current fake file (stored in memory) after first cleaning up (removing) any /// previous fake file. This prevents memory use from increasing for each book previewed. /// </summary> private void RecordAndCleanupFakeFiles(SimulatedPageFile fakeTempFile) { _previousPageFile?.Dispose(); _previousPageFile = fakeTempFile; } private void HidePreview() { _reactBookPreviewControl.Visible = false; _splitContainerForPreviewAndAboutBrowsers.Visible = false; BackColor = Palette.GeneralBackground; // NB: this color is only seen in a flash before browser loads } private void LibraryBookView_Resize(object sender, EventArgs e) { } private void _readmeBrowser_OnBrowserClick(object sender, EventArgs e) { var ge = e as DomEventArgs; var target = (GeckoHtmlElement)ge.Target.CastToGeckoElement(); var anchor = target as Gecko.DOM.GeckoAnchorElement; var href = GetAnchorHref(e); if (href != "" && href != "#") { _readmeBrowser.HandleLinkClick(anchor, ge, _bookSelection.CurrentSelection.FolderPath); } else { // If there's no href, then we are probably doing a 'fetch' to a bloom/api link to produce // some side effect. If we don't mark the event as handled here, geckofx will continue trying // to handle it and possibly produce a Network Error. ge.Handled = true; } } /// <summary> /// Support the "Report a Problem" button when it shows up in the preview window as part of /// a page reporting that we can't open the book for some reason. /// </summary> private void _previewBrowser_OnBrowserClick(object sender, EventArgs e) { if (GetAnchorHref(e).EndsWith("ReportProblem")) { ProblemReportApi.ShowProblemDialog(_reactBookPreviewControl, null, "", "nonfatal"); } } private static string GetAnchorHref(EventArgs e) { var element = (GeckoHtmlElement) (e as DomEventArgs).Target.CastToGeckoElement(); //nb: it might not be an actual anchor; could be an input-button that we've stuck href on return element == null ? "" : element.GetAttribute("href") ?? ""; } private void _splitContainerForPreviewAndAboutBrowsers_SplitterMoved(object sender, SplitterEventArgs e) { _readmeBrowser.Refresh(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFeedItemSetLinkServiceClientTest { [Category("Autogenerated")][Test] public void GetFeedItemSetLinkRequestObject() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink response = client.GetFeedItemSetLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedItemSetLinkRequestObjectAsync() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSetLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink responseCallSettings = await client.GetFeedItemSetLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedItemSetLink responseCancellationToken = await client.GetFeedItemSetLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetFeedItemSetLink() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink response = client.GetFeedItemSetLink(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedItemSetLinkAsync() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSetLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink responseCallSettings = await client.GetFeedItemSetLinkAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedItemSetLink responseCancellationToken = await client.GetFeedItemSetLinkAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetFeedItemSetLinkResourceNames() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink response = client.GetFeedItemSetLink(request.ResourceNameAsFeedItemSetLinkName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedItemSetLinkResourceNamesAsync() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); GetFeedItemSetLinkRequest request = new GetFeedItemSetLinkRequest { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), }; gagvr::FeedItemSetLink expectedResponse = new gagvr::FeedItemSetLink { ResourceNameAsFeedItemSetLinkName = gagvr::FeedItemSetLinkName.FromCustomerFeedFeedItemSetFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]", "[FEED_ITEM_ID]"), FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"), FeedItemSetAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedItemSetLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSetLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::FeedItemSetLink responseCallSettings = await client.GetFeedItemSetLinkAsync(request.ResourceNameAsFeedItemSetLinkName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::FeedItemSetLink responseCancellationToken = await client.GetFeedItemSetLinkAsync(request.ResourceNameAsFeedItemSetLinkName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateFeedItemSetLinksRequestObject() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); MutateFeedItemSetLinksRequest request = new MutateFeedItemSetLinksRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedItemSetLinkOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateFeedItemSetLinksResponse expectedResponse = new MutateFeedItemSetLinksResponse { Results = { new MutateFeedItemSetLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateFeedItemSetLinks(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); MutateFeedItemSetLinksResponse response = client.MutateFeedItemSetLinks(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateFeedItemSetLinksRequestObjectAsync() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); MutateFeedItemSetLinksRequest request = new MutateFeedItemSetLinksRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedItemSetLinkOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateFeedItemSetLinksResponse expectedResponse = new MutateFeedItemSetLinksResponse { Results = { new MutateFeedItemSetLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateFeedItemSetLinksAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemSetLinksResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); MutateFeedItemSetLinksResponse responseCallSettings = await client.MutateFeedItemSetLinksAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateFeedItemSetLinksResponse responseCancellationToken = await client.MutateFeedItemSetLinksAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateFeedItemSetLinks() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); MutateFeedItemSetLinksRequest request = new MutateFeedItemSetLinksRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedItemSetLinkOperation(), }, }; MutateFeedItemSetLinksResponse expectedResponse = new MutateFeedItemSetLinksResponse { Results = { new MutateFeedItemSetLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateFeedItemSetLinks(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); MutateFeedItemSetLinksResponse response = client.MutateFeedItemSetLinks(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateFeedItemSetLinksAsync() { moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetLinkService.FeedItemSetLinkServiceClient>(moq::MockBehavior.Strict); MutateFeedItemSetLinksRequest request = new MutateFeedItemSetLinksRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedItemSetLinkOperation(), }, }; MutateFeedItemSetLinksResponse expectedResponse = new MutateFeedItemSetLinksResponse { Results = { new MutateFeedItemSetLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateFeedItemSetLinksAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemSetLinksResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedItemSetLinkServiceClient client = new FeedItemSetLinkServiceClientImpl(mockGrpcClient.Object, null); MutateFeedItemSetLinksResponse responseCallSettings = await client.MutateFeedItemSetLinksAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateFeedItemSetLinksResponse responseCancellationToken = await client.MutateFeedItemSetLinksAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#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.Text; using System.Data.SqlTypes; using System.IO; using System.Text.RegularExpressions; using SoftLogik.Miscellaneous; namespace SoftLogik.Text { public static class StringUtils { public const string CarriageReturnLineFeed = "\r\n"; public const string Empty = ""; public const char CarriageReturn = '\r'; public const char LineFeed = '\n'; public const char Tab = '\t'; /// <summary> /// Determines whether the string contains white space. /// </summary> /// <param name="s">The string to test for white space.</param> /// <returns> /// <c>true</c> if the string contains white space; otherwise, <c>false</c>. /// </returns> public static bool ContainsWhiteSpace(string s) { if (s == null) throw new ArgumentNullException("s"); for (int i = 0; i < s.Length; i++) { if (char.IsWhiteSpace(s[i])) return true; } return false; } /// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="s">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool IsWhiteSpace(string s) { if (s == null) throw new ArgumentNullException("s"); if (s.Length == 0) return false; for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) return false; } return true; } /// <summary> /// Ensures the target string ends with the specified string. /// </summary> /// <param name="target">The target.</param> /// <param name="value">The value.</param> /// <returns>The target string with the value string at the end.</returns> public static string EnsureEndsWith(string target, string value) { if (target == null) throw new ArgumentNullException("target"); if (value == null) throw new ArgumentNullException("value"); if (target.Length >= value.Length) { if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) == 0) return target; string trimmedString = target.TrimEnd(null); if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) == 0) return target; } return target + value; } /// <summary> /// Determines whether the SqlString is null or empty. /// </summary> /// <param name="s">The string.</param> /// <returns> /// <c>true</c> if the SqlString is null or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty(SqlString s) { if (s.IsNull) return true; else return string.IsNullOrEmpty(s.Value); } /// <summary> /// Determines whether the given string is null or empty or whitespace. /// </summary> /// <param name="s">The s.</param> /// <returns> /// <c>true</c> if the given string is null or empty or whitespace; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmptyOrWhiteSpace(string s) { if (string.IsNullOrEmpty(s)) return true; else if (IsWhiteSpace(s)) return true; else return false; } /// <summary> /// Indents the specified string. /// </summary> /// <param name="s">The string to indent.</param> /// <param name="indentation">The number of characters to indent by.</param> /// <returns></returns> public static string Indent(string s, int indentation) { return Indent(s, indentation, ' '); } /// <summary> /// Indents the specified string. /// </summary> /// <param name="s">The string to indent.</param> /// <param name="indentation">The number of characters to indent by.</param> /// <param name="indentChar">The indent character.</param> /// <returns></returns> public static string Indent(string s, int indentation, char indentChar) { if (s == null) throw new ArgumentNullException("s"); if (indentation <= 0) throw new ArgumentException("Must be greater than zero.", "indentation"); StringReader sr = new StringReader(s); StringWriter sw = new StringWriter(); ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) { tw.Write(new string(indentChar, indentation)); tw.Write(line); }); return sw.ToString(); } private delegate void ActionLine(TextWriter textWriter, string line); private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction) { string line; bool firstLine = true; while ((line = textReader.ReadLine()) != null) { if (!firstLine) textWriter.WriteLine(); else firstLine = false; lineAction(textWriter, line); } } /// <summary> /// Numbers the lines. /// </summary> /// <param name="s">The string to number.</param> /// <returns></returns> public static string NumberLines(string s) { if (s == null) throw new ArgumentNullException("s"); StringReader sr = new StringReader(s); StringWriter sw = new StringWriter(); int lineNumber = 1; ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) { tw.Write(lineNumber.ToString().PadLeft(4)); tw.Write(". "); tw.Write(line); lineNumber++; }); return sw.ToString(); } /// <summary> /// Nulls an empty string. /// </summary> /// <param name="s">The string.</param> /// <returns>Null if the string was null, otherwise the string unchanged.</returns> public static string NullEmptyString(string s) { return (string.IsNullOrEmpty(s)) ? null : s; } /// <summary> /// Replaces the new lines in a string with the given replacement characters. /// </summary> /// <param name="s">The string to replace new lines in.</param> /// <param name="replacement">The replacement characters.</param> /// <returns></returns> public static string ReplaceNewLines(string s, string replacement) { StringReader sr = new StringReader(s); StringBuilder sb = new StringBuilder(); bool first = true; string line; while ((line = sr.ReadLine()) != null) { if (first) first = false; else sb.Append(replacement); sb.Append(line); } return sb.ToString(); } public static string RemoveHtml(string s) { return RemoveHtmlInternal(s, null); } public static string RemoveHtml(string s, IList<string> removeTags) { if (removeTags == null) throw new ArgumentNullException("removeTags"); return RemoveHtmlInternal(s, removeTags); } private static string RemoveHtmlInternal(string s, IList<string> removeTags) { List<string> removeTagsUpper = null; if (removeTags != null) { removeTagsUpper = new List<string>(removeTags.Count); foreach (string tag in removeTags) { removeTagsUpper.Add(tag.ToUpperInvariant()); } } Regex anyTag = new Regex(@"<[/]{0,1}\s*(?<tag>\w*)\s*(?<attr>.*?=['""].*?[""'])*?\s*[/]{0,1}>", RegexOptions.Compiled); return anyTag.Replace(s, delegate(Match match) { string tag = match.Groups["tag"].Value.ToUpperInvariant(); if (removeTagsUpper == null) return string.Empty; else if (removeTagsUpper.Contains(tag)) return string.Empty; else return match.Value; }); } /// <summary> /// Truncates the specified string. /// </summary> /// <param name="s">The string to truncate.</param> /// <param name="maximumLength">The maximum length of the string before it is truncated.</param> /// <returns></returns> public static string Truncate(string s, int maximumLength) { return Truncate(s, maximumLength, "..."); } /// <summary> /// Truncates the specified string. /// </summary> /// <param name="s">The string to truncate.</param> /// <param name="maximumLength">The maximum length of the string before it is truncated.</param> /// <param name="suffix">The suffix to place at the end of the truncated string.</param> /// <returns></returns> public static string Truncate(string s, int maximumLength, string suffix) { if (suffix == null) throw new ArgumentNullException("suffix"); if (maximumLength <= 0) throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength"); int subStringLength = maximumLength - suffix.Length; if (subStringLength <= 0) throw new ArgumentException("Length of suffix string is greater or equal to maximumLength"); if (s != null && s.Length > maximumLength) { string truncatedString = s.Substring(0, subStringLength); // incase the last character is a space truncatedString = truncatedString.TrimEnd(); truncatedString += suffix; return truncatedString; } else { return s; } } /// <summary> /// Creates a StringWriter with the specified capacity. /// </summary> /// <param name="capacity">The capacity of the StringWriter.</param> /// <returns></returns> public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); StringWriter sw = new StringWriter(sb); return sw; } /// <summary> /// Gets the length of a string, returning null if the string is null. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static int? GetLength(string value) { if (value == null) return null; else return value.Length; } /// <summary> /// Returns the specified char's unicode string. /// </summary> /// <param name="c">The c.</param> /// <returns></returns> public static string ToCharAsUnicode(char c) { using (StringWriter w = new StringWriter()) { WriteCharAsUnicode(w, c); return w.ToString(); } } /// <summary> /// Writes the specified char's unicode string to a TextWriter. /// </summary> /// <param name="writer">The writer.</param> /// <param name="c">The c.</param> public static void WriteCharAsUnicode(TextWriter writer, char c) { ValidationUtils.ArgumentNotNull(writer, "writer"); char h1 = MathUtils.IntToHex((c >> 12) & '\x000f'); char h2 = MathUtils.IntToHex((c >> 8) & '\x000f'); char h3 = MathUtils.IntToHex((c >> 4) & '\x000f'); char h4 = MathUtils.IntToHex(c & '\x000f'); writer.Write('\\'); writer.Write('u'); writer.Write(h1); writer.Write(h2); writer.Write(h3); writer.Write(h4); } } }
using System; using System.Collections.Generic; using System.Linq; using NGraphics.Codes; using NGraphics.Interfaces; using NGraphics.Models; using NGraphics.Models.Brushes; using NGraphics.Models.Elements; using NGraphics.Models.Operations; using NGraphics.Models.Transforms; namespace NGraphics { public interface ICanvas { void SaveState(); void Transform(Transform transform); void RestoreState(); void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, BaseBrush brush = null); void DrawPath(IEnumerable<PathOperation> ops, Pen pen = null, BaseBrush brush = null); void DrawRectangle(Rect frame, Pen pen = null, BaseBrush brush = null); void DrawEllipse(Rect frame, Pen pen = null, BaseBrush brush = null); void DrawImage(IImage image, Rect frame, double alpha = 1.0); } public static class CanvasEx { public static void Translate(this ICanvas canvas, double dx, double dy) { canvas.Transform(Transform.Translate(dx, dy)); } public static void Translate(this ICanvas canvas, Size translation) { canvas.Transform(Transform.Translate(translation)); } public static void Translate(this ICanvas canvas, Point translation) { canvas.Transform(Transform.Translate(translation)); } /// <summary> /// Rotate the specified canvas by the given angle (in degrees). /// </summary> /// <param name="angle">Angle in degrees.</param> public static void Rotate(this ICanvas canvas, double angle) { if (angle != 0) { canvas.Transform(Transform.Rotate(angle)); } } /// <param name="angle">Angle in degrees.</param> public static void Rotate(this ICanvas canvas, double angle, Point point) { if (angle != 0) { canvas.Translate(point); canvas.Rotate(angle); canvas.Translate(-point); } } /// <param name="angle">Angle in degrees.</param> public static void Rotate(this ICanvas canvas, double angle, double x, double y) { if (angle != 0) { canvas.Rotate(angle, new Point(x, y)); } } public static void Scale(this ICanvas canvas, double sx, double sy) { if (sx != 1 || sy != 1) { canvas.Transform(Transform.Scale(sx, sy)); } } public static void Scale(this ICanvas canvas, double scale) { if (scale != 1) { canvas.Transform(Transform.Scale(scale, scale)); } } public static void Scale(this ICanvas canvas, Size scale) { if (scale.Width != 1 || scale.Height != 1) { canvas.Transform(Transform.Scale(scale)); } } public static void Scale(this ICanvas canvas, Size scale, Point point) { if (scale.Width != 1 || scale.Height != 1) { canvas.Translate(point); canvas.Scale(scale); canvas.Translate(-point); } } public static void Scale(this ICanvas canvas, double scale, Point point) { if (scale != 1) { canvas.Scale(new Size(scale), point); } } public static void Scale(this ICanvas canvas, double sx, double sy, double x, double y) { if (sx != 1 || sy != 1) { canvas.Scale(new Size(sx, sy), new Point(x, y)); } } public static void Scale(this ICanvas canvas, double scale, double x, double y) { if (scale != 1) { canvas.Scale(new Size(scale), new Point(x, y)); } } public static void DrawRectangle(this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, BaseBrush brush = null) { canvas.DrawRectangle(new Rect(x, y, width, height), pen, brush); } public static void DrawRectangle(this ICanvas canvas, Point position, Size size, Pen pen = null, BaseBrush brush = null) { canvas.DrawRectangle(new Rect(position, size), pen, brush); } public static void FillRectangle(this ICanvas canvas, Rect frame, Color color) { canvas.DrawRectangle(frame, brush: new SolidBrush(color)); } public static void FillRectangle(this ICanvas canvas, double x, double y, double width, double height, Color color) { canvas.DrawRectangle(new Rect(x, y, width, height), brush: new SolidBrush(color)); } public static void FillRectangle(this ICanvas canvas, double x, double y, double width, double height, BaseBrush brush) { canvas.DrawRectangle(new Rect(x, y, width, height), brush: brush); } public static void FillRectangle(this ICanvas canvas, Rect frame, BaseBrush brush) { canvas.DrawRectangle(frame, brush: brush); } public static void StrokeRectangle(this ICanvas canvas, Rect frame, Color color, double width = 1.0) { canvas.DrawRectangle(frame, pen: new Pen(color, width)); } public static void DrawEllipse(this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, BaseBrush brush = null) { canvas.DrawEllipse(new Rect(x, y, width, height), pen, brush); } public static void DrawEllipse(this ICanvas canvas, Point position, Size size, Pen pen = null, BaseBrush brush = null) { canvas.DrawEllipse(new Rect(position, size), pen, brush); } public static void FillEllipse(this ICanvas canvas, Point position, Size size, BaseBrush brush) { canvas.DrawEllipse(new Rect(position, size), null, brush); } public static void FillEllipse(this ICanvas canvas, Point position, Size size, Color color) { canvas.DrawEllipse(new Rect(position, size), null, new SolidBrush(color)); } public static void FillEllipse(this ICanvas canvas, double x, double y, double width, double height, Color color) { canvas.DrawEllipse(new Rect(x, y, width, height), brush: new SolidBrush(color)); } public static void FillEllipse(this ICanvas canvas, double x, double y, double width, double height, BaseBrush brush) { canvas.DrawEllipse(new Rect(x, y, width, height), brush: brush); } public static void FillEllipse(this ICanvas canvas, Rect frame, Color color) { canvas.DrawEllipse(frame, brush: new SolidBrush(color)); } public static void FillEllipse(this ICanvas canvas, Rect frame, BaseBrush brush) { canvas.DrawEllipse(frame, brush: brush); } public static void StrokeEllipse(this ICanvas canvas, Rect frame, Color color, double width = 1.0) { canvas.DrawEllipse(frame, pen: new Pen(color, width)); } public static void StrokeEllipse(this ICanvas canvas, Point position, Size size, Color color, double width = 1.0) { canvas.DrawEllipse(new Rect(position, size), new Pen(color, width), null); } public static void DrawPath(this ICanvas canvas, Action<Path> draw, Pen pen = null, BaseBrush brush = null) { var p = new Path(pen, brush); draw(p); p.Draw(canvas); } public static void FillPath(this ICanvas canvas, IEnumerable<PathOperation> ops, BaseBrush brush) { canvas.DrawPath(ops, brush: brush); } public static void FillPath(this ICanvas canvas, IEnumerable<PathOperation> ops, Color color) { canvas.DrawPath(ops, brush: new SolidBrush(color)); } public static void FillPath(this ICanvas canvas, Action<Path> draw, BaseBrush brush) { var p = new Path(null, brush); draw(p); p.Draw(canvas); } public static void FillPath(this ICanvas canvas, Action<Path> draw, Color color) { FillPath(canvas, draw, new SolidBrush(color)); } public static void DrawLine(this ICanvas canvas, Point start, Point end, Pen pen) { var p = new Path { Pen = pen }; p.MoveTo(start,false); p.LineTo(end); p.Draw(canvas); } public static void DrawLine(this ICanvas canvas, Point start, Point end, Color color, double width = 1.0) { var p = new Path { Pen = new Pen(color, width) }; p.MoveTo(start, false); p.LineTo(end); p.Draw(canvas); } public static void DrawLine(this ICanvas canvas, double x1, double y1, double x2, double y2, Color color, double width = 1.0) { var p = new Path { Pen = new Pen(color, width) }; p.MoveTo(x1, y1,false); p.LineTo(x2, y2,false); p.Draw(canvas); } public static void DrawImage(this ICanvas canvas, IImage image) { canvas.DrawImage(image, new Rect(image.Size)); } public static void DrawImage(this ICanvas canvas, IImage image, double x, double y, double width, double height, double alpha = 1.0) { canvas.DrawImage(image, new Rect(x, y, width, height), alpha); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Web; using NUnit.Framework; using Rhino.Mocks; namespace Talifun.Web.Tests.Http { [TestFixture] public class HttpRequestHeaderHelperTests { #region GetHttpHeaderValue [Test] public void GetHttpHeaderValue_HttpRequestHeaderFound_HeaderValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "Unknown User Agent"; var headerValue = "Talifun Browser"; var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerType, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(headerValue, userAgentValue); } [Test] public void GetHttpHeaderValue_HttpRequestHeaderNotFound_DefaultValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "Unknown User Agent"; var headerValue = string.Empty; //means that header was not set var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerType, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(headerDefaultValue, userAgentValue); } [Test] public void GetHttpHeaderValue_HttpRequestHeaderStringFound_HeaderValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "Unknown User Agent"; var headerValue = "Talifun Browser"; var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerName, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(headerValue, userAgentValue); } [Test] public void GetHttpHeaderValue_HttpRequestHeaderStringNotFound_DefaultValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "Unknown User Agent"; var headerValue = string.Empty; var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerName, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(headerDefaultValue, userAgentValue); } [Test] public void GetHttpHeaderValue_HttpRequestHeaderQuotedStringFound_HeaderValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "Unknown User Agent"; var userAgent = "Talifun Browser"; var headerValue = "\"" + userAgent + "\""; var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerName, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(userAgent, userAgentValue); } [Test] public void GetHttpHeaderValue_IsCaseSensitive_HeaderValue() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerDefaultValue = "abcdef"; var headerValue = "abcdeF"; var headerType = HttpRequestHeader.UserAgent; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var userAgentValue = httpRequestHeaderHelper.GetHttpHeaderValue(httpRequest, headerName, headerDefaultValue); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(headerValue, userAgentValue); } #endregion #region GetHttpHeaderValues [Test] public void GetHttpHeaderValues_NoHttpHeaderQValues_EmptyList() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = string.Empty; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.IsEmpty(headerValues); } [Test] public void GetHttpHeaderValues_HttpHeaderWithOneValueSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "1234567"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(1, headerValues.Count); Assert.AreEqual(headerValue.ToLowerInvariant(), headerValues[0]); } [Test] public void GetHttpHeaderValues_MultipleHttpHeaderValuesSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "gzip"; var identity2 = "deflate"; var headerValue = identity1 + "," + identity2; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValues.Count); Assert.AreEqual(identity1, headerValues[0]); Assert.AreEqual(identity2, headerValues[1]); } [Test] public void GetHttpHeaderValues_MultipleHttpHeaderWithValuesSetWithSpacing_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "gzip"; var identity2 = "deflate"; var headerValue = identity1 + " , " + identity2; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValues.Count); Assert.AreEqual(identity1, headerValues[0]); Assert.AreEqual(identity2, headerValues[1]); } [Test] public void GetHttpHeaderValues_MultipleHttpHeaderWithQuotedValuesSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "deflate"; var identity2 = "gzip, hello"; var headerValue = identity1 + " , \"" + identity2 + "\""; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValues.Count); Assert.AreEqual(identity1, headerValues[0]); Assert.AreEqual(identity2, headerValues[1]); } [Test] public void GetHttpHeaderValues_IsCaseSensitive_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "abcdeF"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValues = httpRequestHeaderHelper.GetHttpHeaderValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(1, headerValues.Count); Assert.AreEqual(headerValue, headerValues[0]); } #endregion #region GetHttpHeaderWithQValues [Test] public void GetHttpHeaderWithQValues_NoHttpHeaderQValues_EmptyList() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = string.Empty; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.IsEmpty(headerValueWithQValues); } [Test] public void GetHttpHeaderWithQValues_HttpHeaderWithNoQValueSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "gzip"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(1, headerValueWithQValues.Count); Assert.AreEqual(headerValue.ToLowerInvariant(), headerValueWithQValues[0].Identity); Assert.IsNull(headerValueWithQValues[0].QValue); } [Test] public void GetHttpHeaderWithQValues_HttpHeaderWithQValueSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity = "gzip"; var qValue = 0.5f; var headerValue = identity + ";q=" + qValue.ToString("N1"); var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(1, headerValueWithQValues.Count); Assert.AreEqual(identity, headerValueWithQValues[0].Identity); Assert.IsNotNull(headerValueWithQValues[0].QValue); Assert.AreEqual(qValue, headerValueWithQValues[0].QValue.Value); } [Test] public void GetHttpHeaderWithQValues_MultipleHttpHeaderWithQValueSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "gzip"; var qValue1 = 0.5f; var identity2 = "deflate"; var qValue2 = 0.8f; var headerValue = identity1 + ";q=" + qValue1.ToString("N1") + "," + identity2 + ";q=" + qValue2.ToString("N1"); var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValueWithQValues.Count); Assert.AreEqual(identity1, headerValueWithQValues[0].Identity); Assert.IsNotNull(headerValueWithQValues[0].QValue); Assert.AreEqual(qValue1, headerValueWithQValues[0].QValue.Value); Assert.AreEqual(identity2, headerValueWithQValues[1].Identity); Assert.IsNotNull(headerValueWithQValues[1].QValue); Assert.AreEqual(qValue2, headerValueWithQValues[1].QValue.Value); } [Test] public void GetHttpHeaderWithQValues_MultipleHttpHeaderWithQValueSetWithSpacing_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "gzip"; var qValue1 = 0.5f; var identity2 = "deflate"; var qValue2 = 0.8f; var headerValue = identity1 + " ; q = " + qValue1.ToString("N1") + " , " + identity2 + "; q=" + qValue2.ToString("N1"); var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValueWithQValues.Count); Assert.AreEqual(identity1, headerValueWithQValues[0].Identity); Assert.IsNotNull(headerValueWithQValues[0].QValue); Assert.AreEqual(qValue1, headerValueWithQValues[0].QValue.Value); Assert.AreEqual(identity2, headerValueWithQValues[1].Identity); Assert.IsNotNull(headerValueWithQValues[1].QValue); Assert.AreEqual(qValue2, headerValueWithQValues[1].QValue.Value); } [Test] public void GetHttpHeaderWithQValues_MultipleHttpHeaderWithQuotedQValueSet_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var identity1 = "gzip"; var qValue1 = 0.5f; var identity2 = "deflate, test"; var qValue2 = 0.8f; var headerValue = identity1 + ";q=" + qValue1.ToString("N1") + ",\"" + identity2 + "\";q=" + qValue2.ToString("N1"); var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(2, headerValueWithQValues.Count); Assert.AreEqual(identity1, headerValueWithQValues[0].Identity); Assert.IsNotNull(headerValueWithQValues[0].QValue); Assert.AreEqual(qValue1, headerValueWithQValues[0].QValue.Value); Assert.AreEqual(identity2, headerValueWithQValues[1].Identity); Assert.IsNotNull(headerValueWithQValues[1].QValue); Assert.AreEqual(qValue2, headerValueWithQValues[1].QValue.Value); } [Test] public void GetHttpHeaderWithQValues_IsCaseSensitive_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "abcdeF"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(1, headerValueWithQValues.Count); Assert.AreEqual(headerValue, headerValueWithQValues[0].Identity); Assert.IsNull(headerValueWithQValues[0].QValue); } [Test] public void GetHttpHeaderWithQValues_InvalidQValueDoubleEquals_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "gzip, deflate, x-gzip, identity; q==0.5"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(5, headerValueWithQValues.Count); Assert.AreEqual("identity", headerValueWithQValues[3].Identity); Assert.IsNull(headerValueWithQValues[3].QValue); Assert.AreEqual("q==0.5", headerValueWithQValues[4].Identity); Assert.IsNull(headerValueWithQValues[4].QValue); } [Test] public void GetHttpHeaderWithQValues_InvalidQValueNotANumber_List() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "gzip, deflate, x-gzip, identity; q=moo"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var headerValueWithQValues = httpRequestHeaderHelper.GetHttpHeaderWithQValues(httpRequest, headerType); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(5, headerValueWithQValues.Count); Assert.AreEqual("identity", headerValueWithQValues[3].Identity); Assert.IsNull(headerValueWithQValues[3].QValue); Assert.AreEqual("q=moo", headerValueWithQValues[4].Identity); Assert.IsNull(headerValueWithQValues[4].QValue); } #endregion #region GetCompressionMode [Test] public void GetCompressionMode_EmptyAcceptEncoding_None() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = string.Empty; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.None, compressionMode); } [Test] public void GetCompressionMode_InvalidAcceptEncoding_None() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "invalid;q=0.5"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.None, compressionMode); } [Test] public void GetCompressionMode_CompressionTermASubstringNotSpecifiedAcceptEncoding_None() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "compression, test, testdeflater"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.None, compressionMode); } [Test] public void GetCompressionMode_DeflateAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "deflate"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.Deflate, compressionMode); } [Test] public void GetCompressionMode_GzipAcceptEncoding_Gzip() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "gzip"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.GZip, compressionMode); } [Test] public void GetCompressionMode_CompressionPreferenceWithoutQValuesAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "gzip, deflate"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.GZip, compressionMode); } [Test] public void GetCompressionMode_CompressionPreferenceWithQValuesAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "deflate;q=0.5, gzip;q=0.9, compress"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.GZip, compressionMode); } [Test] public void GetCompressionMode_WildcardAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "*"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.Deflate, compressionMode); } [Test] public void GetCompressionMode_WildcardWithGzipAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "*, gzip"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.Deflate, compressionMode); } [Test] public void GetCompressionMode_WildcardWithDeflateAcceptEncoding_Gzip() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "*, deflate"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.GZip, compressionMode); } [Test] public void GetCompressionMode_WildcardWithGzipAndDeflateAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = " * , gzip ; q = 0.5, deflate; q=0.9"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.Deflate, compressionMode); } [Test] public void GetCompressionMode_WildcardWithPreferredInvalidAcceptEncoding_Deflate() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = " * , gzip ; q = 0.5, deflate; q=0.7, invalid;q=0.9"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.Deflate, compressionMode); } [Test] public void GetCompressionMode_IsCaseSensitive_Gzip() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "Gzip"; var headerType = HttpRequestHeader.AcceptEncoding; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var compressionMode = httpRequestHeaderHelper.GetCompressionMode(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(ResponseCompressionType.GZip, compressionMode); } #endregion #region GetHttpMethod [Test] public void GetHttpMethod_GetRequest_Get() { //Arrange var httpMethodType = HttpMethod.Get; var httpMethodValue = (string)httpMethodType; var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); httpRequest.Expect(x => x.HttpMethod).Return(httpMethodValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var result = httpRequestHeaderHelper.GetHttpMethod(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.AreEqual(httpMethodType, result); } #endregion #region IsRangeRequest [Test] public void IsRangeRequest_HasRangeHeader_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = "bytes=500-600,601-999"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var isRangeRequest = httpRequestHeaderHelper.IsRangeRequest(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.True(isRangeRequest); } [Test] public void IsRangeRequest_DoesNotHaveRangeHeader_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headerValue = string.Empty; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var isRangeRequest = httpRequestHeaderHelper.IsRangeRequest(httpRequest); //Assert httpRequest.VerifyAllExpectations(); Assert.False(isRangeRequest); } #endregion #region CheckIfModifiedSince [Test] public void CheckIfModifiedSince_HasNoIfModifiedSinceHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = string.Empty; var headerType = HttpRequestHeader.IfModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasBeenModifiedSince = httpRequestHeaderHelper.CheckIfModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasBeenModifiedSince); } [Test] public void CheckIfModifiedSince_HasBeenModifiedSince_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(-1).ToString("r"); var headerType = HttpRequestHeader.IfModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasBeenModifiedSince = httpRequestHeaderHelper.CheckIfModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasBeenModifiedSince); Assert.True(hasBeenModifiedSince.Value); } [Test] public void CheckIfModifiedSince_HasNotBeenModifiedSince_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(1).ToString("r"); var headerType = HttpRequestHeader.IfModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasBeenModifiedSince = httpRequestHeaderHelper.CheckIfModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasBeenModifiedSince); Assert.False(hasBeenModifiedSince.Value); } [Test] public void CheckIfModifiedSince_DateModifiedSinceInvalid_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = "invalid"; var headerType = HttpRequestHeader.IfModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasBeenModifiedSince = httpRequestHeaderHelper.CheckIfModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasBeenModifiedSince); } #endregion #region CheckIfUnmodifiedSince [Test] public void CheckIfUnmodifiedSince_HasNoIfModifiedSinceHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = string.Empty; var headerType = HttpRequestHeader.IfUnmodifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckIfUnmodifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasNotBeenModifiedSince); } [Test] public void CheckIfUnmodifiedSince_HasNotBeenModifiedSince_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(1).ToString("r"); var headerType = HttpRequestHeader.IfUnmodifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckIfUnmodifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasNotBeenModifiedSince); Assert.True(hasNotBeenModifiedSince.Value); } [Test] public void CheckIfUnmodifiedSince_HasBeenModifiedSince_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(-1).ToString("r"); var headerType = HttpRequestHeader.IfUnmodifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckIfUnmodifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasNotBeenModifiedSince); Assert.False(hasNotBeenModifiedSince.Value); } [Test] public void CheckIfUnmodifiedSince_DateUnmodifiedSinceInvalid_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = "Invalid"; var headerType = HttpRequestHeader.IfUnmodifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckIfUnmodifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasNotBeenModifiedSince); } #endregion #region CheckUnlessModifiedSince [Test] public void CheckUnlessModifiedSince_HasNoIfModifiedSinceHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = string.Empty; var headerType = HttpRequestHeader.UnlessModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckUnlessModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasNotBeenModifiedSince); } [Test] public void CheckUnlessModifiedSince_HasNotBeenModifiedSince_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(1).ToString("r"); var headerType = HttpRequestHeader.UnlessModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckUnlessModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasNotBeenModifiedSince); Assert.True(hasNotBeenModifiedSince.Value); } [Test] public void CheckUnlessModifiedSince_HasBeenModifiedSince_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = lastModified.AddSeconds(-1).ToString("r"); var headerType = HttpRequestHeader.UnlessModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckUnlessModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(hasNotBeenModifiedSince); Assert.False(hasNotBeenModifiedSince.Value); } [Test] public void CheckUnlessModifiedSince_DateUnlessModifiedSinceInvalid_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var headerValue = "Invalid"; var headerType = HttpRequestHeader.UnlessModifiedSince; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var hasNotBeenModifiedSince = httpRequestHeaderHelper.CheckUnlessModifiedSince(httpRequest, lastModified); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(hasNotBeenModifiedSince); } #endregion #region CheckIfRange [Test] public void CheckIfRange_NoRangeHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var headerValue = string.Empty; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Headers.Expect(x => x[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNull(satisfiesRangeCheck); } [Test] public void CheckIfRange_NoCheckIfRangeHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var rangeRequestHeaderValue = "bytes=500-600,601-999"; var rangeRequestHeaderType = HttpRequestHeader.Range; var rangeRequestHeaderName = (string)rangeRequestHeaderType; var ifRangeHeaderValue = string.Empty; var ifRangeHeaderType = HttpRequestHeader.IfRange; var ifRangeHeaderName = (string)ifRangeHeaderType; httpRequest.Headers.Expect(x => x[rangeRequestHeaderName]).Return(rangeRequestHeaderValue); httpRequest.Headers.Expect(x => x[ifRangeHeaderName]).Return(ifRangeHeaderValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNull(satisfiesRangeCheck); } [Test] public void CheckIfRange_CheckOnEtagIfRangeHeader_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var rangeRequestHeaderValue = "bytes=500-600,601-999"; var rangeRequestHeaderType = HttpRequestHeader.Range; var rangeRequestHeaderName = (string)rangeRequestHeaderType; var ifRangeHeaderValue = etag; var ifRangeHeaderType = HttpRequestHeader.IfRange; var ifRangeHeaderName = (string)ifRangeHeaderType; httpRequest.Headers.Expect(x => x[rangeRequestHeaderName]).Return(rangeRequestHeaderValue); httpRequest.Headers.Expect(x => x[ifRangeHeaderName]).Return(ifRangeHeaderValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNotNull(satisfiesRangeCheck); Assert.True(satisfiesRangeCheck.Value); } [Test] public void CheckIfRange_CheckOnEtagIfRangeHeader_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var rangeRequestHeaderValue = "bytes=500-600,601-999"; var rangeRequestHeaderType = HttpRequestHeader.Range; var rangeRequestHeaderName = (string)rangeRequestHeaderType; var ifRangeHeaderValue = etag + "8"; var ifRangeHeaderType = HttpRequestHeader.IfRange; var ifRangeHeaderName = (string)ifRangeHeaderType; httpRequest.Headers.Expect(x => x[rangeRequestHeaderName]).Return(rangeRequestHeaderValue); httpRequest.Headers.Expect(x => x[ifRangeHeaderName]).Return(ifRangeHeaderValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNotNull(satisfiesRangeCheck); Assert.False(satisfiesRangeCheck.Value); } [Test] public void CheckIfRange_CheckOnLastModifiedIfRangeHeader_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var rangeRequestHeaderValue = "bytes=500-600,601-999"; var rangeRequestHeaderType = HttpRequestHeader.Range; var rangeRequestHeaderName = (string)rangeRequestHeaderType; var ifRangeHeaderValue = lastModified.ToString("r"); var ifRangeHeaderType = HttpRequestHeader.IfRange; var ifRangeHeaderName = (string)ifRangeHeaderType; httpRequest.Headers.Expect(x => x[rangeRequestHeaderName]).Return(rangeRequestHeaderValue); httpRequest.Headers.Expect(x => x[ifRangeHeaderName]).Return(ifRangeHeaderValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNotNull(satisfiesRangeCheck); Assert.True(satisfiesRangeCheck.Value); } [Test] public void CheckIfRange_CheckOnLastModifiedIfRangeHeader_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var headers = MockRepository.GenerateMock<NameValueCollection>(); httpRequest.Stub(x => x.Headers).Return(headers); var lastModified = new DateTime(2010, 01, 01, 01, 01, 01, DateTimeKind.Utc); var etag = "1234567"; var rangeRequestHeaderValue = "bytes=500-600,601-999"; var rangeRequestHeaderType = HttpRequestHeader.Range; var rangeRequestHeaderName = (string)rangeRequestHeaderType; var ifRangeHeaderValue = lastModified.AddSeconds(-1).ToString("r"); var ifRangeHeaderType = HttpRequestHeader.IfRange; var ifRangeHeaderName = (string)ifRangeHeaderType; httpRequest.Headers.Expect(x => x[rangeRequestHeaderName]).Return(rangeRequestHeaderValue); httpRequest.Headers.Expect(x => x[ifRangeHeaderName]).Return(ifRangeHeaderValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var satisfiesRangeCheck = httpRequestHeaderHelper.CheckIfRange(httpRequest, etag, lastModified); //Assert headers.VerifyAllExpectations(); httpRequest.VerifyAllExpectations(); Assert.IsNotNull(satisfiesRangeCheck); Assert.False(satisfiesRangeCheck.Value); } #endregion #region CheckIfMatch [Test] public void CheckIfMatch_HasNoIfMatchHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = string.Empty; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(ifMatchSatisfied); } [Test] public void CheckIfMatch_HasMatchingEtag_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = entityTag; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_HasMatchingEtags_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = "7654321," + entityTag; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_HasNoMatchingEtag_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = entityTag + "8"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_HasNoMatchingEtags_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = "7654321," + entityTag + "8"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_IsCaseSensitive_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = true; var headerValue = "abcdeF"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_MatchingWildCardAndEntityDoesExist_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = true; var headerValue = "*"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfMatch_MatchingWildCardAndEntityDoesNotExist_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = false; var headerValue = "*"; var headerType = HttpRequestHeader.IfMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } #endregion #region CheckIfNoneMatch [Test] public void CheckIfNoneMatch_HasNoIfNoneMatchHeader_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = string.Empty; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(ifMatchSatisfied); } [Test] public void CheckIfNoneMatch_HasMatchingEtag_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = entityTag; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_HasMatchingEtags_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = "7654321," + entityTag; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_HasNoMatchingEtag_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = entityTag + "8"; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_HasNoMatchingEtags_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "1234567"; var doesEntityExists = true; var headerValue = "7654321," + entityTag + "8"; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_IsCaseSensitive_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = true; var headerValue = "abcdeF"; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_MatchingWildCardAndEntityDoesExist_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = true; var headerValue = "*"; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsFalse(ifMatchSatisfied.Value); } [Test] public void CheckIfNoneMatch_MatchingWildCardAndEntityDoesNotExist_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var entityTag = "abcdef"; var doesEntityExists = false; var headerValue = "*"; var headerType = HttpRequestHeader.IfNoneMatch; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); var ifMatchSatisfied = httpRequestHeaderHelper.CheckIfNoneMatch(httpRequest, entityTag, doesEntityExists); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNotNull(ifMatchSatisfied); Assert.IsTrue(ifMatchSatisfied.Value); } #endregion #region GetRanges [Test] public void GetRanges_NoHeaderSent_Null() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = string.Empty; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.IsNull(rangeResult); Assert.IsNotNull(ranges); Assert.IsFalse(ranges.Any()); } [Test] public void GetRanges_InvalidStartRange_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=unknown-9999"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_InvalidEndRange_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-unknown"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_MalformedRange_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-499,5=100"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_StartRangeLargerThenEndRange_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=499-0"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_EndRangeLargerThenEntityLength_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-20000"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_NegativeStartRange_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=-20000"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_StartRangeLargerThenEntityLength_False() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=20000-"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsFalse(rangeResult.Value); Assert.IsNull(ranges); } [Test] public void GetRanges_First500Bytes_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-499"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(0, rangeItem.StartRange); Assert.AreEqual(499, rangeItem.EndRange); } [Test] public void GetRanges_Second500Bytes_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=500-999"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(500, rangeItem.StartRange); Assert.AreEqual(999, rangeItem.EndRange); } [Test] public void GetRanges_MultipleByteRanges_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-499,500-999"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var firstRangeItem = ranges.First(); var secondRangeItem = ranges.Skip(1).First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(0, firstRangeItem.StartRange); Assert.AreEqual(499, firstRangeItem.EndRange); Assert.AreEqual(500, secondRangeItem.StartRange); Assert.AreEqual(999, secondRangeItem.EndRange); } [Test] public void GetRanges_500BytesFromEnd_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=-500"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(9500, rangeItem.StartRange); Assert.AreEqual(9999, rangeItem.EndRange); } [Test] public void GetRanges_9500BytesToEnd_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=9500-"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(9500, rangeItem.StartRange); Assert.AreEqual(9999, rangeItem.EndRange); } [Test] public void GetRanges_FirstByte_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=0-0"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(0, rangeItem.StartRange); Assert.AreEqual(0, rangeItem.EndRange); } [Test] public void GetRanges_LastByte_True() { //Arrange var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); var contentLength = 10000; var headerValue = "bytes=-1"; var headerType = HttpRequestHeader.Range; var headerName = (string)headerType; httpRequest.Expect(x => x.Headers[headerName]).Return(headerValue); //Act var httpRequestHeaderHelper = new HttpRequestHeaderHelper(); IEnumerable<RangeItem> ranges; var rangeResult = httpRequestHeaderHelper.GetRanges(httpRequest, contentLength, out ranges); var rangeItem = ranges.First(); //Assert httpRequest.VerifyAllExpectations(); Assert.NotNull(rangeResult); Assert.IsTrue(rangeResult.Value); Assert.IsNotNull(ranges); Assert.IsTrue(ranges.Any()); Assert.AreEqual(9999, rangeItem.StartRange); Assert.AreEqual(9999, rangeItem.EndRange); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AccessTokenMvcWebApp.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#if !OMIT_FOREIGN_KEY using System; using System.Diagnostics; using System.Text; using Bitmask = System.UInt64; namespace Core { public partial class Parse { #if !OMIT_TRIGGER int LocateFkeyIndex(Table parent, FKey fkey, out Index indexOut, out int[] colsOut) { indexOut = null; colsOut = null; int colsLength = fkey.Cols.length; // Number of columns in parent key string key = fkey.Cols[0].Col; // Name of left-most parent key column // The caller is responsible for zeroing output parameters. //: _assert(indexOut && *indexOut == nullptr); //: _assert(!colsOut || *colsOut == nullptr); // If this is a non-composite (single column) foreign key, check if it maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx // and *paiCol set to zero and return early. // // Otherwise, for a composite foreign key (more than one column), allocate space for the aiCol array (returned via output parameter *paiCol). // Non-composite foreign keys do not require the aiCol array. int[] cols = null; // Value to return via *paiCol if (colsLength == 1) { // The FK maps to the IPK if any of the following are true: // 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly mapped to the primary key of table pParent, or // 2) The FK is explicitly mapped to a column declared as INTEGER PRIMARY KEY. if (parent.PKey >= 0) if (key == null || string.Equals(parent.Cols[parent.PKey].Name, key, StringComparison.InvariantCultureIgnoreCase)) return 0; } else //: if (colsOut) { Debug.Assert(colsLength > 1); cols = new int[colsLength]; //: (int *)_tagalloc(Ctx, colsLength*sizeof(int)); if (cols == null) return 1; colsOut = cols; } Index index = null; // Value to return via *ppIdx for (index = parent.Index; index != null; index = index.Next) { if (index.Columns.length == colsLength && index.OnError != OE.None) { // pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number of columns. If each indexed column corresponds to a foreign key // column of pFKey, then this index is a winner. if (key == null) { // If zKey is NULL, then this foreign key is implicitly mapped to the PRIMARY KEY of table pParent. The PRIMARY KEY index may be // identified by the test (Index.autoIndex==2). if (index.AutoIndex == 2) { if (cols != null) for (int i = 0; i < colsLength; i++) cols[i] = fkey.Cols[i].From; break; } } else { // If zKey is non-NULL, then this foreign key was declared to map to an explicit list of columns in table pParent. Check if this // index matches those columns. Also, check that the index uses the default collation sequences for each column. int i, j; for (i = 0; i < colsLength; i++) { int col = index.Columns[i]; // Index of column in parent tbl // If the index uses a collation sequence that is different from the default collation sequence for the column, this index is // unusable. Bail out early in this case. string dfltColl = parent.Cols[col].Coll; // Def. collation for column if (string.IsNullOrEmpty(dfltColl)) dfltColl = "BINARY"; if (!string.Equals(index.CollNames[i], dfltColl, StringComparison.InvariantCultureIgnoreCase)) break; string indexCol = parent.Cols[col].Name; // Name of indexed column for (j = 0; j < colsLength; j++) { if (string.Equals(fkey.Cols[j].Col, indexCol, StringComparison.InvariantCultureIgnoreCase)) { if (cols != null) cols[i] = fkey.Cols[j].From; break; } } if (j == colsLength) break; } if (i == colsLength) break; // pIdx is usable } } } if (index == null) { if (!DisableTriggers) ErrorMsg("foreign key mismatch - \"%w\" referencing \"%w\"", fkey.From.Name, fkey.To); C._tagfree(Ctx, ref cols); return 1; } indexOut = index; return 0; } static void FKLookupParent(Parse parse, int db, Table table, Index index, FKey fkey, int[] cols, int regDataId, int incr, bool isIgnore) { Vdbe v = parse.GetVdbe(); // Vdbe to add code to int curId = parse.Tabs - 1; // Cursor number to use int okId = v.MakeLabel(); // jump here if parent key found // If nIncr is less than zero, then check at runtime if there are any outstanding constraints to resolve. If there are not, there is no need // to check if deleting this row resolves any outstanding violations. // // Check if any of the key columns in the child table row are NULL. If any are, then the constraint is considered satisfied. No need to // search for a matching row in the parent table. int i; if (incr < 0) v.AddOp2(OP.FkIfZero, fkey.IsDeferred, okId); for (i = 0; i < fkey.Cols.length; i++) { int regId = cols[i] + regDataId + 1; v.AddOp2(OP.IsNull, regId, okId); } if (!isIgnore) { if (index == null) { // If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY column of the parent table (table pTab). int mustBeIntId; // Address of MustBeInt instruction int regTempId = parse.GetTempReg(); // Invoke MustBeInt to coerce the child key value to an integer (i.e. apply the affinity of the parent key). If this fails, then there // is no matching parent key. Before using MustBeInt, make a copy of the value. Otherwise, the value inserted into the child key column // will have INTEGER affinity applied to it, which may not be correct. v.AddOp2(OP.SCopy, cols[0] + 1 + regDataId, regTempId); mustBeIntId = v.AddOp2(OP.MustBeInt, regTempId, 0); // If the parent table is the same as the child table, and we are about to increment the constraint-counter (i.e. this is an INSERT operation), // then check if the row being inserted matches itself. If so, do not increment the constraint-counter. if (table == fkey.From && incr == 1) v.AddOp3(OP.Eq, regDataId, okId, regTempId); parse.OpenTable(parse, curId, db, table, OP.OpenRead); v.AddOp3(OP.NotExists, curId, 0, regTempId); v.AddOp2(OP.Goto, 0, okId); v.JumpHere(v.CurrentAddr() - 2); v.JumpHere(mustBeIntId); parse.ReleaseTempReg(regTempId); } else { int colsLength = fkey.Cols.length; int regTempId = parse.GetTempRange(colsLength); int regRecId = parse.GetTempReg(); KeyInfo key = IndexKeyinfo(parse, index); v.AddOp3(OP.OpenRead, curId, index.Id, db); v.ChangeP4(v, -1, key, Vdbe.P4T.KEYINFO_HANDOFF); for (i = 0; i < colsLength; i++) v.AddOp2(OP.Copy, cols[i] + 1 + regDataId, regTempId + i); // If the parent table is the same as the child table, and we are about to increment the constraint-counter (i.e. this is an INSERT operation), // then check if the row being inserted matches itself. If so, do not increment the constraint-counter. // If any of the parent-key values are NULL, then the row cannot match itself. So set JUMPIFNULL to make sure we do the OP_Found if any // of the parent-key values are NULL (at this point it is known that none of the child key values are). if (table == fkey.From && incr == 1) { int jumpId = v.CurrentAddr() + colsLength + 1; for (i = 0; i < colsLength; i++) { int childId = cols[i] + 1 + regDataId; int parentId = index.Columns[i] + 1 + regDataId; Debug.Assert(cols[i] != table.PKey); if (index.Columns[i] == table.PKey) parentId = regDataId; // The parent key is a composite key that includes the IPK column v.AddOp3(OP.Ne, childId, jumpId, parentId); v.ChangeP5(SQLITE_JUMPIFNULL); } v.AddOp2(OP.Goto, 0, okId); } v.AddOp3(OP.MakeRecord, regTempId, colsLength, regRecId); v.ChangeP4(-1, IndexAffinityStr(v, index), Vdbe.P4T.TRANSIENT); v.AddOp4Int(OP.Found, curId, okId, regRecId, 0); parse.ReleaseTempReg(regRecId); parse.ReleaseTempRange(regTempId, colsLength); } } if (!fkey.IsDeferred && parse.Toplevel == null && parse.IsMultiWrite == 0) { // Special case: If this is an INSERT statement that will insert exactly one row into the table, raise a constraint immediately instead of // incrementing a counter. This is necessary as the VM code is being generated for will not open a statement transaction. Debug.Assert(incr == 1); HaltConstraint(parse, OE.Abort, "foreign key constraint failed", Vdbe.P4T.STATIC); } else { if (incr > 0 && !fkey.IsDeferred) E.Parse_Toplevel(parse).MayAbort = true; v.AddOp2(OP.FkCounter, fkey.IsDeferred, incr); } v.ResolveLabel(v, okId); v.AddOp1(OP.Close, curId); } static void FKScanChildren(Parse parse, SrcList src, Table table, Index index, FKey fkey, int[] cols, int regDataId, int incr) { Context ctx = parse.Ctx; // Database handle Vdbe v = parse.GetVdbe(); Expr where_ = null; // WHERE clause to scan with Debug.Assert(index == null || index.Table == table); int fkIfZero = 0; // Address of OP_FkIfZero if (incr < 0) fkIfZero = v.AddOp2(OP.FkIfZero, fkey.IsDeferred, 0); // Create an Expr object representing an SQL expression like: // // <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ... // // The collation sequence used for the comparison should be that of the parent key columns. The affinity of the parent key column should // be applied to each child key value before the comparison takes place. for (int i = 0; i < fkey.Cols.length; i++) { int col; // Index of column in child table Expr left = Expr.Expr(ctx, TK.REGISTER, null); // Value from parent table row if (left != null) { // Set the collation sequence and affinity of the LHS of each TK_EQ expression to the parent key column defaults. if (index != null) { col = index.Columns[i]; Column colObj = table.Cols[col]; if (table.PKey == col) col = -1; left.TableId = regDataId + col + 1; left.Aff = colObj.Affinity; string collName = colObj.Coll; if (collName == null) collName = ctx.DefaultColl.Name; left = Expr.AddCollateString(parse, left, collName); } else { left.TableId = regDataId; left.Aff = AFF.INTEGER; } } col = (cols != null ? cols[i] : fkey.Cols[0].From); Debug.Assert(col >= 0); string colName = fkey.From.Cols[col].Name; // Name of column in child table Expr right = Expr.Expr(ctx, TK.ID, colName); // Column ref to child table Expr eq = Expr.PExpr(parse, TK.EQ, left, right, 0); // Expression (pLeft = pRight) where_ = Expr.And(ctx, where_, eq); } // If the child table is the same as the parent table, and this scan is taking place as part of a DELETE operation (operation D.2), omit the // row being deleted from the scan by adding ($rowid != rowid) to the WHERE clause, where $rowid is the rowid of the row being deleted. if (table == fkey.From && incr > 0) { Expr left = Expr.Expr(ctx, TK.REGISTER, null); // Value from parent table row Expr right = Expr.Expr(ctx, TK.COLUMN, null); // Column ref to child table if (left != null && right != null) { left.TableId = regDataId; left.Aff = AFF.INTEGER; right.TableId = src.Ids[0].Cursor; right.ColumnIdx = -1; } Expr eq = Expr.PExpr(parse, TK.NE, left, right, 0); // Expression (pLeft = pRight) where_ = Expr.And(ctx, where_, eq); } // Resolve the references in the WHERE clause. NameContext nameContext; // Context used to resolve WHERE clause nameContext = new NameContext(); // memset( &sNameContext, 0, sizeof( NameContext ) ); nameContext.SrcList = src; nameContext.Parse = parse; ResolveExprNames(nameContext, ref where_); // Create VDBE to loop through the entries in src that match the WHERE clause. If the constraint is not deferred, throw an exception for // each row found. Otherwise, for deferred constraints, increment the deferred constraint counter by incr for each row selected. ExprList dummy = null; WhereInfo whereInfo = Where.Begin(parse, src, where_, ref dummy, 0); // Context used by sqlite3WhereXXX() if (incr > 0 && !fkey.IsDeferred) E.Parse_Toplevel(parse).MayAbort = true; v.AddOp2(OP.FkCounter, fkey.IsDeferred, incr); if (whereInfo != null) Where.End(whereInfo); // Clean up the WHERE clause constructed above. Expr.Delete(ctx, ref where_); if (fkIfZero != 0) v.JumpHere(fkIfZero); } public static FKey FKReferences(Table table) { int nameLength = table.Name.Length; return table.Schema.FKeyHash.Find(table.Name, nameLength, (FKey)null); } static void FKTriggerDelete(Context ctx, Trigger p) { if (p != null) { TriggerStep step = p.StepList; Expr.Delete(ctx, ref step.Where); Expr.ListDelete(ctx, ref step.ExprList); Select.Delete(ctx, ref step.Select); Expr.Delete(ctx, ref p.When); C._tagfree(ctx, ref p); } } public void FKDropTable(SrcList name, Table table) { Context ctx = Ctx; if ((ctx.Flags & Context.FLAG.ForeignKeys) != 0 && !IsVirtual(table) && table.Select == null) { int skipId = 0; Vdbe v = GetVdbe(); Debug.Assert(v != null); // VDBE has already been allocated if (FKReferences(table) == null) { // Search for a deferred foreign key constraint for which this table is the child table. If one cannot be found, return without // generating any VDBE code. If one can be found, then jump over the entire DELETE if there are no outstanding deferred constraints // when this statement is run. FKey p; for (p = table.FKeys; p != null; p = p.NextFrom) if (p.IsDeferred) break; if (p == null) return; skipId = v.MakeLabel(); v.AddOp2(OP.FkIfZero, 1, skipId); } DisableTriggers = true; DeleteFrom(this, SrcListDup(ctx, name, 0), null); DisableTriggers = false; // If the DELETE has generated immediate foreign key constraint violations, halt the VDBE and return an error at this point, before // any modifications to the schema are made. This is because statement transactions are not able to rollback schema changes. v.AddOp2(OP.FkIfZero, 0, v.CurrentAddr() + 2); HaltConstraint(this, OE.Abort, "foreign key constraint failed", Vdbe.P4T.STATIC); if (skipId != 0) v.ResolveLabel(skipId); } } public void FKCheck(Table table, int regOld, int regNew) { Context ctx = Ctx; // Database handle bool isIgnoreErrors = DisableTriggers; // Exactly one of regOld and regNew should be non-zero. Debug.Assert((regOld == 0) != (regNew == 0)); // If foreign-keys are disabled, this function is a no-op. if ((ctx.Flags & Context.FLAG.ForeignKeys) == 0) return; int db = SchemaToIndex(ctx, table.Schema); // Index of database containing pTab string dbName = ctx.DBs[db].Name; // Name of database containing pTab // Loop through all the foreign key constraints for which pTab is the child table (the table that the foreign key definition is part of). FKey fkey; // Used to iterate through FKs for (fkey = table.FKeys; fkey != null; fkey = fkey.NextFrom) { bool isIgnore = false; // Find the parent table of this foreign key. Also find a unique index on the parent key columns in the parent table. If either of these // schema items cannot be located, set an error in pParse and return early. Table to = (DisableTriggers ? FindTable(ctx, fkey.To, dbName) : LocateTable(false, fkey.To, dbName)); // Parent table of foreign key pFKey Index index = null; // Index on key columns in pTo int[] frees = null; if (to == null || LocateFkeyIndex(to, fkey, out index, out frees) != 0) { Debug.Assert(!isIgnoreErrors || (regOld != 0 && regNew == 0)); if (!isIgnoreErrors || ctx.MallocFailed) return; if (to == null) { // If isIgnoreErrors is true, then a table is being dropped. In this se SQLite runs a "DELETE FROM xxx" on the table being dropped // before actually dropping it in order to check FK constraints. If the parent table of an FK constraint on the current table is // missing, behave as if it is empty. i.e. decrement the FK counter for each row of the current table with non-NULL keys. Vdbe v = GetVdbe(); int jumpId = v.CurrentAddr() + fkey.Cols.length + 1; for (int i = 0; i < fkey.Cols.length; i++) { int regId = fkey.Cols[i].From + regOld + 1; v.AddOp2(OP.IsNull, regId, jumpId); } v.AddOp2(OP.FkCounter, fkey.IsDeferred, -1); } continue; } Debug.Assert(fkey.Cols.length == 1 || (frees != null && index != null)); int[] cols; if (frees != null) cols = frees; else { int col = fkey.Cols[0].From; cols = new int[1]; cols[0] = col; } for (int i = 0; i < fkey.Cols.length; i++) { if (cols[i] == table.PKey) cols[i] = -1; #if !OMIT_AUTHORIZATION // Request permission to read the parent key columns. If the authorization callback returns SQLITE_IGNORE, behave as if any // values read from the parent table are NULL. if (ctx.Auth != null) { string colName = to.Cols[index != null ? index.Columns[i] : to.PKey].Name; ARC rcauth = Auth.ReadColumn(this, to.Name, colName, db); isIgnore = (rcauth == ARC.IGNORE); } #endif } // Take a shared-cache advisory read-lock on the parent table. Allocate a cursor to use to search the unique index on the parent key columns // in the parent table. TableLock(db, to.Id, false, to.Name); Tabs++; if (regOld != 0) // A row is being removed from the child table. Search for the parent. If the parent does not exist, removing the child row resolves an outstanding foreign key constraint violation. FKLookupParent(this, db, to, index, fkey, cols, regOld, -1, isIgnore); if (regNew != 0) // A row is being added to the child table. If a parent row cannot be found, adding the child row has violated the FK constraint. FKLookupParent(this, db, to, index, fkey, cols, regNew, +1, isIgnore); C._tagfree(ctx, ref frees); } // Loop through all the foreign key constraints that refer to this table for (fkey = FKReferences(table); fkey != null; fkey = fkey.NextTo) { if (!fkey.IsDeferred && Toplevel == null && !IsMultiWrite) { Debug.Assert(regOld == 0 && regNew != 0); // Inserting a single row into a parent table cannot cause an immediate foreign key violation. So do nothing in this case. continue; } Index index = null; // Foreign key index for pFKey int[] cols = null; if (LocateFkeyIndex(table, fkey, out index, out cols) != 0) { if (isIgnoreErrors || ctx.MallocFailed) return; continue; } Debug.Assert(cols != null || fkey.Cols.length == 1); // Create a SrcList structure containing a single table (the table the foreign key that refers to this table is attached to). This // is required for the sqlite3WhereXXX() interface. SrcList src = SrcListAppend(ctx, null, null, null); if (src != null) { SrcList.SrcListItem item = src.Ids[0]; item.Table = fkey.From; item.Name = fkey.From.Name; item.Table.Refs++; item.Cursor = Tabs++; if (regNew != 0) FKScanChildren(this, src, table, index, fkey, cols, regNew, -1); if (regOld != 0) { // If there is a RESTRICT action configured for the current operation on the parent table of this FK, then throw an exception // immediately if the FK constraint is violated, even if this is a deferred trigger. That's what RESTRICT means. To defer checking // the constraint, the FK should specify NO ACTION (represented using OE_None). NO ACTION is the default. FKScanChildren(this, src, table, index, fkey, cols, regOld, 1); } item.Name = null; SrcListDelete(ctx, ref src); } C._tagfree(ctx, ref cols); } } static uint COLUMN_MASK(int x) { return ((x) > 31) ? 0xffffffff : ((uint)1 << (x)); } //: #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((uint32)1<<(x))) public uint FKOldmask(Table table) { uint mask = 0; if ((Ctx.Flags & Context.FLAG.ForeignKeys) != 0) { FKey p; int i; for (p = table.FKeys; p != null; p = p.NextFrom) for (i = 0; i < p.Cols.length; i++) mask |= COLUMN_MASK(p.Cols[i].From); for (p = FKReferences(table); p != null; p = p.NextTo) { Index index; int[] dummy; LocateFkeyIndex(table, p, out index, out dummy); if (index != null) for (i = 0; i < index.Columns.length; i++) mask |= COLUMN_MASK(index.Columns[i]); } } return mask; } public bool FKRequired(Table table, int[] changes, int chngRowid) { if ((Ctx.Flags & Context.FLAG.ForeignKeys) != 0) { if (changes == null) // A DELETE operation. Foreign key processing is required if the table in question is either the child or parent table for any foreign key constraint. return (FKReferences(table) != null || table.FKeys != null); else // This is an UPDATE. Foreign key processing is only required if operation modifies one or more child or parent key columns. { int i; FKey p; // Check if any child key columns are being modified. for (p = table.FKeys; p != null; p = p.NextFrom) { for (i = 0; i < p.Cols.length; i++) { int childKeyId = p.Cols[i].From; if (changes[childKeyId] >= 0) return true; if (childKeyId == table.PKey && chngRowid != 0) return true; } } // Check if any parent key columns are being modified. for (p = FKReferences(table); p != null; p = p.NextTo) for (i = 0; i < p.Cols.length; i++) { string keyName = p.Cols[i].Col; for (int key = 0; key < table.Cols.length; key++) { Column col = table.Cols[key]; if (!string.IsNullOrEmpty(keyName) ? string.Equals(col.Name, keyName, StringComparison.InvariantCultureIgnoreCase) : (col.ColFlags & COLFLAG.PRIMKEY) != 0) { if (changes[key] >= 0) return true; if (key == table.PKey && chngRowid != 0) return true; } } } } } return false; } static Trigger FKActionTrigger(Parse parse, Table table, FKey fkey, ExprList changes) { Context ctx = parse.Ctx; // Database handle int actionId = (changes != null ? 1 : 0); // 1 for UPDATE, 0 for DELETE OE action = fkey.Actions[actionId]; // One of OE_None, OE_Cascade etc. Trigger trigger = fkey.Triggers[actionId]; // Trigger definition to return if (action != OE.None && trigger == null) { Index index = null; // Parent key index for this FK int[] cols = null; // child table cols . parent key cols if (LocateFkeyIndex(parse, table, fkey, out index, out cols) != 0) return null; Debug.Assert(cols != null || fkey.Cols.length == 1); Expr where_ = null; // WHERE clause of trigger step Expr when = null; // WHEN clause for the trigger ExprList list = null; // Changes list if ON UPDATE CASCADE for (int i = 0; i < fkey.Cols.length; i++) { Token oldToken = new Token("old", 3); // Literal "old" token Token newToken = new Token("new", 3); // Literal "new" token int fromColId = (cols != null ? cols[i] : fkey.Cols[0].From); // Idx of column in child table Debug.Assert(fromColId >= 0); Token fromCol = new Token(); // Name of column in child table Token toCol = new Token(); // Name of column in parent table toCol.data = (index != null ? table.Cols[index.Columns[i]].Name : "oid"); fromCol.data = fkey.From.Cols[fromColId].Name; toCol.length = (uint)toCol.data.Length; fromCol.length = (uint)fromCol.data.Length; // Create the expression "OLD.zToCol = zFromCol". It is important that the "OLD.zToCol" term is on the LHS of the = operator, so // that the affinity and collation sequence associated with the parent table are used for the comparison. Expr eq = Expr.PExpr(parse, TK.EQ, Expr.PExpr(parse, TK.DOT, Expr.PExpr(parse, TK.ID, null, null, oldToken), Expr.PExpr(parse, TK.ID, null, null, toCol) , 0), Expr.PExpr(parse, TK.ID, null, null, fromCol) , 0); // tFromCol = OLD.tToCol where_ = Expr.And(ctx, where_, eq); // For ON UPDATE, construct the next term of the WHEN clause. The final WHEN clause will be like this: // // WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) if (changes != null) { eq = Expr.PExpr(parse, TK.IS, Expr.PExpr(parse, TK.DOT, Expr.PExpr(parse, TK.ID, null, null, oldToken), Expr.PExpr(parse, TK.ID, null, null, toCol), 0), Expr.PExpr(parse, TK.DOT, Expr.PExpr(parse, TK.ID, null, null, newToken), Expr.PExpr(parse, TK.ID, null, null, toCol), 0), 0); when = Expr.And(ctx, when, eq); } if (action != OE.Restrict && (action != OE.Cascade || changes != null)) { Expr newExpr; if (action == OE.Cascade) newExpr = Expr.PExpr(parse, TK.DOT, Expr.PExpr(parse, TK.ID, null, null, newToken), Expr.PExpr(parse, TK.ID, null, null, toCol) , 0); else if (action == OE.SetDflt) { Expr dfltExpr = fkey.From.Cols[fromColId].Dflt; if (dfltExpr != null) newExpr = Expr.Dup(ctx, dfltExpr, 0); else newExpr = Expr.PExpr(parse, TK.NULL, 0, 0, 0); } else newExpr = Expr.PExpr(parse, TK.NULL, 0, 0, 0); list = Expr.ListAppend(parse, list, newExpr); Expr.ListSetName(parse, list, fromCol, 0); } } C._tagfree(ctx, ref cols); string fromName = fkey.From.Name; // Name of child table int fromNameLength = fromName.Length; // Length in bytes of zFrom Select select = null; // If RESTRICT, "SELECT RAISE(...)" if (action == OE.Restrict) { Token from = new Token(); from.data = fromName; from.length = fromNameLength; Expr raise = Expr.Expr(ctx, TK.RAISE, "foreign key constraint failed"); if (raise != null) raise.Affinity = OE.Abort; select = Select.New(parse, Expr.ListAppend(parse, 0, raise), SrcListAppend(ctx, 0, from, null), where_, null, null, null, 0, null, null); where_ = null; } // Disable lookaside memory allocation bool enableLookaside = ctx.Lookaside.Enabled; // Copy of ctx->lookaside.bEnabled ctx.Lookaside.Enabled = false; trigger = new Trigger(); //: trigger = (Trigger *)_tagalloc(ctx, //: sizeof(Trigger) + // Trigger //: sizeof(TriggerStep) + // Single step in trigger program //: fromNameLength + 1 // Space for pStep->target.z //: , true); TriggerStep step = null; // First (only) step of trigger program if (trigger != null) { step = trigger.StepList = new TriggerStep(); //: (TriggerStep)trigger[1]; step.Target.data = fromName; //: (char *)&step[1]; step.Target.length = fromNameLength; //: _memcpy((const char *)step->Target.data, fromName, fromNameLength); step.Where = Expr.Dup(ctx, where_, EXPRDUP_REDUCE); step.ExprList = Expr.ListDup(ctx, list, EXPRDUP_REDUCE); step.Select = Select.Dup(ctx, select, EXPRDUP_REDUCE); if (when != null) { when = Expr.PExpr(parse, TK.NOT, when, 0, 0); trigger.When = Expr.Dup(ctx, when, EXPRDUP_REDUCE); } } // Re-enable the lookaside buffer, if it was disabled earlier. ctx.Lookaside.Enabled = enableLookaside; Expr.Delete(ctx, ref where_); Expr.Delete(ctx, ref when); Expr.ListDelete(ctx, ref list); Select.Delete(ctx, ref select); if (ctx.MallocFailed) { FKTriggerDelete(ctx, trigger); return null; } switch (action) { case OE.Restrict: step.OP = TK.SELECT; break; case OE.Cascade: if (changes == null) { step.OP = TK.DELETE; break; } goto default; default: step.OP = TK.UPDATE; break; } step.Trigger = trigger; trigger.Schema = table.Schema; trigger.TabSchema = table.Schema; fkey.Triggers[actionId] = trigger; trigger.OP = (TK)(changes != null ? TK.UPDATE : TK.DELETE); } return trigger; } public void FKActions(Table table, ExprList changes, int regOld) { // If foreign-key support is enabled, iterate through all FKs that refer to table table. If there is an action associated with the FK // for this operation (either update or delete), invoke the associated trigger sub-program. if ((Ctx.Flags & Context.FLAG.ForeignKeys) != 0) for (FKey fkey = FKReferences(table); fkey != null; fkey = fkey.NextTo) { Trigger action = fkActionTrigger(table, fkey, changes); if (action != null) CodeRowTriggerDirect(this, action, table, regOld, OE.Abort, 0); } } #endif public static void FKDelete(Context ctx, Table table) { Debug.Assert(ctx == null || Btree.SchemaMutexHeld(ctx, 0, table.Schema)); FKey next; // Copy of pFKey.pNextFrom for (FKey fkey = table.FKeys; fkey != null; fkey = next) { // Remove the FK from the fkeyHash hash table. //: if (!ctx || ctx->BytesFreed == 0) { if (fkey.PrevTo != null) fkey.PrevTo.NextTo = fkey.NextTo; else { FKey p = fkey.NextTo; string z = (p != null ? fkey.NextTo.To : fkey.To); table.Schema.FKeyHash.Insert(z, z.Length, p); } if (fkey.NextTo != null) fkey.NextTo.PrevTo = fkey.PrevTo; } // EV: R-30323-21917 Each foreign key constraint in SQLite is classified as either immediate or deferred. Debug.Assert(fkey.IsDeferred == false || fkey.IsDeferred == true); // Delete any triggers created to implement actions for this FK. #if !OMIT_TRIGGER FKTriggerDelete(ctx, fkey.Triggers[0]); FKTriggerDelete(ctx, fkey.Triggers[1]); #endif next = fkey.NextFrom; C._tagfree(ctx, ref fkey); } } } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Xml; using System.Windows.Forms; using gView.Framework.UI; using gView.Framework.Data; using gView.Framework.system; using gView.Explorer.UI; using gView.Framework.IO; using gView.Framework.Globalisation; using gView.Framework.Offline; using gView.Framework.FDB; using System.Threading; using gView.Framework.system.UI; using gView.Framework.UI.Dialogs; namespace gView.Framework.UI.Controls { [gView.Framework.system.RegisterPlugIn("47328671-87F7-4cf7-B59D-2BC111A29BA3")] public partial class ContentsList : UserControl, IExplorerTabPage { public delegate void ItemClickedEvent(List<IExplorerObject> node); public event ItemClickedEvent ItemSelected = null; public delegate void ItemDoubleClickedEvent(ListViewItem node); public event ItemDoubleClickedEvent ItemDoubleClicked = null; private IExplorerObject _exObject = null; private ToolStripMenuItem _renameMenuItem, _deleteMenuItem, _metadataMenuItem, _replicationMenuItem, _appendReplicationIDMenuItem, _checkoutMenuItem, _checkinMenuItem; private CatalogTreeControl _tree = null; private Filter.ExplorerDialogFilter _filter = null; private int _contextItemCount = 0; private IExplorerApplication _app = null; private bool _allowContextMenu = true, _open = true; private Thread _worker = null; private CancelTracker _cancelTracker = new CancelTracker(); public ContentsList() { InitializeComponent(); listView.SmallImageList = ExplorerImageList.List.ImageList; _renameMenuItem = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.Rename", "Rename")); _renameMenuItem.Click += new EventHandler(_renameMenuItem_Click); _deleteMenuItem = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.Delete", "Delete")); _deleteMenuItem.Click += new EventHandler(_deleteMenuItem_Click); _metadataMenuItem = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.Metadata", "Metadata...")); _metadataMenuItem.Click += new EventHandler(_metadataMenuItem_Click); _appendReplicationIDMenuItem = new ToolStripMenuItem("Append ReplicationID"); _appendReplicationIDMenuItem.Click += new EventHandler(_appendReplicationIDMenuItem_Click); _checkoutMenuItem = new ToolStripMenuItem("Checkout..."); _checkoutMenuItem.Click += new EventHandler(_checkoutMenuItem_Click); _checkinMenuItem = new ToolStripMenuItem("Checkin..."); _checkinMenuItem.Click += new EventHandler(_checkinMenuItem_Click); _replicationMenuItem = new ToolStripMenuItem("Replication"); _replicationMenuItem.DropDownItems.Add(_appendReplicationIDMenuItem); _replicationMenuItem.DropDownItems.Add(_checkoutMenuItem); _replicationMenuItem.DropDownItems.Add(_checkinMenuItem); _contextItemCount = contextStrip.Items.Count; LocalizedResources.GlobalizeMenuItem(contextStrip); } internal CatalogTreeControl TreeControl { get { return _tree; } set { _tree = value; if (_tree != null) { _tree.ContentsListView = this; _tree.NodeDeleted += new CatalogTreeControl.NodeDeletedEvent(tree_NodeDeleted); _tree.NodeRenamed += new CatalogTreeControl.NodeRenamedEvent(tree_NodeRenamed); } } } #region TreeEvents void tree_NodeDeleted(IExplorerObject exObject) { DeleteItem(exObject); } void tree_NodeRenamed(IExplorerObject exObject) { RenameItem(exObject); } #endregion internal ImageList SmallImageList { get { return listView.SmallImageList; } set { listView.SmallImageList = listView.LargeImageList = value; } } public List<IExplorerObject> SelectedExplorerObjects { get { List<IExplorerObject> selected = new List<IExplorerObject>(); foreach (ListViewItem item in listView.SelectedItems) { if (item is ExplorerObjectListViewItem && ((ExplorerObjectListViewItem)item).ExplorerObject != null) { selected.Add(((ExplorerObjectListViewItem)item).ExplorerObject); } } return selected; } } public View View { get { return listView.View; } set { listView.View = value; } } public bool IsOpenDialog { get { return _open; } set { _open = value; } } public Filter.ExplorerDialogFilter Filter { get { return _filter; } set { _filter = value; } } #region IExplorerTabPage Members public new Control Control { get { return this; } } public void OnCreate(object hook) { if (hook is IExplorerApplication && ((IExplorerApplication)hook).ApplicationWindow is gView.Explorer.UI.Framework.UI.IFormExplorer) { _app = hook as IExplorerApplication; this.TreeControl = ((gView.Explorer.UI.Framework.UI.IFormExplorer)((IExplorerApplication)hook).ApplicationWindow).CatalogTree.TreeControl; } } public void OnShow() { } public void OnHide() { } public bool ShowWith(IExplorerObject exObject) { return (exObject is IExplorerParentObject); } public string Title { get { return "Contents"; } } public void RefreshContents() { if (this.InvokeRequired) { RefreshContextDelegate d = new RefreshContextDelegate(RefreshContents); this.Invoke(d); } else { if (!(_exObject is IExplorerParentObject)) return; Cursor = Cursors.WaitCursor; ((IExplorerParentObject)_exObject).Refresh(); BuildList(); base.Refresh(); Cursor = Cursors.Default; } } public IExplorerObject ExplorerObject { get { return _exObject; } set { if (_exObject == value) return; listView.Items.Clear(); _exObject = value; if (_exObject == null) return; BuildList(); } } #endregion private void BuildList() { BuildList(false); } private void BuildList(bool checkTreeNodes) { if (_worker != null) { _cancelTracker.Cancel(); //while (_worker != null) ; } //_worker=new Thread(new ParameterizedThreadStart(BuildListThread)); //_worker.Start(checkTreeNodes); BuildListThread(checkTreeNodes); } #region BuildListThread private void BuildListThread(object chkTreeNodes) { bool checkTreeNodes = (bool)chkTreeNodes; ClearList(); if (_exObject is IExplorerParentObject) { List<IExplorerObject> childs = ((IExplorerParentObject)_exObject).ChildObjects; if (childs != null) { IStatusBar statusbar = (_app != null) ? _app.StatusBar : null; List<IExplorerObject> childObjects = ((IExplorerParentObject)_exObject).ChildObjects; if (childObjects == null) return; int pos = 0, count = childObjects.Count; if (statusbar != null) statusbar.ProgressVisible = true; foreach (IExplorerObject exObject in childObjects) { if (exObject == null) continue; if (statusbar != null) { statusbar.ProgressValue = (int)(((double)pos++ / (double)count) * 100.0); statusbar.Text = exObject.Name; statusbar.Refresh(); } if (!_cancelTracker.Continue) { break; } if (_filter != null && !(exObject is IExplorerParentObject) && !(exObject is IExplorerObjectDoubleClick) && _open) { if (!_filter.Match(exObject)) continue; } int imageIndex = gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(exObject); if (imageIndex == -1) continue; string[] texts = null; if (exObject is IExporerOjectSchema) texts = new string[] { exObject.Name, exObject.Type, ((IExporerOjectSchema)exObject).Schema }; else texts = new string[] { exObject.Name, exObject.Type }; ListViewItem item = new ExplorerObjectListViewItem(texts, exObject); item.ImageIndex = imageIndex; AddListItem(item); if (checkTreeNodes && _tree != null) { CheckTree(exObject); } if (exObject is IExplorerObjectDeletable) ((IExplorerObjectDeletable)exObject).ExplorerObjectDeleted += new ExplorerObjectDeletedEvent(ContentsList_ExplorerObjectDeleted); if (exObject is IExplorerObjectRenamable) ((IExplorerObjectRenamable)exObject).ExplorerObjectRenamed += new ExplorerObjectRenamedEvent(ContentsList_ExplorerObjectRenamed); } if (statusbar != null) { statusbar.ProgressVisible = false; statusbar.Text = pos.ToString() + " Objects..."; statusbar.Refresh(); } } } _worker = null; } private delegate void ClearListCallback(); private void ClearList() { if (this.InvokeRequired) { ClearListCallback d = new ClearListCallback(ClearList); this.Invoke(d); } else { listView.Items.Clear(); } } private delegate void AddListItemCallback(ListViewItem item); private void AddListItem(ListViewItem item) { if (this.InvokeRequired) { AddListItemCallback d = new AddListItemCallback(AddListItem); this.Invoke(d, new object[] { item }); } else { //listView.Items.Add(item); int index = listView.Items.Count, count = listView.Items.Count; if (item is ExplorerObjectListViewItem) { var exObject = ((ExplorerObjectListViewItem)item).ExplorerObject; if (exObject != null) { for (index = 0; index < count; index++) { ListViewItem listItem = listView.Items[index]; if(listItem is ExplorerObjectListViewItem) { var listExObject = ((ExplorerObjectListViewItem)listItem).ExplorerObject; if(listExObject!=null) { if (exObject.Priority < listExObject.Priority) break; if (exObject.Priority == listExObject.Priority && exObject.Name.ToLower().CompareTo(listExObject.Name.ToLower()) < 0) break; } } } } } listView.Items.Insert(Math.Min(count, index), item); } } private delegate void CheckTreeCallback(IExplorerObject exObject); private void CheckTree(IExplorerObject exObject) { if (this.InvokeRequired) { CheckTreeCallback d = new CheckTreeCallback(CheckTree); this.Invoke(d, new object[] { exObject }); } else { if (!_tree.HasChildNode(exObject)) _tree.AddChildNode(exObject); } } #endregion private void ContentsList_ExplorerObjectRenamed(IExplorerObject exObject) { ListViewItem item = FindItem(exObject); if (item != null) item.Text = exObject.Name; } private void ContentsList_ExplorerObjectDeleted(IExplorerObject exObject) { ListViewItem item = FindItem(exObject); if (item != null) listView.Items.Remove(item); //_tree.RemoveChildNode(exObject); } private ListViewItem FindItem(IExplorerObject exObject) { if (exObject == null) return null; foreach (ListViewItem item in listView.Items) { if (item is ExplorerObjectListViewItem && ((ExplorerObjectListViewItem)item).ExplorerObject == exObject) return item; } return null; } public bool AllowContextMenu { get { return _allowContextMenu; } set { _allowContextMenu = value; } } #region DragDrop private void listView_DragDrop(object sender, DragEventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { Cursor = Cursors.WaitCursor; ((IExplorerObjectContentDragDropEvents)_exObject).Content_DragDrop(e); Cursor = Cursors.Default; BuildList(true); } } private void listView_DragEnter(object sender, DragEventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { ((IExplorerObjectContentDragDropEvents)_exObject).Content_DragEnter(e); } } private void listView_DragLeave(object sender, EventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { ((IExplorerObjectContentDragDropEvents)_exObject).Content_DragLeave(e); } } private void listView_DragOver(object sender, DragEventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { ((IExplorerObjectContentDragDropEvents)_exObject).Content_DragOver(e); } } private void listView_GiveFeedback(object sender, GiveFeedbackEventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { ((IExplorerObjectContentDragDropEvents)_exObject).Content_GiveFeedback(e); } } private void listView_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { if (_exObject is IExplorerObjectContentDragDropEvents) { ((IExplorerObjectContentDragDropEvents)_exObject).Content_QueryContinueDrag(e); } } #endregion #region IOrder Members public int SortOrder { get { return 0; } } #endregion #region ContextMenu private void listView_Click(object sender, EventArgs e) { ShowContextMenu(); } private void listView_MouseDown(object sender, MouseEventArgs e) { _button = e.Button; if (listView.GetItemAt(_mX, _mY) != null) return; ShowContextMenu(); } //private ExplorerObjectListViewItem _contextItem = null; private IExplorerObject _contextObject = null; ContextMenuStrip _strip = null; private void ShowContextMenu() { if (!_allowContextMenu) return; ListViewItem item = listView.GetItemAt(_mX, _mY); IExplorerObject exObject; if (item is ExplorerObjectListViewItem) { exObject = ((ExplorerObjectListViewItem)item).ExplorerObject; } else { exObject = _exObject; } if (exObject == null) return; Cursor = Cursors.WaitCursor; if (_button == MouseButtons.Right) { ContextMenuStrip strip = BuildContextMenu(exObject, this.SelectedExplorerObjects, item == null); if (strip != null && strip.Items.Count > 0) { if (item == null) _contextObject = null; else _contextObject = ((ExplorerObjectListViewItem)item).ExplorerObject; _strip.Show(listView, new Point(_mX, _mY)); } } Cursor = Cursors.Default; } internal ContextMenuStrip BuildContextMenu(IExplorerObject exObject) { List<IExplorerObject> context = new List<IExplorerObject>(); context.Add(exObject); return BuildContextMenu(exObject, context, false); } private ContextMenuStrip BuildContextMenu(IExplorerObject exObject, List<IExplorerObject> context, bool emptyContentsClick) { if (_strip != null && _strip.Visible == true) { _strip.Close(); } _strip = contextStrip; for (int i = _strip.Items.Count - 1; i >= _contextItemCount; i--) { _strip.Items.RemoveAt(i); } toolStripMenuItemNew.DropDownItems.Clear(); PlugInManager compMan = new PlugInManager(); foreach (XmlNode compNode in compMan.GetPluginNodes(Plugins.Type.IExplorerObject)) { IExplorerObject ex = compMan.CreateInstance(compNode) as IExplorerObject; if (ex is IExplorerObjectCreatable) { if (!((IExplorerObjectCreatable)ex).CanCreate(_exObject)) continue; ToolStripItem createNewItem = new CreateNewToolStripItem(ex); createNewItem.Click += new EventHandler(createNewItem_Click); toolStripMenuItemNew.DropDownItems.Add(createNewItem); } } toolStripMenuItemNew.Enabled = (toolStripMenuItemNew.DropDownItems.Count != 0); if (_app != null) { _app.AppendContextMenuItems(_strip, emptyContentsClick ? null : context/*this.SelectedExplorerObjects*/); } CommandInterpreter.AppendMenuItems(_strip, exObject); if (!emptyContentsClick) { //if (exObject is IExplorerObjectRenamable) //{ // if (_strip.Items.Count > 0) _strip.Items.Add(new ToolStripSeparator()); // _strip.Items.Add(_renameMenuItem); //} //if (exObject is IExplorerObjectDeletable) //{ // _strip.Items.Add(_deleteMenuItem); //} } if (exObject is IExplorerObjectContextMenu) { ToolStripItem[] contextItems = ((IExplorerObjectContextMenu)exObject).ContextMenuItems; if (contextItems != null && contextItems.Length > 0) { _strip.Items.Add(new ToolStripSeparator()); foreach (ToolStripItem contextItem in contextItems) { _strip.Items.Add(contextItem); } } } if (exObject is IExplorerObjectContextMenu2) { ToolStripItem[] contextItems = ((IExplorerObjectContextMenu2)exObject).ContextMenuItems(RefreshContents); if (contextItems != null && contextItems.Length > 0) { _strip.Items.Add(new ToolStripSeparator()); foreach (ToolStripItem contextItem in contextItems) { _strip.Items.Add(contextItem); } } } if (exObject != null && exObject.Object is IFeatureClass) { IFeatureClass fc = (IFeatureClass)exObject.Object; if (fc.Dataset != null && fc.Dataset.Database is IFeatureDatabaseReplication) { _strip.Items.Add(new ToolStripSeparator()); _strip.Items.Add(_replicationMenuItem); _appendReplicationIDMenuItem.Enabled = !Replication.FeatureClassHasRelicationID(fc); _checkoutMenuItem.Enabled = Replication.FeatureClassCanReplicate(fc); _checkinMenuItem.Enabled = (Replication.FeatureClassGeneration(fc) > 0); } } if (exObject is IMetadata) { _strip.Items.Add(new ToolStripSeparator()); _strip.Items.Add(_metadataMenuItem); } _contextObject = exObject; return _strip; } private int _mX = 0, _mY = 0; private MouseButtons _button = MouseButtons.None; private void listView_MouseMove(object sender, MouseEventArgs e) { _mX = e.X; _mY = e.Y; } #endregion public void createNewItem_Click(object sender, EventArgs e) { if (!(sender is CreateNewToolStripItem)) return; IExplorerObject exObject = ((CreateNewToolStripItem)sender).ExplorerObject; CreateNewItem(exObject); } public void CreateNewItem(IExplorerObject exObject) { if (!(exObject is IExplorerObjectCreatable)) return; IExplorerObject newExObj = ((IExplorerObjectCreatable)exObject).CreateExplorerObject(_exObject); if (newExObj == null) return; if (_tree != null) newExObj = _tree.AddChildNode(newExObj); int imageIndex = gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(newExObj); string[] texts = { newExObj.Name, newExObj.Type }; ListViewItem item = new ExplorerObjectListViewItem(texts, newExObj); item.ImageIndex = imageIndex; if (newExObj is IExplorerObjectDeletable) ((IExplorerObjectDeletable)newExObj).ExplorerObjectDeleted += new ExplorerObjectDeletedEvent(ContentsList_ExplorerObjectDeleted); if (newExObj is IExplorerObjectRenamable) ((IExplorerObjectRenamable)newExObj).ExplorerObjectRenamed += new ExplorerObjectRenamedEvent(ContentsList_ExplorerObjectRenamed); listView.Items.Add(item); } private void listView_DoubleClick(object sender, EventArgs e) { ListViewItem item = listView.GetItemAt(_mX, _mY); if (item is ExplorerObjectListViewItem && ((ExplorerObjectListViewItem)item).ExplorerObject is IExplorerObjectDoubleClick) { ExplorerObjectEventArgs args = new ExplorerObjectEventArgs(); ((IExplorerObjectDoubleClick)((ExplorerObjectListViewItem)item).ExplorerObject).ExplorerObjectDoubleClick(args); CheckExplorerObjectEventArgs(args); return; } if (_tree != null) { if (!(item is ExplorerObjectListViewItem)) return; _tree.SelectChildNode(((ExplorerObjectListViewItem)item).ExplorerObject); } if (ItemDoubleClicked != null) ItemDoubleClicked(item); } private void CheckExplorerObjectEventArgs(ExplorerObjectEventArgs args) { if (args.NewExplorerObject != null) { int imageIndex = gView.Explorer.UI.Framework.UI.ExplorerIcons.ImageIndex(args.NewExplorerObject); string[] texts = { args.NewExplorerObject.Name, args.NewExplorerObject.Type }; ListViewItem item = new ExplorerObjectListViewItem(texts, args.NewExplorerObject); item.ImageIndex = imageIndex; listView.Items.Add(item); if (_tree != null) _tree.AddChildNode(args.NewExplorerObject); } } void _deleteMenuItem_Click(object sender, EventArgs e) { //if (_contextItem is ExplorerObjectListViewItem && listView.SelectedItems.Count == 1 && _contextItem == listView.SelectedItems[0]) if (_contextObject != null) { IExplorerObject exObject = _contextObject; //_contextItem.ExplorerObject; if (MessageBox.Show("Do you realy want to delete the selected item (" + _contextObject.Name + ") ?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; if (exObject is IExplorerObjectDeletable) { ExplorerObjectEventArgs args = new ExplorerObjectEventArgs(); //args.Node = _contextItem; ((IExplorerObjectDeletable)exObject).DeleteExplorerObject(args); //if (_tree != null) _tree.RemoveChildNode(exObject); //listView.Items.Remove(_contextItem); } _contextObject = null; } //else if (listView.SelectedItems.Count > 1 && listView.SelectedItems.Contains(_contextItem)) else if (listView.SelectedItems.Count > 1) { bool found = false; foreach (ExplorerObjectListViewItem item in listView.SelectedItems) { if (item.ExplorerObject == _contextObject) { found = true; break; } } _contextObject = null; if (!found) return; if (MessageBox.Show("Do you realy want to delete the " + listView.SelectedItems.Count + " selected items?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; foreach (ListViewItem item in listView.SelectedItems) { if (!(item is ExplorerObjectListViewItem)) continue; IExplorerObject exObject = ((ExplorerObjectListViewItem)item).ExplorerObject; if (!(exObject is IExplorerObjectDeletable)) continue; ExplorerObjectEventArgs args = new ExplorerObjectEventArgs(); ((IExplorerObjectDeletable)exObject).DeleteExplorerObject(args); //if (_tree != null) _tree.RemoveChildNode(exObject); //listView.Items.Remove(item); } } } void _renameMenuItem_Click(object sender, EventArgs e) { //if (_contextObject != null) //{ // FormRenameExplorerObject dlg = new FormRenameExplorerObject(_contextObject); // if (dlg.ShowDialog() == DialogResult.OK) // { // this.RefreshContents(); // } //} //BeginRename(); } void _metadataMenuItem_Click(object sender, EventArgs e) { //if (_contextItem is ExplorerObjectListViewItem) if (_contextObject != null) { IExplorerObject exObject = _contextObject; // ((ExplorerObjectListViewItem)_contextItem).ExplorerObject; if (exObject is IMetadata) { XmlStream xmlStream = new XmlStream(String.Empty); ((IMetadata)exObject).ReadMetadata(xmlStream); FormMetadata dlg = new FormMetadata(xmlStream, exObject.Object); if (dlg.ShowDialog() == DialogResult.OK) { ((IMetadata)exObject).WriteMetadata(dlg.Stream); } } _contextObject = null; } } void _appendReplicationIDMenuItem_Click(object sender, EventArgs e) { //if (_contextItem is ExplorerObjectListViewItem && listView.SelectedItems.Count == 1 && _contextItem == listView.SelectedItems[0]) if (_contextObject != null) { IExplorerObject exObject = _contextObject; //_contextItem.ExplorerObject; if (exObject != null && exObject.Object is IFeatureClass && ((IFeatureClass)exObject.Object).Dataset != null) { IFeatureDatabase fdb = ((IFeatureClass)exObject.Object).Dataset.Database as IFeatureDatabase; if (fdb is IFeatureDatabaseReplication) { ReplicationUI.ShowAddReplicationIDDialog((IFeatureClass)exObject.Object); } } _contextObject = null; } } void _checkoutMenuItem_Click(object sender, EventArgs e) { //if (_contextItem is ExplorerObjectListViewItem && listView.SelectedItems.Count == 1 && _contextItem == listView.SelectedItems[0]) if (_contextObject != null) { IExplorerObject exObject = _contextObject; // _contextItem.ExplorerObject; if (exObject != null && exObject.Object is IFeatureClass && ((IFeatureClass)exObject.Object).Dataset != null) { IFeatureDatabase fdb = ((IFeatureClass)exObject.Object).Dataset.Database as IFeatureDatabase; if (fdb is IFeatureDatabaseReplication) { ReplicationUI.ShowCheckoutDialog((IFeatureClass)exObject.Object); } } _contextObject = null; } } void _checkinMenuItem_Click(object sender, EventArgs e) { //if (_contextItem is ExplorerObjectListViewItem && listView.SelectedItems.Count == 1 && _contextItem == listView.SelectedItems[0]) if (_contextObject != null) { IExplorerObject exObject = _contextObject; // _contextItem.ExplorerObject; if (exObject != null && exObject.Object is IFeatureClass && ((IFeatureClass)exObject.Object).Dataset != null) { IFeatureDatabase fdb = ((IFeatureClass)exObject.Object).Dataset.Database as IFeatureDatabase; if (fdb is IFeatureDatabaseReplication) { ReplicationUI.ShowCheckinDialog((IFeatureClass)exObject.Object); } } _contextObject = null; } } private void listView_ItemDrag(object sender, ItemDragEventArgs e) { ListViewItem item = (ListViewItem)e.Item; if (listView.SelectedItems.Count > 1 && listView.SelectedItems.Contains(item)) { List<IExplorerObjectSerialization> exObjects = new List<IExplorerObjectSerialization>(); foreach (ListViewItem i in listView.SelectedItems) { if (i is ExplorerObjectListViewItem && ((ExplorerObjectListViewItem)i).ExplorerObject != null) { IExplorerObjectSerialization ser = ExplorerObjectManager.SerializeExplorerObject(((ExplorerObjectListViewItem)i).ExplorerObject); if (ser == null) continue; exObjects.Add(ser); } } this.DoDragDrop(exObjects, DragDropEffects.Copy); } else { if (item is ExplorerObjectListViewItem && ((ExplorerObjectListViewItem)item).ExplorerObject != null) { List<IExplorerObjectSerialization> exObjects = new List<IExplorerObjectSerialization>(); IExplorerObjectSerialization ser = ExplorerObjectManager.SerializeExplorerObject(((ExplorerObjectListViewItem)item).ExplorerObject); if (ser != null) { exObjects.Add(ser); this.DoDragDrop(exObjects, DragDropEffects.Copy); } } } } private void listView_SelectedIndexChanged(object sender, EventArgs e) { if (ItemSelected != null) ItemSelected(this.SelectedExplorerObjects); /* if (listView.SelectedItems.Count == 0) { } if (ItemSelected!=null) ItemSelected( listView.SelectedItemslistView.SelectedItems[0] ); * */ } public bool MultiSelection { get { return listView.MultiSelect; } set { listView.MultiSelect = value; } } public void DeleteItem(IExplorerObject exObject) { foreach (ExplorerObjectListViewItem item in listView.Items) { if (ExObjectComparer.Equals(exObject, item.ExplorerObject)) { listView.Items.Remove(item); } } } public void RenameItem(IExplorerObject exObject) { /* if (pos >= 0 && pos < listView.Items.Count) { listView.Items[pos].Text = name; } * */ } private void toolStripMenuItemRefresh_Click(object sender, EventArgs e) { this.RefreshContents(); } #region RenameNode private class RenameTextBox : TextBox { private IExplorerObjectRenamable _exObject; public RenameTextBox(IExplorerObjectRenamable exObject) { _exObject = exObject; base.LostFocus += new EventHandler(RenameTextBox_LostFocus); base.KeyDown += new KeyEventHandler(RenameTextBox_KeyDown); } void RenameTextBox_KeyDown(object sender, KeyEventArgs e) { if (!(sender is RenameTextBox)) return; if (e.KeyCode == Keys.Enter) { this.LostFocus -= new EventHandler(RenameTextBox_LostFocus); if (this.Parent != null) this.Parent.Controls.Remove(sender as RenameTextBox); RenameObject(); } } void RenameTextBox_LostFocus(object sender, EventArgs e) { if (!(sender is RenameTextBox)) return; if (this.Parent != null) this.Parent.Controls.Remove(sender as RenameTextBox); RenameObject(); } public void RenameObject() { if (_exObject != null) { _exObject.RenameExplorerObject(this.Text); } } } private void BeginRename() { if (listView.SelectedItems.Count == 1 && listView.SelectedItems[0] is ExplorerObjectListViewItem) { ExplorerObjectListViewItem item = listView.SelectedItems[0] as ExplorerObjectListViewItem; if (item.ExplorerObject is IExplorerObjectRenamable) { BeginRename(item); } } } private void BeginRename(ExplorerObjectListViewItem item) { if (item == null || !(item.ExplorerObject is IExplorerObjectRenamable)) return; RenameTextBox box = new RenameTextBox(item.ExplorerObject as IExplorerObjectRenamable); box.Bounds = new Rectangle(16, item.Bounds.Y, item.Bounds.Width - 16, item.Bounds.Height); box.Text = item.Text; listView.Controls.Add(box); box.Visible = true; box.Focus(); box.Select(0, item.Text.Length); } #endregion internal ListViewItem GetItemPerPath(string path) { foreach (ListViewItem item in listView.Items) { if (!(item is ExplorerObjectListViewItem)) continue; IExplorerObject exObject = ((ExplorerObjectListViewItem)item).ExplorerObject; if (exObject == null) continue; if (exObject.FullName == path || exObject.FullName == path + @"\") { return item; } } return null; } } internal class ExplorerObjectListViewItem : ListViewItem { private IExplorerObject _exObject = null; public ExplorerObjectListViewItem(string[] items, IExplorerObject exObject) : base(items) { _exObject = exObject; } public IExplorerObject ExplorerObject { get { return _exObject; } } } internal class CreateNewToolStripItem : ToolStripMenuItem { IExplorerObject _exObject; public CreateNewToolStripItem(IExplorerObject exObject) { _exObject = exObject; string name = String.IsNullOrEmpty(_exObject.Name) ? _exObject.Type : _exObject.Name; if (!name.Contains("...")) base.Text = LocalizedResources.GetResString("ArgString.Create", "Create " + name, name); else base.Text = name; if (_exObject.Icon != null && _exObject.Icon.Image != null) base.Image = _exObject.Icon.Image; } public IExplorerObject ExplorerObject { get { return _exObject; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System.Diagnostics; using System.Collections.Generic; /* * This class describes an attribute type and potential values. * This encapsulates the information for one Attdef * in an * Attlist in a DTD as described below: */ internal sealed class SchemaAttDef : SchemaDeclBase, IDtdDefaultAttributeInfo { internal enum Reserve { None, XmlSpace, XmlLang }; private string _defExpanded; // default value in its expanded form private int _lineNum; private int _linePos; private int _valueLineNum; private int _valueLinePos; private Reserve _reserved = Reserve.None; // indicate the attribute type, such as xml:lang or xml:space private readonly bool _defaultValueChecked; private XmlSchemaAttribute _schemaAttribute; public static readonly SchemaAttDef Empty = new SchemaAttDef(); // // Constructors // public SchemaAttDef(XmlQualifiedName name, string prefix) : base(name, prefix) { } public SchemaAttDef(XmlQualifiedName name) : base(name, null) { } private SchemaAttDef() { } // // IDtdAttributeInfo interface // #region IDtdAttributeInfo Members string IDtdAttributeInfo.Prefix { get { return ((SchemaAttDef)this).Prefix; } } string IDtdAttributeInfo.LocalName { get { return ((SchemaAttDef)this).Name.Name; } } int IDtdAttributeInfo.LineNumber { get { return ((SchemaAttDef)this).LineNumber; } } int IDtdAttributeInfo.LinePosition { get { return ((SchemaAttDef)this).LinePosition; } } bool IDtdAttributeInfo.IsNonCDataType { get { return this.TokenizedType != XmlTokenizedType.CDATA; } } bool IDtdAttributeInfo.IsDeclaredInExternal { get { return ((SchemaAttDef)this).IsDeclaredInExternal; } } bool IDtdAttributeInfo.IsXmlAttribute { get { return this.Reserved != SchemaAttDef.Reserve.None; } } #endregion // // IDtdDefaultAttributeInfo interface // #region IDtdDefaultAttributeInfo Members string IDtdDefaultAttributeInfo.DefaultValueExpanded { get { return ((SchemaAttDef)this).DefaultValueExpanded; } } object IDtdDefaultAttributeInfo.DefaultValueTyped { get { return ((SchemaAttDef)this).DefaultValueTyped; } } int IDtdDefaultAttributeInfo.ValueLineNumber { get { return ((SchemaAttDef)this).ValueLineNumber; } } int IDtdDefaultAttributeInfo.ValueLinePosition { get { return ((SchemaAttDef)this).ValueLinePosition; } } #endregion // // Internal properties // internal int LinePosition { get { return _linePos; } set { _linePos = value; } } internal int LineNumber { get { return _lineNum; } set { _lineNum = value; } } internal int ValueLinePosition { get { return _valueLinePos; } set { _valueLinePos = value; } } internal int ValueLineNumber { get { return _valueLineNum; } set { _valueLineNum = value; } } internal string DefaultValueExpanded { get { return (_defExpanded != null) ? _defExpanded : string.Empty; } set { _defExpanded = value; } } internal XmlTokenizedType TokenizedType { get { return Datatype.TokenizedType; } set { this.Datatype = XmlSchemaDatatype.FromXmlTokenizedType(value); } } internal Reserve Reserved { get { return _reserved; } set { _reserved = value; } } internal bool DefaultValueChecked { get { return _defaultValueChecked; } } internal XmlSchemaAttribute SchemaAttribute { get { return _schemaAttribute; } set { _schemaAttribute = value; } } internal void CheckXmlSpace(IValidationEventHandling validationEventHandling) { if (datatype.TokenizedType == XmlTokenizedType.ENUMERATION && (values != null) && (values.Count <= 2)) { string s1 = values[0].ToString(); if (values.Count == 2) { string s2 = values[1].ToString(); if ((s1 == "default" || s2 == "default") && (s1 == "preserve" || s2 == "preserve")) { return; } } else { if (s1 == "default" || s1 == "preserve") { return; } } } validationEventHandling.SendEvent(new XmlSchemaException(SR.Sch_XmlSpace, string.Empty), XmlSeverityType.Error); } internal SchemaAttDef Clone() { return (SchemaAttDef)MemberwiseClone(); } } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.BluetoothAddress // // Copyright (c) 2003-2010 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Diagnostics; namespace InTheHand.Net { /// <summary> /// Represents a Bluetooth device address. /// </summary> /// <remarks>The BluetoothAddress class contains the address of a bluetooth device.</remarks> #if !NETCF [Serializable] #endif public sealed class BluetoothAddress : IComparable, IFormattable #if !NETCF , System.Xml.Serialization.IXmlSerializable //could be supported on NETCFv2 , System.Runtime.Serialization.ISerializable #endif { [NonSerialized] // Custom serialized in text format, to avoid any endian or length issues etc. private byte[] data; #region Constructor internal BluetoothAddress() { data = new byte[8]; } /// <summary> /// Initializes a new instance of the <see cref="BluetoothAddress"/> class with the specified address. /// </summary> /// <param name="address"><see cref="Int64"/> representation of the address.</param> public BluetoothAddress(long address) : this() { //copy value to array BitConverter.GetBytes(address).CopyTo(data,0); } /// <summary> /// Initializes a new instance of the <see cref="BluetoothAddress"/> class with the specified address. /// </summary> /// <param name="address"><see cref="UInt64"/> representation of the address.</param> [CLSCompliant(false)] public BluetoothAddress(ulong address) : this() { //copy value to array BitConverter.GetBytes(address).CopyTo(data, 0); } /// <summary> /// Initializes a new instance of the <see cref="BluetoothAddress"/> class with the specified address. /// </summary> /// - /// <remarks> /// <para>Note: The address should be supplied in little-endian order on the /// current Windows platform (which is little-endian). /// For forward compatibility it would be safer to use the /// <see cref="M:InTheHand.Net.BluetoothAddress.Parse(System.String)"/> method, /// which will be correct for all platforms. /// Or consider /// <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromLittleEndian(System.Byte[])"/> /// or /// <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromBigEndian(System.Byte[])"/>. /// /// </para> /// </remarks> /// - /// <param name="address">Address as 6 byte array.</param> /// <exception cref="T:System.ArgumentNullException">address passed was <see langword="null"/>.</exception> /// <exception cref="T:System.ArgumentException">address passed was not a 6 byte array.</exception> public BluetoothAddress(byte[] address) : this() { if (address == null) { throw new ArgumentNullException("address"); } if(address.Length == 6 || address.Length == 8) { Buffer.BlockCopy(address, 0, data, 0, 6); } else { throw new ArgumentException("Address must be six bytes long.", "address"); } } #endregion #region FactoryMethods /// <summary> /// Create a <see cref="T:InTheHand.Net.BluetoothAddress"/> from an Array of <see cref="T:System.Byte"/> /// where the array is in standard order. /// </summary> /// - /// <remarks> /// <para>Different protocol stacks have different ways of storing a /// Bluetooth Address. Some use an array of bytes e.g. "byte[6]", /// which means that the first byte of the address comes first in /// memory (which we&#x2019;ll call big-endian format). Others /// e.g. the Microsoft stack use a long integer (e.g. uint64) which /// means that the *last* byte of the address come comes first in /// memory (which we&#x2019;ll call little-endian format) /// </para> /// <para>This method creates an address for the first form. /// See <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromLittleEndian(System.Byte[])"/> for the second form. /// </para> /// </remarks> /// - /// <param name="address">An Array of <see cref="T:System.Byte"/> /// with the Bluetooth Address ordered as described above. /// </param> /// - /// <returns>The resultant <see cref="T:InTheHand.Net.BluetoothAddress"/>. /// </returns> /// - /// <seealso cref="M:InTheHand.Net.BluetoothAddress.CreateFromLittleEndian(System.Byte[])"/> public static BluetoothAddress CreateFromBigEndian(byte[] address) { var clone = (byte[])address.Clone(); Array.Reverse(clone); return new BluetoothAddress(clone); } /// <summary> /// Create a <see cref="T:InTheHand.Net.BluetoothAddress"/> from an Array of <see cref="T:System.Byte"/> /// where the array is in reverse order. /// </summary> /// - /// <remarks> /// <para>Different protocol stacks have different ways of storing a /// Bluetooth Address. Some use an array of bytes e.g. "byte[6]", /// which means that the first byte of the address comes first in /// memory (which we&#x2019;ll call big-endian format). Others /// e.g. the Microsoft stack use a long integer (e.g. uint64) which /// means that the *last* byte of the address come comes first in /// memory (which we&#x2019;ll call little-endian format) /// </para> /// <para>This method creates an address for the second form. /// See <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromLittleEndian(System.Byte[])"/> for the first form. /// </para> /// </remarks> /// - /// <param name="address">An Array of <see cref="T:System.Byte"/> /// with the Bluetooth Address ordered as described above. /// </param> /// - /// <returns>The resultant <see cref="T:InTheHand.Net.BluetoothAddress"/>. /// </returns> /// - /// <seealso cref="M:InTheHand.Net.BluetoothAddress.CreateFromBigEndian(System.Byte[])"/> public static BluetoothAddress CreateFromLittleEndian(byte[] address) { var clone = (byte[])address.Clone(); return new BluetoothAddress(clone); } #endregion #region Parse /// <summary> /// Converts the string representation of an address to it's <see cref="BluetoothAddress"/> equivalent. /// A return value indicates whether the operation succeeded. /// </summary> /// <param name="bluetoothString">A string containing an address to convert.</param> /// <param name="result">When this method returns, contains the <see cref="BluetoothAddress"/> equivalent to the address contained in s, if the conversion succeeded, or null (Nothing in Visual Basic) if the conversion failed. /// The conversion fails if the s parameter is null or is not of the correct format.</param> /// <returns>true if s is a valid Bluetooth address; otherwise, false.</returns> public static bool TryParse(string bluetoothString, out BluetoothAddress result) { Exception ex = ParseInternal(bluetoothString, out result); if (ex != null) return false; else return true; } /// <summary> /// Converts the string representation of a Bluetooth address to a new <see cref="BluetoothAddress"/> instance. /// </summary> /// <param name="bluetoothString">A string containing an address to convert.</param> /// <returns>New <see cref="BluetoothAddress"/> instance.</returns> /// <remarks>Address must be specified in hex format optionally separated by the colon or period character e.g. 000000000000, 00:00:00:00:00:00 or 00.00.00.00.00.00.</remarks> /// <exception cref="T:System.ArgumentNullException">bluetoothString is null.</exception> /// <exception cref="T:System.FormatException">bluetoothString is not a valid Bluetooth address.</exception> public static BluetoothAddress Parse(string bluetoothString) { BluetoothAddress result; Exception ex = ParseInternal(bluetoothString, out result); if (ex != null) throw ex; else return result; } #endregion [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Returned to caller.")] static Exception ParseInternal(string bluetoothString, out BluetoothAddress result) { const Exception Success = null; result = null; if (bluetoothString == null) { return new ArgumentNullException("bluetoothString"); } if (bluetoothString.IndexOf(":", StringComparison.Ordinal) > -1) { //assume address in standard hex format 00:00:00:00:00:00 //check length if (bluetoothString.Length != 17) { return new FormatException("bluetoothString is not a valid Bluetooth address."); } try { byte[] babytes = new byte[8]; //split on colons string[] sbytes = bluetoothString.Split(':'); for (int ibyte = 0; ibyte < 6; ibyte++) { //parse hex byte in reverse order babytes[ibyte] = byte.Parse(sbytes[5 - ibyte], System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } result = new BluetoothAddress(babytes); return Success; } catch (Exception ex) { return ex; } } else if (bluetoothString.IndexOf(".", StringComparison.Ordinal) > -1) { //assume address in uri hex format 00.00.00.00.00.00 //check length if (bluetoothString.Length != 17) { return new FormatException("bluetoothString is not a valid Bluetooth address."); } try { byte[] babytes = new byte[8]; //split on periods string[] sbytes = bluetoothString.Split('.'); for (int ibyte = 0; ibyte < 6; ibyte++) { //parse hex byte in reverse order babytes[ibyte] = byte.Parse(sbytes[5 - ibyte], System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } result = new BluetoothAddress(babytes); return Success; } catch (Exception ex) { return ex; } } else { //assume specified as long integer if ((bluetoothString.Length < 12) | (bluetoothString.Length > 16)) { return new FormatException("bluetoothString is not a valid Bluetooth address."); } try { result = new BluetoothAddress(long.Parse(bluetoothString, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture)); return Success; } catch (Exception ex) { return ex; } } } #region SAP /// <summary> /// Significant address part. /// </summary> [CLSCompliant(false)] public uint Sap { get { return BitConverter.ToUInt32(data, 0); } } #endregion #region LAP #endregion #region UAP #endregion #region NAP /// <summary> /// Non-significant address part. /// </summary> [CLSCompliant(false)] public ushort Nap { get { return BitConverter.ToUInt16(data, 4); } } #endregion #region To Byte Array /// <summary> /// Returns the value as a byte array. /// </summary> /// - /// <remarks>In previous versions this returned the internal array, it now /// returns a copy. Addresses should be immutable, particularly for the /// None const! /// </remarks> /// - /// <returns>An array of byte</returns> public byte[] ToByteArray() { //return data; return (byte[])data.Clone(); } /// <summary> /// Returns the value as a byte array, /// where the array is in reverse order. /// </summary> /// - /// <remarks> /// <para>See <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromBigEndian(System.Byte[])"/> for discussion of /// different stack#x2019;s storage formats for Bluetooth Addresses. /// </para> /// <para>In previous versions this returned the internal array, it now /// returns a copy. Addresses should be immutable, particularly for the /// None const! /// </para> /// </remarks> /// - /// <returns>An array of byte of length six representing the Bluetooth address.</returns> public byte[] ToByteArrayLittleEndian() { var clone8 = ToByteArray(); var copy6 = new byte[6]; Array.Copy(clone8, copy6, copy6.Length); return copy6; } /// <summary> /// Returns the value as a byte array, /// where the array is in standard order. /// </summary> /// - /// <remarks> /// <para>See <see cref="M:InTheHand.Net.BluetoothAddress.CreateFromBigEndian(System.Byte[])"/> for discussion of /// different stack#x2019;s storage formats for Bluetooth Addresses. /// </para> /// <para>In previous versions this returned the internal array, it now /// returns a copy. Addresses should be immutable, particularly for the /// None const! /// </para> /// </remarks> /// - /// <returns>An array of byte of length six representing the Bluetooth address.</returns> public byte[] ToByteArrayBigEndian() { var arr6 = ToByteArrayLittleEndian(); Debug.Assert(arr6.Length == 6, "BAD, arr6.Length is: " + arr6.Length); Array.Reverse(arr6); return arr6; } #endregion #region ToInt64 /// <summary> /// Returns the Bluetooth address as a long integer. /// </summary> /// - /// <returns>An <see cref="T:System.Int64"/>.</returns> public long ToInt64() { return BitConverter.ToInt64(data, 0); } #endregion #region ToUInt64 /// <summary> /// Returns the Bluetooth address as an unsigned long integer. /// </summary> /// - /// <returns>An <see cref="T:System.UInt64"/>.</returns> [CLSCompliant(false)] public ulong ToUInt64() { return BitConverter.ToUInt64(data, 0); } #endregion #region Equals /// <summary> /// Compares two <see cref="BluetoothAddress"/> instances for equality. /// </summary> /// - /// <param name="obj">The <see cref="BluetoothAddress"/> /// to compare with the current instance. /// </param> /// - /// <returns><c>true</c> if <paramref name="obj"/> /// is a <see cref="BluetoothAddress"/> and equal to the current instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { BluetoothAddress bta = obj as BluetoothAddress; if(bta!=null) { return (this==bta); } return base.Equals (obj); } #endregion #region Get Hash Code /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return this.ToInt64().GetHashCode(); } #endregion #region Operators /// <summary> /// Returns an indication whether the values of two specified <see cref="BluetoothAddress"/> objects are equal.<para><b>New in v1.5</b></para> /// </summary> /// - /// <param name="x">A <see cref="BluetoothAddress"/> or <see langword="null"/>.</param> /// <param name="y">A <see cref="BluetoothAddress"/> or <see langword="null"/>.</param> /// - /// <returns><c>true</c> if the values of the two instance are equal; /// otherwise, <c>false</c>. /// </returns> public static bool operator ==(BluetoothAddress x, BluetoothAddress y) { if(((object)x == null) && ((object)y == null)) { return true; } if(((object)x != null) && ((object)y != null)) { if(x.ToInt64()==y.ToInt64()) { return true; } } return false; } /// <summary> /// Returns an indication whether the values of two specified <see cref="BluetoothAddress"/> objects are not equal. /// </summary> /// - /// <param name="x">A <see cref="BluetoothAddress"/> or <see langword="null"/>.</param> /// <param name="y">A <see cref="BluetoothAddress"/> or <see langword="null"/>.</param> /// - /// <returns><c>true</c> if the value of the two instance is different; /// otherwise, <c>false</c>. /// </returns> public static bool operator !=(BluetoothAddress x, BluetoothAddress y) { return !(x == y); } #endregion #region To String /// <summary> /// Converts the address to its equivalent string representation. /// </summary> /// <returns>The string representation of this instance.</returns> /// <remarks>The default return format is without a separator character /// - use the <see cref="M:InTheHand.Net.BluetoothAddress.ToString(System.String)"/> /// overload for more formatting options.</remarks> public override string ToString() { return this.ToString("N"); } /// <summary> /// Returns a <see cref="String"/> representation of the value of this <see cref="BluetoothAddress"/> instance, according to the provided format specifier. /// </summary> /// <param name="format">A single format specifier that indicates how to format the value of this address. /// The format parameter can be "N", "C", or "P". /// If format is null or the empty string (""), "N" is used.</param> /// <returns>A <see cref="String"/> representation of the value of this <see cref="BluetoothAddress"/>.</returns> /// <remarks><list type="table"> /// <listheader><term>Specifier</term><term>Format of Return Value </term></listheader> /// <item><term>N</term><term>12 digits: <para>XXXXXXXXXXXX</para></term></item> /// <item><term>C</term><term>12 digits separated by colons: <para>XX:XX:XX:XX:XX:XX</para></term></item> /// <item><term>P</term><term>12 digits separated by periods: <para>XX.XX.XX.XX.XX.XX</para></term></item> /// </list></remarks> public string ToString(string format) { string separator; if(format==null || format==string.Empty) { separator = string.Empty; } else { switch(format.ToUpper(CultureInfo.InvariantCulture)) { case "8": case "N": separator = string.Empty; break; case "C": separator = ":"; break; case "P": separator = "."; break; default: throw new FormatException("Invalid format specified - must be either \"N\", \"C\", \"P\", \"\" or null."); } } System.Text.StringBuilder result = new System.Text.StringBuilder(18); if (format == "8") { result.Append(data[7].ToString("X2") + separator); result.Append(data[6].ToString("X2") + separator); } result.Append(data[5].ToString("X2") + separator); result.Append(data[4].ToString("X2") + separator); result.Append(data[3].ToString("X2") + separator); result.Append(data[2].ToString("X2") + separator); result.Append(data[1].ToString("X2") + separator); result.Append(data[0].ToString("X2")); return result.ToString(); } #endregion #region Static /// <summary> /// Provides a null Bluetooth address. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Is now immutable.")] public static readonly BluetoothAddress None = new BluetoothAddress(); /// <summary> /// /// </summary> internal const int IacFirst = 0x9E8B00; /// <summary> /// /// </summary> internal const int IacLast = 0x9E8B3f; /// <summary> /// Limited Inquiry Access Code. /// </summary> public const int Liac = 0x9E8B00; /// <summary> /// General Inquire Access Code. /// The default inquiry code which is used to discover all devices in range. /// </summary> public const int Giac = 0x9E8B33; #endregion #region IComparable Members int IComparable.CompareTo(object obj) { BluetoothAddress bta = obj as BluetoothAddress; if (bta != null) { return this.ToInt64().CompareTo(bta.ToInt64()); } return -1; } #endregion #region IFormattable Members /// <summary> /// Returns a <see cref="String"/> representation of the value of this /// <see cref="BluetoothAddress"/> instance, according to the provided format specifier. /// </summary> /// - /// <param name="format">A single format specifier that indicates how to format the value of this Address. /// See <see cref="M:InTheHand.Net.BluetoothAddress.ToString(System.String)"/> /// for the possible format strings and their output. /// </param> /// <param name="formatProvider">Ignored. /// </param> /// - /// <returns>A <see cref="String"/> representation of the value of this /// <see cref="BluetoothAddress"/>. /// </returns> /// - /// <remarks>See <see cref="M:InTheHand.Net.BluetoothAddress.ToString(System.String)"/> /// for the possible format strings and their output. /// </remarks> public string ToString(string format, IFormatProvider formatProvider) { //for now just wrap existing ToString method return ToString(format); } #endregion #region IXmlSerializable Members #if !NETCF System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { return null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { String text = reader.ReadElementContentAsString(); BluetoothAddress tmpAddr = BluetoothAddress.Parse(text); this.data = tmpAddr.data; } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { // Serialize the address -- in text format, to avoid any endian or length // issues etc. writer.WriteString(this.ToString("N")); } #endif #endregion #region ISerializable Members #if !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)] private BluetoothAddress(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { String text = info.GetString("dataString"); BluetoothAddress tmpAddr = BluetoothAddress.Parse(text); this.data = tmpAddr.data; } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)] void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { // Serialize the address -- in text format, to avoid any endian or length // issues etc. info.AddValue("dataString", this.ToString("N")); } #endif #endregion #region Clone /// <summary> /// Creates a copy of the <see cref="BluetoothAddress"/>. /// </summary> /// <remarks>Creates a copy including of the internal byte array. /// </remarks> /// <returns>A copy of the <see cref="BluetoothAddress"/>. /// </returns> public object Clone() { BluetoothAddress addr2 = new BluetoothAddress(); addr2.data = (byte[])this.data.Clone(); return addr2; } #endregion } }
using System.Compiler; namespace Microsoft.Zing { internal class TypeSystem : System.Compiler.TypeSystem { internal TypeSystem(ErrorHandler errorHandler) : base(errorHandler) { } // // We add an implicit conversion from "object" to any of our heap-allocated // types. // // We also permit implicit conversions between "int" and "byte". // // TODO: We may need to construct a more elaborate expression here for the // conversion to permit the runtime to make the appropriate checks. // public override bool ImplicitCoercionFromTo(Expression source, TypeNode t1, TypeNode t2) { if (t1 == SystemTypes.Object) { if (t2 is Chan || t2 is Set || t2 is ZArray || t2 is Class) return true; else return false; } if (t2 == SystemTypes.Object) { if (t1 is Chan || t1 is Set || t1 is ZArray || t1 is Class) return true; else return false; } if (t1 == SystemTypes.Int32 && t2 == SystemTypes.UInt8) return true; if (t1 == SystemTypes.UInt8 && t2 == SystemTypes.Int32) return true; return base.ImplicitCoercionFromTo(source, t1, t2); } public override Expression ImplicitCoercion(Expression source, TypeNode targetType, TypeViewer typeViewer) { // LJW: added third parameter "typeViewer" so we override the correct thing if (source == null || source.Type == null || targetType == null) return null; if (source.Type is EnumNode && targetType == SystemTypes.Int32) { return source; } if (source.Type == SystemTypes.Object) { if (targetType is Chan || targetType is Set || targetType is ZArray || targetType is Class) return source; else { this.HandleError(source, System.Compiler.Error.NoImplicitCoercion, "object", targetType.FullName); return null; } } if (targetType == SystemTypes.Object) { if (!(source.Type is Chan || source.Type is Set || source.Type is ZArray || source.Type is Class)) { this.HandleError(source, System.Compiler.Error.NoImplicitCoercion, source.Type.FullName, "object"); return null; } } if (source.Type == SystemTypes.Int32 && targetType == SystemTypes.UInt8) { BinaryExpression binExpr = new BinaryExpression(source, new MemberBinding(null, SystemTypes.UInt8), NodeType.Castclass, source.SourceContext); binExpr.Type = SystemTypes.UInt8; return binExpr; } if (source.Type == SystemTypes.UInt8 && targetType == SystemTypes.Int32) { BinaryExpression binExpr = new BinaryExpression(source, new MemberBinding(null, SystemTypes.Int32), NodeType.Castclass, source.SourceContext); binExpr.Type = SystemTypes.Int32; return binExpr; } return base.ImplicitCoercion(source, targetType, typeViewer); } #if false public override Expression ExplicitLiteralCoercion(Literal lit, TypeNode sourceType, TypeNode targetType) { if (this.suppressOverflowCheck || !sourceType.IsPrimitiveInteger || !targetType.IsPrimitiveInteger) return this.ExplicitCoercion(lit, targetType); else return this.ImplicitLiteralCoercion(lit, sourceType, targetType, true); } public override Literal ImplicitLiteralCoercion(Literal lit, TypeNode sourceType, TypeNode targetType) { return this.ImplicitLiteralCoercion(lit, sourceType, targetType, false); } Literal ImplicitLiteralCoercion(Literal lit, TypeNode sourceType, TypeNode targetType, bool explicitCoercion) { if (sourceType == targetType) return lit; object val = lit.Value; EnumNode eN = targetType as EnumNode; if (eN != null) { if (val is int && ((int)val) == 0) { if (eN.UnderlyingType == SystemTypes.Int64 || eN.UnderlyingType == SystemTypes.UInt64) val = 0L; return new Literal(val, eN, lit.SourceContext); } goto error; } if (targetType.TypeCode == TypeCode.Boolean) { this.HandleError(lit, Error.ConstOutOfRange, lit.SourceContext.SourceText, "bool"); lit.SourceContext.Document = null; return null; } if (targetType.TypeCode == TypeCode.String) { if (val != null || lit.Type != SystemTypes.Object) { this.HandleError(lit, Error.NoImplicitConversion, this.GetTypeName(sourceType), this.GetTypeName(targetType)); lit.SourceContext.Document = null; return null; } return lit; } if (targetType.TypeCode == TypeCode.Char || sourceType.TypeCode == TypeCode.Boolean || sourceType.TypeCode == TypeCode.Decimal) goto error; switch (sourceType.TypeCode) { case TypeCode.Double: switch (targetType.TypeCode) { case TypeCode.Single: this.HandleError(lit, Error.LiteralDoubleCast, "float", "F"); return lit; case TypeCode.Decimal: this.HandleError(lit, Error.LiteralDoubleCast, "decimal", "M"); return lit; default: this.HandleError(lit, Error.NoImplicitConversion, this.GetTypeName(sourceType), this.GetTypeName(targetType)); lit.SourceContext.Document = null; return null; } case TypeCode.Single: switch (targetType.TypeCode) { case TypeCode.Double: break; default: this.HandleError(lit, Error.NoImplicitConversion, this.GetTypeName(sourceType), this.GetTypeName(targetType)); lit.SourceContext.Document = null; return null; } break; case TypeCode.Int64: case TypeCode.UInt64: switch (targetType.TypeCode) { case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.Single: case TypeCode.Double: break; default: if (explicitCoercion) break; this.HandleError(lit, Error.NoImplicitConversion, this.GetTypeName(sourceType), this.GetTypeName(targetType)); lit.SourceContext.Document = null; return null; } break; } try { if (val == null) { if (targetType.IsValueType) goto error; } else val = System.Convert.ChangeType(val, targetType.TypeCode); return new Literal(val, targetType); } catch(InvalidCastException) { } catch(OverflowException) { } catch(FormatException){} error: if (sourceType.IsPrimitiveNumeric && lit.SourceContext.Document != null) { Error e = Error.ConstOutOfRange; if (explicitCoercion) e = Error.ConstOutOfRangeChecked; this.HandleError(lit, e, lit.SourceContext.SourceText, this.GetTypeName(targetType)); } else this.HandleError(lit, Error.NoImplicitConversion, this.GetTypeName(sourceType), this.GetTypeName(targetType)); lit.SourceContext.Document = null; return null; } public override bool ImplicitLiteralCoercionFromTo(Literal lit, TypeNode sourceType, TypeNode targetType) { if (lit == null) return false; if (sourceType == targetType) return true; object val = lit.Value; if (targetType is EnumNode) { if (val is int && ((int)val) == 0) return true; return false; } if (targetType.TypeCode == TypeCode.Boolean) return false; if (targetType.TypeCode == TypeCode.String) { if (val != null || lit.Type != SystemTypes.Object) return false; return true; } if (targetType.TypeCode == TypeCode.Char || sourceType.TypeCode == TypeCode.Boolean || sourceType.TypeCode == TypeCode.Decimal) return false; switch (sourceType.TypeCode) { case TypeCode.Double: return false; case TypeCode.Single: switch (targetType.TypeCode) { case TypeCode.Double: return true; default: return false; } case TypeCode.Int64: case TypeCode.UInt64: switch (targetType.TypeCode) { case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.Single: case TypeCode.Double: break; default: return false; } break; } try { if (val == null) { if (targetType.IsValueType) return false; } else val = System.Convert.ChangeType(val, targetType.TypeCode); return true; } catch(InvalidCastException) { } catch(OverflowException) { } catch(FormatException){} return false; } public override bool IsVoid(TypeNode type) { return (type == SystemTypes.Void || type == Runtime.AsyncClass); } public override string GetTypeName(TypeNode type) { if (this.ErrorHandler == null){return "";} ((ErrorHandler)this.ErrorHandler).currentParameter = this.currentParameter; return this.ErrorHandler.GetTypeName(type); } private void HandleError(Node offendingNode, Error error, params string[] messageParameters) { if (this.ErrorHandler == null) return; ((ErrorHandler)this.ErrorHandler).HandleError(offendingNode, error, messageParameters); } #endif } }
// Lucene version compatibility level 4.8.1 using YAF.Lucene.Net.Analysis.Util; namespace YAF.Lucene.Net.Analysis.Id { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Stemmer for Indonesian. /// <para> /// Stems Indonesian words with the algorithm presented in: /// <c>A Study of Stemming Effects on Information Retrieval in /// Bahasa Indonesia</c>, Fadillah Z Tala. /// http://www.illc.uva.nl/Publications/ResearchReports/MoL-2003-02.text.pdf /// </para> /// </summary> public class IndonesianStemmer { private int numSyllables; private int flags; private const int REMOVED_KE = 1; private const int REMOVED_PENG = 2; private const int REMOVED_DI = 4; private const int REMOVED_MENG = 8; private const int REMOVED_TER = 16; private const int REMOVED_BER = 32; private const int REMOVED_PE = 64; /// <summary> /// Stem a term (returning its new length). /// <para> /// Use <paramref name="stemDerivational"/> to control whether full stemming /// or only light inflectional stemming is done. /// </para> /// </summary> public virtual int Stem(char[] text, int length, bool stemDerivational) { flags = 0; numSyllables = 0; for (int i = 0; i < length; i++) { if (IsVowel(text[i])) { numSyllables++; } } if (numSyllables > 2) { length = RemoveParticle(text, length); } if (numSyllables > 2) { length = RemovePossessivePronoun(text, length); } if (stemDerivational) { length = StemDerivational(text, length); } return length; } private int StemDerivational(char[] text, int length) { int oldLength = length; if (numSyllables > 2) { length = RemoveFirstOrderPrefix(text, length); } if (oldLength != length) // a rule is fired { oldLength = length; if (numSyllables > 2) { length = RemoveSuffix(text, length); } if (oldLength != length) // a rule is fired { if (numSyllables > 2) { length = RemoveSecondOrderPrefix(text, length); } } } // fail else { if (numSyllables > 2) { length = RemoveSecondOrderPrefix(text, length); } if (numSyllables > 2) { length = RemoveSuffix(text, length); } } return length; } private bool IsVowel(char ch) { switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } } private int RemoveParticle(char[] text, int length) { if (StemmerUtil.EndsWith(text, length, "kah") || StemmerUtil.EndsWith(text, length, "lah") || StemmerUtil.EndsWith(text, length, "pun")) { numSyllables--; return length - 3; } return length; } private int RemovePossessivePronoun(char[] text, int length) { if (StemmerUtil.EndsWith(text, length, "ku") || StemmerUtil.EndsWith(text, length, "mu")) { numSyllables--; return length - 2; } if (StemmerUtil.EndsWith(text, length, "nya")) { numSyllables--; return length - 3; } return length; } private int RemoveFirstOrderPrefix(char[] text, int length) { if (StemmerUtil.StartsWith(text, length, "meng")) { flags |= REMOVED_MENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 4); } if (StemmerUtil.StartsWith(text, length, "meny") && length > 4 && IsVowel(text[4])) { flags |= REMOVED_MENG; text[3] = 's'; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "men")) { flags |= REMOVED_MENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "mem")) { flags |= REMOVED_MENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "me")) { flags |= REMOVED_MENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } if (StemmerUtil.StartsWith(text, length, "peng")) { flags |= REMOVED_PENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 4); } if (StemmerUtil.StartsWith(text, length, "peny") && length > 4 && IsVowel(text[4])) { flags |= REMOVED_PENG; text[3] = 's'; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "peny")) { flags |= REMOVED_PENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 4); } if (StemmerUtil.StartsWith(text, length, "pen") && length > 3 && IsVowel(text[3])) { flags |= REMOVED_PENG; text[2] = 't'; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } if (StemmerUtil.StartsWith(text, length, "pen")) { flags |= REMOVED_PENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "pem")) { flags |= REMOVED_PENG; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "di")) { flags |= REMOVED_DI; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } if (StemmerUtil.StartsWith(text, length, "ter")) { flags |= REMOVED_TER; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "ke")) { flags |= REMOVED_KE; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } return length; } private int RemoveSecondOrderPrefix(char[] text, int length) { if (StemmerUtil.StartsWith(text, length, "ber")) { flags |= REMOVED_BER; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (length == 7 && StemmerUtil.StartsWith(text, length, "belajar")) { flags |= REMOVED_BER; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "be") && length > 4 && !IsVowel(text[2]) && text[3] == 'e' && text[4] == 'r') { flags |= REMOVED_BER; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } if (StemmerUtil.StartsWith(text, length, "per")) { numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (length == 7 && StemmerUtil.StartsWith(text, length, "pelajar")) { numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 3); } if (StemmerUtil.StartsWith(text, length, "pe")) { flags |= REMOVED_PE; numSyllables--; return StemmerUtil.DeleteN(text, 0, length, 2); } return length; } private int RemoveSuffix(char[] text, int length) { if (StemmerUtil.EndsWith(text, length, "kan") && (flags & REMOVED_KE) == 0 && (flags & REMOVED_PENG) == 0 && (flags & REMOVED_PE) == 0) { numSyllables--; return length - 3; } if (StemmerUtil.EndsWith(text, length, "an") && (flags & REMOVED_DI) == 0 && (flags & REMOVED_MENG) == 0 && (flags & REMOVED_TER) == 0) { numSyllables--; return length - 2; } if (StemmerUtil.EndsWith(text, length, "i") && !StemmerUtil.EndsWith(text, length, "si") && (flags & REMOVED_BER) == 0 && (flags & REMOVED_KE) == 0 && (flags & REMOVED_PENG) == 0) { numSyllables--; return length - 1; } return length; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Workspaces { public partial class WorkspaceTests { private TestWorkspace CreateWorkspace(bool disablePartialSolutions = true) { return new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, disablePartialSolutions: disablePartialSolutions); } private static async Task WaitForWorkspaceOperationsToComplete(TestWorkspace workspace) { var workspaceWaiter = workspace.ExportProvider .GetExports<IAsynchronousOperationListener, FeatureMetadata>() .First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; await workspaceWaiter.CreateWaitTask(); } [Fact] public async Task TestEmptySolutionUpdateDoesNotFireEvents() { using (var workspace = CreateWorkspace()) { var project = new TestHostProject(workspace); workspace.AddTestProject(project); // wait for all previous operations to complete await WaitForWorkspaceOperationsToComplete(workspace); var solution = workspace.CurrentSolution; bool workspaceChanged = false; workspace.WorkspaceChanged += (s, e) => workspaceChanged = true; // make an 'empty' update by claiming something changed, but its the same as before workspace.OnParseOptionsChanged(project.Id, project.ParseOptions); // wait for any new outstanding operations to complete (there shouldn't be any) await WaitForWorkspaceOperationsToComplete(workspace); // same solution instance == nothing changed Assert.Equal(solution, workspace.CurrentSolution); // no event was fired because nothing was changed Assert.False(workspaceChanged); } } [Fact] public void TestAddProject() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; Assert.Equal(0, solution.Projects.Count()); var project = new TestHostProject(workspace); workspace.AddTestProject(project); solution = workspace.CurrentSolution; Assert.Equal(1, solution.Projects.Count()); } } [Fact] public void TestRemoveExistingProject1() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project = new TestHostProject(workspace); workspace.AddTestProject(project); workspace.OnProjectRemoved(project.Id); solution = workspace.CurrentSolution; Assert.Equal(0, solution.Projects.Count()); } } [Fact] public void TestRemoveExistingProject2() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project = new TestHostProject(workspace); workspace.AddTestProject(project); solution = workspace.CurrentSolution; workspace.OnProjectRemoved(project.Id); solution = workspace.CurrentSolution; Assert.Equal(0, solution.Projects.Count()); } } [Fact] public void TestRemoveNonAddedProject1() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project = new TestHostProject(workspace); Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project.Id)); } } [Fact] public void TestRemoveNonAddedProject2() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project2.Id)); } } [Fact] public async Task TestChangeOptions1() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument( @"#if FOO class C { } #else class D { } #endif"); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); await VerifyRootTypeNameAsync(workspace, "D"); workspace.OnParseOptionsChanged(document.Id.ProjectId, new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" })); await VerifyRootTypeNameAsync(workspace, "C"); } } [Fact] public async Task TestChangeOptions2() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument( @"#if FOO class C { } #else class D { } #endif"); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); await VerifyRootTypeNameAsync(workspace, "D"); workspace.OnParseOptionsChanged(document.Id.ProjectId, new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" })); await VerifyRootTypeNameAsync(workspace, "C"); workspace.OnDocumentClosed(document.Id); } } private static async Task VerifyRootTypeNameAsync(TestWorkspace workspaceSnapshotBuilder, string typeName) { var currentSnapshot = workspaceSnapshotBuilder.CurrentSolution; var type = await GetRootTypeDeclarationAsync(currentSnapshot); Assert.Equal(type.Identifier.ValueText, typeName); } private static async Task<TypeDeclarationSyntax> GetRootTypeDeclarationAsync(Solution currentSnapshot) { var tree = await currentSnapshot.Projects.First().Documents.First().GetSyntaxTreeAsync(); var root = (CompilationUnitSyntax)tree.GetRoot(); var type = (TypeDeclarationSyntax)root.Members[0]; return type; } [Fact] public void TestAddP2PReferenceFails() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id))); } } [Fact] public void TestAddP2PReference1() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var reference = new ProjectReference(project2.Id); workspace.OnProjectReferenceAdded(project1.Id, reference); var snapshot = workspace.CurrentSolution; var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id; var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id; Assert.True(snapshot.GetProject(id1).ProjectReferences.Contains(reference), "ProjectReferences did not contain project2"); } } [Fact] public void TestAddP2PReferenceTwice() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); workspace.AddTestProject(project2); workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)); Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id))); } } [Fact] public void TestRemoveP2PReference1() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); workspace.AddTestProject(project2); workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)); workspace.OnProjectReferenceRemoved(project1.Id, new ProjectReference(project2.Id)); var snapshot = workspace.CurrentSolution; var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id; var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id; Assert.Equal(0, snapshot.GetProject(id1).ProjectReferences.Count()); } } [Fact] public void TestAddP2PReferenceCircularity() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var project1 = new TestHostProject(workspace, name: "project1"); var project2 = new TestHostProject(workspace, name: "project2"); workspace.AddTestProject(project1); workspace.AddTestProject(project2); workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)); Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project2.Id, new ProjectReference(project1.Id))); } } [Fact] public void TestRemoveProjectWithOpenedDocuments() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument(string.Empty); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project1.Id)); workspace.OnDocumentClosed(document.Id); workspace.OnProjectRemoved(project1.Id); } } [Fact] public void TestRemoveProjectWithClosedDocuments() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument(string.Empty); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); workspace.OnDocumentClosed(document.Id); workspace.OnProjectRemoved(project1.Id); } } [Fact] public void TestRemoveOpenedDocument() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument(string.Empty); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); Assert.Throws<ArgumentException>(() => workspace.OnDocumentRemoved(document.Id)); workspace.OnDocumentClosed(document.Id); workspace.OnProjectRemoved(project1.Id); } } [Fact] public async Task TestGetCompilation() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument(@"class C { }"); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); await VerifyRootTypeNameAsync(workspace, "C"); var snapshot = workspace.CurrentSolution; var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id; var compilation = await snapshot.GetProject(id1).GetCompilationAsync(); var classC = compilation.SourceModule.GlobalNamespace.GetMembers("C").Single(); } } [Fact] public async Task TestGetCompilationOnDependentProject() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document1 = new TestHostDocument(@"public class C { }"); var project1 = new TestHostProject(workspace, document1, name: "project1"); var document2 = new TestHostDocument(@"class D : C { }"); var project2 = new TestHostProject(workspace, document2, name: "project2", projectReferences: new[] { project1 }); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var snapshot = workspace.CurrentSolution; var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id; var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id; var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync(); var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classC = classD.BaseType; } } [Fact] public async Task TestGetCompilationOnCrossLanguageDependentProject() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document1 = new TestHostDocument(@"public class C { }"); var project1 = new TestHostProject(workspace, document1, name: "project1"); var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class"); var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 }); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var snapshot = workspace.CurrentSolution; var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id; var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id; var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync(); var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classC = classD.BaseType; } } [Fact] public async Task TestGetCompilationOnCrossLanguageDependentProjectChanged() { using (var workspace = CreateWorkspace()) { var solutionX = workspace.CurrentSolution; var document1 = new TestHostDocument(@"public class C { }"); var project1 = new TestHostProject(workspace, document1, name: "project1"); var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class"); var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 }); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var solutionY = workspace.CurrentSolution; var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id; var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id; var compilation2 = await solutionY.GetProject(id2).GetCompilationAsync(); var errors = compilation2.GetDiagnostics(); var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classC = classD.BaseType; Assert.NotEqual(TypeKind.Error, classC.TypeKind); // change the class name in document1 workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer()); var buffer1 = document1.GetTextBuffer(); // change C to X buffer1.Replace(new Span(13, 1), "X"); // this solution should have the change var solutionZ = workspace.CurrentSolution; var docZ = solutionZ.GetDocument(document1.Id); var docZText = await docZ.GetTextAsync(); var compilation2Z = await solutionZ.GetProject(id2).GetCompilationAsync(); var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classCz = classDz.BaseType; Assert.Equal(TypeKind.Error, classCz.TypeKind); } } [WpfFact] public async Task TestDependentSemanticVersionChangesWhenNotOriginallyAccessed() { using (var workspace = CreateWorkspace(disablePartialSolutions: false)) { var solutionX = workspace.CurrentSolution; var document1 = new TestHostDocument(@"public class C { }"); var project1 = new TestHostProject(workspace, document1, name: "project1"); var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class"); var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 }); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var solutionY = workspace.CurrentSolution; var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id; var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id; var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync(); var errors = compilation2y.GetDiagnostics(); var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classCy = classDy.BaseType; Assert.NotEqual(TypeKind.Error, classCy.TypeKind); // open both documents so background compiler works on their compilations workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer()); workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer()); // change C to X var buffer1 = document1.GetTextBuffer(); buffer1.Replace(new Span(13, 1), "X"); for (int iter = 0; iter < 10; iter++) { WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle); Thread.Sleep(1000); // the current solution should eventually have the change var cs = workspace.CurrentSolution; var doc1Z = cs.GetDocument(document1.Id); var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X"); if (hasX) { var newVersion = await cs.GetProject(project1.Id).GetDependentSemanticVersionAsync(); var newVersionX = await doc1Z.Project.GetDependentSemanticVersionAsync(); Assert.NotEqual(VersionStamp.Default, newVersion); Assert.Equal(newVersion, newVersionX); break; } } } } [WpfFact] public async Task TestGetCompilationOnCrossLanguageDependentProjectChangedInProgress() { using (var workspace = CreateWorkspace(disablePartialSolutions: false)) { var solutionX = workspace.CurrentSolution; var document1 = new TestHostDocument(@"public class C { }"); var project1 = new TestHostProject(workspace, document1, name: "project1"); var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class"); var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 }); workspace.AddTestProject(project1); workspace.AddTestProject(project2); var solutionY = workspace.CurrentSolution; var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id; var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id; var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync(); var errors = compilation2y.GetDiagnostics(); var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classCy = classDy.BaseType; Assert.NotEqual(TypeKind.Error, classCy.TypeKind); // open both documents so background compiler works on their compilations workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer()); workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer()); // change C to X var buffer1 = document1.GetTextBuffer(); buffer1.Replace(new Span(13, 1), "X"); var foundTheError = false; for (int iter = 0; iter < 10; iter++) { WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle); Thread.Sleep(1000); // the current solution should eventually have the change var cs = workspace.CurrentSolution; var doc1Z = cs.GetDocument(document1.Id); var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X"); if (hasX) { var doc2Z = cs.GetDocument(document2.Id); var partialDoc2Z = await doc2Z.WithFrozenPartialSemanticsAsync(CancellationToken.None); var compilation2Z = await partialDoc2Z.Project.GetCompilationAsync(); var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single(); var classCz = classDz.BaseType; if (classCz.TypeKind == TypeKind.Error) { foundTheError = true; break; } } } Assert.True(foundTheError, "Did not find error"); } } [Fact] public async Task TestOpenAndChangeDocument() { using (var workspace = CreateWorkspace()) { var solution = workspace.CurrentSolution; var document = new TestHostDocument(string.Empty); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); var buffer = document.GetTextBuffer(); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); buffer.Insert(0, "class C {}"); solution = workspace.CurrentSolution; var doc = solution.Projects.Single().Documents.First(); var syntaxTree = await doc.GetSyntaxTreeAsync(CancellationToken.None); Assert.True(syntaxTree.GetRoot().Width() > 0, "syntaxTree.GetRoot().Width should be > 0"); workspace.OnDocumentClosed(document.Id); workspace.OnProjectRemoved(project1.Id); } } [Fact] public async Task TestApplyChangesWithDocumentTextUpdated() { using (var workspace = CreateWorkspace()) { var startText = "public class C { }"; var newText = "public class D { }"; var document = new TestHostDocument(startText); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); var buffer = document.GetTextBuffer(); workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer()); // prove the document has the correct text Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString()); // fork the solution to introduce a change. var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.WithDocumentText(document.Id, SourceText.From(newText)); // prove that current document text is unchanged Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString()); // prove buffer is unchanged too Assert.Equal(startText, buffer.CurrentSnapshot.GetText()); workspace.TryApplyChanges(newSolution); // new text should have been pushed into buffer Assert.Equal(newText, buffer.CurrentSnapshot.GetText()); } } [Fact] public void TestApplyChangesWithDocumentAdded() { using (var workspace = CreateWorkspace()) { var doc1Text = "public class C { }"; var doc2Text = "public class D { }"; var document = new TestHostDocument(doc1Text); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); // fork the solution to introduce a change. var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(DocumentId.CreateNewId(project1.Id), "Doc2", SourceText.From(doc2Text)); workspace.TryApplyChanges(newSolution); // new document should have been added. Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); } } [Fact] public void TestApplyChangesWithDocumentRemoved() { using (var workspace = CreateWorkspace()) { var doc1Text = "public class C { }"; var document = new TestHostDocument(doc1Text); var project1 = new TestHostProject(workspace, document, name: "project1"); workspace.AddTestProject(project1); // fork the solution to introduce a change. var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.RemoveDocument(document.Id); workspace.TryApplyChanges(newSolution); // document should have been removed Assert.Equal(0, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); } } [Fact] public async Task TestDocumentEvents() { using (var workspace = CreateWorkspace()) { var doc1Text = "public class C { }"; var document = new TestHostDocument(doc1Text); var project1 = new TestHostProject(workspace, document, name: "project1"); var longEventTimeout = TimeSpan.FromMinutes(5); var shortEventTimeout = TimeSpan.FromSeconds(5); workspace.AddTestProject(project1); // Creating two waiters that will allow us to know for certain if the events have fired. using (var closeWaiter = new EventWaiter()) using (var openWaiter = new EventWaiter()) { // Wrapping event handlers so they can notify us on being called. var documentOpenedEventHandler = openWaiter.Wrap<DocumentEventArgs>( (sender, args) => Assert.True(args.Document.Id == document.Id, "The document given to the 'DocumentOpened' event handler did not have the same id as the one created for the test.")); var documentClosedEventHandler = closeWaiter.Wrap<DocumentEventArgs>( (sender, args) => Assert.True(args.Document.Id == document.Id, "The document given to the 'DocumentClosed' event handler did not have the same id as the one created for the test.")); workspace.DocumentOpened += documentOpenedEventHandler; workspace.DocumentClosed += documentClosedEventHandler; workspace.OpenDocument(document.Id); workspace.CloseDocument(document.Id); // Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified. await WaitForWorkspaceOperationsToComplete(workspace); // Wait to receive signal that events have fired. Assert.True(openWaiter.WaitForEventToFire(longEventTimeout), string.Format("event 'DocumentOpened' was not fired within {0} minutes.", longEventTimeout.Minutes)); Assert.True(closeWaiter.WaitForEventToFire(longEventTimeout), string.Format("event 'DocumentClosed' was not fired within {0} minutes.", longEventTimeout.Minutes)); workspace.DocumentOpened -= documentOpenedEventHandler; workspace.DocumentClosed -= documentClosedEventHandler; workspace.OpenDocument(document.Id); workspace.CloseDocument(document.Id); // Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified. await WaitForWorkspaceOperationsToComplete(workspace); // Verifying that an event has not been called is difficult to prove. // All events should have already been called so we wait 5 seconds and then assume the event handler was removed correctly. Assert.False(openWaiter.WaitForEventToFire(shortEventTimeout), string.Format("event handler 'DocumentOpened' was called within {0} seconds though it was removed from the list.", shortEventTimeout.Seconds)); Assert.False(closeWaiter.WaitForEventToFire(shortEventTimeout), string.Format("event handler 'DocumentClosed' was called within {0} seconds though it was removed from the list.", shortEventTimeout.Seconds)); } } } [Fact] public async Task TestAdditionalFile_Properties() { using (var workspace = CreateWorkspace()) { var document = new TestHostDocument("public class C { }"); var additionalDoc = new TestHostDocument("some text"); var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc }); workspace.AddTestProject(project1); var project = workspace.CurrentSolution.Projects.Single(); Assert.Equal(1, project.Documents.Count()); Assert.Equal(1, project.AdditionalDocuments.Count()); Assert.Equal(1, project.AdditionalDocumentIds.Count); var doc = project.GetDocument(additionalDoc.Id); Assert.Null(doc); var additionalDocument = project.GetAdditionalDocument(additionalDoc.Id); Assert.Equal("some text", (await additionalDocument.GetTextAsync()).ToString()); } } [Fact] public async Task TestAdditionalFile_DocumentChanged() { using (var workspace = CreateWorkspace()) { var startText = @"<setting value = ""foo"""; var newText = @"<setting value = ""foo1"""; var document = new TestHostDocument("public class C { }"); var additionalDoc = new TestHostDocument(startText); var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc }); workspace.AddTestProject(project1); var buffer = additionalDoc.GetTextBuffer(); workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer()); var project = workspace.CurrentSolution.Projects.Single(); var oldVersion = await project.GetSemanticVersionAsync(); // fork the solution to introduce a change. var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.WithAdditionalDocumentText(additionalDoc.Id, SourceText.From(newText)); workspace.TryApplyChanges(newSolution); var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id); // new text should have been pushed into buffer Assert.Equal(newText, buffer.CurrentSnapshot.GetText()); // Text changes are considered top level changes and they change the project's semantic version. Assert.Equal(await doc.GetTextVersionAsync(), await doc.GetTopLevelChangeTextVersionAsync()); Assert.NotEqual(oldVersion, await doc.Project.GetSemanticVersionAsync()); } } [Fact] public async Task TestAdditionalFile_OpenClose() { using (var workspace = CreateWorkspace()) { var startText = @"<setting value = ""foo"""; var document = new TestHostDocument("public class C { }"); var additionalDoc = new TestHostDocument(startText); var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc }); workspace.AddTestProject(project1); var buffer = additionalDoc.GetTextBuffer(); var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id); var text = await doc.GetTextAsync(CancellationToken.None); var version = await doc.GetTextVersionAsync(CancellationToken.None); workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer()); // We don't have a GetOpenAdditionalDocumentIds since we don't need it. But make sure additional documents // don't creep into OpenDocumentIds (Bug: 1087470) Assert.Empty(workspace.GetOpenDocumentIds()); workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version))); // Reopen and close to make sure we are not leaking anything. workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer()); workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version))); Assert.Empty(workspace.GetOpenDocumentIds()); } } [Fact] public void TestAdditionalFile_AddRemove() { using (var workspace = CreateWorkspace()) { var startText = @"<setting value = ""foo"""; var document = new TestHostDocument("public class C { }"); var additionalDoc = new TestHostDocument(startText, "original.config"); var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc }); workspace.AddTestProject(project1); var project = workspace.CurrentSolution.Projects.Single(); // fork the solution to introduce a change. var newDocId = DocumentId.CreateNewId(project.Id); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddAdditionalDocument(newDocId, "app.config", "text"); var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id); workspace.TryApplyChanges(newSolution); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count()); // Now remove the newly added document oldSolution = workspace.CurrentSolution; newSolution = oldSolution.RemoveAdditionalDocument(newDocId); workspace.TryApplyChanges(newSolution); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count()); Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name); } } [Fact] public void TestAdditionalFile_AddRemove_FromProject() { using (var workspace = CreateWorkspace()) { var startText = @"<setting value = ""foo"""; var document = new TestHostDocument("public class C { }"); var additionalDoc = new TestHostDocument(startText, "original.config"); var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc }); workspace.AddTestProject(project1); var project = workspace.CurrentSolution.Projects.Single(); // fork the solution to introduce a change. var doc = project.AddAdditionalDocument("app.config", "text"); workspace.TryApplyChanges(doc.Project.Solution); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count()); // Now remove the newly added document project = workspace.CurrentSolution.Projects.Single(); workspace.TryApplyChanges(project.RemoveAdditionalDocument(doc.Id).Solution); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count()); Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count()); Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name); } } } }
//--------------------------------------------------------------------------- // // <copyright file="GeometryGroup.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class GeometryGroup : Geometry { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new GeometryGroup Clone() { return (GeometryGroup)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new GeometryGroup CloneCurrentValue() { return (GeometryGroup)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void FillRulePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { GeometryGroup target = ((GeometryGroup) d); target.PropertyChanged(FillRuleProperty); } private static void ChildrenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children) // will promote the property value from a default value to a local value. This is technically a sub-property // change because the collection was changed and not a new collection set (GeometryGroup.Children. // Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled // the default value to the compositor. If the property changes from a default value, the new local value // needs to be marshalled to the compositor. We detect this scenario with the second condition // e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be // Default and the NewValueSource will be Local. if (e.IsASubPropertyChange && (e.OldValueSource == e.NewValueSource)) { return; } GeometryGroup target = ((GeometryGroup) d); // If this is both non-null and mutable, we need to unhook the Changed event. GeometryCollection oldCollection = null; GeometryCollection newCollection = null; if ((e.OldValueSource != BaseValueSourceInternal.Default) || e.IsOldValueModified) { oldCollection = (GeometryCollection) e.OldValue; if ((oldCollection != null) && !oldCollection.IsFrozen) { oldCollection.ItemRemoved -= target.ChildrenItemRemoved; oldCollection.ItemInserted -= target.ChildrenItemInserted; } } // If this is both non-null and mutable, we need to hook the Changed event. if ((e.NewValueSource != BaseValueSourceInternal.Default) || e.IsNewValueModified) { newCollection = (GeometryCollection) e.NewValue; if ((newCollection != null) && !newCollection.IsFrozen) { newCollection.ItemInserted += target.ChildrenItemInserted; newCollection.ItemRemoved += target.ChildrenItemRemoved; } } if (oldCollection != newCollection && target.Dispatcher != null) { using (CompositionEngineLock.Acquire()) { DUCE.IResource targetResource = (DUCE.IResource)target; int channelCount = targetResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = targetResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!targetResource.GetHandle(channel).IsNull); // resource shouldn't be null because // 1) If the field is one of our collections, we don't allow null elements // 2) Codegen already made sure the collection contains DUCE.IResources // ... so we'll Assert it if (newCollection != null) { int count = newCollection.Count; for (int i = 0; i < count; i++) { DUCE.IResource resource = newCollection.Internal_GetItem(i) as DUCE.IResource; Debug.Assert(resource != null); resource.AddRefOnChannel(channel); } } if (oldCollection != null) { int count = oldCollection.Count; for (int i = 0; i < count; i++) { DUCE.IResource resource = oldCollection.Internal_GetItem(i) as DUCE.IResource; Debug.Assert(resource != null); resource.ReleaseOnChannel(channel); } } } } } target.PropertyChanged(ChildrenProperty); } #region Public Properties /// <summary> /// FillRule - FillRule. Default value is FillRule.EvenOdd. /// </summary> public FillRule FillRule { get { return (FillRule) GetValue(FillRuleProperty); } set { SetValueInternal(FillRuleProperty, FillRuleBoxes.Box(value)); } } /// <summary> /// Children - GeometryCollection. Default value is new FreezableDefaultValueFactory(GeometryCollection.Empty). /// </summary> public GeometryCollection Children { get { return (GeometryCollection) GetValue(ChildrenProperty); } set { SetValueInternal(ChildrenProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new GeometryGroup(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Read values of properties into local variables Transform vTransform = Transform; GeometryCollection vChildren = Children; // Obtain handles for properties that implement DUCE.IResource DUCE.ResourceHandle hTransform; if (vTransform == null || Object.ReferenceEquals(vTransform, Transform.Identity) ) { hTransform = DUCE.ResourceHandle.Null; } else { hTransform = ((DUCE.IResource)vTransform).GetHandle(channel); } // Store the count of this resource's contained collections in local variables. int ChildrenCount = (vChildren == null) ? 0 : vChildren.Count; // Pack & send command packet DUCE.MILCMD_GEOMETRYGROUP data; unsafe { data.Type = MILCMD.MilCmdGeometryGroup; data.Handle = _duceResource.GetHandle(channel); data.hTransform = hTransform; data.FillRule = FillRule; data.ChildrenSize = (uint)(sizeof(DUCE.ResourceHandle) * ChildrenCount); channel.BeginCommand( (byte*)&data, sizeof(DUCE.MILCMD_GEOMETRYGROUP), (int)(data.ChildrenSize) ); // Copy this collection's elements (or their handles) to reserved data for(int i = 0; i < ChildrenCount; i++) { DUCE.ResourceHandle resource = ((DUCE.IResource)vChildren.Internal_GetItem(i)).GetHandle(channel);; channel.AppendCommandData( (byte*)&resource, sizeof(DUCE.ResourceHandle) ); } channel.EndCommand(); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_GEOMETRYGROUP)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel); GeometryCollection vChildren = Children; if (vChildren != null) { int count = vChildren.Count; for (int i = 0; i < count; i++) { ((DUCE.IResource) vChildren.Internal_GetItem(i)).AddRefOnChannel(channel); } } AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel); GeometryCollection vChildren = Children; if (vChildren != null) { int count = vChildren.Count; for (int i = 0; i < count; i++) { ((DUCE.IResource) vChildren.Internal_GetItem(i)).ReleaseOnChannel(channel); } } ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } private void ChildrenItemInserted(object sender, object item) { if (this.Dispatcher != null) { DUCE.IResource thisResource = (DUCE.IResource)this; using (CompositionEngineLock.Acquire()) { int channelCount = thisResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = thisResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!thisResource.GetHandle(channel).IsNull); // We're on a channel, which means our dependents are also on the channel. DUCE.IResource addResource = item as DUCE.IResource; if (addResource != null) { addResource.AddRefOnChannel(channel); } UpdateResource(channel, true /* skip on channel check */); } } } } private void ChildrenItemRemoved(object sender, object item) { if (this.Dispatcher != null) { DUCE.IResource thisResource = (DUCE.IResource)this; using (CompositionEngineLock.Acquire()) { int channelCount = thisResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = thisResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!thisResource.GetHandle(channel).IsNull); UpdateResource(channel, true /* is on channel check */); // We're on a channel, which means our dependents are also on the channel. DUCE.IResource releaseResource = item as DUCE.IResource; if (releaseResource != null) { releaseResource.ReleaseOnChannel(channel); } } } } } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // Children // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the GeometryGroup.FillRule property. /// </summary> public static readonly DependencyProperty FillRuleProperty; /// <summary> /// The DependencyProperty for the GeometryGroup.Children property. /// </summary> public static readonly DependencyProperty ChildrenProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal const FillRule c_FillRule = FillRule.EvenOdd; internal static GeometryCollection s_Children = GeometryCollection.Empty; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static GeometryGroup() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // Debug.Assert(s_Children == null || s_Children.IsFrozen, "Detected context bound default value GeometryGroup.s_Children (See OS Bug #947272)."); // Initializations Type typeofThis = typeof(GeometryGroup); FillRuleProperty = RegisterProperty("FillRule", typeof(FillRule), typeofThis, FillRule.EvenOdd, new PropertyChangedCallback(FillRulePropertyChanged), new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsFillRuleValid), /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); ChildrenProperty = RegisterProperty("Children", typeof(GeometryCollection), typeofThis, new FreezableDefaultValueFactory(GeometryCollection.Empty), new PropertyChangedCallback(ChildrenPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Reflection.Emit { public sealed partial class AssemblyBuilder : System.Reflection.Assembly { internal AssemblyBuilder() { } public override string? CodeBase { get { throw null; } } public override System.Reflection.MethodInfo? EntryPoint { get { throw null; } } public override string? FullName { get { throw null; } } public override bool GlobalAssemblyCache { get { throw null; } } public override long HostContext { get { throw null; } } public override string ImageRuntimeVersion { get { throw null; } } public override bool IsDynamic { get { throw null; } } public override string Location { get { throw null; } } public override System.Reflection.Module ManifestModule { get { throw null; } } public override bool ReflectionOnly { get { throw null; } } public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) { throw null; } public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder>? assemblyAttributes) { throw null; } public System.Reflection.Emit.ModuleBuilder DefineDynamicModule(string name) { throw null; } public override bool Equals(object? obj) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributesData() { throw null; } public System.Reflection.Emit.ModuleBuilder? GetDynamicModule(string name) { throw null; } public override System.Type[] GetExportedTypes() { throw null; } public override System.IO.FileStream GetFile(string name) { throw null; } public override System.IO.FileStream[] GetFiles(bool getResourceModules) { throw null; } public override int GetHashCode() { throw null; } public override System.Reflection.Module[] GetLoadedModules(bool getResourceModules) { throw null; } public override System.Reflection.ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw null; } public override string[] GetManifestResourceNames() { throw null; } public override System.IO.Stream? GetManifestResourceStream(string name) { throw null; } public override System.IO.Stream? GetManifestResourceStream(System.Type type, string name) { throw null; } public override System.Reflection.Module? GetModule(string name) { throw null; } public override System.Reflection.Module[] GetModules(bool getResourceModules) { throw null; } public override System.Reflection.AssemblyName GetName(bool copiedName) { throw null; } public override System.Reflection.AssemblyName[] GetReferencedAssemblies() { throw null; } public override System.Reflection.Assembly GetSatelliteAssembly(System.Globalization.CultureInfo culture) { throw null; } public override System.Reflection.Assembly GetSatelliteAssembly(System.Globalization.CultureInfo culture, System.Version? version) { throw null; } public override System.Type? GetType(string name, bool throwOnError, bool ignoreCase) { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } [System.FlagsAttribute] public enum AssemblyBuilderAccess { Run = 1, RunAndCollect = 9, } public sealed partial class ConstructorBuilder : System.Reflection.ConstructorInfo { internal ConstructorBuilder() { } public override System.Reflection.MethodAttributes Attributes { get { throw null; } } public override System.Reflection.CallingConventions CallingConvention { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public bool InitLocals { get { throw null; } set { } } public override System.RuntimeMethodHandle MethodHandle { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public System.Reflection.Emit.ParameterBuilder DefineParameter(int iSequence, System.Reflection.ParameterAttributes attributes, string? strParamName) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; } public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize) { throw null; } public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; } public override System.Reflection.ParameterInfo[] GetParameters() { throw null; } public override object Invoke(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture) { throw null; } public override object Invoke(System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture) { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { } public override string ToString() { throw null; } } public sealed partial class EnumBuilder : System.Type { internal EnumBuilder() { } public override System.Reflection.Assembly Assembly { get { throw null; } } public override string? AssemblyQualifiedName { get { throw null; } } public override System.Type? BaseType { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public override string? FullName { get { throw null; } } public override System.Guid GUID { get { throw null; } } public override bool IsConstructedGenericType { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override string? Namespace { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public override System.RuntimeTypeHandle TypeHandle { get { throw null; } } public System.Reflection.Emit.FieldBuilder UnderlyingField { get { throw null; } } public override System.Type UnderlyingSystemType { get { throw null; } } public System.Reflection.TypeInfo? CreateTypeInfo() { throw null; } public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object? literalValue) { throw null; } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; } protected override System.Reflection.ConstructorInfo? GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Type? GetElementType() { throw null; } public override System.Type GetEnumUnderlyingType() { throw null; } public override System.Reflection.EventInfo? GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.EventInfo[] GetEvents() { throw null; } public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo? GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type? GetInterface(string name, bool ignoreCase) { throw null; } public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; } public override System.Type[] GetInterfaces() { throw null; } public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; } protected override System.Reflection.MethodInfo? GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type? GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; } protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Type? returnType, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } protected override bool HasElementTypeImpl() { throw null; } public override object? InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object? target, object?[]? args, System.Reflection.ParameterModifier[]? modifiers, System.Globalization.CultureInfo? culture, string[]? namedParameters) { throw null; } protected override bool IsArrayImpl() { throw null; } protected override bool IsByRefImpl() { throw null; } protected override bool IsCOMObjectImpl() { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } protected override bool IsPointerImpl() { throw null; } protected override bool IsPrimitiveImpl() { throw null; } protected override bool IsValueTypeImpl() { throw null; } public override System.Type MakeArrayType() { throw null; } public override System.Type MakeArrayType(int rank) { throw null; } public override System.Type MakeByRefType() { throw null; } public override System.Type MakePointerType() { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } public sealed partial class EventBuilder { internal EventBuilder() { } public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetAddOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetRaiseMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetRemoveOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } } public sealed partial class FieldBuilder : System.Reflection.FieldInfo { internal FieldBuilder() { } public override System.Reflection.FieldAttributes Attributes { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public override System.RuntimeFieldHandle FieldHandle { get { throw null; } } public override System.Type FieldType { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override object? GetValue(object? obj) { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public void SetConstant(object? defaultValue) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetOffset(int iOffset) { } public override void SetValue(object? obj, object? val, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, System.Globalization.CultureInfo? culture) { } } public sealed partial class GenericTypeParameterBuilder : System.Type { internal GenericTypeParameterBuilder() { } public override System.Reflection.Assembly Assembly { get { throw null; } } public override string? AssemblyQualifiedName { get { throw null; } } public override System.Type? BaseType { get { throw null; } } public override bool ContainsGenericParameters { get { throw null; } } public override System.Reflection.MethodBase? DeclaringMethod { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public override string? FullName { get { throw null; } } public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } } public override int GenericParameterPosition { get { throw null; } } public override System.Guid GUID { get { throw null; } } public override bool IsConstructedGenericType { get { throw null; } } public override bool IsGenericParameter { get { throw null; } } public override bool IsGenericType { get { throw null; } } public override bool IsGenericTypeDefinition { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override string? Namespace { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public override System.RuntimeTypeHandle TypeHandle { get { throw null; } } public override System.Type UnderlyingSystemType { get { throw null; } } public override bool Equals(object? o) { throw null; } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; } protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Type GetElementType() { throw null; } public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.EventInfo[] GetEvents() { throw null; } public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type[] GetGenericArguments() { throw null; } public override System.Type GetGenericTypeDefinition() { throw null; } public override int GetHashCode() { throw null; } public override System.Type GetInterface(string name, bool ignoreCase) { throw null; } public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; } public override System.Type[] GetInterfaces() { throw null; } public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; } protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; } protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Type? returnType, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } protected override bool HasElementTypeImpl() { throw null; } public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object? target, object?[]? args, System.Reflection.ParameterModifier[]? modifiers, System.Globalization.CultureInfo? culture, string[]? namedParameters) { throw null; } protected override bool IsArrayImpl() { throw null; } public override bool IsAssignableFrom(System.Type? c) { throw null; } protected override bool IsByRefImpl() { throw null; } protected override bool IsCOMObjectImpl() { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } protected override bool IsPointerImpl() { throw null; } protected override bool IsPrimitiveImpl() { throw null; } public override bool IsSubclassOf(System.Type c) { throw null; } protected override bool IsValueTypeImpl() { throw null; } public override System.Type MakeArrayType() { throw null; } public override System.Type MakeArrayType(int rank) { throw null; } public override System.Type MakeByRefType() { throw null; } public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; } public override System.Type MakePointerType() { throw null; } public void SetBaseTypeConstraint(System.Type? baseTypeConstraint) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetGenericParameterAttributes(System.Reflection.GenericParameterAttributes genericParameterAttributes) { } public void SetInterfaceConstraints(params System.Type[]? interfaceConstraints) { } public override string ToString() { throw null; } } public sealed partial class MethodBuilder : System.Reflection.MethodInfo { internal MethodBuilder() { } public override System.Reflection.MethodAttributes Attributes { get { throw null; } } public override System.Reflection.CallingConventions CallingConvention { get { throw null; } } public override bool ContainsGenericParameters { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public bool InitLocals { get { throw null; } set { } } public override bool IsGenericMethod { get { throw null; } } public override bool IsGenericMethodDefinition { get { throw null; } } public override bool IsSecurityCritical { get { throw null; } } public override bool IsSecuritySafeCritical { get { throw null; } } public override bool IsSecurityTransparent { get { throw null; } } public override System.RuntimeMethodHandle MethodHandle { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public override System.Reflection.ParameterInfo ReturnParameter { get { throw null; } } public override System.Type ReturnType { get { throw null; } } public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw null; } } public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; } public System.Reflection.Emit.ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, string? strParamName) { throw null; } public override bool Equals(object? obj) { throw null; } public override System.Reflection.MethodInfo GetBaseDefinition() { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Type[] GetGenericArguments() { throw null; } public override System.Reflection.MethodInfo GetGenericMethodDefinition() { throw null; } public override int GetHashCode() { throw null; } public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; } public System.Reflection.Emit.ILGenerator GetILGenerator(int size) { throw null; } public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; } public override System.Reflection.ParameterInfo[] GetParameters() { throw null; } public override object Invoke(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture) { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public override System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { } public void SetParameters(params System.Type[] parameterTypes) { } public void SetReturnType(System.Type? returnType) { } public void SetSignature(System.Type? returnType, System.Type[]? returnTypeRequiredCustomModifiers, System.Type[]? returnTypeOptionalCustomModifiers, System.Type[]? parameterTypes, System.Type[][]? parameterTypeRequiredCustomModifiers, System.Type[][]? parameterTypeOptionalCustomModifiers) { } public override string ToString() { throw null; } } public partial class ModuleBuilder : System.Reflection.Module { internal ModuleBuilder() { } public override System.Reflection.Assembly Assembly { get { throw null; } } public override string FullyQualifiedName { get { throw null; } } public override int MDStreamVersion { get { throw null; } } public override int MetadataToken { get { throw null; } } public override System.Guid ModuleVersionId { get { throw null; } } public override string Name { get { throw null; } } public override string ScopeName { get { throw null; } } public void CreateGlobalFunctions() { } public System.Reflection.Emit.EnumBuilder DefineEnum(string name, System.Reflection.TypeAttributes visibility, System.Type underlyingType) { throw null; } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type? returnType, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type? returnType, System.Type[]? requiredReturnTypeCustomModifiers, System.Type[]? optionalReturnTypeCustomModifiers, System.Type[]? parameterTypes, System.Type[][]? requiredParameterTypeCustomModifiers, System.Type[][]? optionalParameterTypeCustomModifiers) { throw null; } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Type? returnType, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type? parent) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, int typesize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Reflection.Emit.PackingSize packsize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Reflection.Emit.PackingSize packingSize, int typesize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Type[]? interfaces) { throw null; } public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; } public override bool Equals(object? obj) { throw null; } public System.Reflection.MethodInfo GetArrayMethod(System.Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, System.Type? returnType, System.Type[]? parameterTypes) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributesData() { throw null; } public override System.Reflection.FieldInfo? GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingFlags) { throw null; } public override int GetHashCode() { throw null; } public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingFlags) { throw null; } public override void GetPEKind(out System.Reflection.PortableExecutableKinds peKind, out System.Reflection.ImageFileMachine machine) { throw null; } public override System.Type? GetType(string className) { throw null; } public override System.Type? GetType(string className, bool ignoreCase) { throw null; } public override System.Type? GetType(string className, bool throwOnError, bool ignoreCase) { throw null; } public override System.Type[] GetTypes() { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public override bool IsResource() { throw null; } public override System.Reflection.FieldInfo? ResolveField(int metadataToken, System.Type[]? genericTypeArguments, System.Type[]? genericMethodArguments) { throw null; } public override System.Reflection.MemberInfo? ResolveMember(int metadataToken, System.Type[]? genericTypeArguments, System.Type[]? genericMethodArguments) { throw null; } public override System.Reflection.MethodBase? ResolveMethod(int metadataToken, System.Type[]? genericTypeArguments, System.Type[]? genericMethodArguments) { throw null; } public override byte[] ResolveSignature(int metadataToken) { throw null; } public override string ResolveString(int metadataToken) { throw null; } public override System.Type ResolveType(int metadataToken, System.Type[]? genericTypeArguments, System.Type[]? genericMethodArguments) { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } public sealed partial class PropertyBuilder : System.Reflection.PropertyInfo { internal PropertyBuilder() { } public override System.Reflection.PropertyAttributes Attributes { get { throw null; } } public override bool CanRead { get { throw null; } } public override bool CanWrite { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override System.Type PropertyType { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public override System.Reflection.MethodInfo[] GetAccessors(bool nonPublic) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Reflection.MethodInfo? GetGetMethod(bool nonPublic) { throw null; } public override System.Reflection.ParameterInfo[] GetIndexParameters() { throw null; } public override System.Reflection.MethodInfo? GetSetMethod(bool nonPublic) { throw null; } public override object GetValue(object? obj, object?[]? index) { throw null; } public override object GetValue(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture) { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } public void SetConstant(object? defaultValue) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetGetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetSetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public override void SetValue(object? obj, object? value, object?[]? index) { } public override void SetValue(object? obj, object? value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture) { } } public sealed partial class TypeBuilder : System.Type { internal TypeBuilder() { } public const int UnspecifiedTypeSize = 0; public override System.Reflection.Assembly Assembly { get { throw null; } } public override string? AssemblyQualifiedName { get { throw null; } } public override System.Type? BaseType { get { throw null; } } public override System.Reflection.MethodBase? DeclaringMethod { get { throw null; } } public override System.Type? DeclaringType { get { throw null; } } public override string? FullName { get { throw null; } } public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } } public override int GenericParameterPosition { get { throw null; } } public override System.Guid GUID { get { throw null; } } public override bool IsConstructedGenericType { get { throw null; } } public override bool IsGenericParameter { get { throw null; } } public override bool IsGenericType { get { throw null; } } public override bool IsGenericTypeDefinition { get { throw null; } } public override bool IsSecurityCritical { get { throw null; } } public override bool IsSecuritySafeCritical { get { throw null; } } public override bool IsSecurityTransparent { get { throw null; } } public override System.Reflection.Module Module { get { throw null; } } public override string Name { get { throw null; } } public override string? Namespace { get { throw null; } } public System.Reflection.Emit.PackingSize PackingSize { get { throw null; } } public override System.Type? ReflectedType { get { throw null; } } public int Size { get { throw null; } } public override System.RuntimeTypeHandle TypeHandle { get { throw null; } } public override System.Type UnderlyingSystemType { get { throw null; } } public void AddInterfaceImplementation(System.Type interfaceType) { } public System.Reflection.TypeInfo? CreateTypeInfo() { throw null; } public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[]? parameterTypes, System.Type[][]? requiredCustomModifiers, System.Type[][]? optionalCustomModifiers) { throw null; } public System.Reflection.Emit.ConstructorBuilder DefineDefaultConstructor(System.Reflection.MethodAttributes attributes) { throw null; } public System.Reflection.Emit.EventBuilder DefineEvent(string name, System.Reflection.EventAttributes attributes, System.Type eventtype) { throw null; } public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Reflection.FieldAttributes attributes) { throw null; } public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Type[]? requiredCustomModifiers, System.Type[]? optionalCustomModifiers, System.Reflection.FieldAttributes attributes) { throw null; } public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; } public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes) { throw null; } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention) { throw null; } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type? returnType, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type? returnType, System.Type[]? returnTypeRequiredCustomModifiers, System.Type[]? returnTypeOptionalCustomModifiers, System.Type[]? parameterTypes, System.Type[][]? parameterTypeRequiredCustomModifiers, System.Type[][]? parameterTypeOptionalCustomModifiers) { throw null; } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Type? returnType, System.Type[]? parameterTypes) { throw null; } public void DefineMethodOverride(System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) { } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type? parent) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, int typeSize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Reflection.Emit.PackingSize packSize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Reflection.Emit.PackingSize packSize, int typeSize) { throw null; } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type? parent, System.Type[]? interfaces) { throw null; } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[]? returnTypeRequiredCustomModifiers, System.Type[]? returnTypeOptionalCustomModifiers, System.Type[]? parameterTypes, System.Type[][]? parameterTypeRequiredCustomModifiers, System.Type[][]? parameterTypeOptionalCustomModifiers) { throw null; } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[]? parameterTypes) { throw null; } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[]? returnTypeRequiredCustomModifiers, System.Type[]? returnTypeOptionalCustomModifiers, System.Type[]? parameterTypes, System.Type[][]? parameterTypeRequiredCustomModifiers, System.Type[][]? parameterTypeOptionalCustomModifiers) { throw null; } public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer() { throw null; } public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; } public static System.Reflection.ConstructorInfo GetConstructor(System.Type type, System.Reflection.ConstructorInfo constructor) { throw null; } protected override System.Reflection.ConstructorInfo? GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; } public override object[] GetCustomAttributes(bool inherit) { throw null; } public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; } public override System.Type GetElementType() { throw null; } public override System.Reflection.EventInfo? GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.EventInfo[] GetEvents() { throw null; } public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.FieldInfo? GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public static System.Reflection.FieldInfo GetField(System.Type type, System.Reflection.FieldInfo field) { throw null; } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type[] GetGenericArguments() { throw null; } public override System.Type GetGenericTypeDefinition() { throw null; } public override System.Type? GetInterface(string name, bool ignoreCase) { throw null; } public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; } public override System.Type[] GetInterfaces() { throw null; } public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; } public static System.Reflection.MethodInfo GetMethod(System.Type type, System.Reflection.MethodInfo method) { throw null; } protected override System.Reflection.MethodInfo? GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type? GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; } public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; } protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Type? returnType, System.Type[]? types, System.Reflection.ParameterModifier[]? modifiers) { throw null; } protected override bool HasElementTypeImpl() { throw null; } public override object? InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object? target, object?[]? args, System.Reflection.ParameterModifier[]? modifiers, System.Globalization.CultureInfo? culture, string[]? namedParameters) { throw null; } protected override bool IsArrayImpl() { throw null; } public override bool IsAssignableFrom(System.Type? c) { throw null; } protected override bool IsByRefImpl() { throw null; } protected override bool IsCOMObjectImpl() { throw null; } public bool IsCreated() { throw null; } public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; } protected override bool IsPointerImpl() { throw null; } protected override bool IsPrimitiveImpl() { throw null; } public override bool IsSubclassOf(System.Type c) { throw null; } public override System.Type MakeArrayType() { throw null; } public override System.Type MakeArrayType(int rank) { throw null; } public override System.Type MakeByRefType() { throw null; } public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; } public override System.Type MakePointerType() { throw null; } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetParent(System.Type? parent) { } public override string ToString() { throw null; } } }
// Copyright (C) 2014 dot42 // // Original filename: Junit.Runner.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 Junit.Runner { /// <summary> /// <para>An interface to define how a test suite should be loaded. </para> /// </summary> /// <java-name> /// junit/runner/TestSuiteLoader /// </java-name> [Dot42.DexImport("junit/runner/TestSuiteLoader", AccessFlags = 1537)] public partial interface ITestSuiteLoader /* scope: __dot42__ */ { /// <java-name> /// load /// </java-name> [Dot42.DexImport("load", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Load(string suiteClassName) /* MethodBuilder.Create */ ; /// <java-name> /// reload /// </java-name> [Dot42.DexImport("reload", "(Ljava/lang/Class;)Ljava/lang/Class;", AccessFlags = 1025)] global::System.Type Reload(global::System.Type aClass) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Base class for all test runners. This class was born live on stage in Sardinia during XP2000. </para> /// </summary> /// <java-name> /// junit/runner/BaseTestRunner /// </java-name> [Dot42.DexImport("junit/runner/BaseTestRunner", AccessFlags = 1057)] public abstract partial class BaseTestRunner : global::Junit.Framework.ITestListener /* scope: __dot42__ */ { /// <java-name> /// SUITE_METHODNAME /// </java-name> [Dot42.DexImport("SUITE_METHODNAME", "Ljava/lang/String;", AccessFlags = 25)] public const string SUITE_METHODNAME = "suite"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BaseTestRunner() /* MethodBuilder.Create */ { } /// <summary> /// <para>A test started. </para> /// </summary> /// <java-name> /// startTest /// </java-name> [Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// setPreferences /// </java-name> [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] protected internal static void SetPreferences(global::Java.Util.Properties preferences) /* MethodBuilder.Create */ { } /// <java-name> /// getPreferences /// </java-name> [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] protected internal static global::Java.Util.Properties GetPreferences() /* MethodBuilder.Create */ { return default(global::Java.Util.Properties); } /// <java-name> /// savePreferences /// </java-name> [Dot42.DexImport("savePreferences", "()V", AccessFlags = 9)] public static void SavePreferences() /* MethodBuilder.Create */ { } /// <java-name> /// setPreference /// </java-name> [Dot42.DexImport("setPreference", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetPreference(string key, string value) /* MethodBuilder.Create */ { } /// <summary> /// <para>A test ended. </para> /// </summary> /// <java-name> /// endTest /// </java-name> [Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 33)] public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ { } /// <java-name> /// addError /// </java-name> [Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)] public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ { } /// <java-name> /// addFailure /// </java-name> [Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)] public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ { } /// <java-name> /// testStarted /// </java-name> [Dot42.DexImport("testStarted", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestStarted(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testEnded /// </java-name> [Dot42.DexImport("testEnded", "(Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void TestEnded(string testName) /* MethodBuilder.Create */ ; /// <java-name> /// testFailed /// </java-name> [Dot42.DexImport("testFailed", "(ILjunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)] public abstract void TestFailed(int status, global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the Test corresponding to the given suite. This is a template method, subclasses override runFailed(), clearStatus(). </para> /// </summary> /// <java-name> /// getTest /// </java-name> [Dot42.DexImport("getTest", "(Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 1)] public virtual global::Junit.Framework.ITest GetTest(string suiteClassName) /* MethodBuilder.Create */ { return default(global::Junit.Framework.ITest); } /// <summary> /// <para>Returns the formatted string of the elapsed time. </para> /// </summary> /// <java-name> /// elapsedTimeAsString /// </java-name> [Dot42.DexImport("elapsedTimeAsString", "(J)Ljava/lang/String;", AccessFlags = 1)] public virtual string ElapsedTimeAsString(long runTime) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Processes the command line arguments and returns the name of the suite class to run or null </para> /// </summary> /// <java-name> /// processArguments /// </java-name> [Dot42.DexImport("processArguments", "([Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 4)] protected internal virtual string ProcessArguments(string[] args) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the loading behaviour of the test runner </para> /// </summary> /// <java-name> /// setLoading /// </java-name> [Dot42.DexImport("setLoading", "(Z)V", AccessFlags = 1)] public virtual void SetLoading(bool enable) /* MethodBuilder.Create */ { } /// <summary> /// <para>Extract the class name from a String in VA/Java style </para> /// </summary> /// <java-name> /// extractClassName /// </java-name> [Dot42.DexImport("extractClassName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)] public virtual string ExtractClassName(string className) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Truncates a String to the maximum length. </para> /// </summary> /// <java-name> /// truncate /// </java-name> [Dot42.DexImport("truncate", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string Truncate(string s) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Override to define how to handle a failed loading of a test suite. </para> /// </summary> /// <java-name> /// runFailed /// </java-name> [Dot42.DexImport("runFailed", "(Ljava/lang/String;)V", AccessFlags = 1028)] protected internal abstract void RunFailed(string message) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the loaded Class for a suite name. </para> /// </summary> /// <java-name> /// loadSuiteClass /// </java-name> [Dot42.DexImport("loadSuiteClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4)] protected internal virtual global::System.Type LoadSuiteClass(string suiteClassName) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <summary> /// <para>Clears the status message. </para> /// </summary> /// <java-name> /// clearStatus /// </java-name> [Dot42.DexImport("clearStatus", "()V", AccessFlags = 4)] protected internal virtual void ClearStatus() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] public virtual global::Junit.Runner.ITestSuiteLoader GetLoader() /* MethodBuilder.Create */ { return default(global::Junit.Runner.ITestSuiteLoader); } /// <java-name> /// useReloadingTestSuiteLoader /// </java-name> [Dot42.DexImport("useReloadingTestSuiteLoader", "()Z", AccessFlags = 4)] protected internal virtual bool UseReloadingTestSuiteLoader() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetPreference(string key) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPreference /// </java-name> [Dot42.DexImport("getPreference", "(Ljava/lang/String;I)I", AccessFlags = 9)] public static int GetPreference(string key, int dflt) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// inVAJava /// </java-name> [Dot42.DexImport("inVAJava", "()Z", AccessFlags = 9)] public static bool InVAJava() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(global::System.Exception exception) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getFilteredTrace /// </java-name> [Dot42.DexImport("getFilteredTrace", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string GetFilteredTrace(string @string) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// showStackRaw /// </java-name> [Dot42.DexImport("showStackRaw", "()Z", AccessFlags = 12)] protected internal static bool ShowStackRaw() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getPreferences /// </java-name> protected internal static global::Java.Util.Properties Preferences { [Dot42.DexImport("getPreferences", "()Ljava/util/Properties;", AccessFlags = 12)] get{ return GetPreferences(); } [Dot42.DexImport("setPreferences", "(Ljava/util/Properties;)V", AccessFlags = 12)] set{ SetPreferences(value); } } /// <summary> /// <para>Returns the loader to be used.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>not present in JUnit4.10 </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// getLoader /// </java-name> public global::Junit.Runner.ITestSuiteLoader Loader { [Dot42.DexImport("getLoader", "()Ljunit/runner/TestSuiteLoader;", AccessFlags = 1)] get{ return GetLoader(); } } } /// <summary> /// <para>This class defines the current version of JUnit </para> /// </summary> /// <java-name> /// junit/runner/Version /// </java-name> [Dot42.DexImport("junit/runner/Version", AccessFlags = 33)] public partial class Version /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal Version() /* MethodBuilder.Create */ { } /// <java-name> /// id /// </java-name> [Dot42.DexImport("id", "()Ljava/lang/String;", AccessFlags = 9)] public static string Id() /* MethodBuilder.Create */ { return default(string); } } }
using Rhino.Commons.ForTesting; using Rhino.Security.Exceptions; using Rhino.Security.Model; namespace Rhino.Security.Tests { using System; using Commons; using MbUnit.Framework; [TestFixture] public class ActiveRecord_AuthorizationRepositoryFixture : AuthorizationRepositoryFixture { public override string RhinoContainerConfig { get { return "ar-windsor.boo"; } } public override PersistenceFramework PersistenceFramwork { get { return PersistenceFramework.ActiveRecord; } } } [TestFixture] public class NHibernate_AuthorizationRepositoryFixture : AuthorizationRepositoryFixture { public override string RhinoContainerConfig { get { return "nh-windsor.boo"; } } public override PersistenceFramework PersistenceFramwork { get { return PersistenceFramework.NHibernate; } } } public abstract class AuthorizationRepositoryFixture : DatabaseFixture { [Test] public void CanSaveUser() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); UnitOfWork.CurrentSession.Flush(); UnitOfWork.CurrentSession.Evict(ayende); User fromDb = UnitOfWork.CurrentSession.Get<User>(ayende.Id); Assert.IsNotNull(fromDb); Assert.AreEqual(ayende.Name, fromDb.Name); } [Test] public void CanSaveAccount() { Account ayende = new Account(); ayende.Name = "ayende"; Assert.AreNotEqual(Guid.Empty, ayende.SecurityKey); UnitOfWork.CurrentSession.Save(ayende); UnitOfWork.CurrentSession.Flush(); UnitOfWork.CurrentSession.Evict(ayende); Account fromDb = UnitOfWork.CurrentSession.Get<Account>(ayende.Id); Assert.IsNotNull(fromDb); Assert.AreEqual(ayende.Name, fromDb.Name); Assert.AreEqual(fromDb.SecurityKey, ayende.SecurityKey); } [Test] public void CanCreateUsersGroup() { UsersGroup group = authorizationRepository.CreateUsersGroup("Admininstrators"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); UsersGroup groupFromDb = Repository<UsersGroup>.Get(group.Id); Assert.IsNotNull(groupFromDb); Assert.AreEqual(group.Name, groupFromDb.Name); } [Test] public void CanCreateEntitesGroup() { EntitiesGroup group = authorizationRepository.CreateEntitiesGroup("Accounts"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); EntitiesGroup groupFromDb = Repository<EntitiesGroup>.Get(group.Id); Assert.IsNotNull(groupFromDb); Assert.AreEqual(group.Name, groupFromDb.Name); } [Test] [ExpectedException(typeof (ValidationException))] public void CannotCreateEntitiesGroupWithSameName() { authorizationRepository.CreateEntitiesGroup("Admininstrators"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateEntitiesGroup("Admininstrators"); } [Test] [ExpectedException(typeof (ValidationException))] public void CannotCreateUsersGroupsWithSameName() { authorizationRepository.CreateUsersGroup("Admininstrators"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateUsersGroup("Admininstrators"); } [Test] public void CanGetUsersGroupByName() { UsersGroup group = authorizationRepository.CreateUsersGroup("Admininstrators"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetUsersGroupByName("Admininstrators"); Assert.IsNotNull(group); } [Test] public void CanGetEntitiesGroupByName() { EntitiesGroup group = authorizationRepository.CreateEntitiesGroup("Accounts"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetEntitiesGroupByName("Accounts"); Assert.IsNotNull(group); } [Test] public void CanChangeUsersGroupName() { UsersGroup group = authorizationRepository.CreateUsersGroup("Admininstrators"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetUsersGroupByName("Admininstrators"); group.Name = "2"; UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetUsersGroupByName("2"); Assert.IsNotNull(group); group = authorizationRepository.GetUsersGroupByName("Admininstrators"); Assert.IsNull(group); } [Test] public void CanChangeEntitiesGroupName() { EntitiesGroup group = authorizationRepository.CreateEntitiesGroup("Accounts"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetEntitiesGroupByName("Accounts"); group.Name = "2"; UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(group); group = authorizationRepository.GetEntitiesGroupByName("2"); Assert.IsNotNull(group); group = authorizationRepository.GetEntitiesGroupByName("Accounts"); Assert.IsNull(group); } [Test] public void CanAssociateUserWithGroup() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); UsersGroup group = authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "Admins"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(ayende); UnitOfWork.CurrentSession.Evict(group); UsersGroup[] groups = authorizationRepository.GetAssociatedUsersGroupFor(ayende); Assert.AreEqual(1, groups.Length); Assert.AreEqual("Admins", groups[0].Name); } [Test] public void CanAssociateUserWithNestedGroup() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); UsersGroup group = authorizationRepository.CreateChildUserGroupOf("Admins", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "DBA"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(ayende); UnitOfWork.CurrentSession.Evict(group); UsersGroup[] groups = authorizationRepository.GetAssociatedUsersGroupFor(ayende); Assert.AreEqual(2, groups.Length); Assert.AreEqual("Admins", groups[0].Name); Assert.AreEqual("DBA", groups[1].Name); } [Test] public void CanGetAncestryAssociationOfUserWithGroupWithNested() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("Admins", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "DBA"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(2, groups.Length); Assert.AreEqual("DBA", groups[0].Name); Assert.AreEqual("Admins", groups[1].Name); } [Test] public void CanGetAncestryAssociationOfUserWithGroupDirect() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "Admins"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(1, groups.Length); Assert.AreEqual("Admins", groups[0].Name); } [Test] public void CanGetAncestryAssociationOfUserWithGroupWhereNonExists() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(0, groups.Length); } [Test] public void CanGetAncestryAssociationOfUserWithGroupWhereThereIsDirectPathShouldSelectThat() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("Admins", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "Admins"); authorizationRepository.AssociateUserWith(ayende, "DBA"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(1, groups.Length); Assert.AreEqual("Admins", groups[0].Name); } [Test] public void CanGetAncestryAssociationOfUserWithGroupWhereThereIsTwoLevelNesting() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("Admins", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("DBA", "SQLite DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "SQLite DBA"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(3, groups.Length); Assert.AreEqual("SQLite DBA", groups[0].Name); Assert.AreEqual("DBA", groups[1].Name); Assert.AreEqual("Admins", groups[2].Name); } [Test] public void CanGetAncestryAssociationOfUserWithGroupWhereThereIsMoreThanOneIndirectPathShouldSelectShortest() { User ayende = new User(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); authorizationRepository.CreateUsersGroup("Admins"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("Admins", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.CreateChildUserGroupOf("DBA", "SQLite DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(ayende, "DBA"); authorizationRepository.AssociateUserWith(ayende, "SQLite DBA"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] groups = authorizationRepository.GetAncestryAssociation(ayende, "Admins"); Assert.AreEqual(2, groups.Length); Assert.AreEqual("DBA", groups[0].Name); Assert.AreEqual("Admins", groups[1].Name); } [Test] public void CanAssociateAccountWithGroup() { Account ayende = new Account(); ayende.Name = "ayende"; UnitOfWork.CurrentSession.Save(ayende); EntitiesGroup group = authorizationRepository.CreateEntitiesGroup("Accounts"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateEntityWith(ayende, "Accounts"); UnitOfWork.Current.TransactionalFlush(); UnitOfWork.CurrentSession.Evict(ayende); UnitOfWork.CurrentSession.Evict(group); EntitiesGroup[] groups = authorizationRepository.GetAssociatedEntitiesGroupsFor(ayende); Assert.AreEqual(1, groups.Length); Assert.AreEqual("Accounts", groups[0].Name); } [Test] public void CanCreateOperation() { authorizationRepository.CreateOperation("/Account/Delete"); UnitOfWork.Current.TransactionalFlush(); Operation operation = authorizationRepository.GetOperationByName("/Account/Delete"); Assert.IsNotNull(operation, "Could not create operation"); } [Test] public void WhenCreatingNestedOperation_WillCreateParentOperation_IfDoesNotExists() { Operation operation = authorizationRepository.CreateOperation("/Account/Delete"); UnitOfWork.Current.TransactionalFlush(); Operation parentOperation = authorizationRepository.GetOperationByName("/Account"); Assert.IsNotNull(parentOperation); Assert.AreEqual(operation.Parent, parentOperation); } [Test] public void WhenCreatingNestedOperation_WillLinkToParentOperation() { authorizationRepository.CreateOperation("/Account/Delete"); UnitOfWork.Current.TransactionalFlush(); Operation parentOperation = authorizationRepository.GetOperationByName("/Account"); Assert.IsNotNull(parentOperation); // was created in setup Assert.AreEqual(2, parentOperation.Children.Count); // /Edit, /Delete } [Test] public void CanRemoveUserGroup() { authorizationRepository.RemoveUsersGroup("Administrators"); UnitOfWork.Current.TransactionalFlush(); Assert.IsNull(authorizationRepository.GetUsersGroupByName("Administrators")); } [Test] [ExpectedException(typeof (InvalidOperationException), "Cannot remove users group 'Administrators' because is has child groups. Remove those groups and try again." )] public void RemovingParentUserGroupWillFail() { authorizationRepository.CreateChildUserGroupOf("Administrators", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.RemoveUsersGroup("Administrators"); } [Test] public void WhenRemovingUsersGroupThatHasAssociatedPermissionsThoseShouldBeRemoved() { permissionsBuilderService .Allow("/Account/Edit") .For("Administrators") .OnEverything() .DefaultLevel() .Save(); UnitOfWork.Current.TransactionalFlush(); Permission[] permissions = permissionService.GetPermissionsFor(user); Assert.IsNotEmpty(permissions); authorizationRepository.RemoveUsersGroup("Administrators"); UnitOfWork.Current.TransactionalFlush(); permissions = permissionService.GetPermissionsFor(user); Assert.IsEmpty(permissions); } [Test] public void CanRemoveNestedUserGroup() { UsersGroup dbaGroup = authorizationRepository.CreateChildUserGroupOf("Administrators", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.RemoveUsersGroup("DBA"); UnitOfWork.Current.TransactionalFlush(); Assert.IsNull(authorizationRepository.GetUsersGroupByName("DBA")); UsersGroup administratorsGroup = authorizationRepository.GetUsersGroupByName("Administrators"); Assert.AreEqual(0, administratorsGroup.DirectChildren.Count ); Assert.AreEqual(0, administratorsGroup.AllChildren.Count ); Assert.AreEqual(0, dbaGroup.AllParents.Count); } [Test] public void UsersAreNotAssociatedWithRemovedGroups() { authorizationRepository.CreateChildUserGroupOf("Administrators", "DBA"); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.AssociateUserWith(user, "DBA"); UnitOfWork.Current.TransactionalFlush(); UsersGroup[] associedGroups = authorizationRepository.GetAssociatedUsersGroupFor(user); Assert.AreEqual(2, associedGroups.Length); authorizationRepository.RemoveUsersGroup("DBA"); UnitOfWork.Current.TransactionalFlush(); associedGroups = authorizationRepository.GetAssociatedUsersGroupFor(user); Assert.AreEqual(1, associedGroups.Length); } [Test] public void CanRemoveEntitiesGroup() { authorizationRepository.RemoveEntitiesGroup("Important Accounts"); UnitOfWork.Current.TransactionalFlush(); Assert.IsNull(authorizationRepository.GetEntitiesGroupByName("Important Accounts")); ; } [Test] public void WhenRemovingEntitiesGroupAllPermissionsOnItWillBeDeleted() { permissionsBuilderService .Allow("/Account/Edit") .For(user) .On("Important Accounts") .DefaultLevel() .Save(); UnitOfWork.Current.TransactionalFlush(); Permission[] permissions = permissionService.GetPermissionsFor(user); Assert.IsNotEmpty(permissions); authorizationRepository.RemoveEntitiesGroup("Important Accounts"); UnitOfWork.Current.TransactionalFlush(); permissions = permissionService.GetPermissionsFor(user); Assert.IsEmpty(permissions); } [Test] public void CanRemoveOperation() { authorizationRepository.RemoveOperation("/Account/Edit"); UnitOfWork.Current.TransactionalFlush(); Assert.IsNull(authorizationRepository.GetOperationByName("/Account/Edit")); } [Test] [ExpectedException(typeof(InvalidOperationException), "Cannot remove operation '/Account' because it has child operations. Remove those operations and try again.")] public void CannotRemoveParentOperatio() { authorizationRepository.RemoveOperation("/Account"); } [Test] public void CanRemoveNestedOperation() { authorizationRepository.RemoveOperation("/Account/Edit"); UnitOfWork.Current.TransactionalFlush(); Operation parent = authorizationRepository.GetOperationByName("/Account"); Assert.AreEqual(0, parent.Children.Count); } [Test] public void CanRemoveUser() { authorizationRepository.RemoveUser(user); Repository<User>.Delete(user); UnitOfWork.Current.TransactionalFlush(); } [Test] public void RemovingUserWillAlsoRemoveAssociatedPermissions() { permissionsBuilderService .Allow("/Account/Edit") .For(user) .OnEverything() .DefaultLevel() .Save(); UnitOfWork.Current.TransactionalFlush(); authorizationRepository.RemoveUser(user); Repository<User>.Delete(user); UnitOfWork.Current.TransactionalFlush(); } } }
using System; /* * $Id: InfBlocks.cs,v 1.2 2008/05/10 09:35:40 bouncy Exp $ * Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ namespace Org.BouncyCastle.Utilities.Zlib { internal sealed class InfBlocks{ private const int MANY=1440; // And'ing with mask[n] masks the lower n bits private static readonly int[] inflate_mask = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff }; // Table for deflate from PKZIP's appnote.txt. static readonly int[] border = { // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private const int Z_OK=0; private const int Z_STREAM_END=1; private const int Z_NEED_DICT=2; private const int Z_ERRNO=-1; private const int Z_STREAM_ERROR=-2; private const int Z_DATA_ERROR=-3; private const int Z_MEM_ERROR=-4; private const int Z_BUF_ERROR=-5; private const int Z_VERSION_ERROR=-6; private const int TYPE=0; // get type bits (3, including end bit) private const int LENS=1; // get lengths for stored private const int STORED=2;// processing stored block private const int TABLE=3; // get table lengths private const int BTREE=4; // get bit lengths tree for a dynamic block private const int DTREE=5; // get length, distance trees for a dynamic block private const int CODES=6; // processing fixed or dynamic block private const int DRY=7; // output remaining window bytes private const int DONE=8; // finished last block, done private const int BAD=9; // ot a data error--stuck here internal int mode; // current inflate_block mode internal int left; // if STORED, bytes left to copy internal int table; // table lengths (14 bits) internal int index; // index into blens (or border) internal int[] blens; // bit lengths of codes internal int[] bb=new int[1]; // bit length tree depth internal int[] tb=new int[1]; // bit length decoding tree internal InfCodes codes=new InfCodes(); // if CODES, current state int last; // true if this block is the last block // mode independent information internal int bitk; // bits in bit buffer internal int bitb; // bit buffer internal int[] hufts; // single malloc for tree space internal byte[] window; // sliding window internal int end; // one byte after sliding window internal int read; // window read pointer internal int write; // window write pointer internal Object checkfn; // check function internal long check; // check on output internal InfTree inftree=new InfTree(); internal InfBlocks(ZStream z, Object checkfn, int w){ hufts=new int[MANY*3]; window=new byte[w]; end=w; this.checkfn = checkfn; mode = TYPE; reset(z, null); } internal void reset(ZStream z, long[] c){ if(c!=null) c[0]=check; if(mode==BTREE || mode==DTREE){ } if(mode==CODES){ codes.free(z); } mode=TYPE; bitk=0; bitb=0; read=write=0; if(checkfn != null) z.adler=check=z._adler.adler32(0L, null, 0, 0); } internal int proc(ZStream z, int r){ int t; // temporary storage int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; { // bytes to end of window or read pointer // copy input/output information to locals (UPDATE macro restores) p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;} { q=write;m=(int)(q<read?read-q-1:end-q);} // process input based on current state while(true){ switch (mode){ case TYPE: while(k<(3)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } t = (int)(b & 7); last = t & 1; switch (t >> 1){ case 0: { // stored b>>=(3);k-=(3);} t = k & 7; { // go to byte boundary b>>=(t);k-=(t);} mode = LENS; // get length of stored block break; case 1: { // fixed int[] bl=new int[1]; int[] bd=new int[1]; int[][] tl=new int[1][]; int[][] td=new int[1][]; InfTree.inflate_trees_fixed(bl, bd, tl, td, z); codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z); } { b>>=(3);k-=(3);} mode = CODES; break; case 2: { // dynamic b>>=(3);k-=(3);} mode = TABLE; break; case 3: { // illegal b>>=(3);k-=(3);} mode = BAD; z.msg = "invalid block type"; r = Z_DATA_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } break; case LENS: while(k<(32)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } if ((((~b) >> 16) & 0xffff) != (b & 0xffff)){ mode = BAD; z.msg = "invalid stored block lengths"; r = Z_DATA_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } left = (b & 0xffff); b = k = 0; // dump bits mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE); break; case STORED: if (n == 0){ bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } if(m==0){ if(q==end&&read!=0){ q=0; m=(int)(q<read?read-q-1:end-q); } if(m==0){ write=q; r=inflate_flush(z,r); q=write;m=(int)(q<read?read-q-1:end-q); if(q==end&&read!=0){ q=0; m=(int)(q<read?read-q-1:end-q); } if(m==0){ bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } } } r=Z_OK; t = left; if(t>n) t = n; if(t>m) t = m; System.Array.Copy(z.next_in, p, window, q, t); p += t; n -= t; q += t; m -= t; if ((left -= t) != 0) break; mode = last!=0 ? DRY : TYPE; break; case TABLE: while(k<(14)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } table = t = (b & 0x3fff); if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { mode = BAD; z.msg = "too many length or distance symbols"; r = Z_DATA_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if(blens==null || blens.Length<t){ blens=new int[t]; } else{ for(int i=0; i<t; i++){blens[i]=0;} } { b>>=(14);k-=(14);} index = 0; mode = BTREE; goto case BTREE; case BTREE: while (index < 4 + (table >> 10)){ while(k<(3)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } blens[border[index++]] = b&7; { b>>=(3);k-=(3);} } while(index < 19){ blens[border[index++]] = 0; } bb[0] = 7; t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z); if (t != Z_OK){ r = t; if (r == Z_DATA_ERROR){ blens=null; mode = BAD; } bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } index = 0; mode = DTREE; goto case DTREE; case DTREE: while (true){ t = table; if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){ break; } int i, j, c; t = bb[0]; while(k<(t)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } if(tb[0]==-1){ //System.err.println("null..."); } t=hufts[(tb[0]+(b&inflate_mask[t]))*3+1]; c=hufts[(tb[0]+(b&inflate_mask[t]))*3+2]; if (c < 16){ b>>=(t);k-=(t); blens[index++] = c; } else { // c == 16..18 i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; while(k<(t+i)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } b>>=(t);k-=(t); j += (b & inflate_mask[i]); b>>=(i);k-=(i); i = index; t = table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)){ blens=null; mode = BAD; z.msg = "invalid bit length repeat"; r = Z_DATA_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } c = c == 16 ? blens[i-1] : 0; do{ blens[i++] = c; } while (--j!=0); index = i; } } tb[0]=-1; { int[] bl=new int[1]; int[] bd=new int[1]; int[] tl=new int[1]; int[] td=new int[1]; bl[0] = 9; // must be <= 9 for lookahead assumptions bd[0] = 6; // must be <= 9 for lookahead assumptions t = table; t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, z); if (t != Z_OK){ if (t == Z_DATA_ERROR){ blens=null; mode = BAD; } r = t; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); } codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z); } mode = CODES; goto case CODES; case CODES: bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; if ((r = codes.proc(this, z, r)) != Z_STREAM_END){ return inflate_flush(z, r); } r = Z_OK; codes.free(z); p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk; q=write;m=(int)(q<read?read-q-1:end-q); if (last==0){ mode = TYPE; break; } mode = DRY; goto case DRY; case DRY: write=q; r=inflate_flush(z, r); q=write; m=(int)(q<read?read-q-1:end-q); if (read != write){ bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z, r); } mode = DONE; goto case DONE; case DONE: r = Z_STREAM_END; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z, r); case BAD: r = Z_DATA_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z, r); default: r = Z_STREAM_ERROR; bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z, r); } } } internal void free(ZStream z){ reset(z, null); window=null; hufts=null; //ZFREE(z, s); } internal void set_dictionary(byte[] d, int start, int n){ System.Array.Copy(d, start, window, 0, n); read = write = n; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. internal int sync_point(){ return mode == LENS ? 1 : 0; } // copy as much as possible from the sliding window to the output area internal int inflate_flush(ZStream z, int r){ int n; int p; int q; // local copies of source and destination pointers p = z.next_out_index; q = read; // compute number of bytes to copy as far as end of window n = (int)((q <= write ? write : end) - q); if (n > z.avail_out) n = z.avail_out; if (n!=0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if(checkfn != null) z.adler=check=z._adler.adler32(check, window, q, n); // copy as far as end of window System.Array.Copy(window, q, z.next_out, p, n); p += n; q += n; // see if more to copy at beginning of window if (q == end){ // wrap pointers q = 0; if (write == end) write = 0; // compute bytes to copy n = write - q; if (n > z.avail_out) n = z.avail_out; if (n!=0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if(checkfn != null) z.adler=check=z._adler.adler32(check, window, q, n); // copy System.Array.Copy(window, q, z.next_out, p, n); p += n; q += n; } // update pointers z.next_out_index = p; read = q; // done return r; } } }
// 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.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { internal static class SslStreamPal { private const string SecurityPackage = "Microsoft Unified Security Protocol Provider"; private const Interop.SspiCli.ContextFlags RequiredFlags = Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.Confidentiality | Interop.SspiCli.ContextFlags.AllocateMemory; private const Interop.SspiCli.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream; public static Exception GetException(SecurityStatusPal status) { int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status); return new Win32Exception(win32Code); } internal const bool StartMutualAuthAsAnonymous = true; internal const bool CanEncryptEmptyMessage = true; public static void VerifyPackageInfo() { SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true); } public static byte[] ConvertAlpnProtocolListToByteArray(List<SslApplicationProtocol> protocols) { return Interop.Sec_Application_Protocols.ToByteArray(protocols); } public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, ArraySegment<byte> input, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; ThreeSecurityBuffers threeSecurityBuffers = default; SecurityBuffer? incomingSecurity = input.Array != null ? new SecurityBuffer(input.Array, input.Offset, input.Count, SecurityBufferType.SECBUFFER_TOKEN) : (SecurityBuffer?)null; Span<SecurityBuffer> inputBuffers = MemoryMarshal.CreateSpan(ref threeSecurityBuffers._item0, 3); GetIncomingSecurityBuffers(sslAuthenticationOptions, in incomingSecurity, ref inputBuffers); var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, ServerRequiredFlags | (sslAuthenticationOptions.RemoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero), Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, ArraySegment<byte> input, ref byte[] outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; ThreeSecurityBuffers threeSecurityBuffers = default; SecurityBuffer? incomingSecurity = input.Array != null ? new SecurityBuffer(input.Array, input.Offset, input.Count, SecurityBufferType.SECBUFFER_TOKEN) : (SecurityBuffer?)null; Span<SecurityBuffer> inputBuffers = MemoryMarshal.CreateSpan(ref threeSecurityBuffers._item0, 3); GetIncomingSecurityBuffers(sslAuthenticationOptions, in incomingSecurity, ref inputBuffers); var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } private static void GetIncomingSecurityBuffers(SslAuthenticationOptions options, in SecurityBuffer? incomingSecurity, ref Span<SecurityBuffer> incomingSecurityBuffers) { SecurityBuffer? alpnBuffer = null; if (options.ApplicationProtocols != null && options.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(options.ApplicationProtocols); alpnBuffer = new SecurityBuffer(alpnBytes, 0, alpnBytes.Length, SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS); } if (incomingSecurity != null) { if (alpnBuffer != null) { Debug.Assert(incomingSecurityBuffers.Length >= 3); incomingSecurityBuffers[0] = incomingSecurity.GetValueOrDefault(); incomingSecurityBuffers[1] = new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY); incomingSecurityBuffers[2] = alpnBuffer.GetValueOrDefault(); incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 3); } else { Debug.Assert(incomingSecurityBuffers.Length >= 2); incomingSecurityBuffers[0] = incomingSecurity.GetValueOrDefault(); incomingSecurityBuffers[1] = new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY); incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 2); } } else if (alpnBuffer != null) { incomingSecurityBuffers[0] = alpnBuffer.GetValueOrDefault(); incomingSecurityBuffers = incomingSecurityBuffers.Slice(0, 1); } else { incomingSecurityBuffers = default; } } public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; Interop.SspiCli.CredentialUse direction; if (!isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; // CoreFX: always opt-in SCH_USE_STRONG_CRYPTO for TLS. if (((protocolFlags == 0) || (protocolFlags & ~(Interop.SChannel.SP_PROT_SSL2 | Interop.SChannel.SP_PROT_SSL3)) != 0) && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption)) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; } if (NetEventSource.IsEnabled) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential( Interop.SspiCli.SCHANNEL_CRED.CurrentVersion, certificate, flags, protocolFlags, policy); return AcquireCredentialsHandle(direction, secureCredential); } internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context) { Interop.SecPkgContext_ApplicationProtocol alpnContext = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL, ref alpnContext); // Check if the context returned is alpn data, with successful negotiation. if (success && alpnContext.ProtoNegoExt == Interop.ApplicationProtocolNegotiationExt.ALPN && alpnContext.ProtoNegoStatus == Interop.ApplicationProtocolNegotiationStatus.Success) { return alpnContext.Protocol; } return null; } public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, ReadOnlyMemory<byte> input, int headerSize, int trailerSize, ref byte[] output, out int resultSize) { // Ensure that there is sufficient space for the message output. int bufferSizeNeeded; try { bufferSizeNeeded = checked(input.Length + headerSize + trailerSize); } catch { NetEventSource.Fail(securityContext, "Arguments out of range"); throw; } if (output == null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } // Copy the input into the output buffer to prepare for SCHANNEL's expectations input.Span.CopyTo(new Span<byte>(output, headerSize, input.Length)); const int NumSecBuffers = 4; // header + data + trailer + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* outputPtr = output) { Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0]; headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER; headerSecBuffer->pvBuffer = (IntPtr)outputPtr; headerSecBuffer->cbBuffer = headerSize; Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1]; dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize); dataSecBuffer->cbBuffer = input.Length; Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2]; trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER; trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + input.Length); trailerSecBuffer->cbBuffer = trailerSize; Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3]; emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptySecBuffer->cbBuffer = 0; emptySecBuffer->pvBuffer = IntPtr.Zero; int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0); if (errorCode != 0) { if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}"); resultSize = 0; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0); Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length); resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer); return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } } public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count) { const int NumSecBuffers = 4; // data + empty + empty + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* bufferPtr = buffer) { Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0]; dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataBuffer->pvBuffer = (IntPtr)bufferPtr + offset; dataBuffer->cbBuffer = count; for (int i = 1; i < NumSecBuffers; i++) { Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i]; emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptyBuffer->pvBuffer = IntPtr.Zero; emptyBuffer->cbBuffer = 0; } Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. count = 0; for (int i = 0; i < NumSecBuffers; i++) { // Successfully decoded data and placed it at the following position in the buffer, if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA) // or we failed to decode the data, here is the encoded data. || (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA)) { offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr); count = unmanagedBuffer[i].cbBuffer; Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}"); Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}"); break; } } return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode); } } public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN { dwTokenType = Interop.SChannel.SCHANNEL_ALERT, dwAlertType = (uint)alertType, dwAlertNumber = (uint)alertMessage }; byte[] buffer = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref alertToken, 1)).ToArray(); var securityBuffer = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN); public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext) { var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } public static unsafe SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) { SecPkgContext_StreamSizes interopStreamSizes = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES, ref interopStreamSizes); Debug.Assert(success); streamSizes = new StreamSizes(interopStreamSizes); } public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo) { SecPkgContext_ConnectionInfo interopConnectionInfo = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO, ref interopConnectionInfo); Debug.Assert(success); connectionInfo = new SslConnectionInfo(interopConnectionInfo); } private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer) { int protocolFlags = (int)protocols; if (isServer) { protocolFlags &= Interop.SChannel.ServerProtocolMask; } else { protocolFlags &= Interop.SChannel.ClientProtocolMask; } return protocolFlags; } private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( int version, X509Certificate certificate, Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { var credential = new Interop.SspiCli.SCHANNEL_CRED() { hRootStore = IntPtr.Zero, aphMappers = IntPtr.Zero, palgSupportedAlgs = IntPtr.Zero, paCred = IntPtr.Zero, cCreds = 0, cMappers = 0, cSupportedAlgs = 0, dwSessionLifespan = 0, reserved = 0 }; if (policy == EncryptionPolicy.RequireEncryption) { // Prohibit null encryption cipher. credential.dwMinimumCipherStrength = 0; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.NoEncryption) { // Suppress all encryption and require null encryption cipher only credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = -1; } else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } credential.dwVersion = version; credential.dwFlags = flags; credential.grbitEnabledProtocols = protocols; if (certificate != null) { credential.paCred = certificate.Handle; credential.cCreds = 1; } return credential; } // // Security: we temporarily reset thread token to open the handle under process account. // private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } } }
using EPiServer.Commerce.Catalog.ContentTypes; using EPiServer.Core; using EPiServer.Framework.Localization; using EPiServer.Globalization; using EPiServer.Reference.Commerce.Site.Features.Search.Models; using EPiServer.Web.Routing; using Mediachase.Commerce.Website.Search; using Mediachase.Search; using Mediachase.Search.Extensions; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace EPiServer.Reference.Commerce.Site.Features.Search.ViewModels { public class FilterOptionViewModelBinder : DefaultModelBinder { private readonly IContentLoader _contentLoader; private readonly LocalizationService _localizationService; private readonly LanguageResolver _languageResolver; public FilterOptionViewModelBinder(IContentLoader contentLoader, LocalizationService localizationService, LanguageResolver languageResolver) { _contentLoader = contentLoader; _localizationService = localizationService; _languageResolver = languageResolver; } public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { bindingContext.ModelName = "FilterOption"; var model = (FilterOptionViewModel)base.BindModel(controllerContext, bindingContext); if (model == null) { return null; } var contentLink = controllerContext.RequestContext.GetContentLink(); IContent content = null; if (!ContentReference.IsNullOrEmpty(contentLink)) { content = _contentLoader.Get<IContent>(contentLink); } var query = controllerContext.HttpContext.Request.QueryString["q"]; var sort = controllerContext.HttpContext.Request.QueryString["sort"]; var facets = controllerContext.HttpContext.Request.QueryString["facets"]; SetupModel(model, query, sort, facets, content); return model; } protected virtual void SetupModel(FilterOptionViewModel model, string q, string sort, string facets, IContent content) { EnsurePage(model); EnsureQ(model, q); EnsureSort(model, sort); EnsureFacets(model, facets, content); } protected virtual void EnsurePage(FilterOptionViewModel model) { if (model.Page < 1) { model.Page = 1; } } protected virtual void EnsureQ(FilterOptionViewModel model, string q) { if (string.IsNullOrEmpty(model.Q)) { model.Q = q; } } protected virtual void EnsureSort(FilterOptionViewModel model, string sort) { if (string.IsNullOrEmpty(model.Sort)) { model.Sort = sort; } } protected virtual void EnsureFacets(FilterOptionViewModel model, string facets, IContent content) { if (model.FacetGroups == null) { model.FacetGroups = CreateFacetGroups(facets, content); } } private List<FacetGroupOption> CreateFacetGroups(string facets, IContent content) { var facetGroups = new List<FacetGroupOption>(); if (string.IsNullOrEmpty(facets)) { return facetGroups; } foreach (var facet in facets.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries)) { var searchFilter = GetSearchFilter(facet); if (searchFilter != null) { var facetGroup = facetGroups.FirstOrDefault(fg => fg.GroupFieldName == searchFilter.field); if (facetGroup == null) { facetGroup = CreateFacetGroup(searchFilter); facetGroups.Add(facetGroup); } var facetOption = facetGroup.Facets.FirstOrDefault(fo => fo.Name == facet); if (facetOption == null) { facetOption = CreateFacetOption(facet); facetGroup.Facets.Add(facetOption); } } } var nodeContent = content as NodeContent; if (nodeContent == null) { return facetGroups; } var filter = GetSearchFilterForNode(nodeContent); var selectedFilters = facets.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); var nodeFacetValues = filter.Values.SimpleValue.Where(x => selectedFilters.Any(y => y.ToLower().Equals(x.key.ToLower()))); if (!nodeFacetValues.Any()) { return facetGroups; } var nodeFacet = CreateFacetGroup(filter); foreach (var nodeFacetValue in nodeFacetValues) { nodeFacet.Facets.Add(CreateFacetOption(nodeFacetValue.value)); } facetGroups.Add(nodeFacet); return facetGroups; } private SearchFilter GetSearchFilter(string facet) { return SearchFilterHelper.Current.SearchConfig.SearchFilters.FirstOrDefault(filter => filter.Values.SimpleValue.Any(value => string.Equals(value.value, facet, System.StringComparison.InvariantCultureIgnoreCase))); } private FacetGroupOption CreateFacetGroup(SearchFilter searchFilter) { return new FacetGroupOption { GroupFieldName = searchFilter.field, Facets = new List<FacetOption>() }; } private FacetOption CreateFacetOption(string facet) { return new FacetOption { Name = facet, Key = facet, Selected = true }; } public SearchFilter GetSearchFilterForNode(NodeContent nodeContent) { var configFilter = new SearchFilter { field = BaseCatalogIndexBuilder.FieldConstants.Node, Descriptions = new Descriptions { defaultLocale = _languageResolver.GetPreferredCulture().Name }, Values = new SearchFilterValues() }; var desc = new Description { locale = "en", Value = _localizationService.GetString("/Facet/Category") }; configFilter.Descriptions.Description = new[] { desc }; var nodes = _contentLoader.GetChildren<NodeContent>(nodeContent.ContentLink).ToList(); var nodeValues = new SimpleValue[nodes.Count]; var index = 0; var preferredCultureName = _languageResolver.GetPreferredCulture().Name; foreach (var node in nodes) { var val = new SimpleValue { key = node.Code, value = node.Code, Descriptions = new Descriptions { defaultLocale = preferredCultureName } }; var desc2 = new Description { locale = preferredCultureName, Value = node.DisplayName }; val.Descriptions.Description = new[] { desc2 }; nodeValues[index] = val; index++; } configFilter.Values.SimpleValue = nodeValues; return configFilter; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndInt16() { var test = new SimpleBinaryOpTest__AndInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndInt16 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[ElementCount]; private static Int16[] _data2 = new Int16[ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16> _dataTable; static SimpleBinaryOpTest__AndInt16() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AndInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16>(_data1, _data2, new Int16[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.And( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.And( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.And( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndInt16(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { if ((short)(left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((short)(left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<Int16>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Runtime.ReminderService; using Orleans.TestingHost; using TestExtensions; using UnitTests.TestHelper; using Xunit; using Xunit.Sdk; namespace UnitTests.General { public class ConsistentRingProviderTests_Silo : TestClusterPerTest { private const int numAdditionalSilos = 3; private readonly TimeSpan failureTimeout = TimeSpan.FromSeconds(30); private readonly TimeSpan endWait = TimeSpan.FromMinutes(5); enum Fail { First, Random, Last } protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.AddSiloBuilderConfigurator<Configurator>(); builder.AddClientBuilderConfigurator<Configurator>(); } private class Configurator : ISiloConfigurator, IClientBuilderConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorageAsDefault() .UseInMemoryReminderService(); } public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.Configure<GatewayOptions>( options => options.GatewayListRefreshPeriod = TimeSpan.FromMilliseconds(100)); } } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_Basic() { await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); VerificationScenario(0); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1F_Random() { await FailureTest(Fail.Random, 1); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1F_Beginning() { await FailureTest(Fail.First, 1); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1F_End() { await FailureTest(Fail.Last, 1); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_2F_Random() { await FailureTest(Fail.Random, 2); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_2F_Beginning() { await FailureTest(Fail.First, 2); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_2F_End() { await FailureTest(Fail.Last, 2); } private async Task FailureTest(Fail failCode, int numOfFailures) { await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); List<SiloHandle> failures = await getSilosToFail(failCode, numOfFailures); foreach (SiloHandle fail in failures) // verify before failure { VerificationScenario(PickKey(fail.SiloAddress)); // fail.SiloAddress.GetConsistentHashCode()); } logger.Info("FailureTest {0}, Code {1}, Stopping silos: {2}", numOfFailures, failCode, Utils.EnumerableToString(failures, handle => handle.SiloAddress.ToString())); List<uint> keysToTest = new List<uint>(); foreach (SiloHandle fail in failures) // verify before failure { keysToTest.Add(PickKey(fail.SiloAddress)); //fail.SiloAddress.GetConsistentHashCode()); await this.HostedCluster.StopSiloAsync(fail); } await this.HostedCluster.WaitForLivenessToStabilizeAsync(); AssertEventually(() => { foreach (var key in keysToTest) // verify after failure { VerificationScenario(key); } }, failureTimeout); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1J() { await JoinTest(1); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_2J() { await JoinTest(2); } private async Task JoinTest(int numOfJoins) { logger.Info("JoinTest {0}", numOfJoins); await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos - numOfJoins); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(numOfJoins); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); foreach (SiloHandle sh in silos) { VerificationScenario(PickKey(sh.SiloAddress)); } Thread.Sleep(TimeSpan.FromSeconds(15)); } [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1F1J() { await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); List<SiloHandle> failures = await getSilosToFail(Fail.Random, 1); uint keyToCheck = PickKey(failures[0].SiloAddress);// failures[0].SiloAddress.GetConsistentHashCode(); List<SiloHandle> joins = null; // kill a silo and join a new one in parallel logger.Info("Killing silo {0} and joining a silo", failures[0].SiloAddress); var tasks = new Task[2] { Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(failures[0])), this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult()) }; Task.WaitAll(tasks, endWait); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); AssertEventually(() => { VerificationScenario(keyToCheck); // verify failed silo's key VerificationScenario(PickKey(joins[0].SiloAddress)); // verify newly joined silo's key }, failureTimeout); } // failing the secondary in this scenario exposed the bug in DomainGrain ... so, we keep it as a separate test than Ring_1F1J [Fact, TestCategory("Functional"), TestCategory("Ring")] public async Task Ring_1Fsec1J() { await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); //List<SiloHandle> failures = getSilosToFail(Fail.Random, 1); SiloHandle fail = this.HostedCluster.SecondarySilos.First(); uint keyToCheck = PickKey(fail.SiloAddress); //fail.SiloAddress.GetConsistentHashCode(); List<SiloHandle> joins = null; // kill a silo and join a new one in parallel logger.Info("Killing secondary silo {0} and joining a silo", fail.SiloAddress); var tasks = new Task[2] { Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(fail)), this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult()) }; Task.WaitAll(tasks, endWait); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); AssertEventually(() => { VerificationScenario(keyToCheck); // verify failed silo's key VerificationScenario(PickKey(joins[0].SiloAddress)); }, failureTimeout); } private uint PickKey(SiloAddress responsibleSilo) { int iteration = 10000; var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary); for (int i = 0; i < iteration; i++) { double next = random.NextDouble(); uint randomKey = (uint)((double)RangeFactory.RING_SIZE * next); SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo(randomKey).Result; if (responsibleSilo.Equals(s)) return randomKey; } throw new Exception(String.Format("Could not pick a key that silo {0} will be responsible for. Primary.Ring = \n{1}", responsibleSilo, testHooks.GetConsistentRingProviderDiagnosticInfo().Result)); } private void VerificationScenario(uint testKey) { // setup List<SiloAddress> silos = new List<SiloAddress>(); foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) { long hash = siloHandle.SiloAddress.GetConsistentHashCode(); int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; silos.Insert(index, siloHandle.SiloAddress); } // verify parameter key VerifyKey(testKey, silos); // verify some other keys as well, apart from the parameter key // some random keys for (int i = 0; i < 3; i++) { VerifyKey((uint)random.Next(), silos); } // lowest key uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1); VerifyKey(lowest, silos); // highest key uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1); VerifyKey(lowest, silos); } private void VerifyKey(uint key, List<SiloAddress> silos) { var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary); SiloAddress truth = testHooks.GetConsistentRingPrimaryTargetSilo(key).Result; //expected; //if (truth == null) // if the truth isn't passed, we compute it here //{ // truth = silos.Find(siloAddr => (key <= siloAddr.GetConsistentHashCode())); // if (truth == null) // { // truth = silos.First(); // } //} // lookup for 'key' should return 'truth' on all silos foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) // do this for each silo { SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo((uint)key).Result; Assert.Equal(truth, s); } } private async Task<List<SiloHandle>> getSilosToFail(Fail fail, int numOfFailures) { List<SiloHandle> failures = new List<SiloHandle>(); int count = 0, index = 0; // Figure out the primary directory partition and the silo hosting the ReminderTableGrain. var tableGrain = this.GrainFactory.GetGrain<IReminderTableGrain>(InMemoryReminderTable.ReminderTableGrainId); // Ping the grain to make sure it is active. await tableGrain.ReadRows((GrainReference)tableGrain); var tableGrainId = ((GrainReference)tableGrain).GrainId; SiloAddress reminderTableGrainPrimaryDirectoryAddress = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.Primary)).PrimaryForGrain; // ask a detailed report from the directory partition owner, and get the actionvation addresses var addresses = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.GetSiloForAddress(reminderTableGrainPrimaryDirectoryAddress))).LocalDirectoryActivationAddresses; ActivationAddress reminderGrainActivation = addresses.FirstOrDefault(); SortedList<int, SiloHandle> ids = new SortedList<int, SiloHandle>(); foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) { SiloAddress siloAddress = siloHandle.SiloAddress; if (siloAddress.Equals(this.HostedCluster.Primary.SiloAddress)) { continue; } // Don't fail primary directory partition and the silo hosting the ReminderTableGrain. if (siloAddress.Equals(reminderTableGrainPrimaryDirectoryAddress) || siloAddress.Equals(reminderGrainActivation.Silo)) { continue; } ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle); } // we should not fail the primary! // we can't guarantee semantics of 'Fail' if it evalutes to the primary's address switch (fail) { case Fail.First: index = 0; while (count++ < numOfFailures) { while (failures.Contains(ids.Values[index])) { index++; } failures.Add(ids.Values[index]); } break; case Fail.Last: index = ids.Count - 1; while (count++ < numOfFailures) { while (failures.Contains(ids.Values[index])) { index--; } failures.Add(ids.Values[index]); } break; case Fail.Random: default: while (count++ < numOfFailures) { SiloHandle r = ids.Values[random.Next(ids.Count)]; while (failures.Contains(r)) { r = ids.Values[random.Next(ids.Count)]; } failures.Add(r); } break; } return failures; } // for debugging only private void printSilos(string msg) { SortedList<int, SiloAddress> ids = new SortedList<int, SiloAddress>(numAdditionalSilos + 2); foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) { ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle.SiloAddress); } logger.Info("{0} list of silos: ", msg); foreach (var id in ids.Keys.ToList()) { logger.Info("{0} -> {1}", ids[id], id); } } private static void AssertEventually(Action assertion, TimeSpan timeout) { AssertEventually(assertion, timeout, TimeSpan.FromMilliseconds(500)); } private static void AssertEventually(Action assertion, TimeSpan timeout, TimeSpan delayBetweenIterations) { var sw = Stopwatch.StartNew(); while (true) { try { assertion(); return; } catch (XunitException) { if (sw.ElapsedMilliseconds > timeout.TotalMilliseconds) { throw; } } if (delayBetweenIterations > TimeSpan.Zero) { Thread.Sleep(delayBetweenIterations); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class HighPriorityProcessor : IdleProcessor { private readonly IncrementalAnalyzerProcessor _processor; private readonly AsyncDocumentWorkItemQueue _workItemQueue; private Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers; // whether this processor is running or not private Task _running; public HighPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, backOffTimeSpanInMs, shutdownToken) { _processor = processor; _lazyAnalyzers = lazyAnalyzers; _running = SpecializedTasks.EmptyTask; _workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace); Start(); } public Task Running { get { return _running; } } public bool HasAnyWork { get { return _workItemQueue.HasAnyWork; } } public void AddAnalyzer(IIncrementalAnalyzer analyzer) { var analyzers = _lazyAnalyzers.Value; _lazyAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => analyzers.Add(analyzer)); } public void Enqueue(WorkItem item) { Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item"); // we only put workitem in high priority queue if there is a text change. // this is to prevent things like opening a file, changing in other files keep enqueuing // expensive high priority work. if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { return; } // check whether given item is for active document, otherwise, nothing to do here if (_processor._documentTracker == null || _processor._documentTracker.GetActiveDocument() != item.DocumentId) { return; } // we need to clone due to waiter EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile"))); } private void EnqueueActiveFileItem(WorkItem item) { this.UpdateLastAccessTime(); var added = _workItemQueue.AddOrReplace(item); Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added); SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator); } protected override Task WaitAsync(CancellationToken cancellationToken) { return _workItemQueue.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { if (this.CancellationToken.IsCancellationRequested) { return; } var source = new TaskCompletionSource<object>(); try { // mark it as running _running = source.Task; // okay, there must be at least one item in the map // see whether we have work item for the document Contract.ThrowIfFalse(GetNextWorkItem(out var workItem, out var documentCancellation)); var solution = _processor.CurrentSolution; // okay now we have work to do await ProcessDocumentAsync(solution, _lazyAnalyzers.Value, workItem, documentCancellation).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // mark it as done running source.SetResult(null); } } private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation) { // GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail. var documentId = _processor._documentTracker.GetActiveDocument(); if (documentId != null) { if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation)) { return true; } } return _workItemQueue.TryTakeAnyWork( preferableProjectId: null, dependencyGraph: _processor.DependencyGraph, analyzerService: _processor.DiagnosticAnalyzerService, workItem: out workItem, source: out documentCancellation); } private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source) { if (this.CancellationToken.IsCancellationRequested) { return; } var processedEverything = false; var documentId = workItem.DocumentId; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token)) { var cancellationToken = source.Token; var document = solution.GetDocument(documentId); if (document != null) { await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false); } if (!cancellationToken.IsCancellationRequested) { processedEverything = true; } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the document. // let's make sure newly enqueued work item has all the flag needed. if (!processedEverything) { _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything); // remove one that is finished running _workItemQueue.RemoveCancellationSource(workItem.DocumentId); } } public void Shutdown() { _workItemQueue.Dispose(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else using System.Threading.Tasks; namespace System.Diagnostics.Tracing #endif { /// <summary> /// Tracks activities. This is meant to be a singleton (accessed by the ActivityTracer.Instance static property) /// /// Logically this is simply holds the m_current variable that holds the async local that holds the current ActivityInfo /// An ActivityInfo is represents a activity (which knows its creator and thus knows its path). /// /// Most of the magic is in the async local (it gets copied to new tasks) /// /// On every start event call OnStart /// /// Guid activityID; /// Guid relatedActivityID; /// if (OnStart(activityName, out activityID, out relatedActivityID, ForceStop, options)) /// // Log Start event with activityID and relatedActivityID /// /// On every stop event call OnStop /// /// Guid activityID; /// if (OnStop(activityName, ref activityID ForceStop)) /// // Stop event with activityID /// /// On any normal event log the event with activityTracker.CurrentActivityId /// </summary> internal class ActivityTracker { /// <summary> /// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix. /// It updates CurrentActivityId to track. /// /// It returns true if the Start should be logged, otherwise (if it is illegal recursion) it return false. /// /// The start event should use as its activity ID the CurrentActivityId AFTER calling this routine and its /// RelatedActivityID the CurrentActivityId BEFORE calling this routine (the creator). /// /// If activity tracing is not on, then activityId and relatedActivityId are not set /// </summary> public void OnStart(string providerName, string activityName, int task, ref Guid activityId, ref Guid relatedActivityId, EventActivityOptions options) { if (m_current == null) // We are not enabled { // We used to rely on the TPL provider turning us on, but that has the disadvantage that you don't get Start-Stop tracking // until you use Tasks for the first time (which you may never do). Thus we change it to pull rather tan push for whether // we are enabled. if (m_checkedForEnable) return; m_checkedForEnable = true; if (TplEtwProvider.Log.IsEnabled(EventLevel.Informational, TplEtwProvider.Keywords.TasksFlowActivityIds)) Enable(); if (m_current == null) return; } Debug.Assert((options & EventActivityOptions.Disable) == 0); var currentActivity = m_current.Value; var fullActivityName = NormalizeActivityName(providerName, activityName, task); var etwLog = TplEtwProvider.Log; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStartEnter", fullActivityName); etwLog.DebugFacilityMessage("OnStartEnterActivityState", ActivityInfo.LiveActivities(currentActivity)); } if (currentActivity != null) { // Stop activity tracking if we reached the maximum allowed depth if (currentActivity.m_level >= MAX_ACTIVITY_DEPTH) { activityId = Guid.Empty; relatedActivityId = Guid.Empty; if (etwLog.Debug) etwLog.DebugFacilityMessage("OnStartRET", "Fail"); return; } // Check for recursion, and force-stop any activities if the activity already started. if ((options & EventActivityOptions.Recursive) == 0) { ActivityInfo existingActivity = FindActiveActivity(fullActivityName, currentActivity); if (existingActivity != null) { OnStop(providerName, activityName, task, ref activityId); currentActivity = m_current.Value; } } } // Get a unique ID for this activity. long id; if (currentActivity == null) id = Interlocked.Increment(ref m_nextId); else id = Interlocked.Increment(ref currentActivity.m_lastChildID); // The previous ID is my 'causer' and becomes my related activity ID relatedActivityId = EventSource.CurrentThreadActivityId; // Add to the list of started but not stopped activities. ActivityInfo newActivity = new ActivityInfo(fullActivityName, id, currentActivity, relatedActivityId, options); m_current.Value = newActivity; // Remember the current ID so we can log it activityId = newActivity.ActivityId; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStartRetActivityState", ActivityInfo.LiveActivities(newActivity)); etwLog.DebugFacilityMessage1("OnStartRet", activityId.ToString(), relatedActivityId.ToString()); } } /// <summary> /// Called when a work item stops. The activity name = providerName + activityName without 'Stop' suffix. /// It updates m_current variable to track this fact. The Stop event associated with stop should log the ActivityID associated with the event. /// /// If activity tracing is not on, then activityId and relatedActivityId are not set /// </summary> public void OnStop(string providerName, string activityName, int task, ref Guid activityId) { if (m_current == null) // We are not enabled return; var fullActivityName = NormalizeActivityName(providerName, activityName, task); var etwLog = TplEtwProvider.Log; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStopEnter", fullActivityName); etwLog.DebugFacilityMessage("OnStopEnterActivityState", ActivityInfo.LiveActivities(m_current.Value)); } for (; ; ) // This is a retry loop. { ActivityInfo currentActivity = m_current.Value; ActivityInfo newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen. // Search to find the activity to stop in one pass. This insures that we don't let one mistake // (stopping something that was not started) cause all active starts to be stopped // By first finding the target start to stop we are more robust. ActivityInfo activityToStop = FindActiveActivity(fullActivityName, currentActivity); // ignore stops where we can't find a start because we may have popped them previously. if (activityToStop == null) { activityId = Guid.Empty; // TODO add some logging about this. Basically could not find matching start. if (etwLog.Debug) etwLog.DebugFacilityMessage("OnStopRET", "Fail"); return; } activityId = activityToStop.ActivityId; // See if there are any orphans that need to be stopped. ActivityInfo orphan = currentActivity; while (orphan != activityToStop && orphan != null) { if (orphan.m_stopped != 0) // Skip dead activities. { orphan = orphan.m_creator; continue; } if (orphan.CanBeOrphan()) { // We can't pop anything after we see a valid orphan, remember this for later when we update m_current. if (newCurrentActivity == null) newCurrentActivity = orphan; } else { orphan.m_stopped = 1; Debug.Assert(orphan.m_stopped != 0); } orphan = orphan.m_creator; } // try to Stop the activity atomically. Other threads may be trying to do this as well. if (Interlocked.CompareExchange(ref activityToStop.m_stopped, 1, 0) == 0) { // I succeeded stopping this activity. Now we update our m_current pointer // If I haven't yet determined the new current activity, it is my creator. if (newCurrentActivity == null) newCurrentActivity = activityToStop.m_creator; m_current.Value = newCurrentActivity; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStopRetActivityState", ActivityInfo.LiveActivities(newCurrentActivity)); etwLog.DebugFacilityMessage("OnStopRet", activityId.ToString()); } return; } // We failed to stop it. We must have hit a race to stop it. Just start over and try again. } } /// <summary> /// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise) /// </summary> public void Enable() { if (m_current == null) { // Catch the not Implemented try { m_current = new AsyncLocal<ActivityInfo>(ActivityChanging); } catch (NotImplementedException) { #if (!ES_BUILD_PCL && ! ES_BUILD_PN) // send message to debugger without delay System.Diagnostics.Debugger.Log(0, null, "Activity Enabled() called but AsyncLocals Not Supported (pre V4.6). Ignoring Enable"); #endif } } } /// <summary> /// An activity tracker is a singleton, this is how you get the one and only instance. /// </summary> public static ActivityTracker Instance { get { return s_activityTrackerInstance; } } #region private /// <summary> /// Searched for a active (nonstopped) activity with the given name. Returns null if not found. /// </summary> private ActivityInfo FindActiveActivity(string name, ActivityInfo startLocation) { var activity = startLocation; while (activity != null) { if (name == activity.m_name && activity.m_stopped == 0) return activity; activity = activity.m_creator; } return null; } /// <summary> /// Strip out "Start" or "End" suffix from activity name and add providerName prefix. /// If 'task' it does not end in Start or Stop and Task is non-zero use that as the name of the activity /// </summary> private string NormalizeActivityName(string providerName, string activityName, int task) { if (activityName.EndsWith(EventSource.s_ActivityStartSuffix, StringComparison.Ordinal)) activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStartSuffix.Length); else if (activityName.EndsWith(EventSource.s_ActivityStopSuffix, StringComparison.Ordinal)) activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStopSuffix.Length); else if (task != 0) activityName = "task" + task.ToString(); // We use provider name to distinguish between activities from different providers. return providerName + activityName; } // ******************************************************************************* /// <summary> /// An ActivityInfo represents a particular activity. It is almost read-only. The only /// fields that change after creation are /// m_lastChildID - used to generate unique IDs for the children activities and for the most part can be ignored. /// m_stopped - indicates that this activity is dead /// This read-only-ness is important because an activity's m_creator chain forms the /// 'Path of creation' for the activity (which is also its unique ID) but is also used as /// the 'list of live parents' which indicate of those ancestors, which are alive (if they /// are not marked dead they are alive). /// </summary> private class ActivityInfo { public ActivityInfo(string name, long uniqueId, ActivityInfo creator, Guid activityIDToRestore, EventActivityOptions options) { m_name = name; m_eventOptions = options; m_creator = creator; m_uniqueId = uniqueId; m_level = creator != null ? creator.m_level + 1 : 0; m_activityIdToRestore = activityIDToRestore; // Create a nice GUID that encodes the chain of activities that started this one. CreateActivityPathGuid(out m_guid, out m_activityPathGuidOffset); } public Guid ActivityId { get { return m_guid; } } public static string Path(ActivityInfo activityInfo) { if (activityInfo == null) return (""); return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString(); } public override string ToString() { return m_name + "(" + Path(this) + (m_stopped != 0 ? ",DEAD)" : ")"); } public static string LiveActivities(ActivityInfo list) { if (list == null) return ""; return list.ToString() + ";" + LiveActivities(list.m_creator); } public bool CanBeOrphan() { if ((m_eventOptions & EventActivityOptions.Detachable) != 0) return true; return false; } #region private #region CreateActivityPathGuid /// <summary> /// Logically every activity Path (see Path()) that describes the activities that caused this /// (rooted in an activity that predates activity tracking. /// /// We wish to encode this path in the Guid to the extent that we can. Many of the paths have /// many small numbers in them and we take advantage of this in the encoding to output as long /// a path in the GUID as possible. /// /// Because of the possibility of GUID collision, we only use 96 of the 128 bits of the GUID /// for encoding the path. The last 32 bits are a simple checksum (and random number) that /// identifies this as using the convention defined here. /// /// It returns both the GUID which has the path as well as the offset that points just beyond /// the end of the activity (so it can be appended to). Note that if the end is in a nibble /// (it uses nibbles instead of bytes as the unit of encoding, then it will point at the unfinished /// byte (since the top nibble can't be zero you can determine if this is true by seeing if /// this byte is nonZero. This offset is needed to efficiently create the ID for child activities. /// </summary> private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset) { fixed (Guid* outPtr = &idRet) { int activityPathGuidOffsetStart = 0; if (m_creator != null) { activityPathGuidOffsetStart = m_creator.m_activityPathGuidOffset; idRet = m_creator.m_guid; } else { // TODO FIXME - differentiate between AD inside PCL int appDomainID = 0; #if (!ES_BUILD_STANDALONE && !ES_BUILD_PN) appDomainID = System.Threading.Thread.GetDomainID(); #endif // We start with the appdomain number to make this unique among appdomains. activityPathGuidOffsetStart = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)appDomainID); } activityPathGuidOffset = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)m_uniqueId); // If the path does not fit, Make a GUID by incrementing rather than as a path, keeping as much of the path as possible if (12 < activityPathGuidOffset) CreateOverflowGuid(outPtr); } } /// <summary> /// If we can't fit the activity Path into the GUID we come here. What we do is simply /// generate a 4 byte number (s_nextOverflowId). Then look for an ancestor that has /// sufficient space for this ID. By doing this, we preserve the fact that this activity /// is a child (of unknown depth) from that ancestor. /// </summary> private unsafe void CreateOverflowGuid(Guid* outPtr) { // Search backwards for an ancestor that has sufficient space to put the ID. for (ActivityInfo ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator) { if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes. { uint id = unchecked((uint)Interlocked.Increment(ref ancestor.m_lastChildID)); // Get a unique ID // Try to put the ID into the GUID *outPtr = ancestor.m_guid; int endId = AddIdToGuid(outPtr, ancestor.m_activityPathGuidOffset, id, true); // Does it fit? if (endId <= 12) break; } } } /// <summary> /// The encoding for a list of numbers used to make Activity GUIDs. Basically /// we operate on nibbles (which are nice because they show up as hex digits). The /// list is ended with a end nibble (0) and depending on the nibble value (Below) /// the value is either encoded into nibble itself or it can spill over into the /// bytes that follow. /// </summary> enum NumberListCodes : byte { End = 0x0, // ends the list. No valid value has this prefix. LastImmediateValue = 0xA, PrefixCode = 0xB, // all the 'long' encodings go here. If the next nibble is MultiByte1-4 // than this is a 'overflow' id. Unlike the hierarchical IDs these are // allocated densely but don't tell you anything about nesting. we use // these when we run out of space in the GUID to store the path. MultiByte1 = 0xC, // 1 byte follows. If this Nibble is in the high bits, it the high bits of the number are stored in the low nibble. // commented out because the code does not explicitly reference the names (but they are logically defined). // MultiByte2 = 0xD, // 2 bytes follow (we don't bother with the nibble optimization) // MultiByte3 = 0xE, // 3 bytes follow (we don't bother with the nibble optimization) // MultiByte4 = 0xF, // 4 bytes follow (we don't bother with the nibble optimization) } /// Add the activity id 'id' to the output Guid 'outPtr' starting at the offset 'whereToAddId' /// Thus if this number is 6 that is where 'id' will be added. This will return 13 (12 /// is the maximum number of bytes that fit in a GUID) if the path did not fit. /// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a /// special (longer prefix) that indicates that this ID is allocated differently private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false) { byte* ptr = (byte*)outPtr; byte* endPtr = ptr + 12; ptr += whereToAddId; if (endPtr <= ptr) return 13; // 12 means we might exactly fit, 13 means we definately did not fit if (0 < id && id <= (uint)NumberListCodes.LastImmediateValue && !overflow) WriteNibble(ref ptr, endPtr, id); else { uint len = 4; if (id <= 0xFF) len = 1; else if (id <= 0xFFFF) len = 2; else if (id <= 0xFFFFFF) len = 3; if (overflow) { if (endPtr <= ptr + 2) // I need at least 2 bytes return 13; // Write out the prefix code nibble and the length nibble WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.PrefixCode); } // The rest is the same for overflow and non-overflow case WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.MultiByte1 + (len - 1)); // Do we have an odd nibble? If so flush it or use it for the 12 byte case. if (ptr < endPtr && *ptr != 0) { // If the value < 4096 we can use the nibble we are otherwise just outputting as padding. if (id < 4096) { // Indicate this is a 1 byte multicode with 4 high order bits in the lower nibble. *ptr = (byte)(((uint)NumberListCodes.MultiByte1 << 4) + (id >> 8)); id &= 0xFF; // Now we only want the low order bits. } ptr++; } // Write out the bytes. while (0 < len) { if (endPtr <= ptr) { ptr++; // Indicate that we have overflowed break; } *ptr++ = (byte)id; id = (id >> 8); --len; } } // Compute the checksum uint* sumPtr = (uint*)outPtr; // We set the last DWORD the sum of the first 3 DWORDS in the GUID. This // This last number is a random number (it identifies us as us) the process ID to make it unique per process. sumPtr[3] = (sumPtr[0] + sumPtr[1] + sumPtr[2] + 0x599D99AD) ^ EventSource.s_currentPid; return (int)(ptr - ((byte*)outPtr)); } /// <summary> /// Write a single Nible 'value' (must be 0-15) to the byte buffer represented by *ptr. /// Will not go past 'endPtr'. Also it assumes that we never write 0 so we can detect /// whether a nibble has already been written to ptr because it will be nonzero. /// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes /// the new byte (in the high bits) of the next byte. /// </summary> private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) { Debug.Assert(value < 16); Debug.Assert(ptr < endPtr); if (*ptr != 0) *ptr++ |= (byte)value; else *ptr = (byte)(value << 4); } #endregion // CreateGuidForActivityPath readonly internal string m_name; // The name used in the 'start' and 'stop' APIs to help match up readonly long m_uniqueId; // a small number that makes this activity unique among its siblings internal readonly Guid m_guid; // Activity Guid, it is basically an encoding of the Path() (see CreateActivityPathGuid) internal readonly int m_activityPathGuidOffset; // Keeps track of where in m_guid the causality path stops (used to generated child GUIDs) internal readonly int m_level; // current depth of the Path() of the activity (used to keep recursion under control) readonly internal EventActivityOptions m_eventOptions; // Options passed to start. internal long m_lastChildID; // used to create a unique ID for my children activities internal int m_stopped; // This work item has stopped readonly internal ActivityInfo m_creator; // My parent (creator). Forms the Path() for the activity. readonly internal Guid m_activityIdToRestore; // The Guid to restore after a stop. #endregion } // This callback is used to initialize the m_current AsyncLocal Variable. // Its job is to keep the ETW Activity ID (part of thread local storage) in sync // with m_current.ActivityID void ActivityChanging(AsyncLocalValueChangedArgs<ActivityInfo> args) { ActivityInfo cur = args.CurrentValue; ActivityInfo prev = args.PreviousValue; // Are we popping off a value? (we have a prev, and it creator is cur) // Then check if we should use the GUID at the time of the start event if (prev != null && prev.m_creator == cur) { // If the saved activity ID is not the same as the creator activity // that takes precedence (it means someone explicitly did a SetActivityID) // Set it to that and get out if (cur == null || prev.m_activityIdToRestore != cur.ActivityId) { EventSource.SetCurrentThreadActivityId(prev.m_activityIdToRestore); return; } } // OK we did not have an explicit SetActivityID set. Then we should be // setting the activity to current ActivityInfo. However that activity // might be dead, in which case we should skip it, so we never set // the ID to dead things. while (cur != null) { // We found a live activity (typically the first time), set it to that. if (cur.m_stopped == 0) { EventSource.SetCurrentThreadActivityId(cur.ActivityId); return; } cur = cur.m_creator; } // we can get here if there is no information on our activity stack (everything is dead) // currently we do nothing, as that seems better than setting to Guid.Emtpy. } /// <summary> /// Async local variables have the property that the are automatically copied whenever a task is created and used /// while that task is running. Thus m_current 'flows' to any task that is caused by the current thread that /// last set it. /// /// This variable points a a linked list that represents all Activities that have started but have not stopped. /// </summary> AsyncLocal<ActivityInfo> m_current; bool m_checkedForEnable; // Singleton private static ActivityTracker s_activityTrackerInstance = new ActivityTracker(); // Used to create unique IDs at the top level. Not used for nested Ids (each activity has its own id generator) static long m_nextId = 0; private const ushort MAX_ACTIVITY_DEPTH = 100; // Limit maximum depth of activities to be tracked at 100. // This will avoid leaking memory in case of activities that are never stopped. #endregion } #if ES_BUILD_STANDALONE || ES_BUILD_PN /******************************** SUPPORT *****************************/ /// <summary> /// This is supplied by the framework. It is has the semantics that the value is copied to any new Tasks that is created /// by the current task. Thus all causally related code gets this value. Note that reads and writes to this VARIABLE /// (not what it points it) to this does not need to be protected by locks because it is inherently thread local (you always /// only get your thread local copy which means that you never have races. /// </summary> /// #if ES_BUILD_STANDALONE [EventSource(Name = "Microsoft.Tasks.Nuget")] #else [EventSource(Name = "System.Diagnostics.Tracing.TplEtwProvider")] #endif internal class TplEtwProvider : EventSource { public class Keywords { public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80; public const EventKeywords Debug = (EventKeywords)0x20000; } public static TplEtwProvider Log = new TplEtwProvider(); public bool Debug { get { return IsEnabled(EventLevel.Verbose, Keywords.Debug); } } public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(1, Facility, Message); } public void DebugFacilityMessage1(string Facility, string Message, string Arg) { WriteEvent(2, Facility, Message, Arg); } public void SetActivityId(Guid Id) { WriteEvent(3, Id); } } #endif #if ES_BUILD_AGAINST_DOTNET_V35 || ES_BUILD_PCL || NO_ASYNC_LOCAL // In these cases we don't have any Async local support. Do nothing. internal sealed class AsyncLocalValueChangedArgs<T> { public T PreviousValue { get { return default(T); } } public T CurrentValue { get { return default(T); } } } internal sealed class AsyncLocal<T> { public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) { throw new NotImplementedException("AsyncLocal only available on V4.6 and above"); } public T Value { get { return default(T); } set { } } } #endif }
// "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 System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Net; using System.Text; using System.Threading; using HtmlRenderer.Entities; using HtmlRenderer.Utils; namespace HtmlRenderer.Handlers { /// <summary> /// Handler for all loading image logic.<br/> /// <p> /// Loading by <see cref="HtmlRenderer.Entities.HtmlImageLoadEventArgs"/>.<br/> /// Loading by file path.<br/> /// Loading by URI.<br/> /// </p> /// </summary> /// <remarks> /// <para> /// Supports sync and async image loading. /// </para> /// <para> /// If the image object is created by the handler on calling dispose of the handler the image will be released, this /// makes release of unused images faster as they can be large.<br/> /// Disposing image load handler will also cancel download of image from the web. /// </para> /// </remarks> internal sealed class ImageLoadHandler : IDisposable { #region Fields and Consts /// <summary> /// the container of the html to handle load image for /// </summary> private readonly HtmlContainer _htmlContainer; /// <summary> /// callback raised when image load process is complete with image or without /// </summary> // ReSharper disable RedundantNameQualifier private readonly Utils.ActionInt<Image, Rectangle, bool> _loadCompleteCallback; // ReSharper restore RedundantNameQualifier /// <summary> /// the web client used to download image from URL (to cancel on dispose) /// </summary> private WebClient _client; /// <summary> /// Must be open as long as the image is in use /// </summary> private FileStream _imageFileStream; /// <summary> /// the image instance of the loaded image /// </summary> private Image _image; /// <summary> /// the image rectangle restriction as returned from image load event /// </summary> private Rectangle _imageRectangle; /// <summary> /// to know if image load event callback was sync or async raised /// </summary> private bool _asyncCallback; /// <summary> /// flag to indicate if to release the image object on box dispose (only if image was loaded by the box) /// </summary> private bool _releaseImageObject; /// <summary> /// is the handler has been disposed /// </summary> private bool _disposed; #endregion /// <summary> /// Init. /// </summary> /// <param name="htmlContainer">the container of the html to handle load image for</param> /// <param name="loadCompleteCallback">callback raised when image load process is complete with image or without</param> public ImageLoadHandler(HtmlContainer htmlContainer, ActionInt<Image, Rectangle, bool> loadCompleteCallback) { ArgChecker.AssertArgNotNull(htmlContainer, "htmlContainer"); ArgChecker.AssertArgNotNull(loadCompleteCallback, "loadCompleteCallback"); _htmlContainer = htmlContainer; _loadCompleteCallback = loadCompleteCallback; } /// <summary> /// the image instance of the loaded image /// </summary> public Image Image { get { return _image; } } /// <summary> /// the image rectangle restriction as returned from image load event /// </summary> public Rectangle Rectangle { get { return _imageRectangle; } } /// <summary> /// Set image of this image box by analyzing the src attribute.<br/> /// Load the image from inline base64 encoded string.<br/> /// Or from calling property/method on the bridge object that returns image or URL to image.<br/> /// Or from file path<br/> /// Or from URI. /// </summary> /// <remarks> /// File path and URI image loading is executed async and after finishing calling <see cref="ImageLoadComplete"/> /// on the main thread and not thread-pool. /// </remarks> /// <param name="src">the source of the image to load</param> /// <param name="attributes">the collection of attributes on the element to use in event</param> /// <returns>the image object (null if failed)</returns> public void LoadImage(string src, Dictionary<string, string> attributes) { try { var args = new HtmlImageLoadEventArgs(src, attributes, OnHtmlImageLoadEventCallback); _htmlContainer.RaiseHtmlImageLoadEvent(args); _asyncCallback = !_htmlContainer.AvoidAsyncImagesLoading; if (!args.Handled) { if (!string.IsNullOrEmpty(src)) { if (src.StartsWith("data:image", StringComparison.CurrentCultureIgnoreCase)) { SetFromInlineData(src); } else { SetImageFromPath(src); } } else { ImageLoadComplete(false); } } } catch (Exception ex) { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Exception in handling image source", ex); ImageLoadComplete(false); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _disposed = true; ReleaseObjects(); } #region Private methods /// <summary> /// Set the image using callback from load image event, use the given data. /// </summary> /// <param name="path">the path to the image to load (file path or uri)</param> /// <param name="image">the image to load</param> /// <param name="imageRectangle">optional: limit to specific rectangle of the image and not all of it</param> private void OnHtmlImageLoadEventCallback(string path, Image image, Rectangle imageRectangle) { if (!_disposed) { _imageRectangle = imageRectangle; if (image != null) { _image = image; ImageLoadComplete(_asyncCallback); } else if (!string.IsNullOrEmpty(path)) { SetImageFromPath(path); } else { ImageLoadComplete(_asyncCallback); } } } /// <summary> /// Load the image from inline base64 encoded string data. /// </summary> /// <param name="src">the source that has the base64 encoded image</param> private void SetFromInlineData(string src) { _image = GetImageFromData(src); if (_image == null) _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed extract image from inline data"); _releaseImageObject = true; ImageLoadComplete(false); } /// <summary> /// Extract image object from inline base64 encoded data in the src of the html img element. /// </summary> /// <param name="src">the source that has the base64 encoded image</param> /// <returns>image from base64 data string or null if failed</returns> private static Image GetImageFromData(string src) { var s = src.Substring(src.IndexOf(':') + 1).Split(new[] { ',' }, 2); if (s.Length == 2) { int imagePartsCount = 0, base64PartsCount = 0; foreach (var part in s[0].Split(new[] { ';' })) { var pPart = part.Trim(); if (pPart.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) imagePartsCount++; if (pPart.Equals("base64", StringComparison.InvariantCultureIgnoreCase)) base64PartsCount++; } if (imagePartsCount > 0) { byte[] imageData = base64PartsCount > 0 ? Convert.FromBase64String(s[1].Trim()) : new UTF8Encoding().GetBytes(Uri.UnescapeDataString(s[1].Trim())); return Image.FromStream(new MemoryStream(imageData)); } } return null; } /// <summary> /// Load image from path of image file or URL. /// </summary> /// <param name="path">the file path or uri to load image from</param> private void SetImageFromPath(string path) { var uri = CommonUtils.TryGetUri(path); if (uri != null && uri.Scheme != "file") { SetImageFromUrl(uri); } else { var fileInfo = CommonUtils.TryGetFileInfo(uri != null ? uri.AbsolutePath : path); if (fileInfo != null) { SetImageFromFile(fileInfo); } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed load image, invalid source: " + path); ImageLoadComplete(false); } } } /// <summary> /// Load the image file on thread-pool thread and calling <see cref="ImageLoadComplete"/> after. /// </summary> /// <param name="source">the file path to get the image from</param> private void SetImageFromFile(FileInfo source) { if( source.Exists ) { if (_htmlContainer.AvoidAsyncImagesLoading) LoadImageFromFile(source); else ThreadPool.QueueUserWorkItem(state => LoadImageFromFile(source)); } else { ImageLoadComplete(); } } /// <summary> /// Load the image file on thread-pool thread and calling <see cref="ImageLoadComplete"/> after.<br/> /// Calling <see cref="ImageLoadComplete"/> on the main thread and not thread-pool. /// </summary> /// <param name="source">the file path to get the image from</param> private void LoadImageFromFile(FileInfo source) { try { if (source.Exists) { _imageFileStream = File.Open(source.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _image = Image.FromStream(_imageFileStream); _releaseImageObject = true; } ImageLoadComplete(); } catch (Exception ex) { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image from disk: " + source, ex); ImageLoadComplete(); } } /// <summary> /// Load image from the given URI by downloading it.<br/> /// Create local file name in temp folder from the URI, if the file already exists use it as it has already been downloaded. /// If not download the file using <see cref="DownloadImageFromUrlAsync"/>. /// </summary> private void SetImageFromUrl(Uri source) { var filePath = CommonUtils.GetLocalfileName(source); if( filePath.Exists && filePath.Length > 0 ) { SetImageFromFile(filePath); } else { if (_htmlContainer.AvoidAsyncImagesLoading) DownloadImageFromUrl(source, filePath); else ThreadPool.QueueUserWorkItem(DownloadImageFromUrlAsync, new KeyValuePair<Uri, FileInfo>(source, filePath)); } } /// <summary> /// Download the requested file in the URI to the given file path.<br/> /// Use async sockets API to download from web, <see cref="OnDownloadImageCompleted(object,System.ComponentModel.AsyncCompletedEventArgs)"/>. /// </summary> private void DownloadImageFromUrl(Uri source, FileInfo filePath) { try { using (var client = _client = new WebClient()) { client.DownloadFile(source, filePath.FullName); OnDownloadImageCompleted(false, null, filePath, client); } } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// Download the requested file in the URI to the given file path.<br/> /// Use async sockets API to download from web, <see cref="OnDownloadImageCompleted(object,System.ComponentModel.AsyncCompletedEventArgs)"/>. /// </summary> /// <param name="data">key value pair of URL and file info to download the file to</param> private void DownloadImageFromUrlAsync(object data) { var uri = ((KeyValuePair<Uri, FileInfo>) data).Key; var filePath = ((KeyValuePair<Uri, FileInfo>) data).Value; try { _client = new WebClient(); _client.DownloadFileCompleted += OnDownloadImageCompleted; _client.DownloadFileAsync(uri, filePath.FullName, filePath); } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// On download image complete to local file use <see cref="LoadImageFromFile"/> to load the image file.<br/> /// If the download canceled do nothing, if failed report error. /// </summary> private void OnDownloadImageCompleted(object sender, AsyncCompletedEventArgs e) { try { using (var client = (WebClient)sender) { client.DownloadFileCompleted -= OnDownloadImageCompleted; OnDownloadImageCompleted(e.Cancelled, e.Error, (FileInfo)e.UserState, client); } } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// On download image complete to local file use <see cref="LoadImageFromFile"/> to load the image file.<br/> /// If the download canceled do nothing, if failed report error. /// </summary> private void OnDownloadImageCompleted(bool cancelled, Exception error, FileInfo filePath, WebClient client) { if (!cancelled && !_disposed) { if (error == null) { filePath.Refresh(); var contentType = CommonUtils.GetResponseContentType(client); if( contentType != null && contentType.StartsWith("image", StringComparison.OrdinalIgnoreCase) ) { LoadImageFromFile(filePath); } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image, not image content type: " + contentType); ImageLoadComplete(); filePath.Delete(); } } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image from URL: " + client.BaseAddress, error); ImageLoadComplete(); } } } /// <summary> /// Flag image load complete and request refresh for re-layout and invalidate. /// </summary> private void ImageLoadComplete(bool async = true) { // can happen if some operation return after the handler was disposed if(_disposed) ReleaseObjects(); else _loadCompleteCallback(_image, _imageRectangle, async); } /// <summary> /// Release the image and client objects. /// </summary> private void ReleaseObjects() { if (_releaseImageObject && _image != null) { _image.Dispose(); _image = null; } if (_imageFileStream != null) { _imageFileStream.Dispose(); _imageFileStream = null; } if (_client != null) { _client.CancelAsync(); _client.Dispose(); _client = null; } } #endregion } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry // // 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.Globalization; using System.Text; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization.Utilities; namespace YamlDotNet.Serialization.NodeDeserializers { public sealed class ScalarNodeDeserializer : INodeDeserializer { bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value) { var scalar = reader.Allow<Scalar>(); if (scalar == null) { value = null; return false; } if (expectedType.IsEnum()) { value = Enum.Parse(expectedType, scalar.Value, true); } else { TypeCode typeCode = expectedType.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: value = bool.Parse(scalar.Value); break; case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, scalar.Value, YamlFormatter.NumberFormat); break; case TypeCode.Single: value = Single.Parse(scalar.Value, YamlFormatter.NumberFormat); break; case TypeCode.Double: value = Double.Parse(scalar.Value, YamlFormatter.NumberFormat); break; case TypeCode.Decimal: value = Decimal.Parse(scalar.Value, YamlFormatter.NumberFormat); break; case TypeCode.String: value = scalar.Value; break; case TypeCode.Char: value = scalar.Value[0]; break; case TypeCode.DateTime: // TODO: This is probably incorrect. Use the correct regular expression. value = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture); break; default: if (expectedType == typeof(object)) { // Default to string value = scalar.Value; } else { value = TypeConverter.ChangeType(scalar.Value, expectedType); } break; } } return true; } private object DeserializeIntegerHelper(TypeCode typeCode, string value, IFormatProvider formatProvider) { StringBuilder numberBuilder = new StringBuilder(); int currentIndex = 0; bool isNegative = false; int numberBase = 0; long result = 0; if (value[0] == '-') { currentIndex++; isNegative = true; } else if (value[0] == '+') { currentIndex++; } if (value[currentIndex] == '0') { // Could be binary, octal, hex, decimal (0) // If there are no characters remaining, it's a decimal zero if (currentIndex == value.Length - 1) { numberBase = 10; result = 0; } else { // Check the next character currentIndex++; if (value[currentIndex] == 'b') { // Binary numberBase = 2; currentIndex++; } else if (value[currentIndex] == 'x') { // Hex numberBase = 16; currentIndex++; } else { // Octal numberBase = 8; } } // Copy remaining digits to the number buffer (skip underscores) while (currentIndex < value.Length) { if (value[currentIndex] != '_') { numberBuilder.Append(value[currentIndex]); } currentIndex++; } // Parse the magnitude of the number switch (numberBase) { case 2: case 8: // TODO: how to incorporate the numberFormat? result = Convert.ToInt64(numberBuilder.ToString(), numberBase); break; case 16: result = Int64.Parse(numberBuilder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); break; case 10: // Result is already zero break; } } else { // Could be decimal or base 60 string[] chunks = value.Substring(currentIndex).Split(':'); result = 0; for (int chunkIndex = 0; chunkIndex < chunks.Length; chunkIndex++) { result *= 60; // TODO: verify that chunks after the first are non-negative and less than 60 result += long.Parse(chunks[chunkIndex].Replace("_", "")); } } if (isNegative) { result = -result; } switch (typeCode) { case TypeCode.Byte: return (byte)result; case TypeCode.Int16: return (short)result; case TypeCode.Int32: return (int)result; case TypeCode.Int64: return result; case TypeCode.SByte: return (sbyte)result; case TypeCode.UInt16: return (ushort)result; case TypeCode.UInt32: return (uint)result; case TypeCode.UInt64: return (ulong)result; default: return result; } } } }
/* Copyright (c) 2006-2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ using System; using System.Xml; using System.IO; using System.Collections; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Spreadsheets { /// <summary> /// Entry API customization class for defining entries in a List feed. /// </summary> public class ListEntry : AbstractEntry { /// <summary> /// Category used to label entries that contain Cell extension data. /// </summary> public static AtomCategory LIST_CATEGORY = new AtomCategory(GDataSpreadsheetsNameTable.List, new AtomUri(BaseNameTable.gKind)); #region Schema Extensions /// <summary> /// GData schema extension describing a custom element in a spreadsheet. /// </summary> public class Custom : IExtensionElementFactory { private string localName; private string value; /// <summary> /// Constructs an empty custom element /// </summary> public Custom() { LocalName = null; Value = null; } /// <summary> /// The local name of the custom element /// </summary> public string LocalName { get { return localName; } set { localName = value; } } /// <summary> /// The value of the custom element /// </summary> public string Value { get { return value; } set { this.value = value; } } /// <summary> /// Parses an XML node to create a Custom object /// </summary> /// <param name="node">Custom node</param> /// <param name="parser">AtomFeedParser to use</param> /// <returns>The created Custom object</returns> public static Custom ParseCustom(XmlNode node, AtomFeedParser parser) { if (node == null) { throw new ArgumentNullException("node"); } Custom custom = new Custom(); if (node.Attributes.Count > 1) { throw new ArgumentException("Custom elements should have 0 attributes"); } if (node.HasChildNodes && node.FirstChild.NodeType != XmlNodeType.Text) { // throw new ArgumentException("Custom elements should have 0 children"); } custom.LocalName = node.LocalName; if (node.HasChildNodes) { custom.Value = node.FirstChild.Value; } else { custom.value = ""; } return custom; } #region overload for persistence /// <summary> /// Custom elements are equal if they have the same local name. /// </summary> /// <param name="value">The custom element to compare against.</param> /// <returns>True if the LocalNames are equal, false otherwise</returns> public override bool Equals(object value) { Custom newCustom = value as Custom; if (newCustom != null) { return this.LocalName.Equals(newCustom.LocalName); } return false; } /// <summary> /// The hash code is simply the hash of the local name /// </summary> /// <returns>The hash code calculated by String on the LocalName</returns> public override int GetHashCode() { return this.LocalName.GetHashCode(); } /// <summary> /// Returns the constant representing the XML element. /// </summary> public string XmlName { get { return LocalName; } } /// <summary> /// Used to save the EntryLink instance into the passed in xmlwriter /// </summary> /// <param name="writer">the XmlWriter to write into</param> public void Save(XmlWriter writer) { if (LocalName != null && Value != null) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); writer.WriteString(Value); writer.WriteEndElement(); } } #endregion #region IExtensionElementFactory Members public string XmlNameSpace { get { return GDataSpreadsheetsNameTable.NSGSpreadsheetsExtended; } } public string XmlPrefix { get { return GDataSpreadsheetsNameTable.ExtendedPrefix; } } public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return ParseCustom(node, parser); } #endregion } // class Custom #endregion #region Collection ////////////////////////////////////////////////////////////////////// /// <summary>Typed collection for Custom Extensions.</summary> ////////////////////////////////////////////////////////////////////// public class CustomElementCollection : CollectionBase { /// <summary>holds the owning feed</summary> private AtomBase atomElement; private CustomElementCollection() { } /// <summary>constructor</summary> public CustomElementCollection(AtomBase atomElement) : base() { this.atomElement = atomElement; } /// <summary>standard typed accessor method </summary> public Custom this[ int index ] { get { return( (Custom) List[index] ); } set { this.atomElement.ExtensionElements.Remove((Custom)List[index]); List[index] = value; this.atomElement.ExtensionElements.Add(value); } } /// <summary>standard typed add method </summary> public int Add( Custom value ) { this.atomElement.ExtensionElements.Add(value); return( List.Add( value ) ); } /// <summary>standard typed indexOf method </summary> public int IndexOf( Custom value ) { return( List.IndexOf( value ) ); } /// <summary>standard typed insert method </summary> public void Insert( int index, Custom value ) { if (this.atomElement.ExtensionElements.Contains(value)) { this.atomElement.ExtensionElements.Remove(value); } this.atomElement.ExtensionElements.Add(value); List.Insert( index, value ); } /// <summary>standard typed remove method </summary> public void Remove( Custom value ) { this.atomElement.ExtensionElements.Remove(value); List.Remove( value ); } /// <summary>standard typed Contains method </summary> public bool Contains( Custom value ) { // If value is not of type AtomEntry, this will return false. return( List.Contains( value ) ); } /// <summary>standard typed OnValidate Override </summary> protected override void OnValidate( Object value ) { if (value as Custom == null) throw new ArgumentException( "value must be of type Google.GData.Extensions.When.", "value" ); } /// <summary>standard override OnClear, to remove the objects from the extension list</summary> protected override void OnClear() { for (int i=0; i< this.Count;i++) { this.atomElement.ExtensionElements.Remove((Custom)List[i]); } } } #endregion private CustomElementCollection elements; /// <summary> /// Constructs a new ListEntry instance with the appropriate category /// to indicate that it is a list entry. /// </summary> public ListEntry() : base() { Categories.Add(LIST_CATEGORY); elements = new CustomElementCollection(this); } /// <summary> /// The custom elements in this list entry /// </summary> public CustomElementCollection Elements { get { return elements; } } #region override persistence /// <summary> /// Parses the inner state of the element. TODO. /// </summary> /// <param name="e">The extension element that should be added to this entry</param> /// <param name="parser">The AtomFeedParser that called this</param> public override void Parse(ExtensionElementEventArgs e, AtomFeedParser parser) { if (String.Compare(e.ExtensionElement.NamespaceURI, GDataSpreadsheetsNameTable.NSGSpreadsheetsExtended, true) == 0) { Elements.Add(Custom.ParseCustom(e.ExtensionElement, parser)); e.DiscardEntry = true; } } } #endregion }