content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; using FileUpload.Areas.HelpPage.ModelDescriptions; namespace FileUpload.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API. /// </summary> public Collection<ParameterDescription> UriParameters { get; private set; } /// <summary> /// Gets or sets the documentation for the request. /// </summary> public string RequestDocumentation { get; set; } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the request body. /// </summary> public ModelDescription RequestModelDescription { get; set; } /// <summary> /// Gets the request body parameter descriptions. /// </summary> public IList<ParameterDescription> RequestBodyParameters { get { return GetParameterDescriptions(RequestModelDescription); } } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the resource. /// </summary> public ModelDescription ResourceDescription { get; set; } /// <summary> /// Gets the resource property descriptions. /// </summary> public IList<ParameterDescription> ResourceProperties { get { return GetParameterDescriptions(ResourceDescription); } } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription) { ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; if (collectionModelDescription != null) { complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } } return null; } } }
36.574074
123
0.614684
[ "MIT" ]
armitage03/Bitbucket
FileUpload/Areas/HelpPage/Models/HelpPageApiModel.cs
3,950
C#
using LogServices.Interfaces; using System; using System.Collections.Generic; namespace LogServices { public class LogService : ILogService { private List<ILogHandler> _logHandlers = new List<ILogHandler>(); public void AddHandler(ILogHandler handler) { _logHandlers.Add(handler); } public void RemoveHandler(ILogHandler handler) { _logHandlers.Remove(handler); } public void Info(string message) { foreach(var handler in _logHandlers) { handler?.Info(message); } } public void Warn(string message) { foreach(var handler in _logHandlers) { handler?.Warn(message); } } public void Error(string message) { foreach (var handler in _logHandlers) { handler?.Error(message); } } public void Exception(Exception exception) { foreach (var handler in _logHandlers) { handler?.Exception(exception); } } public IEnumerable<ILogHandler> GetHandlers() { return _logHandlers; } } }
22.186441
73
0.516425
[ "MIT" ]
Antihero-Studios/log-services
LogServices/Assets/LogServices/LogService.cs
1,311
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Shouldly; using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Microsoft.Build.Shared.FileSystem; using Xunit; using Xunit.Abstractions; using Microsoft.Build.Utilities; #nullable disable namespace Microsoft.Build.UnitTests { public class FileMatcherTest : IDisposable { private readonly TestEnvironment _env; public FileMatcherTest(ITestOutputHelper output) { _env = TestEnvironment.Create(output); } public void Dispose() { _env.Dispose(); } [Theory] [InlineData("*.txt", 5)] [InlineData("???.cs", 1)] [InlineData("????.cs", 1)] [InlineData("file?.txt", 1)] [InlineData("fi?e?.txt", 2)] [InlineData("???.*", 1)] [InlineData("????.*", 4)] [InlineData("*.???", 5)] [InlineData("f??e1.txt", 2)] [InlineData("file.*.txt", 1)] public void GetFilesPatternMatching(string pattern, int expectedMatchCount) { TransientTestFolder testFolder = _env.CreateFolder(); foreach (var file in new[] { "Foo.cs", "Foo2.cs", "file.txt", "file1.txt", "file1.txtother", "fie1.txt", "fire1.txt", "file.bak.txt" }) { File.WriteAllBytes(Path.Combine(testFolder.Path, file), new byte[1]); } string[] fileMatches = FileMatcher.Default.GetFiles(testFolder.Path, pattern); fileMatches.Length.ShouldBe(expectedMatchCount, $"Matches: '{String.Join("', '", fileMatches)}'"); } [Theory] [MemberData(nameof(GetFilesComplexGlobbingMatchingInfo.GetTestData), MemberType = typeof(GetFilesComplexGlobbingMatchingInfo))] public void GetFilesComplexGlobbingMatching(GetFilesComplexGlobbingMatchingInfo info) { TransientTestFolder testFolder = _env.CreateFolder(); // Create directories and files foreach (string fullPath in GetFilesComplexGlobbingMatchingInfo.FilesToCreate.Select(i => Path.Combine(testFolder.Path, i.ToPlatformSlash()))) { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); File.WriteAllBytes(fullPath, new byte[1]); } void VerifyImpl(FileMatcher fileMatcher, string include, string[] excludes, bool shouldHaveNoMatches = false, string customMessage = null) { string[] matchedFiles = fileMatcher.GetFiles(testFolder.Path, include, excludes?.ToList()); if (shouldHaveNoMatches) { matchedFiles.ShouldBeEmpty(customMessage); } else { // The matches are: // 1. Normalized ("\" regardless of OS and lowercase) // 2. Sorted // Are the same as the expected matches sorted matchedFiles .Select(i => i.Replace(Path.DirectorySeparatorChar, '\\')) .OrderBy(i => i) .ToArray() .ShouldBe(info.ExpectedMatches.OrderBy(i => i), caseSensitivity: Case.Insensitive, customMessage: customMessage); } } var fileMatcherWithCache = new FileMatcher(FileSystems.Default, new ConcurrentDictionary<string, IReadOnlyList<string>>()); void Verify(string include, string[] excludes, bool shouldHaveNoMatches = false, string customMessage = null) { // Verify using the default non-caching FileMatcher. VerifyImpl(FileMatcher.Default, include, excludes, shouldHaveNoMatches, customMessage); // Verify using a caching FileMatcher and do it twice to exercise the cache. VerifyImpl(fileMatcherWithCache, include, excludes, shouldHaveNoMatches, customMessage); VerifyImpl(fileMatcherWithCache, include, excludes, shouldHaveNoMatches, customMessage); } // Normal matching Verify(info.Include, info.Excludes); // Include forward slash Verify(info.Include.Replace('\\', '/'), info.Excludes, customMessage: "Include directory separator was changed to forward slash"); // Excludes forward slash Verify(info.Include, info.Excludes?.Select(o => o.Replace('\\', '/')).ToArray(), customMessage: "Excludes directory separator was changed to forward slash"); // Uppercase includes Verify(info.Include.ToUpperInvariant(), info.Excludes, info.ExpectNoMatches, "Include was changed to uppercase"); // Changing the case of the exclude break Linux if (!NativeMethodsShared.IsLinux) { // Uppercase excludes Verify(info.Include, info.Excludes?.Select(o => o.ToUpperInvariant()).ToArray(), false, "Excludes were changed to uppercase"); } // Backward compatibilities: // 1. When an include or exclude starts with a fixed directory part e.g. "src/foo/**", // then matching should be case-sensitive on Linux, as the directory was checked for its existance // by using Directory.Exists, which is case-sensitive on Linux (on OSX is not). // 2. On Unix, when an include uses a simple ** wildcard e.g. "**\*.cs", the file pattern e.g. "*.cs", // should be matched case-sensitive, as files were retrieved by using the searchPattern parameter // of Directory.GetFiles, which is case-sensitive on Unix. } /// <summary> /// A test data class for providing data to the <see cref="FileMatcherTest.GetFilesComplexGlobbingMatching"/> test. /// </summary> public class GetFilesComplexGlobbingMatchingInfo { /// <summary> /// The list of known files to create. /// </summary> public static string[] FilesToCreate = { @"src\foo.cs", @"src\bar.cs", @"src\baz.cs", @"src\foo\foo.cs", @"src\foo\licence", @"src\bar\bar.cs", @"src\baz\baz.cs", @"src\foo\inner\foo.cs", @"src\foo\inner\foo\foo.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs", @"src\bar\inner\foo\foo.cs", @"subd\sub.cs", @"subdirectory\subdirectory.cs", @"build\baz\foo.cs", @"readme.txt", @"licence" }; /// <summary> /// Gets or sets the include pattern. /// </summary> public string Include { get; set; } /// <summary> /// Gets or sets a list of exclude patterns. /// </summary> public string[] Excludes { get; set; } /// <summary> /// Gets or sets the list of expected matches. /// </summary> public string[] ExpectedMatches { get; set; } /// <summary> /// Get or sets a value indicating to expect no matches if the include pattern is mutated to uppercase. /// </summary> public bool ExpectNoMatches { get; set; } public override string ToString() { IEnumerable<string> GetParts() { yield return $"Include = {Include}"; if (Excludes != null) { yield return $"Excludes = {String.Join(";", Excludes)}"; } if (ExpectNoMatches) { yield return "ExpectNoMatches"; } } return String.Join(", ", GetParts()); } /// <summary> /// Gets the test data /// </summary> public static IEnumerable<object[]> GetTestData() { yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\**\inner\**\*.cs", ExpectedMatches = new[] { @"src\foo\inner\foo.cs", @"src\foo\inner\foo\foo.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs", @"src\bar\inner\foo\foo.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\**\inner\**\*.cs", Excludes = new[] { @"src\foo\inner\foo.*.cs" }, ExpectedMatches = new[] { @"src\foo\inner\foo.cs", @"src\foo\inner\foo\foo.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs", @"src\bar\inner\foo\foo.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\**\inner\**\*.cs", Excludes = new[] { @"**\foo\**" }, ExpectedMatches = new[] { @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\**\inner\**\*.cs", Excludes = new[] { @"src\bar\inner\baz\**" }, ExpectedMatches = new[] { @"src\foo\inner\foo.cs", @"src\foo\inner\foo\foo.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\foo\foo.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; #if !MONO // https://github.com/mono/mono/issues/8441 yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\foo\**\*.cs", Excludes = new[] { @"src\foo\**\foo\**" }, ExpectedMatches = new[] { @"src\foo\foo.cs", @"src\foo\inner\foo.cs", @"src\foo\inner\bar\bar.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\foo\inner\**\*.cs", Excludes = new[] { @"src\foo\**\???\**" }, ExpectedMatches = new[] { @"src\foo\inner\foo.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; #endif yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"**\???\**\*.cs", ExpectedMatches = new[] { @"src\foo.cs", @"src\bar.cs", @"src\baz.cs", @"src\foo\foo.cs", @"src\bar\bar.cs", @"src\baz\baz.cs", @"src\foo\inner\foo.cs", @"src\foo\inner\foo\foo.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs", @"src\bar\inner\foo\foo.cs", @"build\baz\foo.cs" } } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"**\*.*", Excludes = new[] { @"**\???\**\*.cs", @"subd*\*", }, ExpectedMatches = new[] { @"readme.txt", @"licence", @"src\foo\licence", } } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"**\?a?\**\?a?\*.c?", ExpectedMatches = new[] { @"src\bar\inner\baz\baz.cs" } } }; yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"**\?a?\**\?a?.c?", Excludes = new[] { @"**\?a?\**\?a?\*.c?" }, ExpectedMatches = new[] { @"src\bar\bar.cs", @"src\baz\baz.cs", @"src\foo\inner\bar\bar.cs", @"src\bar\inner\baz.cs" } } }; // Regression test for https://github.com/dotnet/msbuild/issues/4175 yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"subdirectory\**", Excludes = new[] { @"sub\**" }, ExpectedMatches = new[] { @"subdirectory\subdirectory.cs", }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; // Regression test for https://github.com/dotnet/msbuild/issues/6502 yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\**", Excludes = new[] { @"**\foo\**", }, ExpectedMatches = new[] { @"src\foo.cs", @"src\bar.cs", @"src\baz.cs", @"src\bar\bar.cs", @"src\baz\baz.cs", @"src\bar\inner\baz.cs", @"src\bar\inner\baz\baz.cs", }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; // Hits the early elimination of exclude file patterns that do not intersect with the include. // The exclude is redundant and can be eliminated before starting the file system walk. yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\foo\**\*.cs", Excludes = new[] { @"src\foo\**\foo\**", @"src\foo\**\*.vb" // redundant exclude }, ExpectedMatches = new[] { @"src\foo\foo.cs", @"src\foo\inner\foo.cs", @"src\foo\inner\bar\bar.cs" }, ExpectNoMatches = NativeMethodsShared.IsLinux, } }; // Hits the early elimination of exclude file patterns that do not intersect with the include. // The exclude is not redundant and must not be eliminated. yield return new object[] { new GetFilesComplexGlobbingMatchingInfo { Include = @"src\foo\**\*.cs", Excludes = new[] { @"src\foo\**\*.*" // effective exclude }, ExpectedMatches = Array.Empty<string>(), ExpectNoMatches = NativeMethodsShared.IsLinux, } }; } } [Fact] public void WildcardMatching() { var inputs = new List<Tuple<string, string, bool>> { // No wildcards new Tuple<string, string, bool>("a", "a", true), new Tuple<string, string, bool>("a", "", false), new Tuple<string, string, bool>("", "a", false), // Non ASCII characters new Tuple<string, string, bool>("šđčćž", "šđčćž", true), // * wildcard new Tuple<string, string, bool>("abc", "*bc", true), new Tuple<string, string, bool>("abc", "a*c", true), new Tuple<string, string, bool>("abc", "ab*", true), new Tuple<string, string, bool>("ab", "*ab", true), new Tuple<string, string, bool>("ab", "a*b", true), new Tuple<string, string, bool>("ab", "ab*", true), new Tuple<string, string, bool>("aba", "ab*ba", false), new Tuple<string, string, bool>("", "*", true), // ? wildcard new Tuple<string, string, bool>("abc", "?bc", true), new Tuple<string, string, bool>("abc", "a?c", true), new Tuple<string, string, bool>("abc", "ab?", true), new Tuple<string, string, bool>("ab", "?ab", false), new Tuple<string, string, bool>("ab", "a?b", false), new Tuple<string, string, bool>("ab", "ab?", false), new Tuple<string, string, bool>("", "?", false), // Mixed wildcards new Tuple<string, string, bool>("a", "*?", true), new Tuple<string, string, bool>("a", "?*", true), new Tuple<string, string, bool>("ab", "*?", true), new Tuple<string, string, bool>("ab", "?*", true), new Tuple<string, string, bool>("abc", "*?", true), new Tuple<string, string, bool>("abc", "?*", true), // Multiple mixed wildcards new Tuple<string, string, bool>("a", "??", false), new Tuple<string, string, bool>("ab", "?*?", true), new Tuple<string, string, bool>("ab", "*?*?*", true), new Tuple<string, string, bool>("abc", "?**?*?", true), new Tuple<string, string, bool>("abc", "?**?*c?", false), new Tuple<string, string, bool>("abcd", "?b*??", true), new Tuple<string, string, bool>("abcd", "?a*??", false), new Tuple<string, string, bool>("abcd", "?**?c?", true), new Tuple<string, string, bool>("abcd", "?**?d?", false), new Tuple<string, string, bool>("abcde", "?*b*?*d*?", true), // ? wildcard in the input string new Tuple<string, string, bool>("?", "?", true), new Tuple<string, string, bool>("?a", "?a", true), new Tuple<string, string, bool>("a?", "a?", true), new Tuple<string, string, bool>("a?b", "a?", false), new Tuple<string, string, bool>("a?ab", "a?aab", false), new Tuple<string, string, bool>("aa?bbbc?d", "aa?bbc?dd", false), // * wildcard in the input string new Tuple<string, string, bool>("*", "*", true), new Tuple<string, string, bool>("*a", "*a", true), new Tuple<string, string, bool>("a*", "a*", true), new Tuple<string, string, bool>("a*b", "a*", true), new Tuple<string, string, bool>("a*ab", "a*aab", false), new Tuple<string, string, bool>("a*abab", "a*b", true), new Tuple<string, string, bool>("aa*bbbc*d", "aa*bbc*dd", false), new Tuple<string, string, bool>("aa*bbbc*d", "a*bbc*d", true) }; foreach (var input in inputs) { try { Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1, input.Item2)); Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1.ToUpperInvariant(), input.Item2)); Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1, input.Item2.ToUpperInvariant())); } catch (Exception) { Console.WriteLine($"Input {input.Item1} with pattern {input.Item2} failed"); throw; } } } /* * Method: GetFileSystemEntries * * Simulate Directories.GetFileSystemEntries where file names are short. * */ private static IReadOnlyList<string> GetFileSystemEntries(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory) { if ( pattern == @"LONGDI~1" && (@"D:\" == path || @"\\server\share\" == path || path.Length == 0) ) { return new string[] { Path.Combine(path, "LongDirectoryName") }; } else if ( pattern == @"LONGSU~1" && (@"D:\LongDirectoryName" == path || @"\\server\share\LongDirectoryName" == path || @"LongDirectoryName" == path) ) { return new string[] { Path.Combine(path, "LongSubDirectory") }; } else if ( pattern == @"LONGFI~1.TXT" && (@"D:\LongDirectoryName\LongSubDirectory" == path || @"\\server\share\LongDirectoryName\LongSubDirectory" == path || @"LongDirectoryName\LongSubDirectory" == path) ) { return new string[] { Path.Combine(path, "LongFileName.txt") }; } else if ( pattern == @"pomegr~1" && @"c:\apple\banana\tomato" == path ) { return new string[] { Path.Combine(path, "pomegranate") }; } else if ( @"c:\apple\banana\tomato\pomegranate\orange" == path ) { // No files exist here. This is an empty directory. return Array.Empty<string>(); } else { Console.WriteLine("GetFileSystemEntries('{0}', '{1}')", path, pattern); Assert.True(false, "Unexpected input into GetFileSystemEntries"); } return new string[] { "<undefined>" }; } private static readonly char S = Path.DirectorySeparatorChar; public static IEnumerable<object[]> NormalizeTestData() { yield return new object[] { null, null }; yield return new object[] { "", "" }; yield return new object[] { " ", " " }; yield return new object[] { @"\\", @"\\" }; yield return new object[] { @"\\/\//", @"\\" }; yield return new object[] { @"\\a/\b/\", $@"\\a{S}b" }; yield return new object[] { @"\", @"\" }; yield return new object[] { @"\/\/\/", @"\" }; yield return new object[] { @"\a/\b/\", $@"\a{S}b" }; yield return new object[] { "/", "/" }; yield return new object[] { @"/\/\", "/" }; yield return new object[] { @"/a\/b/\\", $@"/a{S}b" }; yield return new object[] { @"c:\", @"c:\" }; yield return new object[] { @"c:/", @"c:\" }; yield return new object[] { @"c:/\/\/", @"c:\" }; yield return new object[] { @"c:/ab", @"c:\ab" }; yield return new object[] { @"c:\/\a//b", $@"c:\a{S}b" }; yield return new object[] { @"c:\/\a//b\/", $@"c:\a{S}b" }; yield return new object[] { @"..\/a\../.\b\/", $@"..{S}a{S}..{S}.{S}b" }; yield return new object[] { @"**/\foo\/**\/", $@"**{S}foo{S}**" }; yield return new object[] { "AbCd", "AbCd" }; } [Theory] [MemberData(nameof(NormalizeTestData))] public void NormalizeTest(string inputString, string expectedString) { FileMatcher.Normalize(inputString).ShouldBe(expectedString); } /// <summary> /// Simple test of the MatchDriver code. /// </summary> [Fact] public void BasicMatchDriver() { MatchDriver ( "Source" + Path.DirectorySeparatorChar + "**", new string[] // Files that exist and should match. { "Source" + Path.DirectorySeparatorChar + "Bart.txt", "Source" + Path.DirectorySeparatorChar + "Sub" + Path.DirectorySeparatorChar + "Homer.txt", }, new string[] // Files that exist and should not match. { "Destination" + Path.DirectorySeparatorChar + "Bart.txt", "Destination" + Path.DirectorySeparatorChar + "Sub" + Path.DirectorySeparatorChar + "Homer.txt", }, null ); } /// <summary> /// This pattern should *not* recurse indefinitely since there is no '**' in the pattern: /// /// c:\?emp\foo /// /// </summary> [Fact] public void Regress162390() { MatchDriver ( @"c:\?emp\foo.txt", new string[] { @"c:\temp\foo.txt" }, // Should match new string[] { @"c:\timp\foo.txt" }, // Shouldn't match new string[] // Should not even consider. { @"c:\temp\sub\foo.txt" } ); } /* * Method: GetLongFileNameForShortLocalPath * * Convert a short local path to a long path. * */ [Fact] public void GetLongFileNameForShortLocalPath() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"D:\LONGDI~1\LONGSU~1\LONGFI~1.TXT", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } /* * Method: GetLongFileNameForLongLocalPath * * Convert a long local path to a long path (nop). * */ [Fact] public void GetLongFileNameForLongLocalPath() { string longPath = FileMatcher.GetLongPathName ( @"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } /* * Method: GetLongFileNameForShortUncPath * * Convert a short UNC path to a long path. * */ [Fact] public void GetLongFileNameForShortUncPath() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"\\server\share\LONGDI~1\LONGSU~1\LONGFI~1.TXT", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } /* * Method: GetLongFileNameForLongUncPath * * Convert a long UNC path to a long path (nop) * */ [Fact] public void GetLongFileNameForLongUncPath() { string longPath = FileMatcher.GetLongPathName ( @"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } /* * Method: GetLongFileNameForRelativePath * * Convert a short relative path to a long path * */ [Fact] public void GetLongFileNameForRelativePath() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"LONGDI~1\LONGSU~1\LONGFI~1.TXT", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } /* * Method: GetLongFileNameForRelativePathPreservesTrailingSlash * * Convert a short relative path with a trailing backslash to a long path * */ [Fact] public void GetLongFileNameForRelativePathPreservesTrailingSlash() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"LONGDI~1\LONGSU~1\", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"LongDirectoryName\LongSubDirectory\", longPath); } /* * Method: GetLongFileNameForRelativePathPreservesExtraSlashes * * Convert a short relative path with doubled embedded backslashes to a long path * */ [Fact] public void GetLongFileNameForRelativePathPreservesExtraSlashes() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"LONGDI~1\\LONGSU~1\\", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"LongDirectoryName\\LongSubDirectory\\", longPath); } /* * Method: GetLongFileNameForMixedLongAndShort * * Only part of the path might be short. * */ [Fact] public void GetLongFileNameForMixedLongAndShort() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"c:\apple\banana\tomato\pomegr~1\orange\", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\", longPath); } /* * Method: GetLongFileNameWherePartOfThePathDoesntExist * * Part of the path may not exist. In this case, we treat the non-existent parts * as if they were already a long file name. * */ [Fact] public void GetLongFileNameWherePartOfThePathDoesntExist() { if (!NativeMethodsShared.IsWindows) { return; // "Short names are for Windows only" } string longPath = FileMatcher.GetLongPathName ( @"c:\apple\banana\tomato\pomegr~1\orange\chocol~1\vanila~1", new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) ); Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\chocol~1\vanila~1", longPath); } [Fact] public void BasicMatch() { ValidateFileMatch("file.txt", "File.txt", false); ValidateNoFileMatch("file.txt", "File.bin", false); } [Fact] public void MatchSingleCharacter() { ValidateFileMatch("file.?xt", "File.txt", false); ValidateNoFileMatch("file.?xt", "File.bin", false); } [Fact] public void MatchMultipleCharacters() { ValidateFileMatch("*.txt", "*.txt", false); ValidateNoFileMatch("*.txt", "*.bin", false); } [Fact] public void SimpleRecursive() { ValidateFileMatch("**", ".\\File.txt", true); } [Fact] public void DotForCurrentDirectory() { ValidateFileMatch(Path.Combine(".", "File.txt"), Path.Combine(".", "File.txt"), false); ValidateNoFileMatch(Path.Combine(".", "File.txt"), Path.Combine(".", "File.bin"), false); } [Fact] public void DotDotForParentDirectory() { ValidateFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine("..", "..", "File.txt"), false); if (NativeMethodsShared.IsWindows) { // On Linux *. * does not pick up files with no extension ValidateFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine("..", "..", "File"), false); } ValidateNoFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine(new [] {"..", "..", "dir1", "dir2", "File.txt"}), false); ValidateNoFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine(new [] {"..", "..", "dir1", "dir2", "File"}), false); } [Fact] public void ReduceDoubleSlashesBaseline() { // Baseline ValidateFileMatch( NativeMethodsShared.IsWindows ? "f:\\dir1\\dir2\\file.txt" : "/dir1/dir2/file.txt", NativeMethodsShared.IsWindows ? "f:\\dir1\\dir2\\file.txt" : "/dir1/dir2/file.txt", false); ValidateFileMatch(Path.Combine("**", "*.cs"), Path.Combine("dir1", "dir2", "file.cs"), true); ValidateFileMatch(Path.Combine("**", "*.cs"), "file.cs", true); } [Fact] public void ReduceDoubleSlashes() { ValidateFileMatch("f:\\\\dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("..\\**/\\*.cs", "..\\dir1\\dir2\\file.cs", true); ValidateFileMatch("..\\**/.\\*.cs", "..\\dir1\\dir2\\file.cs", true); ValidateFileMatch("..\\**\\./.\\*.cs", "..\\dir1\\dir2\\file.cs", true); } [Fact] public void DoubleSlashesOnBothSidesOfComparison() { ValidateFileMatch("f:\\\\dir1\\dir2\\file.txt", "f:\\\\dir1\\dir2\\file.txt", false, false); ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\file.txt", "f:\\\\dir1\\\\\\dir2\\file.txt", false, false); ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", "f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", false, false); ValidateFileMatch("..\\**/\\*.cs", "..\\dir1\\dir2\\\\file.cs", true, false); ValidateFileMatch("..\\**/.\\*.cs", "..\\dir1\\dir2//\\file.cs", true, false); ValidateFileMatch("..\\**\\./.\\*.cs", "..\\dir1/\\/\\/dir2\\file.cs", true, false); } [Fact] public void DecomposeDotSlash() { ValidateFileMatch("f:\\.\\dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\dir1\\.\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\dir1\\dir2\\.\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\.//dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\dir1\\.//dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch("f:\\dir1\\dir2\\.//file.txt", "f:\\dir1\\dir2\\file.txt", false); ValidateFileMatch(".\\dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false); ValidateFileMatch(".\\.\\dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false); ValidateFileMatch(".//dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false); ValidateFileMatch(".//.//dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false); } [Fact] public void RecursiveDirRecursive() { // Check that a wildcardpath of **\x\**\ matches correctly since, \**\ is a // separate code path. ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\y\x\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\y\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\y\x\y\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\file.txt", true); ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\x\file.txt", true); } [Fact] public void Regress155731() { ValidateFileMatch(@"a\b\**\**\**\**\**\e\*", @"a\b\c\d\e\f.txt", true); ValidateFileMatch(@"a\b\**\e\*", @"a\b\c\d\e\f.txt", true); ValidateFileMatch(@"a\b\**\**\e\*", @"a\b\c\d\e\f.txt", true); ValidateFileMatch(@"a\b\**\**\**\e\*", @"a\b\c\d\e\f.txt", true); ValidateFileMatch(@"a\b\**\**\**\**\e\*", @"a\b\c\d\e\f.txt", true); } [Fact] public void ParentWithoutSlash() { // However, we don't wtool this to match, ValidateNoFileMatch(@"C:\foo\**", @"C:\foo", true); // because we don't know whether foo is a file or folder. // Same for UNC ValidateNoFileMatch ( "\\\\server\\c$\\Documents and Settings\\User\\**", "\\\\server\\c$\\Documents and Settings\\User", true ); } [Fact] public void Unc() { // Check UNC functionality ValidateFileMatch ( "\\\\server\\c$\\**\\*.cs", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", true ); ValidateNoFileMatch ( "\\\\server\\c$\\**\\*.cs", "\\\\server\\c$\\Documents and Settings\\User\\Source.txt", true ); ValidateFileMatch ( "\\\\**", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", true ); ValidateFileMatch ( "\\\\**\\*.*", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", true ); ValidateFileMatch ( "**", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", true ); } [Fact] public void ExplicitToolCompatibility() { // Explicit ANT compatibility. These patterns taken from the ANT documentation. ValidateFileMatch("**/SourceSafe/*", "./SourceSafe/Repository", true); ValidateFileMatch("**\\SourceSafe/*", "./SourceSafe/Repository", true); ValidateFileMatch("**/SourceSafe/*", ".\\SourceSafe\\Repository", true); ValidateFileMatch("**/SourceSafe/*", "./org/IIS/SourceSafe/Entries", true); ValidateFileMatch("**/SourceSafe/*", "./org/IIS/pluggin/tools/tool/SourceSafe/Entries", true); ValidateNoFileMatch("**/SourceSafe/*", "./org/IIS/SourceSafe/foo/bar/Entries", true); ValidateNoFileMatch("**/SourceSafe/*", "./SourceSafeRepository", true); ValidateNoFileMatch("**/SourceSafe/*", "./aSourceSafe/Repository", true); ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin/tools/tool/docs/index.html", true); ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin/test.xml", true); ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin\\test.xml", true); ValidateNoFileMatch("org/IIS/pluggin/**", "org/IIS/abc.cs", true); ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/SourceSafe/Entries", true); ValidateFileMatch("org/IIS/**/SourceSafe/*", "org\\IIS/SourceSafe/Entries", true); ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS\\SourceSafe/Entries", true); ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/pluggin/tools/tool/SourceSafe/Entries", true); ValidateNoFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/SourceSafe/foo/bar/Entries", true); ValidateNoFileMatch("org/IIS/**/SourceSafe/*", "org/IISSourceSage/Entries", true); } [Fact] public void ExplicitToolIncompatibility() { // NOTE: Weirdly, ANT syntax is to match a file here. // We don't because MSBuild philosophy is that a trailing slash indicates a directory ValidateNoFileMatch("**/test/**", ".\\test", true); // NOTE: We deviate from ANT format here. ANT would append a ** to any path // that ends with '/' or '\'. We think this is the wrong thing because 'folder\' // is a valid folder name. ValidateNoFileMatch("org/", "org/IISSourceSage/Entries", false); ValidateNoFileMatch("org\\", "org/IISSourceSage/Entries", false); } [Fact] public void MultipleStarStar() { // Multiple-** matches ValidateFileMatch("c:\\**\\user\\**\\*.*", "c:\\Documents and Settings\\user\\NTUSER.DAT", true); ValidateNoFileMatch("c:\\**\\user1\\**\\*.*", "c:\\Documents and Settings\\user\\NTUSER.DAT", true); ValidateFileMatch("c:\\**\\user\\**\\*.*", "c://Documents and Settings\\user\\NTUSER.DAT", true); ValidateNoFileMatch("c:\\**\\user1\\**\\*.*", "c:\\Documents and Settings//user\\NTUSER.DAT", true); } [Fact] public void RegressItemRecursionWorksAsExpected() { // Regress bug#54411: Item recursion doesn't work as expected on "c:\foo\**" ValidateFileMatch("c:\\foo\\**", "c:\\foo\\two\\subfile.txt", true); } [Fact] public void IllegalPaths() { // Certain patterns are illegal. ValidateIllegal("**.cs"); ValidateIllegal("***"); ValidateIllegal("****"); ValidateIllegal("*.cs**"); ValidateIllegal("*.cs**"); ValidateIllegal("...\\*.cs"); ValidateIllegal("http://www.website.com"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Nothing's too long for Unix [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] public void IllegalTooLongPathOptOutWave17_0() { using (var env = TestEnvironment.Create()) { ChangeWaves.ResetStateForTests(); env.SetEnvironmentVariable("MSBUILDDISABLEFEATURESFROMVERSION", ChangeWaves.Wave17_0.ToString()); BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly(); string longString = new string('X', 500) + "*"; // need a wildcard to do anything string[] result = FileMatcher.Default.GetFiles(@"c:\", longString); Assert.Equal(longString, result[0]); // Does not throw ChangeWaves.ResetStateForTests(); } // Not checking that GetFileSpecMatchInfo returns the illegal-path flag, // not certain that won't break something; this fix is merely to avoid a crash. } [Fact] public void SplitFileSpec() { /************************************************************************************* * Call ValidateSplitFileSpec with various supported combinations. *************************************************************************************/ ValidateSplitFileSpec("foo.cs", "", "", "foo.cs"); ValidateSplitFileSpec("**\\foo.cs", "", "**\\", "foo.cs"); ValidateSplitFileSpec("f:\\dir1\\**\\foo.cs", "f:\\dir1\\", "**\\", "foo.cs"); ValidateSplitFileSpec("..\\**\\foo.cs", "..\\", "**\\", "foo.cs"); ValidateSplitFileSpec("f:\\dir1\\foo.cs", "f:\\dir1\\", "", "foo.cs"); ValidateSplitFileSpec("f:\\dir?\\foo.cs", "f:\\", "dir?\\", "foo.cs"); ValidateSplitFileSpec("dir?\\foo.cs", "", "dir?\\", "foo.cs"); ValidateSplitFileSpec(@"**\test\**", "", @"**\test\**\", "*.*"); ValidateSplitFileSpec("bin\\**\\*.cs", "bin\\", "**\\", "*.cs"); ValidateSplitFileSpec("bin\\**\\*.*", "bin\\", "**\\", "*.*"); ValidateSplitFileSpec("bin\\**", "bin\\", "**\\", "*.*"); ValidateSplitFileSpec("bin\\**\\", "bin\\", "**\\", ""); ValidateSplitFileSpec("bin\\**\\*", "bin\\", "**\\", "*"); ValidateSplitFileSpec("**", "", "**\\", "*.*"); } [Fact] public void Regress367780_CrashOnStarDotDot() { string workingPath = _env.CreateFolder().Path; string workingPathSubfolder = Path.Combine(workingPath, "SubDir"); string offendingPattern = Path.Combine(workingPath, @"*\..\bar"); string[] files = Array.Empty<string>(); Directory.CreateDirectory(workingPath); Directory.CreateDirectory(workingPathSubfolder); files = FileMatcher.Default.GetFiles(workingPath, offendingPattern); } [Fact] public void Regress141071_StarStarSlashStarStarIsLiteral() { string workingPath = _env.CreateFolder().Path; string fileName = Path.Combine(workingPath, "MyFile.txt"); string offendingPattern = Path.Combine(workingPath, @"**\**"); Directory.CreateDirectory(workingPath); File.WriteAllText(fileName, "Hello there."); var files = FileMatcher.Default.GetFiles(workingPath, offendingPattern); string result = String.Join(", ", files); Console.WriteLine(result); Assert.DoesNotContain("**", result); Assert.Contains("MyFile.txt", result); } [Fact] public void Regress14090_TrailingDotMatchesNoExtension() { string workingPath = _env.CreateFolder().Path; string workingPathSubdir = Path.Combine(workingPath, "subdir"); string workingPathSubdirBing = Path.Combine(workingPathSubdir, "bing"); string offendingPattern = Path.Combine(workingPath, @"**\sub*\*."); Directory.CreateDirectory(workingPath); Directory.CreateDirectory(workingPathSubdir); File.AppendAllText(workingPathSubdirBing, "y"); var files = FileMatcher.Default.GetFiles(workingPath, offendingPattern); string result = String.Join(", ", files); Console.WriteLine(result); Assert.Single(files); } [Fact] public void Regress14090_TrailingDotMatchesNoExtension_Part2() { ValidateFileMatch(@"c:\mydir\**\*.", @"c:\mydir\subdir\bing", true, /* simulate filesystem? */ false); ValidateNoFileMatch(@"c:\mydir\**\*.", @"c:\mydir\subdir\bing.txt", true); } [Fact] public void FileEnumerationCacheTakesExcludesIntoAccount() { try { using (var env = TestEnvironment.Create()) { env.SetEnvironmentVariable("MsBuildCacheFileEnumerations", "1"); var testProject = env.CreateTestProjectWithFiles(string.Empty, new[] {"a.cs", "b.cs", "c.cs"}); var files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs"); Array.Sort(files); Assert.Equal(new []{"a.cs", "b.cs", "c.cs"}, files); files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs", new List<string> {"a.cs"}); Array.Sort(files); Assert.Equal(new[] {"b.cs", "c.cs" }, files); files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs", new List<string> {"a.cs", "c.cs"}); Array.Sort(files); Assert.Equal(new[] {"b.cs" }, files); } } finally { FileMatcher.ClearFileEnumerationsCache(); } } [Fact] public void RemoveProjectDirectory() { string[] strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray(); Assert.Equal("1.file", strings[0]); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file"}; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray(); Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "directory\\1.file" : "directory/1.file"); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray(); Assert.Equal("1.file", strings[0]); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory" ).ToArray(); Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file"); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray(); Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" ); if (NativeMethodsShared.IsWindows) { strings = new string[1] { "\\Machine\\1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine").ToArray(); Assert.Equal("1.file", strings[0]); strings = new string[1] { "\\Machine\\directory\\1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine").ToArray(); Assert.Equal("directory\\1.file", strings[0]); strings = new string[1] { "\\Machine\\directory\\1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray(); Assert.Equal("1.file", strings[0]); strings = new string[1] { "\\Machine\\1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray(); Assert.Equal("\\Machine\\1.file", strings[0]); strings = new string[1] { "\\Machine\\directorymorechars\\1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray(); Assert.Equal("\\Machine\\directorymorechars\\1.file", strings[0]); } } [Theory] [InlineData( @"src/**/*.cs", // Include Pattern new string[] // Matching files { @"src/a.cs", @"src/a\b\b.cs", } )] [InlineData( @"src/test/**/*.cs", // Include Pattern new string[] // Matching files { @"src/test/a.cs", @"src/test/a\b\c.cs", } )] [InlineData( @"src/test/**/a/b/**/*.cs", // Include Pattern new string[] // Matching files { @"src/test/dir\a\b\a.cs", @"src/test/dir\a\b\c\a.cs", } )] public void IncludePatternShouldNotPreserveUserSlashesInFixedDirPart(string include, string[] matching) { MatchDriver(include, null, matching, null, null, normalizeAllPaths: false, normalizeExpectedMatchingFiles: true); } [Theory] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"bin\**" }, new string[] // Matching files { }, new string[] // Non matching files { }, new[] // Non matching files that shouldn't be touched { @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" } )] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"bin\**" }, new[] // Matching files { "a.cs", @"b\b.cs", }, new[] // Non matching files { @"b\b.txt" }, new[] // Non matching files that shouldn't be touched { @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" } )] public void ExcludePattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable) { MatchDriver(include, exclude, matching, nonMatching, untouchable); } [Fact] public void ExcludeSpecificFiles() { MatchDriverWithDifferentSlashes( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"Program_old.cs", @"Properties\AssemblyInfo_old.cs" }, new[] // Matching files { @"foo.cs", @"Properties\AssemblyInfo.cs", @"Foo\Bar\Baz\Buzz.cs" }, new[] // Non matching files { @"Program_old.cs", @"Properties\AssemblyInfo_old.cs" }, Array.Empty<string>() // Non matching files that shouldn't be touched ); } [Fact] public void ExcludePatternAndSpecificFiles() { MatchDriverWithDifferentSlashes( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"bin\**", @"Program_old.cs", @"Properties\AssemblyInfo_old.cs" }, new[] // Matching files { @"foo.cs", @"Properties\AssemblyInfo.cs", @"Foo\Bar\Baz\Buzz.cs" }, new[] // Non matching files { @"foo.txt", @"Foo\foo.txt", @"Program_old.cs", @"Properties\AssemblyInfo_old.cs" }, new[] // Non matching files that shouldn't be touched { @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" } ); } [Theory] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"**\bin\**\*.cs", @"src\Common\**", }, new[] // Matching files { @"foo.cs", @"src\Framework\Properties\AssemblyInfo.cs", @"src\Framework\Foo\Bar\Baz\Buzz.cs" }, new[] // Non matching files { @"foo.txt", @"src\Framework\Readme.md", @"src\Common\foo.cs", // Ideally these would be untouchable @"src\Framework\bin\foo.cs", @"src\Framework\bin\Debug", @"src\Framework\bin\Debug\foo.cs", }, new[] // Non matching files that shouldn't be touched { @"src\Common\Properties\", @"src\Common\Properties\AssemblyInfo.cs", } )] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns { @"**\bin\**\*.cs", @"src\Co??on\**", }, new[] // Matching files { @"foo.cs", @"src\Framework\Properties\AssemblyInfo.cs", @"src\Framework\Foo\Bar\Baz\Buzz.cs" }, new[] // Non matching files { @"foo.txt", @"src\Framework\Readme.md", @"src\Common\foo.cs", // Ideally these would be untouchable @"src\Framework\bin\foo.cs", @"src\Framework\bin\Debug", @"src\Framework\bin\Debug\foo.cs", @"src\Common\Properties\AssemblyInfo.cs" }, new[] // Non matching files that shouldn't be touched { @"src\Common\Properties\" } )] [InlineData( @"src\**\proj\**\*.cs", // Include Pattern new[] // Exclude patterns { @"src\**\proj\**\none\**\*", }, new[] // Matching files { @"src\proj\m1.cs", @"src\proj\a\m2.cs", @"src\b\proj\m3.cs", @"src\c\proj\d\m4.cs", }, new[] // Non matching files { @"nm1.cs", @"a\nm2.cs", @"src\nm3.cs", @"src\a\nm4.cs", // Ideally these would be untouchable @"src\proj\none\nm5.cs", @"src\proj\a\none\nm6.cs", @"src\b\proj\none\nm7.cs", @"src\c\proj\d\none\nm8.cs", @"src\e\proj\f\none\g\nm8.cs", }, new string[] // Non matching files that shouldn't be touched { } )] // patterns with excludes that ideally would prune entire recursive subtrees (files in pruned tree aren't touched at all) but the exclude pattern is too complex for that to work with the current logic public void ExcludeComplexPattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable) { MatchDriverWithDifferentSlashes(include, exclude, matching, nonMatching, untouchable); } [Theory] // Empty string is valid [InlineData( "", "", "", "", "^(?<WILDCARDDIR>)(?<FILENAME>)$", false, true )] // ... anywhere is invalid [InlineData( @"...\foo", "", "", "", "", false, false )] // : not placed at second index is invalid [InlineData( "http://www.website.com", "", "", "", "", false, false )] // ** not alone in filename part is invalid [InlineData( "**foo", "", "", "**foo", "", false, false )] // ** not alone in filename part is invalid [InlineData( "foo**", "", "", "foo**", "", false, false )] // ** not alone between slashes in wildcard part is invalid [InlineData( @"**foo\bar", "", @"**foo\", "bar", "", false, false )] // .. placed after any ** is invalid [InlineData( @"**\..\bar", "", @"**\..\", "bar", "", false, false )] // Common wildcard characters in wildcard and filename part [InlineData( @"*fo?ba?\*fo?ba?", "", @"*fo?ba?\", "*fo?ba?", @"^(?<WILDCARDDIR>[^/\\]*fo.ba.[/\\]+)(?<FILENAME>[^/\\]*fo.ba.)$", true, true )] // Special case for ? and * when trailing . in filename part [InlineData( "?oo*.", "", "", "?oo*.", @"^(?<WILDCARDDIR>)(?<FILENAME>[^\.].oo[^\.]*)$", false, true )] // Skip the .* portion of any *.* sequence in filename part [InlineData( "*.*foo*.*", "", "", "*.*foo*.*", @"^(?<WILDCARDDIR>)(?<FILENAME>[^/\\]*foo[^/\\]*)$", false, true )] // Collapse successive directory separators [InlineData( @"\foo///bar\\\?foo///bar\\\foo", @"\foo///bar\\\", @"?foo///bar\\\", "foo", @"^[/\\]+foo[/\\]+bar[/\\]+(?<WILDCARDDIR>.foo[/\\]+bar[/\\]+)(?<FILENAME>foo)$", true, true )] // Collapse successive relative separators [InlineData( @"\./.\foo/.\./bar\./.\?foo/.\./bar\./.\foo", @"\./.\foo/.\./bar\./.\", @"?foo/.\./bar\./.\", "foo", @"^[/\\]+foo[/\\]+bar[/\\]+(?<WILDCARDDIR>.foo[/\\]+bar[/\\]+)(?<FILENAME>foo)$", true, true )] // Collapse successive recursive operators [InlineData( @"foo\**/**\bar/**\**/foo\**/**\bar", @"foo\", @"**/**\bar/**\**/foo\**/**\", "bar", @"^foo[/\\]+(?<WILDCARDDIR>((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?<FILENAME>bar)$", true, true )] // Collapse all three cases combined [InlineData( @"foo\\\.///**\\\.///**\\\.///bar\\\.///**\\\.///**\\\.///foo\\\.///**\\\.///**\\\.///bar", @"foo\\\.///", @"**\\\.///**\\\.///bar\\\.///**\\\.///**\\\.///foo\\\.///**\\\.///**\\\.///", "bar", @"^foo[/\\]+(?<WILDCARDDIR>((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?<FILENAME>bar)$", true, true )] public void GetFileSpecInfoCommon( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, bool expectedIsLegalFileSpec ) { if (NativeMethodsShared.IsUnixLike) { expectedFixedDirectoryPart = FileUtilities.FixFilePath(expectedFixedDirectoryPart); expectedWildcardDirectoryPart = FileUtilities.FixFilePath(expectedWildcardDirectoryPart); } TestGetFileSpecInfo( filespec, expectedFixedDirectoryPart, expectedWildcardDirectoryPart, expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, expectedIsLegalFileSpec ); } [PlatformSpecific(TestPlatforms.Windows)] [Theory] // Escape pecial regex characters valid in Windows paths [InlineData( @"$()+.[^{\?$()+.[^{\$()+.[^{", @"$()+.[^{\", @"?$()+.[^{\", "$()+.[^{", @"^\$\(\)\+\.\[\^\{[/\\]+(?<WILDCARDDIR>.\$\(\)\+\.\[\^\{[/\\]+)(?<FILENAME>\$\(\)\+\.\[\^\{)$", true, true )] // Preserve UNC paths in fixed directory part [InlineData( @"\\\.\foo/bar", @"\\\.\foo/", "", "bar", @"^\\\\foo[/\\]+(?<WILDCARDDIR>)(?<FILENAME>bar)$", false, true )] public void GetFileSpecInfoWindows( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, bool expectedIsLegalFileSpec ) { TestGetFileSpecInfo( filespec, expectedFixedDirectoryPart, expectedWildcardDirectoryPart, expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, expectedIsLegalFileSpec ); } [PlatformSpecific(TestPlatforms.AnyUnix)] [Theory] // Escape regex characters valid in Unix paths [InlineData( @"$()+.[^{|\?$()+.[^{|\$()+.[^{|", @"$()+.[^{|/", @"?$()+.[^{|/", "$()+.[^{|", @"^\$\(\)\+\.\[\^\{\|[/\\]+(?<WILDCARDDIR>.\$\(\)\+\.\[\^\{\|[/\\]+)(?<FILENAME>\$\(\)\+\.\[\^\{\|)$", true, true )] // Collapse leading successive directory separators in fixed directory part [InlineData( @"\\\.\foo/bar", @"///./foo/", "", "bar", @"^[/\\]+foo[/\\]+(?<WILDCARDDIR>)(?<FILENAME>bar)$", false, true )] public void GetFileSpecInfoUnix( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, bool expectedIsLegalFileSpec ) { TestGetFileSpecInfo( filespec, expectedFixedDirectoryPart, expectedWildcardDirectoryPart, expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, expectedIsLegalFileSpec ); } private void TestGetFileSpecInfo( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, bool expectedIsLegalFileSpec ) { FileMatcher.Default.GetFileSpecInfo( filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart, out bool needsRecursion, out bool isLegalFileSpec ); string matchFileExpression = isLegalFileSpec ? FileMatcher.RegularExpressionFromFileSpec(fixedDirectoryPart, wildcardDirectoryPart, filenamePart) : string.Empty; fixedDirectoryPart.ShouldBe(expectedFixedDirectoryPart); wildcardDirectoryPart.ShouldBe(expectedWildcardDirectoryPart); filenamePart.ShouldBe(expectedFilenamePart); matchFileExpression.ShouldBe(expectedMatchFileExpression); needsRecursion.ShouldBe(expectedNeedsRecursion); isLegalFileSpec.ShouldBe(expectedIsLegalFileSpec); } #region Support functions. /// <summary> /// This support class simulates a file system. /// It accepts multiple sets of files and keeps track of how many files were "hit" /// In this case, "hit" means that the caller asked for that file directly. /// </summary> internal class MockFileSystem { /// <summary> /// Array of files (set1) /// </summary> private string[] _fileSet1; /// <summary> /// Array of files (set2) /// </summary> private string[] _fileSet2; /// <summary> /// Array of files (set3) /// </summary> private string[] _fileSet3; /// <summary> /// Number of times a file from set 1 was requested. /// </summary> private int _fileSet1Hits = 0; /// <summary> /// Number of times a file from set 2 was requested. /// </summary> private int _fileSet2Hits = 0; /// <summary> /// Number of times a file from set 3 was requested. /// </summary> private int _fileSet3Hits = 0; /// <summary> /// Construct. /// </summary> /// <param name="fileSet1">First set of files.</param> /// <param name="fileSet2">Second set of files.</param> /// <param name="fileSet3">Third set of files.</param> internal MockFileSystem ( string[] fileSet1, string[] fileSet2, string[] fileSet3 ) { _fileSet1 = fileSet1; _fileSet2 = fileSet2; _fileSet3 = fileSet3; } /// <summary> /// Number of times a file from set 1 was requested. /// </summary> internal int FileHits1 { get { return _fileSet1Hits; } } /// <summary> /// Number of times a file from set 2 was requested. /// </summary> internal int FileHits2 { get { return _fileSet2Hits; } } /// <summary> /// Number of times a file from set 3 was requested. /// </summary> internal int FileHits3 { get { return _fileSet3Hits; } } /// <summary> /// Return files that match the given files. /// </summary> /// <param name="candidates">Candidate files.</param> /// <param name="path">The path to search within</param> /// <param name="pattern">The pattern to search for.</param> /// <param name="files">Hashtable receives the files.</param> /// <returns></returns> private int GetMatchingFiles(string[] candidates, string path, string pattern, ISet<string> files) { int hits = 0; if (candidates != null) { foreach (string candidate in candidates) { string normalizedCandidate = Normalize(candidate); // Get the candidate directory. string candidateDirectoryName = ""; if (normalizedCandidate.IndexOfAny(FileMatcher.directorySeparatorCharacters) != -1) { candidateDirectoryName = Path.GetDirectoryName(normalizedCandidate); } // Does the candidate directory match the requested path? if (FileUtilities.PathsEqual(path, candidateDirectoryName)) { // Match the basic *.* or null. These both match any file. if ( pattern == null || String.Equals(pattern, "*.*", StringComparison.OrdinalIgnoreCase) ) { ++hits; files.Add(FileMatcher.Normalize(candidate)); } else if (pattern.Substring(0, 2) == "*.") // Match patterns like *.cs { string tail = pattern.Substring(1); string candidateTail = candidate.Substring(candidate.Length - tail.Length); if (String.Equals(tail, candidateTail, StringComparison.OrdinalIgnoreCase)) { ++hits; files.Add(FileMatcher.Normalize(candidate)); } } else if (pattern.Substring(pattern.Length - 4, 2) == ".?") // Match patterns like foo.?xt { string leader = pattern.Substring(0, pattern.Length - 4); string candidateLeader = candidate.Substring(candidate.Length - leader.Length - 4, leader.Length); if (String.Equals(leader, candidateLeader, StringComparison.OrdinalIgnoreCase)) { string tail = pattern.Substring(pattern.Length - 2); string candidateTail = candidate.Substring(candidate.Length - 2); if (String.Equals(tail, candidateTail, StringComparison.OrdinalIgnoreCase)) { ++hits; files.Add(FileMatcher.Normalize(candidate)); } } } else if (!FileMatcher.HasWildcards(pattern)) { if (normalizedCandidate == Path.Combine(path, pattern)) { ++hits; files.Add(candidate); } } else { Assert.True(false, String.Format("Unhandled case in GetMatchingFiles: {0}", pattern)); } } } } return hits; } /// <summary> /// Given a path and pattern, return all the simulated directories out of candidates. /// </summary> /// <param name="candidates">Candidate file to extract directories from.</param> /// <param name="path">The path to search.</param> /// <param name="pattern">The pattern to match.</param> /// <param name="directories">Receives the directories.</param> private void GetMatchingDirectories(string[] candidates, string path, string pattern, ISet<string> directories) { if (candidates != null) { foreach (string candidate in candidates) { string normalizedCandidate = Normalize(candidate); if (IsMatchingDirectory(path, normalizedCandidate)) { int nextSlash = normalizedCandidate.IndexOfAny(FileMatcher.directorySeparatorCharacters, path.Length + 1); if (nextSlash != -1) { // UNC paths start with a \\ fragment. Match against \\ when path is empty (i.e., inside the current working directory) string match = normalizedCandidate.StartsWith(@"\\") && string.IsNullOrEmpty(path) ? @"\\" : normalizedCandidate.Substring(0, nextSlash); string baseMatch = Path.GetFileName(normalizedCandidate.Substring(0, nextSlash)); if ( String.Equals(pattern, "*.*", StringComparison.OrdinalIgnoreCase) || pattern == null ) { directories.Add(FileMatcher.Normalize(match)); } else if // Match patterns like ?emp ( pattern.Substring(0, 1) == "?" && pattern.Length == baseMatch.Length ) { string tail = pattern.Substring(1); string baseMatchTail = baseMatch.Substring(1); if (String.Equals(tail, baseMatchTail, StringComparison.OrdinalIgnoreCase)) { directories.Add(FileMatcher.Normalize(match)); } } else { Assert.True(false, String.Format("Unhandled case in GetMatchingDirectories: {0}", pattern)); } } } } } } /// <summary> /// Method that is delegable for use by FileMatcher. This method simulates a filesystem by returning /// files and\or folders that match the requested path and pattern. /// </summary> /// <param name="entityType">Files, Directories or both</param> /// <param name="path">The path to search.</param> /// <param name="pattern">The pattern to search (may be null)</param> /// <returns>The matched files or folders.</returns> internal IReadOnlyList<string> GetAccessibleFileSystemEntries(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory) { string normalizedPath = Normalize(path); ISet<string> files = new HashSet<string>(); if (entityType == FileMatcher.FileSystemEntity.Files || entityType == FileMatcher.FileSystemEntity.FilesAndDirectories) { _fileSet1Hits += GetMatchingFiles(_fileSet1, normalizedPath, pattern, files); _fileSet2Hits += GetMatchingFiles(_fileSet2, normalizedPath, pattern, files); _fileSet3Hits += GetMatchingFiles(_fileSet3, normalizedPath, pattern, files); } if (entityType == FileMatcher.FileSystemEntity.Directories || entityType == FileMatcher.FileSystemEntity.FilesAndDirectories) { GetMatchingDirectories(_fileSet1, normalizedPath, pattern, files); GetMatchingDirectories(_fileSet2, normalizedPath, pattern, files); GetMatchingDirectories(_fileSet3, normalizedPath, pattern, files); } return files.ToList(); } /// <summary> /// Given a path, fix it up so that it can be compared to another path. /// </summary> /// <param name="path">The path to fix up.</param> /// <returns>The normalized path.</returns> internal static string Normalize(string path) { if (path.Length == 0) { return path; } string normalized = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); if (Path.DirectorySeparatorChar != '\\') { normalized = path.Replace("\\", Path.DirectorySeparatorChar.ToString()); } // Replace leading UNC. if (normalized.StartsWith(@"\\")) { normalized = "<:UNC:>" + normalized.Substring(2); } // Preserve parent-directory markers. normalized = normalized.Replace(@".." + Path.DirectorySeparatorChar, "<:PARENT:>"); // Just get rid of doubles enough to satisfy our test cases. string doubleSeparator = Path.DirectorySeparatorChar.ToString() + Path.DirectorySeparatorChar.ToString(); normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString()); normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString()); normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString()); // Strip any .\ normalized = normalized.Replace(@"." + Path.DirectorySeparatorChar, ""); // Put back the preserved markers. normalized = normalized.Replace("<:UNC:>", @"\\"); normalized = normalized.Replace("<:PARENT:>", @".." + Path.DirectorySeparatorChar); return normalized; } /// <summary> /// Determines whether candidate is in a subfolder of path. /// </summary> /// <param name="path"></param> /// <param name="candidate"></param> /// <returns>True if there is a match.</returns> private bool IsMatchingDirectory(string path, string candidate) { string normalizedPath = Normalize(path); string normalizedCandidate = Normalize(candidate); // Current directory always matches for non-rooted paths. if (path.Length == 0 && !Path.IsPathRooted(candidate)) { return true; } if (normalizedCandidate.Length > normalizedPath.Length) { if (String.Compare(normalizedPath, 0, normalizedCandidate, 0, normalizedPath.Length, StringComparison.OrdinalIgnoreCase) == 0) { if (FileUtilities.EndsWithSlash(normalizedPath)) { return true; } else if (FileUtilities.IsSlash(normalizedCandidate[normalizedPath.Length])) { return true; } } } return false; } /// <summary> /// Searches the candidates array for one that matches path /// </summary> /// <param name="path"></param> /// <param name="candidates"></param> /// <returns>The index of the first match or negative one.</returns> private int IndexOfFirstMatchingDirectory(string path, string[] candidates) { if (candidates != null) { int i = 0; foreach (string candidate in candidates) { if (IsMatchingDirectory(path, candidate)) { return i; } ++i; } } return -1; } /// <summary> /// Delegable method that returns true if the given directory exists in this simulated filesystem /// </summary> /// <param name="path">The path to check.</param> /// <returns>True if the directory exists.</returns> internal bool DirectoryExists(string path) { if (IndexOfFirstMatchingDirectory(path, _fileSet1) != -1) { return true; } if (IndexOfFirstMatchingDirectory(path, _fileSet2) != -1) { return true; } if (IndexOfFirstMatchingDirectory(path, _fileSet3) != -1) { return true; } return false; } } /// <summary> /// A general purpose method used to: /// /// (1) Simulate a file system. /// (2) Check whether all matchingFiles where hit by the filespec pattern. /// (3) Check whether all nonmatchingFiles were *not* hit by the filespec pattern. /// (4) Check whether all untouchableFiles were not even requested (usually for perf reasons). /// /// These can be used in various combinations to test the filematcher framework. /// </summary> /// <param name="filespec">A FileMatcher filespec, possibly with wildcards.</param> /// <param name="matchingFiles">Files that exist and should be matched.</param> /// <param name="nonmatchingFiles">Files that exists and should not be matched.</param> /// <param name="untouchableFiles">Files that exist but should not be requested.</param> private static void MatchDriver ( string filespec, string[] matchingFiles, string[] nonmatchingFiles, string[] untouchableFiles ) { MatchDriver(filespec, null, matchingFiles, nonmatchingFiles, untouchableFiles); } /// <summary> /// Runs the test 4 times with the include and exclude using either forward or backward slashes. /// Expects the <param name="filespec"></param> and <param name="excludeFileSpects"></param> to contain only backward slashes /// /// To preserve current MSBuild behaviour, it only does so if the path is not rooted. Rooted paths do not support forward slashes (as observed on MSBuild 14.0.25420.1) /// </summary> private static void MatchDriverWithDifferentSlashes ( string filespec, string[] excludeFilespecs, string[] matchingFiles, string[] nonmatchingFiles, string[] untouchableFiles ) { // tests should call this method with backward slashes Assert.DoesNotContain(filespec, "/"); foreach (var excludeFilespec in excludeFilespecs) { Assert.DoesNotContain(excludeFilespec, "/"); } var forwardSlashFileSpec = Helpers.ToForwardSlash(filespec); var forwardSlashExcludeSpecs = excludeFilespecs.Select(Helpers.ToForwardSlash).ToArray(); MatchDriver(filespec, excludeFilespecs, matchingFiles, nonmatchingFiles, untouchableFiles); MatchDriver(filespec, forwardSlashExcludeSpecs, matchingFiles, nonmatchingFiles, untouchableFiles); MatchDriver(forwardSlashFileSpec, excludeFilespecs, matchingFiles, nonmatchingFiles, untouchableFiles); MatchDriver(forwardSlashFileSpec, forwardSlashExcludeSpecs, matchingFiles, nonmatchingFiles, untouchableFiles); } private static void MatchDriver(string filespec, string[] excludeFilespecs, string[] matchingFiles, string[] nonmatchingFiles, string[] untouchableFiles, bool normalizeAllPaths = true, bool normalizeExpectedMatchingFiles = false) { MockFileSystem mockFileSystem = new MockFileSystem(matchingFiles, nonmatchingFiles, untouchableFiles); var fileMatcher = new FileMatcher(new FileSystemAdapter(mockFileSystem), mockFileSystem.GetAccessibleFileSystemEntries); string[] files = fileMatcher.GetFiles ( String.Empty, /* we don't need project directory as we use mock filesystem */ filespec, excludeFilespecs?.ToList() ); Func<string[], string[]> normalizeAllFunc = (paths => normalizeAllPaths ? paths.Select(MockFileSystem.Normalize).ToArray() : paths); Func<string[], string[]> normalizeMatching = (paths => normalizeExpectedMatchingFiles ? paths.Select(MockFileSystem.Normalize).ToArray() : paths); string[] normalizedFiles = normalizeAllFunc(files); // Validate the matching files. if (matchingFiles != null) { string[] normalizedMatchingFiles = normalizeAllFunc(normalizeMatching(matchingFiles)); foreach (string matchingFile in normalizedMatchingFiles) { int timesFound = 0; foreach (string file in normalizedFiles) { if (String.Equals(file, matchingFile, StringComparison.OrdinalIgnoreCase)) { ++timesFound; } } Assert.Equal(1, timesFound); } } // Validate the non-matching files if (nonmatchingFiles != null) { string[] normalizedNonMatchingFiles = normalizeAllFunc(nonmatchingFiles); foreach (string nonmatchingFile in normalizedNonMatchingFiles) { int timesFound = 0; foreach (string file in normalizedFiles) { if (String.Equals(file, nonmatchingFile, StringComparison.OrdinalIgnoreCase)) { ++timesFound; } } Assert.Equal(0, timesFound); } } // Check untouchable files. Assert.Equal(0, mockFileSystem.FileHits3); // "At least one file that was marked untouchable was referenced." } /// <summary> /// Simulate GetFileSystemEntries /// </summary> /// <param name="path"></param> /// <param name="pattern"></param> /// <returns>Array of matching file system entries (can be empty).</returns> private static IReadOnlyList<string> GetFileSystemEntriesLoopBack(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory) { return new string[] { Path.Combine(path, pattern) }; } /************************************************************************************* * Validate that SplitFileSpec(...) is returning the expected constituent values. *************************************************************************************/ private static FileMatcher loopBackFileMatcher = new FileMatcher(FileSystems.Default, GetFileSystemEntriesLoopBack); private static void ValidateSplitFileSpec ( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, string expectedFilenamePart ) { string fixedDirectoryPart; string wildcardDirectoryPart; string filenamePart; loopBackFileMatcher.SplitFileSpec ( filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart ); expectedFixedDirectoryPart = FileUtilities.FixFilePath(expectedFixedDirectoryPart); expectedWildcardDirectoryPart = FileUtilities.FixFilePath(expectedWildcardDirectoryPart); expectedFilenamePart = FileUtilities.FixFilePath(expectedFilenamePart); if ( expectedWildcardDirectoryPart != wildcardDirectoryPart || expectedFixedDirectoryPart != fixedDirectoryPart || expectedFilenamePart != filenamePart ) { Console.WriteLine("Expect Fixed '{0}' got '{1}'", expectedFixedDirectoryPart, fixedDirectoryPart); Console.WriteLine("Expect Wildcard '{0}' got '{1}'", expectedWildcardDirectoryPart, wildcardDirectoryPart); Console.WriteLine("Expect Filename '{0}' got '{1}'", expectedFilenamePart, filenamePart); Assert.True(false, "FileMatcher Regression: Failure while validating SplitFileSpec."); } } /************************************************************************************* * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * do indeed match. *************************************************************************************/ private static void ValidateFileMatch ( string filespec, string fileToMatch, bool shouldBeRecursive ) { ValidateFileMatch(filespec, fileToMatch, shouldBeRecursive, /* Simulate filesystem? */ true); } /************************************************************************************* * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * do indeed match. *************************************************************************************/ private static void ValidateFileMatch ( string filespec, string fileToMatch, bool shouldBeRecursive, bool fileSystemSimulation ) { if (!IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive)) { Assert.True(false, "FileMatcher Regression: Failure while validating that files match."); } // Now, simulate a filesystem with only fileToMatch. Make sure the file exists that way. if (fileSystemSimulation) { MatchDriver ( filespec, new string[] { fileToMatch }, null, null ); } } /************************************************************************************* * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * DON'T match. *************************************************************************************/ private static void ValidateNoFileMatch ( string filespec, string fileToMatch, bool shouldBeRecursive ) { if (IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive)) { Assert.True(false, "FileMatcher Regression: Failure while validating that files don't match."); } // Now, simulate a filesystem with only fileToMatch. Make sure the file doesn't exist that way. MatchDriver ( filespec, null, new string[] { fileToMatch }, null ); } /************************************************************************************* * Verify that the given filespec is illegal. *************************************************************************************/ private static void ValidateIllegal ( string filespec ) { Regex regexFileMatch; bool needsRecursion; bool isLegalFileSpec; loopBackFileMatcher.GetFileSpecInfoWithRegexObject ( filespec, out regexFileMatch, out needsRecursion, out isLegalFileSpec ); if (isLegalFileSpec) { Assert.True(false, "FileMatcher Regression: Expected an illegal filespec, but got a legal one."); } // Now, FileMatcher is supposed to take any legal file name and just return it immediately. // Let's see if it does. MatchDriver ( filespec, // Not legal. new string[] { filespec }, // Should match null, null ); } /************************************************************************************* * Given a pattern (filespec) and a candidate filename (fileToMatch) return true if * FileMatcher would say that they match. *************************************************************************************/ private static bool IsFileMatchAssertIfIllegal ( string filespec, string fileToMatch, bool shouldBeRecursive ) { FileMatcher.Result match = FileMatcher.Default.FileMatch(filespec, fileToMatch); if (!match.isLegalFileSpec) { Console.WriteLine("Checking FileSpec: '{0}' against '{1}'", filespec, fileToMatch); Assert.True(false, "FileMatcher Regression: Invalid filespec."); } if (shouldBeRecursive != match.isFileSpecRecursive) { Console.WriteLine("Checking FileSpec: '{0}' against '{1}'", filespec, fileToMatch); Assert.True(shouldBeRecursive); // "FileMatcher Regression: Match was recursive when it shouldn't be." Assert.False(shouldBeRecursive); // "FileMatcher Regression: Match was not recursive when it should have been." } return match.isMatch; } #endregion private class FileSystemAdapter : IFileSystem { private readonly MockFileSystem _mockFileSystem; public FileSystemAdapter(MockFileSystem mockFileSystem) { _mockFileSystem = mockFileSystem; } public TextReader ReadFile(string path) => throw new NotImplementedException(); public Stream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share) => throw new NotImplementedException(); public string ReadFileAllText(string path) => throw new NotImplementedException(); public byte[] ReadFileAllBytes(string path) => throw new NotImplementedException(); public IEnumerable<string> EnumerateFiles(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) { return FileSystems.Default.EnumerateFiles(path, searchPattern, searchOption); } public IEnumerable<string> EnumerateDirectories(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) { return FileSystems.Default.EnumerateDirectories(path, searchPattern, searchOption); } public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) { return FileSystems.Default.EnumerateFileSystemEntries(path, searchPattern, searchOption); } public FileAttributes GetAttributes(string path) => throw new NotImplementedException(); public DateTime GetLastWriteTimeUtc(string path) => throw new NotImplementedException(); public bool DirectoryExists(string path) { return _mockFileSystem.DirectoryExists(path); } public bool FileExists(string path) { return FileSystems.Default.FileExists(path); } public bool FileOrDirectoryExists(string path) { return FileSystems.Default.FileOrDirectoryExists(path); } } } }
39.762421
237
0.466912
[ "MIT" ]
GaryPlattenburg/msbuild
src/Shared/UnitTests/FileMatcher_Tests.cs
106,454
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using CommonGUI; namespace NeowUi { public class CompanyBrandingBottomBar : FlickerFreePanel { int logoRightEdge; public CompanyBrandingBottomBar () { logoRightEdge = 20; } protected override void OnPaint (PaintEventArgs e) { base.OnPaint(e); using (Brush brush = new LinearGradientBrush (FillRegion, FillColour1, FillColour2, FillAngle)) { e.Graphics.FillRectangle(brush, 0, 0, Width - 1, Height - 1); } Image image = LibCore.Repository.TheInstance.GetImage(LibCore.AppInfo.TheInstance.Location + @"\images\panels\poweredbyCompany.png"); e.Graphics.DrawImage(image, new Rectangle (Width - image.Width - logoRightEdge, (Height - image.Height) / 2, image.Width, image.Height)); } protected override void OnSizeChanged (EventArgs e) { base.OnSizeChanged(e); Invalidate(); } public int LogoRightEdge { get { return logoRightEdge; } set { logoRightEdge = value; Invalidate(); } } public Color FillColour1 { get { return Color.FromArgb(221, 221, 221); } } public Color FillColour2 { get { return Color.FromArgb(89, 89, 89); } } public Rectangle FillRegion { get { return new Rectangle (0, 0, Width, Height); } } public int FillAngle { get { return 90; } } } }
17.065934
140
0.646491
[ "MIT-0" ]
business-sims-toolkit/business-sims-toolkit
dev/libraries/eboards/NeowUi/CompanyBrandingBottomBar.cs
1,555
C#
using System; using MySql.Data.MySqlClient; using System.Collections.Generic; namespace DMPDistributedDBBackend { public class DatabaseDriver { private DatabaseConnection databaseConnection; private Dictionary<ReferenceID, string> pairMatch = new Dictionary<ReferenceID, string>(); private Dictionary<string, TrackingObject> trackingObjects = new Dictionary<string, TrackingObject>(); private Dictionary<ReferenceID, ReportingMessage> connectedClients = new Dictionary<ReferenceID, ReportingMessage>(); public DatabaseDriver(DatabaseConnection databaseConnection) { this.databaseConnection = databaseConnection; SQLCleanupDatabase(); } public void HandleConnect(string serverID, int clientID, string remoteAddress, int remotePort) { ReferenceID thisReference = new ReferenceID(serverID, clientID); lock (connectedClients) { connectedClients.Add(thisReference, null); } } public void HandleReport(string serverID, int clientID, ReportingMessage reportMessage) { ReferenceID thisReference = new ReferenceID(serverID, clientID); lock (connectedClients) { connectedClients[thisReference] = reportMessage; } if (!pairMatch.ContainsKey(thisReference)) { pairMatch.Add(thisReference, reportMessage.serverHash); if (!trackingObjects.ContainsKey(reportMessage.serverHash)) { trackingObjects.Add(reportMessage.serverHash, new TrackingObject()); SQLConnect(reportMessage, trackingObjects[reportMessage.serverHash]); } TrackingObject trackingObject = trackingObjects[reportMessage.serverHash]; trackingObject.referenceCount++; Console.WriteLine(reportMessage.serverHash + " references: " + trackingObject.referenceCount); } SQLReport(reportMessage, trackingObjects[reportMessage.serverHash]); } public void HandleDisconnect(string serverID, int clientID) { ReferenceID thisReference = new ReferenceID(serverID, clientID); lock (connectedClients) { connectedClients.Remove(thisReference); } if (pairMatch.ContainsKey(thisReference)) { string serverHash = pairMatch[thisReference]; TrackingObject trackingObject = trackingObjects[serverHash]; trackingObject.referenceCount--; Console.WriteLine(serverHash + " references: " + trackingObject.referenceCount); if (trackingObject.referenceCount == 0) { SQLDisconnect(serverHash, trackingObject); trackingObjects.Remove(serverHash); } pairMatch.Remove(thisReference); } } private void SQLConnect(ReportingMessage reportMessage, TrackingObject trackingObject) { string initSqlQuery = "CALL gameserverinit(@serverhash, @namex, @descriptionx, @gameportx, @gameaddressx, @protocolx, @programversion, @maxplayersx, @modcontrolx, @modcontrolshax, @gamemodex, @cheatsx, @warpmodex, @universex, @bannerx, @homepagex, @httpportx, @adminx, @teamx, @locationx, @fixedipx);"; Dictionary<string, object> parameters = reportMessage.GetParameters(); try { databaseConnection.ExecuteNonReader(initSqlQuery, parameters); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on connection (add server), error: " + e.Message); } string playerSqlQuery = "CALL gameserverplayer(@hash, @player, '1')"; foreach (string connectedPlayer in reportMessage.players) { Console.WriteLine("Player " + connectedPlayer + " joined " + reportMessage.serverHash); Dictionary<string, object> playerParams = new Dictionary<string, object>(); playerParams["@hash"] = reportMessage.serverHash; playerParams["@player"] = connectedPlayer; try { databaseConnection.ExecuteNonReader(playerSqlQuery, playerParams); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on connection (add player), error: " + e.Message); } trackingObject.players = reportMessage.players; } } private void SQLReport(ReportingMessage reportMessage, TrackingObject trackingObject) { //Take all the currently connected players and remove the players that were connected already to generate a list of players to be added List<string> addList = new List<string>(reportMessage.players); foreach (string player in trackingObject.players) { if (addList.Contains(player)) { addList.Remove(player); } } //Take all the old players connected and remove the players that are connected already to generate a list of players to be removed List<string> removeList = new List<string>(trackingObject.players); foreach (string player in reportMessage.players) { if (removeList.Contains(player)) { removeList.Remove(player); } } //Add new players foreach (string player in addList) { Console.WriteLine("Player " + player + " joined " + reportMessage.serverHash); Dictionary<string, object> playerParams = new Dictionary<string, object>(); playerParams["hash"] = reportMessage.serverHash; playerParams["player"] = player; string sqlQuery = "CALL gameserverplayer(@hash ,@player, '1')"; try { databaseConnection.ExecuteNonReader(sqlQuery, playerParams); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on report (add player), error: " + e.Message); } } //Remove old players foreach (string player in removeList) { Console.WriteLine("Player " + player + " left " + reportMessage.serverHash); Dictionary<string, object> playerParams = new Dictionary<string, object>(); playerParams["hash"] = reportMessage.serverHash; playerParams["player"] = player; string sqlQuery = "CALL gameserverplayer(@hash ,@player, '0')"; try { databaseConnection.ExecuteNonReader(sqlQuery, playerParams); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on report (remove player), error: " + e.Message); } } trackingObject.players = reportMessage.players; } private void SQLDisconnect(string serverHash, TrackingObject trackingObject) { //Remove old players foreach (string player in trackingObject.players) { Dictionary<string, object> playerParams = new Dictionary<string, object>(); playerParams["hash"] = serverHash; playerParams["player"] = player; string sqlQuery = "CALL gameserverplayer(@hash ,@player, '0')"; try { databaseConnection.ExecuteNonReader(sqlQuery, playerParams); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on disconnect (remove player), error: " + e.Message); } } Dictionary<string, object> offlineParams = new Dictionary<string, object>(); offlineParams["@hash"] = serverHash; string mySql = "CALL gameserveroffline(@hash)"; try { databaseConnection.ExecuteNonReader(mySql, offlineParams); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on disconnect (remove server), error: " + e.Message); } } public void SQLCleanupDatabase() { try { databaseConnection.ExecuteNonReader("CALL gameserverscleanup()"); } catch (Exception e) { Console.WriteLine("WARNING: Ignoring error on cleanup, error: " + e.Message); } } public void PrintServers() { lock (connectedClients) { foreach (KeyValuePair<ReferenceID, ReportingMessage> kvp in connectedClients) { if (kvp.Value == null) { Console.WriteLine("@" + kvp.Key.serverID + ":" + kvp.Key.clientID + ": CONNECTING"); } else { Console.WriteLine("@" + kvp.Key.serverID + ":" + kvp.Key.clientID + " " + kvp.Value.gameAddress + ":" + kvp.Value.gamePort + ", " + kvp.Value.players.Length + " players."); } } } } private struct ReferenceID { public readonly string serverID; public readonly int clientID; public ReferenceID(string serverID, int clientID) { this.serverID = serverID; this.clientID = clientID; } public override bool Equals(object obj) { if (obj is ReferenceID) { ReferenceID rhs = (ReferenceID)obj; return (serverID == rhs.serverID && clientID == rhs.clientID); } return false; } public override int GetHashCode() { return (serverID + clientID).GetHashCode(); } } } }
42.23506
314
0.549288
[ "Unlicense" ]
godarklight/DMPDistributedDBBackend
DMPDistributedDBBackend/DatabaseDriver.cs
10,603
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the application-insights-2018-11-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ApplicationInsights.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ApplicationInsights.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeComponentConfigurationRecommendation operation /// </summary> public class DescribeComponentConfigurationRecommendationResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeComponentConfigurationRecommendationResponse response = new DescribeComponentConfigurationRecommendationResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ComponentConfiguration", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ComponentConfiguration = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonApplicationInsightsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeComponentConfigurationRecommendationResponseUnmarshaller _instance = new DescribeComponentConfigurationRecommendationResponseUnmarshaller(); internal static DescribeComponentConfigurationRecommendationResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeComponentConfigurationRecommendationResponseUnmarshaller Instance { get { return _instance; } } } }
40.881356
202
0.666874
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ApplicationInsights/Generated/Model/Internal/MarshallTransformations/DescribeComponentConfigurationRecommendationResponseUnmarshaller.cs
4,824
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; namespace Steeltoe.Common.Util { public static class MimeTypeUtils { public static readonly IComparer<MimeType> SPECIFICITY_COMPARATOR = new MimeType.SpecificityComparator<MimeType>(); public static readonly MimeType ALL = new MimeType("*", "*"); public static readonly string ALL_VALUE = "*/*"; public static readonly MimeType APPLICATION_JSON = new MimeType("application", "json"); public static readonly string APPLICATION_JSON_VALUE = "application/json"; public static readonly MimeType APPLICATION_OCTET_STREAM = new MimeType("application", "octet-stream"); public static readonly string APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream"; public static readonly MimeType APPLICATION_XML = new MimeType("application", "xml"); public static readonly string APPLICATION_XML_VALUE = "application/xml"; public static readonly MimeType IMAGE_GIF = new MimeType("image", "gif"); public static readonly string IMAGE_GIF_VALUE = "image/gif"; public static readonly MimeType IMAGE_JPEG = new MimeType("image", "jpeg"); public static readonly string IMAGE_JPEG_VALUE = "image/jpeg"; public static readonly MimeType IMAGE_PNG = new MimeType("image", "png"); public static readonly string IMAGE_PNG_VALUE = "image/png"; public static readonly MimeType TEXT_HTML = new MimeType("text", "html"); public static readonly string TEXT_HTML_VALUE = "text/html"; public static readonly MimeType TEXT_PLAIN = new MimeType("text", "plain"); public static readonly string TEXT_PLAIN_VALUE = "text/plain"; public static readonly MimeType TEXT_XML = new MimeType("text", "xml"); public static readonly string TEXT_XML_VALUE = "text/xml"; private static readonly ConcurrentDictionary<string, MimeType> _cachedMimeTypes = new ConcurrentDictionary<string, MimeType>(); private static readonly char[] BOUNDARY_CHARS = new char[] { '-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static volatile Random _random; private static object _lock = new object(); public static MimeType ParseMimeType(string mimeType) { return _cachedMimeTypes.GetOrAdd(mimeType, ParseMimeTypeInternal(mimeType)); } public static List<MimeType> ParseMimeTypes(string mimeTypes) { if (string.IsNullOrEmpty(mimeTypes)) { return new List<MimeType>(); } var tokens = Tokenize(mimeTypes); var results = new List<MimeType>(); foreach (var token in tokens) { results.Add(ParseMimeType(token)); } return results; } public static List<string> Tokenize(string mimeTypes) { if (string.IsNullOrEmpty(mimeTypes)) { return new List<string>(); } var tokens = new List<string>(); var inQuotes = false; var startIndex = 0; var i = 0; while (i < mimeTypes.Length) { switch (mimeTypes[i]) { case '"': inQuotes = !inQuotes; break; case ',': if (!inQuotes) { tokens.Add(mimeTypes.Substring(startIndex, i - startIndex)); startIndex = i + 1; } break; case '\\': i++; break; } i++; } tokens.Add(mimeTypes.Substring(startIndex)); return tokens; } public static string Tostring(ICollection<MimeType> mimeTypes) { var builder = new StringBuilder(); foreach (var mimeType in mimeTypes) { mimeType.AppendTo(builder); builder.Append(", "); } var built = builder.ToString(); if (built.EndsWith(", ")) { built = built.Substring(0, built.Length - 2); } return built; } public static void SortBySpecificity(List<MimeType> mimeTypes) { if (mimeTypes == null) { throw new ArgumentNullException(nameof(mimeTypes)); } if (mimeTypes.Count > 1) { mimeTypes.Sort(SPECIFICITY_COMPARATOR); } } public static char[] GenerateMultipartBoundary() { var randomToUse = InitRandom(); var size = randomToUse.Next(11) + 30; var boundary = new char[size]; for (var i = 0; i < boundary.Length; i++) { boundary[i] = BOUNDARY_CHARS[randomToUse.Next(BOUNDARY_CHARS.Length)]; } return boundary; } public static string GenerateMultipartBoundaryString() { return new string(GenerateMultipartBoundary()); } private static MimeType ParseMimeTypeInternal(string mimeType) { if (string.IsNullOrEmpty(mimeType)) { throw new ArgumentException("'mimeType' must not be empty"); } var index = mimeType.IndexOf(';'); var fullType = (index >= 0 ? mimeType.Substring(0, index) : mimeType).Trim(); if (string.IsNullOrEmpty(fullType)) { throw new ArgumentException(mimeType, "'mimeType' must not be empty"); } if (MimeType.WILDCARD_TYPE.Equals(fullType)) { fullType = "*/*"; } var subIndex = fullType.IndexOf('/'); if (subIndex == -1) { throw new ArgumentException(mimeType + " does not contain '/'"); } if (subIndex == fullType.Length - 1) { throw new ArgumentException(mimeType + " does not contain subtype after '/'"); } var type = fullType.Substring(0, subIndex); var subtype = fullType.Substring(subIndex + 1, fullType.Length - type.Length - 1); if (MimeType.WILDCARD_TYPE.Equals(type) && !MimeType.WILDCARD_TYPE.Equals(subtype)) { throw new ArgumentException(mimeType + " wildcard type is legal only in '*/*' (all mime types)"); } Dictionary<string, string> parameters = null; do { var nextIndex = index + 1; var quoted = false; while (nextIndex < mimeType.Length) { var ch = mimeType[nextIndex]; if (ch == ';') { if (!quoted) { break; } } else if (ch == '"') { quoted = !quoted; } nextIndex++; } var parameter = mimeType.Substring(index + 1, nextIndex - index - 1).Trim(); if (parameter.Length > 0) { if (parameters == null) { parameters = new Dictionary<string, string>(4); } var eqIndex = parameter.IndexOf('='); if (eqIndex >= 0) { var attribute = parameter.Substring(0, eqIndex).Trim(); var value = parameter.Substring(eqIndex + 1, parameter.Length - eqIndex - 1).Trim(); parameters[attribute] = value; } } index = nextIndex; } while (index < mimeType.Length); try { return new MimeType(type, subtype, parameters); } catch (Exception ex) { throw new ArgumentException(mimeType + " " + ex.Message); } } private static Random InitRandom() { var randomToUse = _random; if (randomToUse == null) { lock (_lock) { randomToUse = _random; if (randomToUse == null) { randomToUse = new Random(); _random = randomToUse; } } } return randomToUse; } } }
35.710037
135
0.488132
[ "Apache-2.0" ]
DaviGia/Steeltoe
src/Common/src/Common/Util/MimeTypeUtils.cs
9,608
C#
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; namespace MithrilShards.Network.Benchmark.Benchmarks { [SimpleJob(RuntimeMoniker.NetCoreApp31)] [RankColumn, MarkdownExporterAttribute.GitHub, MemoryDiagnoser] public class DiscardThrow { object _data; [GlobalSetup] public void Setup() { _data = new object(); } [Benchmark] public void WithDiscard() => WithDiscard(_data); public static void WithDiscard(object data) { _ = data ?? throw new Exception(); } [Benchmark] public void WithIf() => WithIf(_data); public static void WithIf(object data) { if (data == null) { throw new Exception(); } } } }
19.875
66
0.601258
[ "MIT" ]
MithrilMan/MithrilShards
benchmarks/MithrilShards.P2P.Benchmark/Benchmarks/Spot/DiscardThrow.cs
797
C#
using System; using UnityEngine; namespace Sisus.Attributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class RequireTriggerAttribute : RequireComponentsAttribute, IComponentModifiedCallbackReceiver<Collider> { /// <summary> /// Determines whether collider isTrigger value must be true or false. /// </summary> public bool requiredIsTriggerValue = true; public RequireTriggerAttribute() : base(typeof(Collider)) { requiredIsTriggerValue = true; } public RequireTriggerAttribute(bool requireIsTriggerValue) : base(typeof(Collider)) { requiredIsTriggerValue = requireIsTriggerValue; } public RequireTriggerAttribute(Type colliderType) : base(colliderType) { requiredIsTriggerValue = true; } public RequireTriggerAttribute(bool requireIsTriggerValue, Type colliderType) : base(colliderType) { requiredIsTriggerValue = requireIsTriggerValue; } /// <inheritdoc/> public void OnComponentAdded(Component attributeHolder, Collider addedComponent) { if(addedComponent.isTrigger != requiredIsTriggerValue) { addedComponent.isTrigger = requiredIsTriggerValue; } } /// <inheritdoc/> public void OnComponentModified(Component attributeHolder, Collider modifiedComponent) { if(modifiedComponent.isTrigger != requiredIsTriggerValue) { Debug.LogWarning(attributeHolder.GetType().Name + " requires that " + modifiedComponent.GetType().Name + ".isTrigger is " + requiredIsTriggerValue + "."); modifiedComponent.isTrigger = requiredIsTriggerValue; } } } }
29.166667
158
0.759365
[ "MIT" ]
rafaeldolfe/MasterServerChess
Assets/Sisus/Attributes/RequireTriggerAttribute.cs
1,577
C#
using System; using System.Text.RegularExpressions; namespace Discord_Bot { public class Command { public Command(CommandAttribute attribute, Func<Input, Output> func) { Pattern = attribute.Pattern; Hint = attribute.Hint; Description = attribute.Description; Func = func; } public Regex Pattern { get; } public string Hint { get; } public string Description { get; } public Func<Input, Output> Func { get; } } }
21.5
72
0.659619
[ "MIT" ]
ISmarsh/Discord-Bot
Discord-Bot.Core/Command.cs
475
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebAPI_Buoi2.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
47.211712
229
0.58649
[ "Apache-2.0" ]
davidbull931997/asp.net
WebAPI_Buoi2/WebAPI_Buoi2/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
20,962
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunController : MonoBehaviour { public Gun gun; Player player; SpriteRenderer gunRenderer; Transform gunTransform; private void Start() { player = Player.instance; gunRenderer = GetComponentInChildren<SpriteRenderer>(); gunTransform = gunRenderer.transform; InitGun(); } private void Update() { PointInDirectionOfPlayer(); Shooting(); } private void InitGun() { gunRenderer.sprite = gun.sprite; } private void PointInDirectionOfPlayer() { bool facingRight = player.IsFacingRight(); Direction direction = player.GetDirection(); Vector2 handleOffset = new Vector2(gun.handleOffsetX, gun.handleOffsetY); float facingRightMultiplier = facingRight ? -1 : 1; float facingUpMultiplier = (direction == Direction.UP ? 1 : -1); float x = 0; float y = 0; float rot = 0; if(direction == Direction.UP || direction == Direction.DOWN) { y = facingUpMultiplier * facingRightMultiplier * handleOffset.y; rot = facingUpMultiplier * -90f; } else { rot = 90f - (facingRightMultiplier * 90f); y = facingRightMultiplier * handleOffset.y; } x = handleOffset.x; gunRenderer.flipX = false; gunRenderer.flipY = facingRight; gunTransform.localPosition = new Vector3(x, y, 0) * 0.0625f; transform.eulerAngles = new Vector3(0, 0, rot); } private void Shooting() { if(Input.GetButtonDown("Fire2")) { GameObject shootableObject = Instantiate(gun.shootablePrefab, gunTransform.position, Quaternion.identity); IShootable shootable = shootableObject.GetComponent<IShootable>(); shootable.Shoot(); } } }
25.753247
118
0.604639
[ "MIT" ]
BrendanStEsprit/CaveStoryUnityTutorial
CaveStoryTutorial E07/Assets/Scripts/Guns/GunController.cs
1,985
C#
// ------------------------------------------- // 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; using ControlFreak2; using ControlFreak2.Internal; using ControlFreak2Editor.Internal; namespace ControlFreak2Editor.Inspectors { // --------------------- // Button Creation Wizard // ---------------------- public class TouchButtonCreationWizard : ControlCreationWizardBase { private DigitalBinding pressBinding, toggleBinding; private DigitalBindingInspector pressBindingInsp, toggleBindingInsp; private AxisBinding touchPressureBinding; private AxisBindingInspector touchPressureBindingInsp; // ---------------- static public void ShowWizard(TouchControlPanel panel, BindingSetup bindingSetup = null, System.Action onCreationCallback = null) { TouchButtonCreationWizard w = (TouchButtonCreationWizard)EditorWindow.GetWindow(typeof(TouchButtonCreationWizard), true, "CF2 Button Wizard"); if (w != null) { w.Init(panel, bindingSetup, onCreationCallback); w.ShowPopup(); } } // ------------------- public TouchButtonCreationWizard() : base() { this.minSize = new Vector2(this.minSize.x, 500); this.pressBinding = new DigitalBinding(); this.pressBindingInsp = new DigitalBindingInspector(null, new GUIContent("Press Binding")); this.toggleBinding = new DigitalBinding(); this.toggleBindingInsp = new DigitalBindingInspector(null, new GUIContent("Toggle Binding")); this.touchPressureBinding = new AxisBinding(); this.touchPressureBindingInsp = new AxisBindingInspector(null, new GUIContent("Touch Pressure Binding"), false, InputRig.InputSource.Analog, this.DrawPressureBindingExtraGUI); } // ------------------ protected override void DrawHeader () { GUILayout.Box(GUIContent.none, CFEditorStyles.Inst.headerButton, GUILayout.ExpandWidth(true)); } // ------------------ protected void Init(TouchControlPanel panel, BindingSetup bindingSetup, System.Action onCreationCallback) { base.Init(panel, onCreationCallback); if (bindingSetup != null) { bindingSetup.Apply(this); } this.controlName = TouchControlWizardUtils.GetUniqueButtonName(panel.rig); this.defaultControlName = this.controlName; string uniqueNameSuffix = ""; if ((bindingSetup != null) && !string.IsNullOrEmpty(bindingSetup.pressAxis)) uniqueNameSuffix = bindingSetup.pressAxis; else if ((bindingSetup != null) && !string.IsNullOrEmpty(bindingSetup.toggleAxis)) uniqueNameSuffix = bindingSetup.toggleAxis; if (!string.IsNullOrEmpty(uniqueNameSuffix)) this.controlName = (uniqueNameSuffix + "-Button"); this.defaultSprite = TouchControlWizardUtils.GetDefaultButtonSprite(uniqueNameSuffix); } // --------------------- override protected void DrawBindingGUI() { InspectorUtils.BeginIndentedSection(new GUIContent("Binding")); this.pressBindingInsp.Draw(this.pressBinding, this.panel.rig); this.touchPressureBindingInsp.Draw(this.touchPressureBinding, this.panel.rig); this.toggleBindingInsp.Draw(this.toggleBinding, this.panel.rig); InspectorUtils.EndIndentedSection(); } // -------------------- override protected void OnCreatePressed(bool selectAfterwards) { ControlFreak2.TouchButton button = (ControlFreak2.TouchButton)this.CreateDynamicTouchControl(typeof(ControlFreak2.TouchButton)); TouchControlWizardUtils.CreateButtonAnimator(button, "-Sprite", this.defaultSprite, 1.0f); if (this.pressBinding.enabled) button.pressBinding.CopyFrom(this.pressBinding); if (this.touchPressureBinding.enabled) { button.touchPressureBinding.CopyFrom(this.touchPressureBinding); button.emulateTouchPressure = this.emulateTouchPressure; } if (this.toggleBinding.enabled) { button.toggle = true; button.toggleOnlyBinding.CopyFrom(this.toggleBinding); } Undo.RegisterCreatedObjectUndo(button.gameObject, "Create Touch Button"); if (selectAfterwards) Selection.activeObject = button; } // ------------------------- // Button Wizard Binding Setup class. // ------------------------ public class BindingSetup { public string pressAxis, toggleAxis; public KeyCode pressKey, toggleKey; // ----------------- static public BindingSetup PressAxis (string pressAxis) { return (new BindingSetup(pressAxis)); } static public BindingSetup PressKey (KeyCode pressKey) { return (new BindingSetup(null, pressKey)); } static public BindingSetup PressKeyOrAxis (KeyCode pressKey, string pressAxis) { return (new BindingSetup(pressAxis, pressKey)); } static public BindingSetup ToggleAxis (string toggleAxis) { return (new BindingSetup(null, KeyCode.None, toggleAxis)); } static public BindingSetup ToggleKey (KeyCode toggleKey) { return (new BindingSetup(null, KeyCode.None, null, toggleKey)); } static public BindingSetup ToggleKeyOrAxis (KeyCode toggleKey, string toggleAxis) { return (new BindingSetup(null, KeyCode.None, toggleAxis, toggleKey)); } // -------------------- public BindingSetup(string pressAxis = null, KeyCode pressKey = KeyCode.None, string toggleAxis = null, KeyCode toggleKey = KeyCode.None) { this.pressAxis = pressAxis; this.pressKey = pressKey; this.toggleAxis = toggleAxis; this.toggleKey = toggleKey; } // ---------------------- public void Apply(TouchButtonCreationWizard wizard) { SetupDigitalBinding(wizard.pressBinding, this.pressAxis, this.pressKey); SetupDigitalBinding(wizard.toggleBinding, this.toggleAxis, this.toggleKey); } } } } #endif
29.482051
157
0.706384
[ "MIT" ]
ReiiYuki/Firebase-Unity-Realtime-Movement-Demo
Assets/Plugins/Control-Freak-2/Scripts/Editor-Scripts/Wizards/TouchButtonCreationWizard.cs
5,751
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using Onion.Application.Exceptions; using Xunit; using FluentAssertions; namespace Onion.Application.Tests.Exceptions { public partial class AccountExceptionTests { [Fact, Trait("Category", "Integration")] public void AccountException_Constructor_WithSerializableProperties() { // Arrange AccountException ex = new AccountException("Message", "Account"); AccountException deserializedEx; // Assert ex.Message.Should().Be("Message"); ex.Account.Should().Be("Account"); // Act string exception = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Fill exception with de-serialized one deserializedEx = (AccountException) bf.Deserialize(ms); } // Assert deserializedEx.Message.Should().Be("Message"); deserializedEx.Account.Should().Be("Account"); ex.ToString().Should().Be(deserializedEx.ToString()); } } }
32.041667
90
0.59883
[ "MIT" ]
tahq69/Onion
Onion.Application.Tests/Exceptions/AccountExceptionTests.cs
1,540
C#
using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace MyWindowsMediaPlayer.Model { [DataContract] public class Playlist { #region Fields #endregion #region Properties [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public ObservableCollection<Media> Medias { get; set; } #endregion #region Contructors public Playlist(int id, string name = "playlist") { this.Id = id; this.Name = name; this.Medias = new ObservableCollection<Media>(); } #endregion #region Methods public void AddToPlaylist(Media media) { this.Medias.Add(media); } public void RemoveFromPlaylist(Media media) { this.Medias.Remove(media); } #endregion } }
21.577778
63
0.556128
[ "Apache-2.0" ]
kortescode/My-Windows-Media-Player
MyWindowsMediaPlayer/Model/Playlist.cs
973
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V3109 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public partial class UKCT_MT140701UK01InFulfillmentOfTemplateId { private UKCT_MT140701UK01InFulfillmentOfTemplateIdRoot rootField; private UKCT_MT140701UK01InFulfillmentOfTemplateIdExtension extensionField; private string assigningAuthorityNameField; private bool displayableField; private bool displayableFieldSpecified; private static System.Xml.Serialization.XmlSerializer serializer; [System.Xml.Serialization.XmlAttributeAttribute()] public UKCT_MT140701UK01InFulfillmentOfTemplateIdRoot root { get { return this.rootField; } set { this.rootField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public UKCT_MT140701UK01InFulfillmentOfTemplateIdExtension extension { get { return this.extensionField; } set { this.extensionField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string assigningAuthorityName { get { return this.assigningAuthorityNameField; } set { this.assigningAuthorityNameField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool displayable { get { return this.displayableField; } set { this.displayableField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool displayableSpecified { get { return this.displayableFieldSpecified; } set { this.displayableFieldSpecified = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT140701UK01InFulfillmentOfTemplateId)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT140701UK01InFulfillmentOfTemplateId object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT140701UK01InFulfillmentOfTemplateId object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT140701UK01InFulfillmentOfTemplateId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT140701UK01InFulfillmentOfTemplateId obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT140701UK01InFulfillmentOfTemplateId); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT140701UK01InFulfillmentOfTemplateId obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT140701UK01InFulfillmentOfTemplateId Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT140701UK01InFulfillmentOfTemplateId)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT140701UK01InFulfillmentOfTemplateId object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT140701UK01InFulfillmentOfTemplateId object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT140701UK01InFulfillmentOfTemplateId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT140701UK01InFulfillmentOfTemplateId obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT140701UK01InFulfillmentOfTemplateId); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT140701UK01InFulfillmentOfTemplateId obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT140701UK01InFulfillmentOfTemplateId LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT140701UK01InFulfillmentOfTemplateId object /// </summary> public virtual UKCT_MT140701UK01InFulfillmentOfTemplateId Clone() { return ((UKCT_MT140701UK01InFulfillmentOfTemplateId)(this.MemberwiseClone())); } #endregion } }
44.008032
1,358
0.596824
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V3109/Generated/UKCT_MT140701UK01InFulfillmentOfTemplateId.cs
10,958
C#
using System; namespace Sfa.Tl.Matching.Domain { public class MergeKeyAttribute : Attribute { //this is a placeholder Attribute used to identify which column to use when comparing two tables for merge } }
25.111111
114
0.721239
[ "MIT" ]
SkillsFundingAgency/tl-matching
src/Sfa.Tl.Matching.Domain/MergeKeyAttribute.cs
228
C#
using System; namespace Gwen.UnitTest { public class UnitTestAttribute : Attribute { public string Category { get; set; } public int Order { get; set; } public string Name { get; set; } public UnitTestAttribute() { Order = Int32.MaxValue; } } }
15.647059
43
0.669173
[ "MIT" ]
Yeyti/Gwen.CS
Gwen.UnitTest/Attributes.cs
268
C#
//------------------------------------------------------------------------------ // <copyright file="LoginViewAdapter.cs" company="Aras Corporation"> // © 2017-2019 Aras Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Aras.VS.MethodPlugin.Dialogs.Views { public class LoginViewAdapter : ViewAdaper<LoginView,ViewResult> { public LoginViewAdapter(LoginView view) : base(view) { } public override ViewResult ShowDialog() { var result = view.ShowDialog(); return new ViewResult() { DialogOperationResult = result }; } } }
29.090909
81
0.535938
[ "MIT" ]
FilenkoAndriy/ArasVSMethodPlugin
Aras.VS.MethodPlugin/Dialogs/Views/LoginViewAdapter.cs
643
C#
using MongoDB.Driver; using MongoDB.Driver.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace MongoDB.Entities { public partial class Many<TChild> : IEnumerable<TChild> where TChild : IEntity { /// <summary> /// An IQueryable of JoinRecords for this relationship /// </summary> /// <param name="session">An optional session if using within a transaction</param> /// <param name="options">An optional AggregateOptions object</param> public IMongoQueryable<JoinRecord> JoinQueryable(IClientSessionHandle session = null, AggregateOptions options = null) { return session == null ? JoinCollection.AsQueryable(options) : JoinCollection.AsQueryable(session, options); } /// <summary> /// Get an IQueryable of parents matching a single child ID for this relationship. /// </summary> /// <typeparam name="TParent">The type of the parent IEntity</typeparam> /// <param name="childID">A child ID</param> /// <param name="session">An optional session if using within a transaction</param> /// <param name="options">An optional AggregateOptions object</param> public IMongoQueryable<TParent> ParentsQueryable<TParent>(string childID, IClientSessionHandle session = null, AggregateOptions options = null) where TParent : IEntity { return ParentsQueryable<TParent>(new[] { childID }, session, options); } /// <summary> /// Get an IQueryable of parents matching multiple child IDs for this relationship. /// </summary> /// <typeparam name="TParent">The type of the parent IEntity</typeparam> /// <param name="childIDs">An IEnumerable of child IDs</param> /// <param name="session">An optional session if using within a transaction</param> /// <param name="options">An optional AggregateOptions object</param> public IMongoQueryable<TParent> ParentsQueryable<TParent>(IEnumerable<string> childIDs, IClientSessionHandle session = null, AggregateOptions options = null) where TParent : IEntity { if (typeof(TParent) == typeof(TChild)) throw new InvalidOperationException("Both parent and child types cannot be the same"); if (isInverse) { return JoinQueryable(session, options) .Where(j => childIDs.Contains(j.ParentID)) .Join( DB.Collection<TParent>(), j => j.ChildID, p => p.ID, (_, p) => p) .Distinct(); } else { return JoinQueryable(session, options) .Where(j => childIDs.Contains(j.ChildID)) .Join( DB.Collection<TParent>(), j => j.ParentID, p => p.ID, (_, p) => p) .Distinct(); } } /// <summary> /// Get an IQueryable of parents matching a supplied IQueryable of children for this relationship. /// </summary> /// <typeparam name="TParent">The type of the parent IEntity</typeparam> /// <param name="children">An IQueryable of children</param> /// <param name="session">An optional session if using within a transaction</param> /// <param name="options">An optional AggregateOptions object</param> public IMongoQueryable<TParent> ParentsQueryable<TParent>(IMongoQueryable<TChild> children, IClientSessionHandle session = null, AggregateOptions options = null) where TParent : IEntity { if (typeof(TParent) == typeof(TChild)) throw new InvalidOperationException("Both parent and child types cannot be the same"); if (isInverse) { return children .Join( JoinQueryable(session, options), c => c.ID, j => j.ParentID, (_, j) => j) .Join( DB.Collection<TParent>(), j => j.ChildID, p => p.ID, (_, p) => p) .Distinct(); } else { return children .Join( JoinQueryable(session, options), c => c.ID, j => j.ChildID, (_, j) => j) .Join( DB.Collection<TParent>(), j => j.ParentID, p => p.ID, (_, p) => p) .Distinct(); } } /// <summary> /// An IQueryable of child Entities for the parent. /// </summary> /// <param name="session">An optional session if using within a transaction</param> /// <param name="options">An optional AggregateOptions object</param> public IMongoQueryable<TChild> ChildrenQueryable(IClientSessionHandle session = null, AggregateOptions options = null) { parent.ThrowIfUnsaved(); if (isInverse) { return JoinQueryable(session, options) .Where(j => j.ChildID == parent.ID) .Join( DB.Collection<TChild>(), j => j.ParentID, c => c.ID, (_, c) => c); } else { return JoinQueryable(session, options) .Where(j => j.ParentID == parent.ID) .Join( DB.Collection<TChild>(), j => j.ChildID, c => c.ID, (_, c) => c); } } /// <inheritdoc/> public IEnumerator<TChild> GetEnumerator() => ChildrenQueryable().GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => ChildrenQueryable().GetEnumerator(); } }
43.810458
194
0.487095
[ "MIT" ]
cuongdo926/MongoDB.Entities
MongoDB.Entities/Relationships/Many.Queryable.cs
6,705
C#
using System; namespace nac.Forms.lib { public class Util { public static bool CanChangeType<T>(object val, out T valConvertedToT) { valConvertedToT = default(T); try { var result = Convert.ChangeType(val, typeof(T)); if (result is T newVal) { valConvertedToT = newVal; return true; } } catch { } return false; } } }
20.592593
78
0.413669
[ "MIT" ]
Nathan-TheGeek/dotnetCoreAvaloniaNCForms
nac.Forms/lib/Util.cs
558
C#
namespace OrdersApp.Domain.Core { public class OrderDetail { public Order Order { get; set; } public int Quantity { get; set; } public Product Product { get; set; } } }
20.6
44
0.587379
[ "Apache-2.0" ]
acnagrellos/NetCoreDemo
OrdersApp/4.Domain/OrdersApp.Domain.Core/OrderDetail.cs
208
C#
namespace Domain { public class Associado : Usuario { } }
10.142857
36
0.591549
[ "MIT" ]
WillaOnStenci/Arca
backend/ContaMicroservice/Domain/Associado.cs
73
C#
/******************************************************************************* * 类 名 称:SerializationHelper * 命名空间:HOTINST.COMMON.Serialization * 文 件 名:XMLSerializationHelper.cs * 创建时间:2014-10-9 * 作 者:谭玉 * 说 明:XML序列化及反序列化 * 修改时间: * 修改历史: * 2016.5.4 汪锋 添加注释 * 2016.5.25 汪锋 新增对象序列化成XML格式字符串SaveToXmlString * 2016.5.25 汪锋 新增XML格式字符串反序列化成对象LoadFromXmlString *******************************************************************************/ using System; using System.IO; using System.Text; using System.Xml.Serialization; namespace HOTINST.COMMON.Serialization { public partial class SerializationHelper { /// <summary> /// 序列化到XML文件 /// </summary> /// <typeparam name="T">要序列化对象的数据类型</typeparam> /// <param name="filePath">文件名(含路径)</param> /// <param name="sourceObj">待序列化的对象</param> /// <param name="xmlRootName">XML根节点名称</param> public static void SaveToXml<T>(string filePath, T sourceObj, string xmlRootName) { if(string.IsNullOrWhiteSpace(xmlRootName)) { throw new ArgumentNullException(nameof(xmlRootName), "请指定根节点名称。"); } try { if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null) { using (StreamWriter writer = new StreamWriter(filePath, false)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(writer, sourceObj); } } } catch (Exception ex) { System.Diagnostics.Debug.Print(ex.Message); } } /// <summary> /// 从XML文件反序列化到变量 /// </summary> /// <typeparam name="T">要反序列化对象的数据类型</typeparam> /// <param name="filePath">文件名(含路径)</param> /// <param name="xmlRootName">XML根节点名称</param> /// <returns>返回反序列化后指定数据类型的变量</returns> public static T LoadFromXml<T>(string filePath, string xmlRootName) { if(string.IsNullOrWhiteSpace(xmlRootName)) { throw new ArgumentNullException(nameof(xmlRootName), "请指定根节点名称。"); } T result = default(T); try { if (File.Exists(filePath)) { using (StreamReader reader = new StreamReader(filePath)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(reader); } } } catch (Exception ex) { System.Diagnostics.Debug.Print(ex.Message); throw; } return result; } /// <summary> /// 序列化成XML格式的字符串 /// </summary> /// <typeparam name="T">要序列化对象的数据类型</typeparam> /// <param name="sourceObj">待序列化的对象</param> /// <param name="xmlRootName">XML根节点名称</param> /// <returns>序列化成功返回XML格式的字符串,失败则返回空字符串</returns> public static string SaveToXmlString<T>(T sourceObj, string xmlRootName) { if(string.IsNullOrWhiteSpace(xmlRootName)) { throw new ArgumentNullException(nameof(xmlRootName), "请指定根节点名称。"); } try { if (sourceObj != null) { using (MemoryStream objMemoryStream = new MemoryStream()) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(objMemoryStream, sourceObj); return Encoding.UTF8.GetString(objMemoryStream.ToArray()); } } } catch (Exception ex) { System.Diagnostics.Debug.Print(ex.Message); } return string.Empty; } /// <summary> /// 从XML格式的字符串反序列化到变量 /// </summary> /// <typeparam name="T">要反序列化对象的数据类型</typeparam> /// <param name="xmlString">XML格式的字符串</param> /// <param name="xmlRootName">XML根节点名称</param> /// <returns>返回反序列化后指定数据类型的变量</returns> public static T LoadFromXmlString<T>(string xmlString, string xmlRootName) { if(string.IsNullOrWhiteSpace(xmlRootName)) { throw new ArgumentNullException(nameof(xmlRootName), "请指定根节点名称。"); } T result = default(T); try { if (!string.IsNullOrWhiteSpace(xmlString)) { using (MemoryStream objMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString))) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); result = (T)xmlSerializer.Deserialize(objMemoryStream); } } } catch (Exception ex) { System.Diagnostics.Debug.Print(ex.Message); } return result; } } }
33.506329
118
0.519078
[ "Apache-2.0" ]
tyeagle/Hotinst
Source/HOTINST.COMMON/HOTINST.COMMON/Serialization/XMLSerializationHelper.cs
5,924
C#
using BepInEx.Configuration; // ReSharper disable ConvertToConstant.Local namespace Pasukaru.DSP.AutoStationConfig { public static class Config { private static readonly string GENERAL_SECTION = "General"; private static readonly string PLS_SECTION = "Planetary Logistics Station"; private static readonly string ILS_SECTION = "Interstellar Logistics Station"; public static class General { public static ConfigEntry<bool> NotifyWhenDroneOrVesselMissing; public static ConfigEntry<bool> PlaySoundWhenDroneOrVesselMissing; } public static class PLS { public static ConfigEntry<int> ChargingPowerInPercent; public static ConfigEntry<int> DroneTransportRange; public static ConfigEntry<int> MinDroneLoad; public static ConfigEntry<double> DroneInsertPercentage; } public static class ILS { public static ConfigEntry<int> ChargingPowerInPercent; public static ConfigEntry<int> DroneTransportRange; public static ConfigEntry<int> MinDroneLoad; public static ConfigEntry<double> DroneInsertPercentage; public static ConfigEntry<int> VesselTransportRange; public static ConfigEntry<int> MinVesselLoad; public static ConfigEntry<double> VesselInsertPercentage; public static ConfigEntry<double> MinWarpDistance; public static ConfigEntry<bool> WarperInLastItemSlot; public static ConfigEntry<ELogisticStorage> WarperLocalMode; public static ConfigEntry<ELogisticStorage> WarperRemoteMode; public static ConfigEntry<bool> UseOrbitalCollectors; public static ConfigEntry<bool> MustEquipWarp; } internal static void Init(ConfigFile config) { //////////////////// // General Config // //////////////////// General.NotifyWhenDroneOrVesselMissing = config.Bind(GENERAL_SECTION, "Notify when Drone or Vessel missing", true, "Sends a notification when there are not enough drones or vessel in your inventory to auto fill"); General.PlaySoundWhenDroneOrVesselMissing = config.Bind(GENERAL_SECTION, "Play sound when Drone or Vessel missing", true, "Plays a sound along to the drone/vessel notification. Only works when the notification is turned on."); //////////////// // PLS Config // //////////////// // Slider in Game UI uses prefabDesc.workEnergyPerTick*5 as MAX // prefabDesc.workEnergyPerTick/2 as MIN. // Which means, MIN = 10% // Slider increments in 1%, so int range 10-100 is a perfect fit PLS.ChargingPowerInPercent = config.Bind(PLS_SECTION, "Charging Power", 100, new ConfigDescription( "Maximum power load in percent. For a vanilla PLS, 10% = 6MW, 100% = 60MW", new AcceptableValueRange<int>(10, 100), new { } ) ); // Slider in Game UI uses 20° - 180° Which will be converted to an internal representation. See: Util.ConvertDegreesToDroneRange // Slider increments in 1°, so int range 20-180 is a perfect fit PLS.DroneTransportRange = config.Bind(PLS_SECTION, "Drone Transport Range", 180, new ConfigDescription( "Planetary Drone range in degrees (°).", new AcceptableValueRange<int>(20, 180), new { } ) ); // Slider allows 1, 10, 20, 30, ...100% PLS.MinDroneLoad = config.Bind(PLS_SECTION, "Min Load of Drones", 100, new ConfigDescription( "Min. Load of Drones in percent.", new AcceptableValueRange<int>(1,100), new { } ) ); PLS.DroneInsertPercentage = config.Bind(PLS_SECTION, "Drone Insert Percentage", 1d, new ConfigDescription( "Amount of drones to insert. For vanilla PLS, 0.05 = 5% = 50/100*5 = 2.5, rounded down to 2.", new AcceptableValueRange<double>(0, 1), new { } ) ); //////////////// // ILS Config // //////////////// ILS.ChargingPowerInPercent = config.Bind(ILS_SECTION, "Charging Power", 100, new ConfigDescription( "Maximum power load in percent. For a vanilla ILS, 10% = 30MW, 100% = 300MW", new AcceptableValueRange<int>(10, 100), new { } ) ); ILS.DroneTransportRange = config.Bind(ILS_SECTION, "Drone Transport Range", 180, new ConfigDescription( "Planetary Drone range in degrees (°).", new AcceptableValueRange<int>(20, 180), new { } ) ); ILS.MinDroneLoad = config.Bind(ILS_SECTION, "Min Load of Drones", 100, new ConfigDescription( "Min. Load of Drones in percent.", new AcceptableValueRange<int>(1,100), new { } ) ); ILS.DroneInsertPercentage = config.Bind(ILS_SECTION, "Drone Insert Percentage", 1d, new ConfigDescription( "Amount of drones to insert. For vanilla ILS, 0.05 = 5% = 50/100*5 = 2.5, rounded down to 2.", new AcceptableValueRange<double>(0, 1), new { } ) ); ILS.VesselTransportRange = config.Bind(ILS_SECTION, "Vessel Transport Range", 10000, new ConfigDescription( "Interstellar Vessel range in Light Years (LY). 10000 = infinite", new AcceptableValueList<int>(1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 10000), new { } ) ); ILS.MinVesselLoad = config.Bind(ILS_SECTION, "Min Load of Vessels", 100, new ConfigDescription( "Min. Load of Vessels in percent.", new AcceptableValueRange<int>(1,100), new { } ) ); ILS.VesselInsertPercentage = config.Bind(ILS_SECTION, "Vessel Insert Percentage", 1d, new ConfigDescription( "Amount of vessels to insert. 0.01 = 1%. For vanilla ILS, 0.15 => 10/100*15 = 1.5, rounded down to 1.", new AcceptableValueRange<double>(0, 1), new { } ) ); ILS.MinWarpDistance = config.Bind(ILS_SECTION, "Distance to enable Warp", 0.5, new ConfigDescription( "Minimum distance to enable warp in AUs. 0.5 to 60", new AcceptableValueList<double>(0.5, 1, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 60), new { } ) ); ILS.WarperInLastItemSlot = config.Bind(ILS_SECTION, "Add Warpers in last Slot", true, "If true, the last item slot will automatically select Space Warpers" ); ILS.WarperLocalMode = config.Bind(ILS_SECTION, "Warper Local Mode", ELogisticStorage.Demand, "Local logistics mode of the Warpers when \"Add Warpers in last Slot\" is true" ); ILS.WarperRemoteMode = config.Bind(ILS_SECTION, "Warper Remote Mode", ELogisticStorage.None, "Remote logistics mode of the Warpers when \"Add Warpers in last Slot\" is true" ); ILS.UseOrbitalCollectors = config.Bind(ILS_SECTION, "Pull from Orbital Collectors?", true, "Toggle to retrieve from Orbital collectors."); ILS.MustEquipWarp = config.Bind(ILS_SECTION, "Must Equip Warpers", true, "Toggle for must equip warpers."); } } }
43.820513
140
0.537741
[ "MIT" ]
Pasukaru/DSP-Mods
AutoStationConfig/Config.cs
8,552
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using React_Demo.Models; namespace React_Demo.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(GetData()); } private List<Product> GetData() { var turboData = new List<Product>() { new Product{ Title = "Garrett Dual Ball Bearing GT2554R", SKU = "GAR-471171-3", Brand = "Garrett", Price = 1168.44, Image = "gt2554r.jpg" }, new Product{ Title = "Garrett Dual Ball Bearing GT2560R", SKU = "GAR-GT2560R", Brand = "Garrett", Price = 1188.76, Image = "gt2560r.jpg" }, new Product{ Title = "Garrett Dual Ball Bearing GT2854R", SKU = "GAR-471171-3", Brand = "Garrett", Price = 1169.47, Image = "gt2854r.jpg" }, new Product{ Title = "Garrett Dual Ball Bearing GT2859R", SKU = "GAR-GT2859R", Brand = "Garrett", Price = 1151.56, Image = "gt2859r.jpg" }, new Product{ Title = "Garrett Dual Ball Bearing GT2860R", SKU = "GAR-GT2860R", Brand = "Garrett", Price = 1210.64, Image = "gt2860r.jpg" }, new Product{ Title = "Garrett Dual Ball Bearing GT2860RS (Disco Potato)", SKU = "GAR-GT2860RS", Brand = "Garrett", Price = 1318.74, Image = "gt2860rs.jpg" }, }; return turboData; } } }
31.362319
80
0.401571
[ "Unlicense" ]
JustinCoded/ReactJS_TS_MVC
React-Demo-Starter/React-Demo/Controllers/HomeController.cs
2,166
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipayMarketingCampaignPrizeAmountQueryResponse. /// </summary> public class AlipayMarketingCampaignPrizeAmountQueryResponse : AopResponse { /// <summary> /// 奖品剩余数量,数值 /// </summary> [XmlElement("remain_amount")] public string RemainAmount { get; set; } } }
24.111111
79
0.612903
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/AlipayMarketingCampaignPrizeAmountQueryResponse.cs
452
C#
using System; using Kopernicus.ConfigParser.BuiltinTypeParsers; using UnityEngine; using UnityEngine.UI; using static KittopiaTech.UI.Framework.Declaration.DialogGUI; using Object = System.Object; namespace KittopiaTech.UI.ValueEditors { public class NumericCollectionEditor<TNum, TEd> : ValueEditor where TEd : ValueEditor { protected override void BuildDialog() { // Skin Skin = KittopiaTech.Skin; // Build a list of collection elements NumericCollectionParser<TNum> collectionParser = (NumericCollectionParser<TNum>) GetValue(); // Display a scroll area GUIScrollList(new Vector2(290, 400), false, true, () => { GUIVerticalLayout(true, false, 2f, new RectOffset(8, 26, 8, 8), TextAnchor.UpperLeft, () => { GUIContentSizer(ContentSizeFitter.FitMode.Unconstrained, ContentSizeFitter.FitMode.PreferredSize, true); // Use a box as a seperator GUISpace(5f); GUIBox(-1f, 1f, () => { }); GUISpace(5f); // Display all elements for (Int32 j = 0; j < collectionParser.Value.Count; j++) { Int32 i = j; // Add / Remove Buttons GUIHorizontalLayout(() => { GUIFlexibleSpace(); GUIButton("V", () => { TNum tmp = collectionParser.Value[i]; collectionParser.Value[i] = collectionParser.Value[i - 1]; collectionParser.Value[i - 1] = tmp; SetValue(collectionParser); }, 25f, 25f, false, () => { }, Enabled<DialogGUIButton>(() => i != 0).And(Rotation<DialogGUIButton>(180, 0, 0)) .And(Scale<DialogGUIButton>(0.7f))); GUIButton("V", () => { TNum tmp = collectionParser.Value[i]; collectionParser.Value[i] = collectionParser.Value[i + 1]; collectionParser.Value[i + 1] = tmp; SetValue(collectionParser); }, 25f, 25f, false, () => { }, Enabled<DialogGUIButton>(() => i != collectionParser.Value.Count - 1) .And(Scale<DialogGUIButton>(0.7f))); GUIButton("+", () => { collectionParser.Value.Insert(i, default(TNum)); SetValue(collectionParser); Redraw(); }, 25f, 25f, false, () => { }); GUIButton("x", () => { collectionParser.Value.RemoveAt(i); SetValue(collectionParser); Redraw(); }, 25f, 25f, false, () => { }); }); // Display the editor Integrate((ValueEditor) Activator.CreateInstance(typeof(TEd), _name + " - I:" + i, new Func<Object>(() => Reference), new Func<Object>(() => collectionParser.Value[i]), new Action<Object>(s => { collectionParser.Value[i] = (NumericParser<TNum>) s; SetValue(collectionParser); }) )); // Use a box as a seperator GUISpace(5f); GUIBox(-1f, 1f, () => { }); GUISpace(5f); } if (collectionParser.Value.Count == 0) { // Add / Remove Buttons GUIHorizontalLayout(() => { GUIButton("+", () => { collectionParser.Value.Insert(collectionParser.Value.Count, default(TNum)); SetValue(collectionParser); Redraw(); }, 25f, 25f, false, () => { }); }); // Use a box as a seperator GUISpace(5f); GUIBox(-1f, 1f, () => { }); GUISpace(5f); } }); }); } public override Single GetWidth() { return 400; } public NumericCollectionEditor(String name, Func<Object> reference, Func<Object> getValue, Action<Object> setValue) : base(name, reference, getValue, setValue) { } } }
43.585366
167
0.38892
[ "MIT" ]
Kopernicus/KittopiaTech
src/UI/ValueEditors/NumericCollectionEditor.cs
5,363
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Extensions.Configuration; namespace DevFlexer.RemoteConfigurationService.Client.Parsers { public class XmlConfigurationFileParser : IConfigurationFileParser { private const string NameAttributeKey = "Name"; private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase); public IDictionary<string, string> Parse(Stream input) => ParseStream(input); private IDictionary<string, string> ParseStream(Stream input) { _data.Clear(); var readerSettings = new XmlReaderSettings() { CloseInput = false, DtdProcessing = DtdProcessing.Prohibit, IgnoreComments = true, IgnoreWhitespace = true }; using (var reader = CreateXmlReader(input, readerSettings)) { var prefixStack = new Stack<string>(); SkipUntilRootElement(reader); ProcessAttributes(reader, prefixStack, _data, AddNamePrefix); ProcessAttributes(reader, prefixStack, _data, AddAttributePair); var preNodeType = reader.NodeType; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: prefixStack.Push(reader.LocalName); ProcessAttributes(reader, prefixStack, _data, AddNamePrefix); ProcessAttributes(reader, prefixStack, _data, AddAttributePair); if (reader.IsEmptyElement) { prefixStack.Pop(); } break; case XmlNodeType.EndElement: if (prefixStack.Any()) { if (preNodeType == XmlNodeType.Element) { var key = ConfigurationPath.Combine(prefixStack.Reverse()); _data[key] = string.Empty; } prefixStack.Pop(); } break; case XmlNodeType.CDATA: case XmlNodeType.Text: { var key = ConfigurationPath.Combine(prefixStack.Reverse()); if (_data.ContainsKey(key)) { throw new FormatException($"A duplicate key '{key}' was found."); } _data[key] = reader.Value; break; } case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: break; default: throw new FormatException($"Unsupported node type '{reader.NodeType}' was found."); } preNodeType = reader.NodeType; if (preNodeType == XmlNodeType.Element && reader.IsEmptyElement) { preNodeType = XmlNodeType.EndElement; } } } return _data; } private static XmlReader CreateXmlReader(Stream input, XmlReaderSettings settings) { var memStream = new MemoryStream(); input.CopyTo(memStream); memStream.Position = 0; var document = new XmlDocument(); using (var reader = XmlReader.Create(memStream, settings)) { document.Load(reader); } memStream.Position = 0; return XmlReader.Create(memStream, settings); } private static void SkipUntilRootElement(XmlReader reader) { while (reader.Read()) { if (reader.NodeType != XmlNodeType.XmlDeclaration && reader.NodeType != XmlNodeType.ProcessingInstruction) { break; } } } private static void ProcessAttributes(XmlReader reader, Stack<string> prefixStack, IDictionary<string, string> data, Action<XmlReader, Stack<string>, IDictionary<string, string>, XmlWriter> action, XmlWriter writer = null) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (!string.IsNullOrEmpty(reader.NamespaceURI)) { throw new FormatException("Namespace is not supported."); } action(reader, prefixStack, data, writer); } reader.MoveToElement(); } private static void AddNamePrefix(XmlReader reader, Stack<string> prefixStack, IDictionary<string, string> data, XmlWriter writer) { if (!string.Equals(reader.LocalName, NameAttributeKey, StringComparison.OrdinalIgnoreCase)) { return; } if (prefixStack.Any()) { var lastPrefix = prefixStack.Pop(); prefixStack.Push(ConfigurationPath.Combine(lastPrefix, reader.Value)); } else { prefixStack.Push(reader.Value); } } private static void AddAttributePair(XmlReader reader, Stack<string> prefixStack, IDictionary<string, string> data, XmlWriter writer) { prefixStack.Push(reader.LocalName); var key = ConfigurationPath.Combine(prefixStack.Reverse()); if (data.ContainsKey(key)) { throw new FormatException($"A duplicate key '{key}' was found."); } data[key] = reader.Value; prefixStack.Pop(); } } }
36.071823
132
0.485526
[ "MIT" ]
devflexer/DevFlexer.RemoteConfigurationService
src/DevFlexer.RemoteConfigurationService.Client/Parsers/XmlConfigurationFileParser.cs
6,531
C#
namespace TheTankGame.Core { using System; using System.Collections.Generic; using System.Linq; using Contracts; using IO.Contracts; public class Engine : IEngine { private bool isRunning; private readonly IReader reader; private readonly IWriter writer; private readonly ICommandInterpreter commandInterpreter; public Engine( IReader reader, IWriter writer, ICommandInterpreter commandInterpreter) { this.reader = reader; this.writer = writer; this.commandInterpreter = commandInterpreter; this.isRunning = false; } public void Run() { this.isRunning = true; while(this.isRunning == true) { List<string> inputParameters = reader.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).ToList(); writer.WriteLine(this.commandInterpreter.ProcessInput(inputParameters)); if(inputParameters[0] == "Terminate") { this.isRunning = false; } } } } }
27.636364
124
0.553454
[ "MIT" ]
PETROV442518/SoftUni
TheTankGame/TheTankGame/Core/Engine.cs
1,218
C#
namespace SpellforceDataEditor.special_forms { partial class SaveDataEditorForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TreeChunks = new System.Windows.Forms.TreeView(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.RawData = new System.Windows.Forms.RichTextBox(); this.ButtonUnpack = new System.Windows.Forms.Button(); this.ButtonExtract = new System.Windows.Forms.Button(); this.OpenSave = new System.Windows.Forms.OpenFileDialog(); this.LabelChunkData = new System.Windows.Forms.Label(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // TreeChunks // this.TreeChunks.Location = new System.Drawing.Point(12, 27); this.TreeChunks.Name = "TreeChunks"; this.TreeChunks.Size = new System.Drawing.Size(236, 444); this.TreeChunks.TabIndex = 0; this.TreeChunks.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeChunks_AfterSelect); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1032, 24); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.Size = new System.Drawing.Size(103, 22); this.openToolStripMenuItem.Text = "Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // statusStrip1 // this.statusStrip1.Location = new System.Drawing.Point(0, 502); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(1032, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // RawData // this.RawData.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.RawData.Location = new System.Drawing.Point(254, 53); this.RawData.Name = "RawData"; this.RawData.ReadOnly = true; this.RawData.Size = new System.Drawing.Size(766, 418); this.RawData.TabIndex = 3; this.RawData.Text = "testing"; // // ButtonUnpack // this.ButtonUnpack.Location = new System.Drawing.Point(254, 477); this.ButtonUnpack.Name = "ButtonUnpack"; this.ButtonUnpack.Size = new System.Drawing.Size(75, 23); this.ButtonUnpack.TabIndex = 4; this.ButtonUnpack.Text = "Unpack"; this.ButtonUnpack.UseVisualStyleBackColor = true; this.ButtonUnpack.Click += new System.EventHandler(this.ButtonUnpack_Click); // // ButtonExtract // this.ButtonExtract.Location = new System.Drawing.Point(945, 476); this.ButtonExtract.Name = "ButtonExtract"; this.ButtonExtract.Size = new System.Drawing.Size(75, 23); this.ButtonExtract.TabIndex = 5; this.ButtonExtract.Text = "Extract"; this.ButtonExtract.UseVisualStyleBackColor = true; this.ButtonExtract.Click += new System.EventHandler(this.ButtonExtract_Click); // // OpenSave // this.OpenSave.Filter = "All files|*.*|Save files (.sav)|*.sav"; // // LabelChunkData // this.LabelChunkData.AutoSize = true; this.LabelChunkData.Location = new System.Drawing.Point(254, 37); this.LabelChunkData.Name = "LabelChunkData"; this.LabelChunkData.Size = new System.Drawing.Size(38, 13); this.LabelChunkData.TabIndex = 6; this.LabelChunkData.Text = "testing"; // // SaveDataEditorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1032, 524); this.Controls.Add(this.LabelChunkData); this.Controls.Add(this.ButtonExtract); this.Controls.Add(this.ButtonUnpack); this.Controls.Add(this.RawData); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.TreeChunks); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "SaveDataEditorForm"; this.Text = "SaveDataEditorForm"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TreeView TreeChunks; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.RichTextBox RawData; private System.Windows.Forms.Button ButtonUnpack; private System.Windows.Forms.Button ButtonExtract; private System.Windows.Forms.OpenFileDialog OpenSave; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.Label LabelChunkData; } }
45.871166
160
0.601846
[ "MIT" ]
leszekd25/spellforce_data_editor
SpellforceDataEditor/special forms/SaveDataEditorForm.Designer.cs
7,479
C#
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Cache; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform; using Microsoft.VisualStudio.TestTools.UnitTesting; using Test.ADAL.NET.Common; using Test.ADAL.NET.Common.Mocks; namespace Test.ADAL.NET.Unit { /// <summary> /// This test class executes and validates OBO scenarios where token cache may or may not /// contain entries with user assertion hash. It accounts for cases where there is /// a single user and when there are multiple users in the cache. /// user assertion hash exists so that the API can deterministically identify the user /// in the cache when a usernae is not passed in. It also allows the API to acquire /// new token when a different assertion is passed for the user. this is needed because /// the user may have authenticated with updated claims like MFA/device auth on the client. /// </summary> [TestClass] public class OboFlowTests { private readonly DateTimeOffset _expirationTime = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(30); private static readonly string[] _cacheNoise = { "", "different" }; [TestInitialize] public void TestInitialize() { HttpMessageHandlerFactory.InitializeMockProvider(); ResetInstanceDiscovery(); } public void ResetInstanceDiscovery() { InstanceDiscovery.InstanceCache.Clear(); HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant))); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserNoHashInCacheNoUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; foreach (var cachenoise in _cacheNoise) { //cache entry has no user assertion hash await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); } ResetInstanceDiscovery(); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with no username. this will result in a network call because cache entry with no assertion hash is // treated as a cache miss. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First(x => x.UserAssertionHash != null).UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserNoHashInCacheMatchingUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; foreach (var cachenoise in _cacheNoise) { //cache entry has no user assertion hash await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); } ResetInstanceDiscovery(); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with matching username from cache entry. this will result in a network call // because cache entry with no assertion hash is treated as a cache miss. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First(x => x.UserAssertionHash != null).UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserNoHashInCacheDifferentUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; foreach (var cachenoise in _cacheNoise) { TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, cachenoise + TestConstants.DefaultUniqueId, cachenoise + TestConstants.DefaultDisplayableId); //cache entry has no user assertion hash context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, }; } ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); string displayableId2 = "extra" + TestConstants.DefaultDisplayableId; string uniqueId2 = "extra" + TestConstants.DefaultUniqueId; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(uniqueId2, displayableId2, TestConstants.DefaultResource), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with diferent username from cache entry. this will result in a network call // because cache lookup failed for non-existant user var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, "non-existant" + TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(displayableId2, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(3, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First(x => x.UserAssertionHash != null) .UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserWithHashInCacheNoUsernameAndMatchingAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; //cache entry has user assertion hash string tokenInCache = "obo-access-token"; foreach (var cachenoise in _cacheNoise) { TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, cachenoise + TestConstants.DefaultUniqueId, cachenoise + TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(cachenoise + accessToken) }; } ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with no username and matching assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.IsNotNull(result.AccessToken); Assert.AreEqual(tokenInCache, result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserWithHashInCacheNoUsernameAndDifferentAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; //cache entry has user assertion hash string tokenInCache = "obo-access-token"; foreach (var cachenoise in _cacheNoise) { await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(cachenoise + accessToken) }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); } ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with no username and different assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion("non-existant" + accessToken)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserWithHashInCacheMatchingUsernameAndMatchingAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; //cache entry has user assertion hash string tokenInCache = "obo-access-token"; foreach (var cachenoise in _cacheNoise) { TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, cachenoise + TestConstants.DefaultUniqueId, cachenoise + TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(cachenoise + accessToken) }; } ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with matching username and matching assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.IsNotNull(result.AccessToken); Assert.AreEqual(tokenInCache, result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task MultiUserWithHashInCacheMatchingUsernameAndDifferentAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; //cache entry has user assertion hash string tokenInCache = "obo-access-token"; foreach (var cachenoise in _cacheNoise) { await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = cachenoise + "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", cachenoise + tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = cachenoise + TestConstants.DefaultDisplayableId, UniqueId = cachenoise + TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(cachenoise + accessToken) }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); } ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with matching username and different assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion("non-existant" + accessToken, OAuthGrantType.JwtBearer, TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserNoHashInCacheNoUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, //cache entry has no user assertion hash }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with no username. this will result in a network call because cache entry with no assertion hash is // treated as a cache miss. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserNoHashInCacheMatchingUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, //cache entry has no user assertion hash }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with matching username from cache entry. this will result in a network call // because cache entry with no assertion hash is treated as a cache miss. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserNoHashInCacheDifferentUsernamePassedInAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); //cache entry has no user assertion hash context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-token-in-cache", _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, }; ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); string displayableId2 = "extra" + TestConstants.DefaultDisplayableId; string uniqueId2 = "extra" + TestConstants.DefaultUniqueId; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(uniqueId2, displayableId2, TestConstants.DefaultResource), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); // call acquire token with diferent username from cache entry. this will result in a network call // because cache lookup failed for non-existant user var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, displayableId2 )).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(displayableId2, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First( s => s.Result.UserInfo != null && s.Result.UserInfo.DisplayableId.Equals(displayableId2)) .UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserWithHashInCacheNoUsernameAndMatchingAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); //cache entry has user assertion hash string tokenInCache = "obo-access-token"; context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(accessToken) }; ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with no username and matching assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.IsNotNull(result.AccessToken); Assert.AreEqual(tokenInCache, result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserWithHashInCacheNoUsernameAndDifferentAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; string tokenInCache = "obo-access-token"; await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(accessToken + "different") }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with no username and different assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserWithHashInCacheMatchingUsernameAndMatchingAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); //cache entry has user assertion hash string tokenInCache = "obo-access-token"; context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(accessToken) }; ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with matching username and matching assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.IsNotNull(result.AccessToken); Assert.AreEqual(tokenInCache, result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserWithHashInCacheMatchingUsernameAndDifferentAssertionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; string tokenInCache = "obo-access-token"; await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(accessToken + "different") }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with matching username and different assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientCredential, new UserAssertion(accessToken)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); //assertion hash should be stored in the cache entry. Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), context.TokenCache.tokenCacheDictionary.Values.First().UserAssertionHash); } [TestMethod] [TestCategory("OboFlowTests")] public async Task SingleUserWithHashInCacheMatchingUsernameAndMatchingAssertionDifferentResourceTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); string accessToken = "access-token"; TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.UserPlusClient, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); //cache entry has user assertion hash string tokenInCache = "obo-access-token"; context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", tokenInCache, _expirationTime) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, UserAssertionHash = CryptographyHelper.CreateSha256Hash(accessToken) }; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.AnotherResource, TestConstants.DefaultDisplayableId, TestConstants.DefaultUniqueId), PostData = new Dictionary<string, string>() { {"client_id", TestConstants.DefaultClientId}, {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"} } }); ClientCredential clientCredential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); // call acquire token with matching username and different assertion hash. this will result in a cache // hit. var result = await context.AcquireTokenAsync(TestConstants.AnotherResource, clientCredential, new UserAssertion(accessToken, OAuthGrantType.JwtBearer, TestConstants.DefaultDisplayableId)).ConfigureAwait(false); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount(), "all mocks should have been consumed"); Assert.IsNotNull(result.AccessToken); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); //there should be only one cache entry. Assert.AreEqual(2, context.TokenCache.Count); //assertion hash should be stored in the cache entry. foreach (var value in context.TokenCache.tokenCacheDictionary.Values) { Assert.AreEqual(CryptographyHelper.CreateSha256Hash(accessToken), value.UserAssertionHash); } } } }
52.353862
181
0.615073
[ "MIT" ]
jpda/azure-activedirectory-library-for-dotnet
tests/Test.ADAL.NET.Unit/OboFlowTests.cs
50,157
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.ObjectModel; using System.Speech.Internal; namespace System.Speech.Recognition.SrgsGrammar { [Serializable] internal class SrgsItemList : Collection<SrgsItem> { #region Interfaces Implementations protected override void InsertItem(int index, SrgsItem item) { Helpers.ThrowIfNull(item, nameof(item)); base.InsertItem(index, item); } #endregion } }
25.782609
71
0.686341
[ "MIT" ]
belav/runtime
src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItemList.cs
593
C#
using System; using System.Collections.Generic; using System.Text; namespace MXGP.Core.Contracts { public interface IEngine { } }
13.090909
33
0.715278
[ "MIT" ]
MrWeRtY/SoftUni-Repo
Exams/MotocrosWorldChampionshipMXGP/MXGP/Core/Contracts/IEngine.cs
146
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using OrchardCore.Admin; using OrchardCore.DisplayManagement.Theming; using OrchardCore.Entities; using OrchardCore.Settings; using OrchardCore.Users.Models; namespace OrchardCore.Users.Services { /// <summary> /// Provides the theme defined in the site configuration for the current scope (request). /// This selector provides AdminTheme as default or fallback for Account|Registration|ResetPassword /// controllers based on SiteSettings. /// The same <see cref="ThemeSelectorResult"/> is returned if called multiple times /// during the same scope. /// </summary> public class UsersThemeSelector : IThemeSelector { private readonly ISiteService _siteService; private readonly IAdminThemeService _adminThemeService; private readonly IHttpContextAccessor _httpContextAccessor; public UsersThemeSelector( ISiteService siteService, IAdminThemeService adminThemeService, IHttpContextAccessor httpContextAccessor) { _siteService = siteService; _adminThemeService = adminThemeService; _httpContextAccessor = httpContextAccessor; } public async Task<ThemeSelectorResult> GetThemeAsync() { var routeValues = _httpContextAccessor.HttpContext.Request.RouteValues; if (routeValues["area"]?.ToString() == "OrchardCore.Users") { bool useSiteTheme; switch (routeValues["controller"]?.ToString()) { case "Account": useSiteTheme = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>().UseSiteTheme; break; case "Registration": useSiteTheme = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>().UseSiteTheme; break; case "ResetPassword": useSiteTheme = (await _siteService.GetSiteSettingsAsync()).As<ResetPasswordSettings>().UseSiteTheme; break; default: return null; } var adminThemeName = await _adminThemeService.GetAdminThemeNameAsync(); if (String.IsNullOrEmpty(adminThemeName)) { return null; } return new ThemeSelectorResult { Priority = useSiteTheme ? -100 : 100, ThemeName = adminThemeName }; } return null; } } }
36.184211
124
0.594182
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore.Modules/OrchardCore.Users/Services/UsersThemeSelector.cs
2,750
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.IoTSiteWise; using Amazon.IoTSiteWise.Model; namespace Amazon.PowerShell.Cmdlets.IOTSW { /// <summary> /// Updates an IoT SiteWise Monitor project. /// </summary> [Cmdlet("Update", "IOTSWProject", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS IoT SiteWise UpdateProject API operation.", Operation = new[] {"UpdateProject"}, SelectReturnType = typeof(Amazon.IoTSiteWise.Model.UpdateProjectResponse))] [AWSCmdletOutput("None or Amazon.IoTSiteWise.Model.UpdateProjectResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.IoTSiteWise.Model.UpdateProjectResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class UpdateIOTSWProjectCmdlet : AmazonIoTSiteWiseClientCmdlet, IExecutor { #region Parameter ProjectDescription /// <summary> /// <para> /// <para>A new description for the project.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ProjectDescription { get; set; } #endregion #region Parameter ProjectId /// <summary> /// <para> /// <para>The ID of the project to update.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ProjectId { get; set; } #endregion #region Parameter ProjectName /// <summary> /// <para> /// <para>A new friendly name for the project.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ProjectName { get; set; } #endregion #region Parameter ClientToken /// <summary> /// <para> /// <para>A unique case-sensitive identifier that you can provide to ensure the idempotency /// of the request. Don't reuse this client token if a new idempotent request is required.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.IoTSiteWise.Model.UpdateProjectResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the ProjectId parameter. /// The -PassThru parameter is deprecated, use -Select '^ProjectId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ProjectId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.ProjectId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-IOTSWProject (UpdateProject)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.IoTSiteWise.Model.UpdateProjectResponse, UpdateIOTSWProjectCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.ProjectId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ClientToken = this.ClientToken; context.ProjectDescription = this.ProjectDescription; context.ProjectId = this.ProjectId; #if MODULAR if (this.ProjectId == null && ParameterWasBound(nameof(this.ProjectId))) { WriteWarning("You are passing $null as a value for parameter ProjectId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ProjectName = this.ProjectName; #if MODULAR if (this.ProjectName == null && ParameterWasBound(nameof(this.ProjectName))) { WriteWarning("You are passing $null as a value for parameter ProjectName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.IoTSiteWise.Model.UpdateProjectRequest(); if (cmdletContext.ClientToken != null) { request.ClientToken = cmdletContext.ClientToken; } if (cmdletContext.ProjectDescription != null) { request.ProjectDescription = cmdletContext.ProjectDescription; } if (cmdletContext.ProjectId != null) { request.ProjectId = cmdletContext.ProjectId; } if (cmdletContext.ProjectName != null) { request.ProjectName = cmdletContext.ProjectName; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.IoTSiteWise.Model.UpdateProjectResponse CallAWSServiceOperation(IAmazonIoTSiteWise client, Amazon.IoTSiteWise.Model.UpdateProjectRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS IoT SiteWise", "UpdateProject"); try { #if DESKTOP return client.UpdateProject(request); #elif CORECLR return client.UpdateProjectAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ClientToken { get; set; } public System.String ProjectDescription { get; set; } public System.String ProjectId { get; set; } public System.String ProjectName { get; set; } public System.Func<Amazon.IoTSiteWise.Model.UpdateProjectResponse, UpdateIOTSWProjectCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
44.187726
282
0.606291
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/IoTSiteWise/Basic/Update-IOTSWProject-Cmdlet.cs
12,240
C#
using System; using System.Collections.Generic; namespace Demo.EntityFramework.MySql.Models { public partial class OrdersTaxStatus { public OrdersTaxStatus() { Orders = new HashSet<Orders>(); } public sbyte Id { get; set; } public string TaxStatusName { get; set; } public virtual ICollection<Orders> Orders { get; set; } } }
21.157895
63
0.614428
[ "MIT" ]
penCsharpener/Demo.EntityFramework.MySql
EntityFramework/Demo.EntityFramework.MySql/Models/OrdersTaxStatus.cs
404
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using YamlDotNet.Serialization; namespace KubeClient.Models { /// <summary> /// ObjectMetricSource indicates how to scale on a metric describing a kubernetes object (for example, hits-per-second on an Ingress object). /// </summary> public partial class ObjectMetricSourceV2Beta1 { /// <summary> /// metricName is the name of the metric in question. /// </summary> [YamlMember(Alias = "metricName")] [JsonProperty("metricName", NullValueHandling = NullValueHandling.Include)] public string MetricName { get; set; } /// <summary> /// targetValue is the target value of the metric (as a quantity). /// </summary> [YamlMember(Alias = "targetValue")] [JsonProperty("targetValue", NullValueHandling = NullValueHandling.Include)] public string TargetValue { get; set; } /// <summary> /// target is the described Kubernetes object. /// </summary> [YamlMember(Alias = "target")] [JsonProperty("target", NullValueHandling = NullValueHandling.Include)] public CrossVersionObjectReferenceV2Beta1 Target { get; set; } } }
36.228571
149
0.643533
[ "MIT" ]
PhilippCh/dotnet-kube-client
src/KubeClient/Models/generated/ObjectMetricSourceV2Beta1.cs
1,268
C#
using OneOf; using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; namespace AntDesign.Charts { public class FunnelConfig : IFunnelViewConfig, IPlotConfig { [JsonPropertyName("funnelStyle")] public object FunnelStyle { get; set; } [JsonPropertyName("percentage")] public object Percentage { get; set; } [JsonPropertyName("transpose")] public bool? Transpose { get; set; } [JsonPropertyName("dynamicHeight")] public bool? DynamicHeight { get; set; } [JsonPropertyName("compareField")] public string CompareField { get; set; } [JsonPropertyName("compareText")] public object CompareText { get; set; } [JsonPropertyName("renderer")] public string Renderer { get; set; } [JsonPropertyName("data")] public object Data { get; set; } [JsonPropertyName("meta")] public object Meta { get; set; } [JsonIgnore] public OneOf<int?, string, int[]> Padding { get; set; } [JsonPropertyName("padding")] public object PaddingMapping => Padding.Value; [JsonPropertyName("xField")] public string XField { get; set; } [JsonPropertyName("yField")] public string YField { get; set; } [JsonIgnore] public OneOf<string, string[], object> Color { get; set; } [JsonPropertyName("color")] public object ColorMapping => Color.Value; [JsonPropertyName("xAxis")] public Axis XAxis { get; set; } [JsonPropertyName("yAxis")] public Axis YAxis { get; set; } [JsonIgnore] public OneOf<Label, object> Label { get; set; } [JsonPropertyName("label")] public object LabelMapping => Label.Value; [JsonPropertyName("tooltip")] public Tooltip Tooltip { get; set; } [JsonPropertyName("legend")] public Legend Legend { get; set; } [JsonIgnore] public OneOf<bool?, Animation, object> Animation { get; set; } [JsonPropertyName("animation")] public object AnimationMapping => Animation.Value; [JsonIgnore] public OneOf<string, object> Theme { get; set; } [JsonPropertyName("theme")] public object ThemeMapping => Theme.Value; [JsonIgnore] public OneOf<string, object> ResponsiveTheme { get; set; } [JsonPropertyName("responsiveTheme")] public object ResponsiveThemeMapping => ResponsiveTheme.Value; [JsonPropertyName("interactions")] public Interaction[] Interactions { get; set; } [JsonPropertyName("responsive")] public bool? Responsive { get; set; } [JsonPropertyName("title")] public Title Title { get; set; } [JsonPropertyName("description")] public Description Description { get; set; } [JsonPropertyName("guideLine")] public GuideLineConfig[] GuideLine { get; set; } [JsonPropertyName("defaultState")] public ViewConfigDefaultState DefaultState { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("forceFit")] public bool? ForceFit { get; set; } [JsonPropertyName("width")] public int? Width { get; set; } [JsonPropertyName("height")] public int? Height { get; set; } [JsonPropertyName("pixelRatio")] public int? PixelRatio { get; set; } [JsonPropertyName("localRefresh")] public bool? LocalRefresh { get; set; } [JsonPropertyName("appendPadding")] public int? AppendPadding { get; set; } } public interface IFunnelViewConfig : IViewConfig { [JsonPropertyName("funnelStyle")] public object FunnelStyle { get; set; }//export interface FunnelStyle { [k: string]: any; } [JsonPropertyName("percentage")] public object Percentage { get; set; } /* percentage?: Partial<{ visible: boolean; line: Partial<{ visible: boolean; style: LineStyle; }>; text: Partial<{ visible: boolean; content: string; style: TextStyle; }>; value: Partial<{ visible: boolean; style: TextStyle; formatter: (yValueUpper: any, yValueLower: any) => string; }>; offsetX: number; offsetY: number; spacing: number; }>; */ [JsonPropertyName("transpose")] public bool? Transpose { get; set; } [JsonPropertyName("dynamicHeight")] public bool? DynamicHeight { get; set; } [JsonPropertyName("compareField")] public string CompareField { get; set; } [JsonPropertyName("compareText")] public object CompareText { get; set; } /* compareText?: Partial<{ visible: boolean; offsetX: number; offsetY: number; style: TextStyle; }>; */ } }
36.769231
99
0.570179
[ "Apache-2.0" ]
CAPCHIK/ant-design-charts-blazor
src/AntDesign.Charts/Components/Plots/Funnel/FunnelConfig.cs
5,258
C#
// lucene version compatibility level: 4.8.1 using Lucene.Net.Analysis.Cn.Smart.Hhmm; using Lucene.Net.Analysis.TokenAttributes; using System; using System.Collections.Generic; namespace Lucene.Net.Analysis.Cn.Smart { /* * 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> /// A <see cref="TokenFilter"/> that breaks sentences into words. /// <para/> /// @lucene.experimental /// </summary> [Obsolete("Use HMMChineseTokenizer instead.")] public sealed class WordTokenFilter : TokenFilter { private readonly WordSegmenter wordSegmenter; // LUCENENET: marked readonly private IEnumerator<SegToken> tokenIter; private IList<SegToken> tokenBuffer; private readonly ICharTermAttribute termAtt; private readonly IOffsetAttribute offsetAtt; private readonly ITypeAttribute typeAtt; private int tokStart; // only used if the length changed before this filter private int tokEnd; // only used if the length changed before this filter private bool hasIllegalOffsets; // only if the length changed before this filter /// <summary> /// Construct a new <see cref="WordTokenFilter"/>. /// </summary> /// <param name="input"><see cref="TokenStream"/> of sentences.</param> public WordTokenFilter(TokenStream input) : base(input) { this.wordSegmenter = new WordSegmenter(); this.termAtt = AddAttribute<ICharTermAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); this.typeAtt = AddAttribute<ITypeAttribute>(); } public override bool IncrementToken() { if (tokenIter is null || !tokenIter.MoveNext()) { // there are no remaining tokens from the current sentence... are there more sentences? if (m_input.IncrementToken()) { tokStart = offsetAtt.StartOffset; tokEnd = offsetAtt.EndOffset; // if length by start + end offsets doesn't match the term text then assume // this is a synonym and don't adjust the offsets. hasIllegalOffsets = (tokStart + termAtt.Length) != tokEnd; // a new sentence is available: process it. tokenBuffer = wordSegmenter.SegmentSentence(termAtt.ToString(), offsetAtt.StartOffset); tokenIter = tokenBuffer.GetEnumerator(); /* * it should not be possible to have a sentence with 0 words, check just in case. * returning EOS isn't the best either, but its the behavior of the original code. */ if (!tokenIter.MoveNext()) { return false; } } else { return false; // no more sentences, end of stream! } } // WordTokenFilter must clear attributes, as it is creating new tokens. ClearAttributes(); // There are remaining tokens from the current sentence, return the next one. SegToken nextWord = tokenIter.Current; termAtt.CopyBuffer(nextWord.CharArray, 0, nextWord.CharArray.Length); if (hasIllegalOffsets) { offsetAtt.SetOffset(tokStart, tokEnd); } else { offsetAtt.SetOffset(nextWord.StartOffset, nextWord.EndOffset); } typeAtt.Type = "word"; return true; } public override void Reset() { base.Reset(); tokenIter?.Dispose(); // LUCENENET specific tokenIter = null; } /// <summary> /// Releases resources used by the <see cref="WordTokenFilter"/> and /// if overridden in a derived class, optionally releases unmanaged resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; /// <c>false</c> to release only unmanaged resources.</param> // LUCENENET specific protected override void Dispose(bool disposing) { try { if (disposing) { tokenIter?.Dispose(); // LUCENENET specific - dispose tokenIter and set to null tokenIter = null; } } finally { base.Dispose(disposing); } } } }
40.276596
108
0.562951
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Analysis.SmartCn/WordTokenFilter.cs
5,541
C#
using System; using FilterPipelineExample.Filters; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace FilterPipelineExample.Controllers { [ApiController] [LogResourceFilter, LogActionFilter, LogAuthorizationFilter, LogResultFilter, LogExceptionFilter, LogAlwaysRunResultFilter] public class ValuesController : Controller { [HttpGet("values")] public IActionResult Index() { Console.WriteLine("Executing HomeController.Index"); return Content("Home Page"); } [HttpGet("exception")] public IActionResult Exception() { Console.WriteLine("Executing HomeController.Exception"); throw new Exception("Exception thrown!"); } public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("Executing HomeController.OnActionExecuting"); //context.Result = new ContentResult() //{ // Content = "HomeController.OnActionExecuting - Short-circuiting ", //}; } public override void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine($"Executing HomeController.OnActionExecuted: cancelled {context.Canceled}"); //context.ExceptionHandled = true; //context.Result = new ContentResult() //{ // Content = "HomeController - convert to success ", //}; } } }
33.391304
127
0.630859
[ "MIT" ]
AnzhelikaKravchuk/asp-dot-net-core-in-action-2e
Chapter13/A_FilterPipelineExample/FilterPipelineExample/Controllers/ValuesController.cs
1,538
C#
namespace MotiNet.Entities { public interface IEntityCodeGenerator<in TEntity> where TEntity : class { string GenerateCode(object manager, TEntity entity); } }
21
60
0.68254
[ "MIT" ]
motix/MotiNet-Entities
src/MotiNet.Extensions.Entities.Core/_CodeGenerators/IEntityCodeGenerator.cs
191
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using StackExchange.Redis; namespace CoreCms.Net.Caching.AutoMate.RedisCache { public class RedisOperationRepository : IRedisOperationRepository { private readonly ILogger<RedisOperationRepository> _logger; private readonly ConnectionMultiplexer _redis; private readonly IDatabase _database; public RedisOperationRepository(ILogger<RedisOperationRepository> logger, ConnectionMultiplexer redis) { _logger = logger; _redis = redis; _database = redis.GetDatabase(); } private IServer GetServer() { var endpoint = _redis.GetEndPoints(); return _redis.GetServer(endpoint.First()); } public async Task Clear() { foreach (var endPoint in _redis.GetEndPoints()) { var server = GetServer(); foreach (var key in server.Keys()) { await _database.KeyDeleteAsync(key); } } } public async Task<bool> Exist(string key) { return await _database.KeyExistsAsync(key); } public async Task<string> Get(string key) { return await _database.StringGetAsync(key); } public async Task Remove(string key) { await _database.KeyDeleteAsync(key); } public async Task Set(string key, object value, TimeSpan cacheTime) { if (value != null) { //序列化,将object值生成RedisValue await _database.StringSetAsync(key, JsonConvert.SerializeObject(value), cacheTime); } } public async Task<TEntity> Get<TEntity>(string key) { var value = await _database.StringGetAsync(key); if (value.HasValue) { //需要用的反序列化,将Redis存储的Byte[],进行反序列化 return JsonConvert.DeserializeObject<TEntity>(value); } else { return default; } } /// <summary> /// 根据key获取RedisValue /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<RedisValue[]> ListRangeAsync(string redisKey) { return await _database.ListRangeAsync(redisKey); } /// <summary> /// 在列表头部插入值。如果键不存在,先创建再插入值 /// </summary> /// <param name="redisKey"></param> /// <param name="redisValue"></param> /// <returns></returns> public async Task<long> ListLeftPushAsync(string redisKey, string redisValue) { return await _database.ListLeftPushAsync(redisKey, redisValue); } /// <summary> /// 在列表尾部插入值。如果键不存在,先创建再插入值 /// </summary> /// <param name="redisKey"></param> /// <param name="redisValue"></param> /// <returns></returns> public async Task<long> ListRightPushAsync(string redisKey, string redisValue) { return await _database.ListRightPushAsync(redisKey, redisValue); } /// <summary> /// 在列表尾部插入数组集合。如果键不存在,先创建再插入值 /// </summary> /// <param name="redisKey"></param> /// <param name="redisValue"></param> /// <returns></returns> public async Task<long> ListRightPushAsync(string redisKey, IEnumerable<string> redisValue) { var redislist = new List<RedisValue>(); foreach (var item in redisValue) { redislist.Add(item); } return await _database.ListRightPushAsync(redisKey, redislist.ToArray()); } /// <summary> /// 移除并返回存储在该键列表的第一个元素 反序列化 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<T> ListLeftPopAsync<T>(string redisKey) where T : class { var cacheValue = await _database.ListLeftPopAsync(redisKey); if (string.IsNullOrEmpty(cacheValue)) return null; var res = JsonConvert.DeserializeObject<T>(cacheValue); return res; } /// <summary> /// 移除并返回存储在该键列表的最后一个元素 反序列化 /// 只能是对象集合 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<T> ListRightPopAsync<T>(string redisKey) where T : class { var cacheValue = await _database.ListRightPopAsync(redisKey); if (string.IsNullOrEmpty(cacheValue)) return null; var res = JsonConvert.DeserializeObject<T>(cacheValue); return res; } /// <summary> /// 移除并返回存储在该键列表的第一个元素 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<string> ListLeftPopAsync(string redisKey) { return await _database.ListLeftPopAsync(redisKey); } /// <summary> /// 移除并返回存储在该键列表的最后一个元素 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<string> ListRightPopAsync(string redisKey) { return await _database.ListRightPopAsync(redisKey); } /// <summary> /// 列表长度 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<long> ListLengthAsync(string redisKey) { return await _database.ListLengthAsync(redisKey); } /// <summary> /// 返回在该列表上键所对应的元素 /// </summary> /// <param name="redisKey"></param> /// <returns></returns> public async Task<IEnumerable<string>> ListRangeAsync(string redisKey, int db = -1) { var result = await _database.ListRangeAsync(redisKey); return result.Select(o => o.ToString()); } /// <summary> /// 根据索引获取指定位置数据 /// </summary> /// <param name="redisKey"></param> /// <param name="start"></param> /// <param name="stop"></param> /// <returns></returns> public async Task<IEnumerable<string>> ListRangeAsync(string redisKey, int start, int stop) { var result = await _database.ListRangeAsync(redisKey, start, stop); return result.Select(o => o.ToString()); } /// <summary> /// 删除List中的元素 并返回删除的个数 /// </summary> /// <param name="redisKey">key</param> /// <param name="redisValue">元素</param> /// <param name="type">大于零 : 从表头开始向表尾搜索,小于零 : 从表尾开始向表头搜索,等于零:移除表中所有与 VALUE 相等的值</param> /// <returns></returns> public async Task<long> ListDelRangeAsync(string redisKey, string redisValue, long type = 0) { return await _database.ListRemoveAsync(redisKey, redisValue, type); } /// <summary> /// 清空List /// </summary> /// <param name="redisKey"></param> public async Task ListClearAsync(string redisKey) { await _database.ListTrimAsync(redisKey, 1, 0); } } }
32.25974
110
0.550859
[ "Apache-2.0" ]
XRJ1230663/CoreShop
CoreCms.Net.Caching/AutoMate/RedisCache/RedisOperationRepository.cs
8,022
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx.Synchronous; namespace Nito.AsyncEx { /// <summary> /// An async-compatible producer/consumer queue. /// </summary> /// <typeparam name="T">The type of elements contained in the queue.</typeparam> [DebuggerDisplay("Count = {_queue.Count}, MaxCount = {_maxCount}")] [DebuggerTypeProxy(typeof(AsyncProducerConsumerQueue<>.DebugView))] public sealed class AsyncProducerConsumerQueue<T> { /// <summary> /// The underlying queue. /// </summary> private readonly Queue<T> _queue; /// <summary> /// The maximum number of elements allowed in the queue. /// </summary> private readonly int _maxCount; /// <summary> /// The mutual-exclusion lock protecting <c>_queue</c> and <c>_completed</c>. /// </summary> private readonly AsyncLock _mutex; /// <summary> /// A condition variable that is signalled when the queue is not full. /// </summary> private readonly AsyncConditionVariable _completedOrNotFull; /// <summary> /// A condition variable that is signalled when the queue is completed or not empty. /// </summary> private readonly AsyncConditionVariable _completedOrNotEmpty; /// <summary> /// Whether this producer/consumer queue has been marked complete for adding. /// </summary> private bool _completed; /// <summary> /// Creates a new async-compatible producer/consumer queue with the specified initial elements and a maximum element count. /// </summary> /// <param name="collection">The initial elements to place in the queue. This may be <c>null</c> to start with an empty collection.</param> /// <param name="maxCount">The maximum element count. This must be greater than zero, and greater than or equal to the number of elements in <paramref name="collection"/>.</param> public AsyncProducerConsumerQueue(IEnumerable<T> collection, int maxCount) { if (maxCount <= 0) throw new ArgumentOutOfRangeException(nameof(maxCount), "The maximum count must be greater than zero."); _queue = collection == null ? new Queue<T>() : new Queue<T>(collection); if (maxCount < _queue.Count) throw new ArgumentException("The maximum count cannot be less than the number of elements in the collection.", nameof(maxCount)); _maxCount = maxCount; _mutex = new AsyncLock(); _completedOrNotFull = new AsyncConditionVariable(_mutex); _completedOrNotEmpty = new AsyncConditionVariable(_mutex); } /// <summary> /// Creates a new async-compatible producer/consumer queue with the specified initial elements. /// </summary> /// <param name="collection">The initial elements to place in the queue. This may be <c>null</c> to start with an empty collection.</param> public AsyncProducerConsumerQueue(IEnumerable<T> collection) : this(collection, int.MaxValue) { } /// <summary> /// Creates a new async-compatible producer/consumer queue with a maximum element count. /// </summary> /// <param name="maxCount">The maximum element count. This must be greater than zero.</param> public AsyncProducerConsumerQueue(int maxCount) : this(null, maxCount) { } /// <summary> /// Creates a new async-compatible producer/consumer queue. /// </summary> public AsyncProducerConsumerQueue() : this(null, int.MaxValue) { } /// <summary> /// Whether the queue is empty. This property assumes that the <c>_mutex</c> is already held. /// </summary> private bool Empty { get { return _queue.Count == 0; } } /// <summary> /// Whether the queue is full. This property assumes that the <c>_mutex</c> is already held. /// </summary> private bool Full { get { return _queue.Count == _maxCount; } } /// <summary> /// Marks the producer/consumer queue as complete for adding. /// </summary> public void CompleteAdding() { using (_mutex.Lock()) { _completed = true; _completedOrNotEmpty.NotifyAll(); _completedOrNotFull.NotifyAll(); } } /// <summary> /// Enqueues an item to the producer/consumer queue. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding. /// </summary> /// <param name="item">The item to enqueue.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the enqueue operation.</param> /// <param name="sync">Whether to run this method synchronously.</param> private async Task DoEnqueueAsync(T item, CancellationToken cancellationToken, bool sync) { using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false)) { // Wait for the queue to be not full. while (Full && !_completed) { if (sync) _completedOrNotFull.Wait(); else await _completedOrNotFull.WaitAsync(cancellationToken).ConfigureAwait(false); } // If the queue has been marked complete, then abort. if (_completed) throw new InvalidOperationException("Enqueue failed; the producer/consumer queue has completed adding."); _queue.Enqueue(item); _completedOrNotEmpty.Notify(); } } /// <summary> /// Enqueues an item to the producer/consumer queue. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding. /// </summary> /// <param name="item">The item to enqueue.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the enqueue operation.</param> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding.</exception> public Task EnqueueAsync(T item, CancellationToken cancellationToken) { return DoEnqueueAsync(item, cancellationToken, sync: false); } /// <summary> /// Enqueues an item to the producer/consumer queue. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding. /// </summary> /// <param name="item">The item to enqueue.</param> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding.</exception> public Task EnqueueAsync(T item) { return EnqueueAsync(item, CancellationToken.None); } /// <summary> /// Enqueues an item to the producer/consumer queue. This method may block the calling thread. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding. /// </summary> /// <param name="item">The item to enqueue.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the enqueue operation.</param> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding.</exception> public void Enqueue(T item, CancellationToken cancellationToken) { DoEnqueueAsync(item, cancellationToken, sync: true).WaitAndUnwrapException(); } /// <summary> /// Enqueues an item to the producer/consumer queue. This method may block the calling thread. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding. /// </summary> /// <param name="item">The item to enqueue.</param> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding.</exception> public void Enqueue(T item) { Enqueue(item, CancellationToken.None); } /// <summary> /// Waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer queue has completed adding and there are no more items. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the asynchronous wait.</param> /// <param name="sync">Whether to run this method synchronously.</param> private async Task<bool> DoOutputAvailableAsync(CancellationToken cancellationToken, bool sync) { using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false)) { while (Empty && !_completed) { if (sync) _completedOrNotEmpty.Wait(); else await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false); } return !Empty; } } /// <summary> /// Asynchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer queue has completed adding and there are no more items. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the asynchronous wait.</param> public Task<bool> OutputAvailableAsync(CancellationToken cancellationToken) { return DoOutputAvailableAsync(cancellationToken, sync: false); } /// <summary> /// Asynchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer queue has completed adding and there are no more items. /// </summary> public Task<bool> OutputAvailableAsync() { return OutputAvailableAsync(CancellationToken.None); } /// <summary> /// Synchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer queue has completed adding and there are no more items. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the asynchronous wait.</param> public bool OutputAvailable(CancellationToken cancellationToken) { return DoOutputAvailableAsync(cancellationToken, sync: true).WaitAndUnwrapException(); } /// <summary> /// Synchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer queue has completed adding and there are no more items. /// </summary> public bool OutputAvailable() { return OutputAvailable(CancellationToken.None); } /// <summary> /// Provides a (synchronous) consuming enumerable for items in the producer/consumer queue. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the synchronous enumeration.</param> public IEnumerable<T> GetConsumingEnumerable(CancellationToken cancellationToken) { while (true) { var result = TryDoDequeueAsync(cancellationToken, sync: true).WaitAndUnwrapException(); if (!result.Item1) yield break; yield return result.Item2; } } /// <summary> /// Provides a (synchronous) consuming enumerable for items in the producer/consumer queue. /// </summary> public IEnumerable<T> GetConsumingEnumerable() { return GetConsumingEnumerable(CancellationToken.None); } /// <summary> /// Attempts to dequeue an item from the producer/consumer queue. Returns <c>false</c> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the dequeue operation.</param> /// <param name="sync">Whether to run this method synchronously.</param> private async Task<Tuple<bool, T>> TryDoDequeueAsync(CancellationToken cancellationToken, bool sync) { using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false)) { while (Empty && !_completed) { if (sync) _completedOrNotEmpty.Wait(cancellationToken); else await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false); } if (_completed && Empty) return Tuple.Create(false, default(T)); var item = _queue.Dequeue(); _completedOrNotFull.Notify(); return Tuple.Create(true, item); } } /// <summary> /// Dequeues an item from the producer/consumer queue. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the dequeue operation.</param> /// <param name="sync">Whether to run this method synchronously.</param> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding and is empty.</exception> private async Task<T> DoDequeueAsync(CancellationToken cancellationToken, bool sync) { var result = await TryDoDequeueAsync(cancellationToken, sync).ConfigureAwait(false); if (result.Item1) return result.Item2; throw new InvalidOperationException("Dequeue failed; the producer/consumer queue has completed adding and is empty."); } /// <summary> /// Dequeues an item from the producer/consumer queue. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the dequeue operation.</param> /// <returns>The dequeued item.</returns> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding and is empty.</exception> public Task<T> DequeueAsync(CancellationToken cancellationToken) { return DoDequeueAsync(cancellationToken, sync: false); } /// <summary> /// Dequeues an item from the producer/consumer queue. Returns the dequeued item. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <returns>The dequeued item.</returns> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding and is empty.</exception> public Task<T> DequeueAsync() { return DequeueAsync(CancellationToken.None); } /// <summary> /// Dequeues an item from the producer/consumer queue. Returns the dequeued item. This method may block the calling thread. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the dequeue operation.</param> /// <returns>The dequeued item.</returns> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding and is empty.</exception> public T Dequeue(CancellationToken cancellationToken) { return DoDequeueAsync(cancellationToken, sync: true).WaitAndUnwrapException(); } /// <summary> /// Dequeues an item from the producer/consumer queue. Returns the dequeued item. This method may block the calling thread. Throws <see cref="InvalidOperationException"/> if the producer/consumer queue has completed adding and is empty. /// </summary> /// <returns>The dequeued item.</returns> /// <exception cref="InvalidOperationException">The producer/consumer queue has been marked complete for adding and is empty.</exception> public T Dequeue() { return Dequeue(CancellationToken.None); } [DebuggerNonUserCode] internal sealed class DebugView { private readonly AsyncProducerConsumerQueue<T> _queue; public DebugView(AsyncProducerConsumerQueue<T> queue) { _queue = queue; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { return _queue._queue.ToArray(); } } } } }
48.118457
244
0.627011
[ "MIT" ]
6bee/AsyncEx
src/Nito.AsyncEx.Coordination/AsyncProducerConsumerQueue.cs
17,469
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CSB; using Aliyun.Acs.CSB.Transform; using Aliyun.Acs.CSB.Transform.V20171118; namespace Aliyun.Acs.CSB.Model.V20171118 { public class FindAllLinkRuleRequest : RpcAcsRequest<FindAllLinkRuleResponse> { public FindAllLinkRuleRequest() : base("CSB", "2017-11-18", "FindAllLinkRule") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private long? csbId; public long? CsbId { get { return csbId; } set { csbId = value; DictionaryUtil.Add(QueryParameters, "CsbId", value.ToString()); } } public override bool CheckShowJsonItemName() { return false; } public override FindAllLinkRuleResponse GetResponse(UnmarshallerContext unmarshallerContext) { return FindAllLinkRuleResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
31.884058
134
0.695909
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-csb/CSB/Model/V20171118/FindAllLinkRuleRequest.cs
2,200
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0002.Models { public partial class VCmdMstRgv { public string CmdSno { get; set; } public int WmsTskId { get; set; } public string Cmdsts { get; set; } public string TrnDate { get; set; } public string ActTime { get; set; } public string EndTime { get; set; } public string Prt { get; set; } public string CmdMode { get; set; } public string StnNo { get; set; } public string Loc { get; set; } public string NewLoc { get; set; } public string LocSize { get; set; } public string RodId { get; set; } public string Trace { get; set; } public string Result { get; set; } public string TrnNo { get; set; } public int? BillingStatus { get; set; } public string CreateUser { get; set; } public string BillingNo { get; set; } public string CmdNo { get; set; } public string LineId { get; set; } public string Plcd51 { get; set; } public string Cticketcode { get; set; } public string Packageno { get; set; } public string Remark { get; set; } public int? Updata { get; set; } public string Msg { get; set; } public string Cdefine1 { get; set; } public string Cdefine2 { get; set; } public string Cdefine3 { get; set; } public string Height { get; set; } public string Reason { get; set; } public string Pc { get; set; } public string AreaId { get; set; } public string CraneStataus { get; set; } } }
38.425532
97
0.569767
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0002/Models/VCmdMstRgv.cs
1,808
C#
// <copyright file="InputButtonControlTestsEdge.cs" company="Automate The Planet Ltd."> // Copyright 2020 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bellatrix.Web.Tests.Controls { [TestClass] [Browser(BrowserType.Edge, Lifecycle.ReuseIfStarted)] [AllureSuite("Input Button Control")] [AllureFeature("Edge Browser")] public class InputButtonControlTestsEdge : MSTest.WebTest { public override void TestInit() => App.NavigationService.NavigateToLocalPage(ConfigurationService.GetSection<TestPagesSettings>().ButtonLocalPage); [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void SetTextToStop_When_UseClickMethod_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton"); buttonElement.Click(); Assert.AreEqual("Stop", buttonElement.Value); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnRed_When_Hover_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton1"); buttonElement.Hover(); Assert.AreEqual("color: red;", buttonElement.GetStyle()); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnBlue_When_Focus_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton2"); buttonElement.Focus(); Assert.AreEqual("color: blue;", buttonElement.GetStyle()); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnFalse_When_DisabledAttributeNotPresent_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton"); bool isDisabled = buttonElement.IsDisabled; Assert.IsFalse(isDisabled); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnTrue_When_DisabledAttributePresent_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton3"); bool isDisabled = buttonElement.IsDisabled; Assert.IsTrue(isDisabled); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnStart_When_ValueAttributePresent_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton"); var actualValue = buttonElement.Value; Assert.AreEqual("Start", actualValue); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Edge), TestCategory(Categories.Windows)] public void ReturnEmpty_When_UseInnerText_Edge() { var buttonElement = App.ElementCreateService.CreateById<Button>("myButton"); Assert.AreEqual(string.Empty, buttonElement.InnerText); } } }
37.490741
155
0.678933
[ "Apache-2.0" ]
alexandrejulien/BELLATRIX
tests/Bellatrix.Web.Tests/Controls/Button/InputButtonControlTestsEdge.cs
4,051
C#
namespace WebWarehouse.Services.Data.Warehouses { using System.Collections.Generic; using System.Threading.Tasks; public interface IWarehousesService { Task<IEnumerable<T>> GetAllAsync<T>(int? count = null); } }
22
63
0.702479
[ "MIT" ]
iltodbul/WebWarehouse
Services/WebWarehouse.Services.Data/Warehouses/IWarehousesService.cs
244
C#
/******************************************************* * * 作者:胡庆访 * 创建日期:20170914 * 说明:此文件只包含一个类,具体内容见类型注释。 * 运行环境:.NET 4.0 * 版本号:1.0.0 * * 历史记录: * 创建文件 胡庆访 20170914 14:06 * *******************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace Rafy { /// <summary> /// 使用 ExecutionContext 中的 CallContext 来实现跨线程数据共享的 ContextProvider。 /// /// CallContext 相关的文档见: /// http://blog.csdn.net/wsxqaz/article/details/9083093 /// /// 注意: /// 目前此类存在以下问题,所以暂时不使用: /// 使用后,单元测试无法正常运行了。详见:http://www.cnblogs.com/artech/archive/2010/08/29/1811683.html /// </summary> public class CallContextAppContextProvider : IAppContextProvider { private static readonly string CurrentPrincipalName = "Rafy.CallContextAppContextProvider.CurrentPrincipal"; private static readonly string DataContainerName = "Rafy.CallContextAppContextProvider.DataContainer"; public IPrincipal CurrentPrincipal { get => CallContext.LogicalGetData(CurrentPrincipalName) as IPrincipal; set => CallContext.LogicalSetData(CurrentPrincipalName, value); } public IDictionary<string, object> DataContainer { get => CallContext.LogicalGetData(DataContainerName) as IDictionary<string, object>; set => CallContext.LogicalSetData(DataContainerName, value); } } }
30.423077
116
0.639697
[ "MIT" ]
zgynhqf/trunk
Rafy/Rafy/Utils/Context/CallContextAppContextProvider.cs
1,822
C#
using UnityEngine; using UnityEditor; [InitializeOnLoad] public class HierarchyWindowGroupHeader : Editor { static HierarchyWindowGroupHeader() { EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI; } static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect) { var gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject; if (gameObject != null && gameObject.name.StartsWith("---", System.StringComparison.Ordinal)) { EditorGUI.DrawRect(selectionRect, Color.gray); EditorGUI.DropShadowLabel(selectionRect, gameObject.name.Replace("-", "").ToUpperInvariant()); } } }
37.105263
106
0.70922
[ "MIT" ]
Howard-Day/DrDoomthorne
Assets/_Scripts/Utils/Editor/HierarchyWindowGroupHeader.cs
707
C#
/*<FILE_LICENSE> * Azos (A to Z Application Operating System) Framework * The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. </FILE_LICENSE>*/ using System; using Azos.Instrumentation; using Azos.Serialization.Arow; using Azos.Serialization.BSON; namespace Azos.Log.Instrumentation { [Serializable] public abstract class LogLongGauge : LongGauge, IInstrumentationInstrument { protected LogLongGauge(string source, long value) : base(source, value) { } } [Serializable] [Arow("21420BC2-A2F4-461D-A087-59F5AC4D843D")] public class LogMsgQueueSize : LogLongGauge, IMemoryInstrument { protected LogMsgQueueSize(string source, long value) : base(source, value) { } public static void Record(IInstrumentation inst, string source, long value) { if (inst!=null && inst.Enabled) inst.Record(new LogMsgQueueSize(source, value)); } public override string Description { get { return "Log message count in queue"; } } public override string ValueUnitName { get { return CoreConsts.UNIT_NAME_MESSAGE; } } protected override Datum MakeAggregateInstance() { return new LogMsgQueueSize(this.Source, 0); } } [Serializable] [Arow("E0E7D9AE-0165-4F81-95C9-113B297C625D")] public class LogMsgCount : LogLongGauge, IMemoryInstrument { protected LogMsgCount(string source, long value) : base(source, value) { } public static void Record(IInstrumentation inst, string source, long value) { if (inst!=null && inst.Enabled) inst.Record(new LogMsgCount(source, value)); } public override string Description { get { return "Log message count"; } } public override string ValueUnitName { get { return CoreConsts.UNIT_NAME_MESSAGE; } } protected override Datum MakeAggregateInstance() { return new LogMsgCount(this.Source, 0); } } }
28.507246
89
0.712761
[ "MIT" ]
JohnPKosh/azos
src/Azos/Log/Instrumentation/Gauges.cs
1,967
C#
using Nethereum.BlockchainProcessing.BlockStorage.Entities.Mapping; using Nethereum.Hex.HexTypes; using Nethereum.Model; using System; using System.Collections.Generic; using System.Text; namespace ProDerivatives.Ethereum { public class BlockInfo { public long BlockNumber { get; private set; } public DateTime Timestamp { get; private set; } public BlockInfo(HexBigInteger blockNumber, HexBigInteger timestamp) { BlockNumber = blockNumber.ToLong(); Timestamp = new DateTime(timestamp.ToLong() * 1000 * 10000 + new DateTime(1970, 1, 1).Ticks); } public BlockInfo(HexBigInteger blockNumber, DateTime timestamp) { BlockNumber = blockNumber.ToLong(); Timestamp = timestamp; } } }
28.75
105
0.668323
[ "Apache-2.0" ]
ProDerivatives/ProDerivatives.Ethereum
src/BlockInfo.cs
807
C#
using System.Collections.Generic; using System.Text; namespace BizHawk.Client.Common { internal partial class Bk2Movie { protected readonly Bk2Header Header = new Bk2Header(); private string _syncSettingsJson = ""; public IDictionary<string, string> HeaderEntries => Header; public SubtitleList Subtitles { get; } = new SubtitleList(); public IList<string> Comments { get; } = new List<string>(); public string SyncSettingsJson { get => _syncSettingsJson; set { if (_syncSettingsJson != value) { Changes = true; _syncSettingsJson = value; } } } public ulong Rerecords { get { if (!Header.ContainsKey(HeaderKeys.Rerecords)) { // Modifying the header itself can cause a race condition between loading a movie and rendering the rerecord count, causing a movie's rerecord count to be overwritten with 0 during loading. return 0; } return ulong.Parse(Header[HeaderKeys.Rerecords]); } set { if (Header[HeaderKeys.Rerecords] != value.ToString()) { Changes = true; Header[HeaderKeys.Rerecords] = value.ToString(); } } } public virtual bool StartsFromSavestate { get => Header.ContainsKey(HeaderKeys.StartsFromSavestate) && bool.Parse(Header[HeaderKeys.StartsFromSavestate]); set { if (value) { Header[HeaderKeys.StartsFromSavestate] = "True"; } else { Header.Remove(HeaderKeys.StartsFromSavestate); } } } public bool StartsFromSaveRam { get => Header.ContainsKey(HeaderKeys.StartsFromSaveram) && bool.Parse(Header[HeaderKeys.StartsFromSaveram]); set { if (value) { if (!Header.ContainsKey(HeaderKeys.StartsFromSaveram)) { Header.Add(HeaderKeys.StartsFromSaveram, "True"); } } else { if (Header.ContainsKey(HeaderKeys.StartsFromSaveram)) { Header.Remove(HeaderKeys.StartsFromSaveram); } } } } public string GameName { get => Header.ContainsKey(HeaderKeys.GameName) ? Header[HeaderKeys.GameName] : ""; set { if (Header[HeaderKeys.GameName] != value) { Changes = true; Header[HeaderKeys.GameName] = value; } } } public string SystemID { get => Header.ContainsKey(HeaderKeys.Platform) ? Header[HeaderKeys.Platform] : ""; set { if (Header[HeaderKeys.Platform] != value) { Changes = true; Header[HeaderKeys.Platform] = value; } } } public string Hash { get => Header[HeaderKeys.Sha1]; set { if (Header[HeaderKeys.Sha1] != value) { Changes = true; Header[HeaderKeys.Sha1] = value; } } } public string Author { get => Header[HeaderKeys.Author]; set { if (Header[HeaderKeys.Author] != value) { Changes = true; Header[HeaderKeys.Author] = value; } } } public string Core { get => Header[HeaderKeys.Core]; set { if (Header[HeaderKeys.Core] != value) { Changes = true; Header[HeaderKeys.Core] = value; } } } public string BoardName { get => Header[HeaderKeys.BoardName]; set { if (Header[HeaderKeys.BoardName] != value) { Changes = true; Header[HeaderKeys.BoardName] = value; } } } public string EmulatorVersion { get => Header[HeaderKeys.EmulationVersion]; set { if (Header[HeaderKeys.EmulationVersion] != value) { Changes = true; Header[HeaderKeys.EmulationVersion] = value; } } } public string FirmwareHash { get => Header[HeaderKeys.FirmwareSha1]; set { if (Header[HeaderKeys.FirmwareSha1] != value) { Changes = true; Header[HeaderKeys.FirmwareSha1] = value; } } } protected string CommentsString() { var sb = new StringBuilder(); foreach (var comment in Comments) { sb.AppendLine(comment); } return sb.ToString(); } public string TextSavestate { get; set; } public byte[] BinarySavestate { get; set; } public int[] SavestateFramebuffer { get; set; } public byte[] SaveRam { get; set; } } }
20.386792
195
0.59602
[ "MIT" ]
RetroEdit/BizHawk
src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs
4,324
C#
using Zinnia.Extension; namespace Test.Zinnia.Extension { using NUnit.Framework; using UnityEngine; using Assert = UnityEngine.Assertions.Assert; public class GameObjectExtensionsTest { [Test] public void TryGetComponentValid() { GameObject valid = new GameObject(); Assert.AreEqual(valid.GetComponent<Component>(), valid.TryGetComponent<Component>()); Object.DestroyImmediate(valid); } [Test] public void TryGetComponentInvalid() { GameObject invalid = null; Assert.IsNull(invalid.TryGetComponent<Component>()); } [Test] public void TrySetActive() { GameObject valid = new GameObject(); Assert.IsTrue(valid.activeInHierarchy); valid.TrySetActive(false); Assert.IsFalse(valid.activeInHierarchy); valid.TrySetActive(true); Assert.IsTrue(valid.activeInHierarchy); Object.DestroyImmediate(valid); } [Test] public void FindRigidbodyOnSameValid() { GameObject valid = new GameObject(); Rigidbody rigidbody = valid.AddComponent<Rigidbody>(); Assert.AreEqual(rigidbody, valid.TryGetComponent<Rigidbody>(true)); Object.DestroyImmediate(valid); } [Test] public void FindRigidbodyInvalid() { GameObject invalid = null; Assert.IsNull(invalid.TryGetComponent<Rigidbody>(true)); } [Test] public void FindRigidbodyOnDescendantValid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); Rigidbody rigidbody = child.AddComponent<Rigidbody>(); Assert.AreEqual(rigidbody, parent.TryGetComponent<Rigidbody>(true)); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void FindRigidbodyOnAncestorValid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); Rigidbody rigidbody = parent.AddComponent<Rigidbody>(); Assert.AreEqual(rigidbody, child.TryGetComponent<Rigidbody>(false, true)); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void FindRigidbodyOnDescendantFirstValid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); GameObject grandchild = new GameObject(); child.transform.SetParent(parent.transform); grandchild.transform.SetParent(child.transform); parent.AddComponent<Rigidbody>(); Rigidbody rigidbody = grandchild.AddComponent<Rigidbody>(); Assert.AreEqual(rigidbody, child.TryGetComponent<Rigidbody>(true, true)); Object.DestroyImmediate(grandchild); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void FindRigidbodyOnAncestorFirstValid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); GameObject grandchild = new GameObject(); child.transform.SetParent(parent.transform); grandchild.transform.SetParent(child.transform); Rigidbody rigidbody = parent.AddComponent<Rigidbody>(); grandchild.AddComponent<Rigidbody>(); Assert.AreEqual(rigidbody, child.TryGetComponent<Rigidbody>(false, true)); Object.DestroyImmediate(grandchild); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void FindRigidbodyOnDescendantFirstInvalid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); GameObject grandchild = new GameObject(); child.transform.SetParent(parent.transform); grandchild.transform.SetParent(child.transform); parent.AddComponent<Rigidbody>(); Assert.IsNull(child.TryGetComponent<Rigidbody>(true, false)); Object.DestroyImmediate(grandchild); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void FindRigidbodyOnAncestorFirstInvalid() { GameObject parent = new GameObject(); GameObject child = new GameObject(); GameObject grandchild = new GameObject(); child.transform.SetParent(parent.transform); grandchild.transform.SetParent(child.transform); grandchild.AddComponent<Rigidbody>(); Assert.IsNull(child.TryGetComponent<Rigidbody>(false, true)); Object.DestroyImmediate(grandchild); Object.DestroyImmediate(child); Object.DestroyImmediate(parent); } [Test] public void TryGetPosition() { Vector3 destinationPosition = Vector3.one * 2f; GameObject parent = new GameObject(); parent.transform.position = destinationPosition; Assert.AreEqual(destinationPosition, parent.TryGetPosition()); Object.DestroyImmediate(parent); } [Test] public void TryGetPositionLocal() { Vector3 destinationPosition = Vector3.one * 2f; GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); child.transform.position = destinationPosition; parent.transform.position = destinationPosition * 2f; Assert.AreEqual(destinationPosition, child.TryGetPosition(true)); Object.DestroyImmediate(parent); Object.DestroyImmediate(child); } [Test] public void TryGetRotation() { Quaternion destinationRotation = Quaternion.Euler(Vector3.up * 90f); GameObject parent = new GameObject(); parent.transform.rotation = destinationRotation; Assert.AreEqual(destinationRotation.ToString(), parent.TryGetRotation().ToString()); Object.DestroyImmediate(parent); } [Test] public void TryGetRotationLocal() { Quaternion destinationRotation = Quaternion.Euler(Vector3.up * 90f); GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); child.transform.localRotation = destinationRotation; parent.transform.localRotation = Quaternion.Euler(Vector3.up * 145f); Assert.AreEqual(destinationRotation.ToString(), child.TryGetRotation(true).ToString()); Object.DestroyImmediate(parent); Object.DestroyImmediate(child); } [Test] public void TryGetEulerRotation() { Vector3 destinationEulerRotation = Vector3.up * 90f; GameObject parent = new GameObject(); parent.transform.eulerAngles = destinationEulerRotation; Assert.AreEqual(destinationEulerRotation, parent.TryGetEulerRotation()); Object.DestroyImmediate(parent); } [Test] public void TryGetEulerRotationLocal() { Vector3 destinationRotation = Vector3.up * 90f; GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); child.transform.localEulerAngles = destinationRotation; parent.transform.localEulerAngles = Vector3.up * 145f; Assert.AreEqual(destinationRotation.ToString(), child.TryGetEulerRotation(true).ToString()); Object.DestroyImmediate(parent); Object.DestroyImmediate(child); } [Test] public void TryGetScale() { Vector3 destinationScale = Vector3.one * 2f; GameObject parent = new GameObject(); parent.transform.SetGlobalScale(destinationScale); Assert.AreEqual(destinationScale, parent.TryGetScale()); Object.DestroyImmediate(parent); } [Test] public void TryGetScaleLocal() { Vector3 destinationScale = Vector3.one * 2f; GameObject parent = new GameObject(); GameObject child = new GameObject(); child.transform.SetParent(parent.transform); child.transform.localScale = destinationScale; parent.transform.SetGlobalScale(destinationScale * 2f); Assert.AreEqual(destinationScale, child.TryGetScale(true)); Object.DestroyImmediate(parent); Object.DestroyImmediate(child); } } }
34.845588
105
0.594218
[ "MIT" ]
Borck/Zinnia.Unity
Tests/Editor/Extension/GameObjectExtensionsTest.cs
9,480
C#
using System; using System.Text; namespace Lorem.Test.Framework.Optimizely.CMS.Utility { public static class IpsumGenerator { private static int Seed = 0; public static string GenerateMobilePhoneNumber() { Random random = new Random(Seed++ + DateTime.Now.Second); return string.Format("{0}{1}{2}-{3} {4} {5}", random.Next(0, 9), random.Next(0, 9), random.Next(0, 9), random.Next(10, 99), random.Next(10, 99), random.Next(100, 999)); } public static string GenerateEmail(bool forceUnique = false) { if (forceUnique) { return $"{Guid.NewGuid().ToString("N")}@autogen.lorem"; } string email = string.Format("{0}.{1}@autogen.lorem", Generate(1, false), Generate(1, false)); return email.ToLower(); } public static string GenerateName() { Random random = new Random(Seed++ + DateTime.Now.Second); int randomNameIndex = random.Next(names.Length - 1); string firstname = names[randomNameIndex]; int randomLastnameIndex = random.Next(lastnames.Length - 1); string lastname = lastnames[randomLastnameIndex]; return $"{firstname} {lastname}"; } public static string Generate(int minWords, int maxWords, bool includeDot = true) { Random random = new Random(Seed++ + DateTime.Now.Second); return Generate(random.Next(minWords, maxWords), includeDot); } public static string Generate(int totalWords, bool includeDot = true) { StringBuilder builder = new StringBuilder(); Random random = new Random(Seed++ + DateTime.Now.Second); double dotAfterWord = (int)(totalWords * random.NextDouble()); bool nextCharUpperCase = true; for (int index = 0; index < totalWords; index++) { if (includeDot && index != 0 && index % dotAfterWord == 0) { builder.Append(". "); nextCharUpperCase = true; dotAfterWord = (int)(totalWords * random.NextDouble()); } int randomWordIndex = random.Next(words.Length - 1); string randomWord = words[randomWordIndex]; if (nextCharUpperCase) { randomWord = char.ToUpper(randomWord[0]) + randomWord.Substring(1); nextCharUpperCase = false; } builder.Append(randomWord).Append(' '); } if (includeDot) { builder.Append("."); } string value = builder.ToString().Trim(); return value.Replace(" .", "."); } public static int Random(int min, int max) { Random random = new Random(Seed++ + DateTime.Now.Second); return random.Next(min, max); } #region Words private static readonly string[] names = new string[] { "Adam", "Adrian", "Albin", "Alex", "Alexander", "Alfred", "Ali", "Alvin", "André", "Andreas", "Anton", "Arvid", "August", "Axel", "Benjamin", "Carl", "Casper", "Charlie", "Christian", "Christoffer", "Daniel", "David", "Dennis", "Eddie", "Edvin", "Elias", "Elliot", "Emanuel", "Emil", "Erik", "Fabian", "Felix", "Filip", "Fredrik", "Gabriel", "Gustav", "Hampus", "Hannes", "Henrik", "Herman", "Hugo", "Isak", "Jack", "Jacob", "Jesper", "Joakim", "Joel", "Johan", "Johannes", "John", "Jonas", "Jonathan", "Josef", "Kalle", "Kevin", "Leo", "Leon", "Liam", "Linus", "Love", "Lucas", "Ludvig", "Malte", "Marcus", "Martin", "Mattias", "Max", "Maximilian", "Melker", "Melvin", "Mikael", "Mohammed", "Måns", "Neo", "Niklas", "Nils", "Noah", "Noel", "Oliver", "Olle", "Oscar", "Otto", "Pontus", "Rasmus", "Rickard", "Robin", "Samuel", "Sebastian", "Simon", "Theo", "Theodor", "Tim", "Tobias", "Viggo", "Viktor", "Wilhelm", "Ville", "William", "Wilmer", "Vincent", "Agnes", "Alexandra", "Alice", "Alicia", "Alma", "Alva", "Amanda", "Andrea", "Anna", "Annie", "Astrid", "Cassandra", "Cornelia", "Ebba", "Elin", "Elina", "Ella", "Ellen", "Ellinor", "Elsa", "Elvira", "Emelie", "Emilia", "Emma", "Emmy", "Engla", "Ester", "Evelina", "Fanny", "Felicia", "Filippa", "Frida", "Gabriella", "Hanna", "Hedda", "Hilda", "Ida", "Isabella", "Isabelle", "Jasmine", "Jennifer", "Jenny", "Johanna", "Jonna", "Josefine", "Julia", "Kajsa", "Klara", "Lina", "Linn", "Linnéa", "Lisa", "Liv", "Louise", "Lova", "Lovisa", "Madeleine", "Maja", "Malin", "Maria", "Matilda", "Meja", "Melissa", "Michelle", "Mikaela", "Minna", "Miranda", "Moa", "Molly", "My", "Nathalie", "Nellie", "Nicole", "Nora", "Nova", "Olivia", "Rebecka", "Ronja", "Saga", "Sandra", "Sanna", "Sara", "Selma", "Siri", "Smilla", "Sofia", "Sofie", "Stella", "Stina", "Thea", "Tilda", "Tilde", "Tindra", "Tova", "Tove", "Tuva", "Tyra", "Vendela", "Vera", "Victoria", "Wilma" }; private static readonly string[] lastnames = new string[] { "Andersson", "Johansson", "Karlsson", "Nilsson", "Eriksson", "Larsson", "Olsson", "Persson", "Svensson", "Gustafsson", "Pettersson", "Jonsson", "Jansson", "Hansson", "Bengtsson", "Jönsson", "Lindberg", "Jakobsson", "Magnusson", "Olofsson", "Lindström", "Lindqvist", "Lindgren", "Axelsson", "Berg", "Bergström", "Lundberg", "Lind", "Lundgren", "Lundqvist", "Mattsson", "Berglund", "Fredriksson", "Sandberg", "Henriksson", "Forsberg", "Sjöberg", "Wallin", "Engström", "Eklund", "Danielsson", "Lundin", "Håkansson", "Ali", "Mohamed", "Björk", "Gunnarsson", "Bergman", "Holm", "Wikström", "Samuelsson", "Fransson", "Isaksson", "Bergqvist", "Nyström", "Holmberg", "Arvidsson", "Löfgren", "Söderberg", "Nyberg", "Blomqvist", "Claesson", "Nordström", "Mårtensson", "Lundström", "Viklund", "Eliasson", "Pålsson", "Björklund", "Berggren", "Ahmed", "Sandström", "Lund", "Nordin", "Hassan", "Ström", "Åberg", "Hermansson", "Ekström", "Holmgren", "Falk", "Dahlberg", "Hellström", "Hedlund", "Sundberg", "Sjögren", "Ek", "Blom", "Abrahamsson", "Martinsson", "Öberg", "Andreasson", "Månsson", "Strömberg", "Åkesson", "Hansen", "Norberg", "Jonasson", "Lindholm", "Dahl" }; private static readonly string[] words = new string[] { "abhorreant", "accommodare", "accumsan", "accusam", "accusamus", "accusamus", "accusata", "accusata", "ad", "ad", "adhuc", "adipisci", "adipiscing", "admodum", "adolescens", "adversarium", "aeque", "aeterno", "affert", "agam", "albucius", "albucius", "alia", "alienum", "alii", "aliquam", "aliquando", "aliquando", "aliquid", "aliquip", "altera", "alterum", "amet", "an", "an", "ancillae", "animal", "animal", "antiopam", "antiopam", "apeirian", "apeirian", "aperiam", "aperiri", "appareat", "appareat", "appellantur", "appellantur", "appetere", "argumentum", "assentior", "assentior", "assueverit", "assum", "assum", "at", "at", "atomorum", "atqui", "audiam", "audiam", "audire", "augue", "autem", "blandit", "bonorum", "bonorum", "brute", "case", "causae", "cetero", "ceteros", "choro", "cibo", "civibus", "civibus", "clita", "commodo", "commodo", "commune", "complectitur", "comprehensam", "comprehensam", "conceptam", "concludaturque", "concludaturque", "conclusionemque", "congue", "consectetuer", "consequat", "consequuntur", "consequuntur", "consetetur", "consetetur", "constituam", "constituam", "constituto", "constituto", "consul", "consulatu", "consulatu", "contentiones", "convenire", "convenire", "copiosae", "corpora", "corpora", "corrumpit", "corrumpit", "cotidieque", "cu", "cu", "cum", "cum", "debet", "debet", "debitis", "decore", "definiebas", "definiebas", "definitionem", "definitiones", "definitiones", "delectus", "delenit", "deleniti", "delicata", "delicata", "delicatissimi", "delicatissimi", "democritum", "denique", "denique", "deseruisse", "deseruisse", "deserunt", "deserunt", "deterruisset", "detracto", "detracto", "detraxit", "detraxit", "diam", "dicam", "dicant", "dicat", "diceret", "diceret", "dicit", "dico", "dicta", "dictas", "dictas", "dicunt", "dignissim", "disputando", "disputando", "disputationi", "disputationi", "dissentias", "dissentias", "dissentiet", "dissentiunt", "dissentiunt", "docendi", "doctus", "dolor", "dolore", "dolorem", "dolores", "dolorum", "dolorum", "doming", "duo", "duo", "ea", "ea", "eam", "eam", "efficiantur", "efficiantur", "efficiendi", "efficiendi", "ei", "ei", "eirmod", "eius", "elaboraret", "elaboraret", "electram", "eleifend", "eleifend", "eligendi", "elit", "elitr", "eloquentiam", "eloquentiam", "enim", "eos", "eos", "epicurei", "epicurei", "epicuri", "epicuri", "equidem", "erant", "erat", "eripuit", "eripuit", "eros", "errem", "errem", "error", "erroribus", "eruditi", "esse", "essent", "est", "est", "et", "et", "etiam", "eu", "eu", "euismod", "eum", "eum", "euripidis", "everti", "everti", "evertitur", "evertitur", "ex", "ex", "exerci", "expetenda", "expetenda", "expetendis", "explicari", "explicari", "fabellas", "fabulas", "facer", "facete", "facilis", "facilisi", "facilisis", "facilisis", "falli", "fastidii", "fastidii", "ferri", "feugait", "feugiat", "fierent", "forensibus", "forensibus", "fugit", "fugit", "fuisset", "gloriatur", "graece", "graeci", "graecis", "graeco", "gubergren", "gubergren", "habemus", "habeo", "harum", "has", "has", "hendrerit", "hendrerit", "hinc", "his", "his", "homero", "honestatis", "id", "id", "idque", "ignota", "iisque", "illud", "illum", "impedit", "imperdiet", "impetus", "in", "in", "inani", "inciderint", "inciderint", "incorrupte", "incorrupte", "indoctum", "inermis", "inermis", "inimicus", "inimicus", "insolens", "instructior", "integre", "intellegam", "intellegat", "intellegebat", "intellegebat", "interesset", "interpretaris", "interpretaris", "invenire", "invenire", "invidunt", "ipsum", "iracundia", "iriure", "iudicabit", "iudico", "iudico", "ius", "ius", "iusto", "iuvaret", "justo", "labitur", "laboramus", "laboramus", "labore", "labores", "labores", "laoreet", "latine", "laudem", "legendos", "legere", "legimus", "liber", "liberavisse", "libris", "lobortis", "lobortis", "lorem", "lucilius", "lucilius", "ludus", "luptatum", "luptatum", "magna", "maiestatis", "maiorum", "maiorum", "malis", "malis", "malorum", "malorum", "maluisset", "maluisset", "mandamus", "mazim", "mea", "mea", "mediocrem", "mediocritatem", "mei", "mei", "meis", "mel", "mel", "meliore", "melius", "menandri", "mentitum", "mentitum", "minim", "minimum", "minimum", "mnesarchum", "mnesarchum", "moderatius", "modo", "modus", "molestiae", "molestie", "mollis", "movet", "mucius", "mundi", "mundi", "munere", "mutat", "mutat", "nam", "nam", "natum", "ne", "ne", "nec", "nec", "necessitatibus", "neglegentur", "neglegentur", "nemore", "nibh", "nihil", "nisl", "no", "no", "nobis", "noluisse", "noluisse", "nominati", "nominati", "nominavi", "nominavi", "nonumes", "nonumy", "noster", "nostro", "nostrud", "nostrum", "novum", "nulla", "nullam", "numquam", "nusquam", "nusquam", "oblique", "ocurreret", "odio", "offendit", "offendit", "officiis", "omittam", "omittantur", "omnes", "omnesque", "omnis", "omnium", "oporteat", "oportere", "oportere", "option", "oratio", "ornatus", "partem", "partem", "partiendo", "patrioque", "paulo", "per", "per", "percipit", "percipit", "percipitur", "perfecto", "perfecto", "pericula", "periculis", "perpetua", "persecuti", "persequeris", "persius", "persius", "pertinacia", "pertinacia", "pertinax", "petentium", "petentium", "phaedrum", "phaedrum", "philosophia", "placerat", "platonem", "ponderum", "ponderum", "populo", "porro", "posidonium", "posidonium", "posse", "possim", "possit", "postea", "postea", "postulant", "postulant", "praesent", "pri", "pri", "prima", "primis", "principes", "principes", "pro", "pro", "probatus", "probo", "prodesset", "prodesset", "prompta", "prompta", "propriae", "purto", "putant", "putent", "putent", "quaeque", "quaerendum", "quaerendum", "quaestio", "qualisque", "qualisque", "quando", "quando", "quas", "quem", "qui", "qui", "quidam", "quis", "quo", "quo", "quod", "quodsi", "quodsi", "quot", "rationibus", "rationibus", "rebum", "recteque", "recusabo", "referrentur", "reformidans", "regione", "reprehendunt", "reprimique", "repudiandae", "repudiandae", "repudiare", "reque", "ridens", "sadipscing", "sadipscing", "saepe", "saepe", "sale", "salutandi", "salutatus", "sanctus", "saperet", "sapientem", "scaevola", "scribentur", "scribentur", "scripserit", "scripserit", "scripta", "scriptorem", "scriptorem", "sea", "sea", "sed", "sed", "semper", "semper", "senserit", "sensibus", "sensibus", "sententiae", "signiferumque", "similique", "similique", "simul", "singulis", "sint", "sit", "sit", "soleat", "soleat", "solet", "solum", "soluta", "sonet", "splendide", "stet", "suas", "suavitate", "summo", "sumo", "suscipiantur", "suscipiantur", "suscipit", "tacimates", "tale", "tamquam", "tantas", "tation", "te", "te", "tempor", "temporibus", "theophrastus", "tibique", "tibique", "timeam", "timeam", "tincidunt", "tincidunt", "tollit", "torquatos", "tota", "tractatos", "tractatos", "tritani", "ubique", "ullamcorper", "ullamcorper", "ullum", "unum", "unum", "urbanitas", "usu", "usu", "ut", "ut", "utamur", "utinam", "utroque", "vel", "vel", "velit", "veniam", "verear", "verear", "veri", "veritus", "vero", "verterem", "vide", "vide", "viderer", "vidisse", "vidit", "vim", "vim", "viris", "virtute", "vis", "vis", "vitae", "vituperata", "vituperatoribus", "vituperatoribus", "vivendo", "vivendum", "vix", "vix", "vocent", "vocibus", "volumus", "voluptaria", "voluptatibus", "voluptatum", "voluptua", "voluptua", "volutpat", "volutpat", "vulputate", "vulputate", "wisi", "zril" }; #endregion } }
24.71177
114
0.312219
[ "MIT" ]
Crasnam/episerver-testframework
src/net48/Lorem.Test.Framework.Optimizely.CMS/Utility/IpsumGenerator.cs
26,695
C#
namespace FoodShortage.Models { using Contracts; public class Citizen : Person, IIdentifiable { public Citizen( string name, int age, string id, string birthdate) : base(name, age, birthdate) { this.Id = id; } public string Id { get; private set; } public override void BuyFood() { this.Food += 10; } } }
18.72
48
0.470085
[ "MIT" ]
DiyanApostolov/SoftUni-Software-Engineering
C# OOP/Homeworks-And-Labs/03.InterfacesAndAbstraction-Exercise/06.FoodShortage/Models/Citizen.cs
470
C#
using System.ComponentModel.DataAnnotations; namespace Kasp.Identity.Core.Entities.UserEntities.XEntities; public class UserEditModelBase { [MaxLength(100)] public string Name { get; set; } }
24.5
62
0.795918
[ "MIT" ]
mo3in/Kasp
src/Kasp.Identity.Core/Entities/UserEntities/XEntities/UserEditModelBase.cs
196
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.IO; using System.IO.Compression; using System.Text; namespace SimpleIdServer.Saml.Helpers { public static class Compression { public static string Decompress(string parameter) { if (TryDecompress(parameter, out string result)) { return result; } return Encoding.UTF8.GetString(Convert.FromBase64String(parameter)); } public static bool TryDecompress(string parameter, out string result) { result = null; try { using (var originalStream = new MemoryStream(Convert.FromBase64String(parameter))) using (var decompressedStream = new MemoryStream()) { using (var deflateStream = new DeflateStream(originalStream, CompressionMode.Decompress)) { deflateStream.CopyTo(decompressedStream); } result = Encoding.UTF8.GetString(decompressedStream.ToArray()); return true; } } catch { return false; } } public static string Compress(string parameter) { using (var compressedStream = new MemoryStream()) using (var deflateStream = new DeflateStream(compressedStream, CompressionLevel.Optimal)) { using (var originalStream = new StreamWriter(deflateStream)) { originalStream.Write(parameter); } var buffer = compressedStream.GetBuffer(); var lastIndex = Array.FindLastIndex(buffer, b => b != 0); Array.Resize(ref buffer, lastIndex + 1); return Convert.ToBase64String(buffer); } } } }
33.031746
109
0.551177
[ "Apache-2.0" ]
LaTranche31/SimpleIdServer
src/Saml/SimpleIdServer.Saml/Helpers/Compression.cs
2,083
C#
/* * Copyright 2020 Mikhail Shiryaev * * 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. * * * Product : Rapid SCADA * Module : SCADA-Web * Summary : View web form * * Author : Mikhail Shiryaev * Created : 2016 * Modified : 2020 */ using Scada.UI; using Scada.Web.Plugins; using Scada.Web.Shell; using System; using System.Text; namespace Scada.Web { /// <summary> /// View web form /// <para>Веб-форма представления</para> /// </summary> public partial class WFrmView : System.Web.UI.Page { private UserData userData; // данные пользователя приложения protected int initialViewID; // ид. первоначального представления protected string initialViewUrl; // ссылка первоначального представления /// <summary> /// Генерировать HTML-код нижних закладок /// </summary> protected string GenerateBottomTabsHtml() { const string TabTemplate = "<div class='tab{0}' data-code='{1}' data-url='{2}' data-depends='{3}'>{4}</div>"; StringBuilder sbHtml = new StringBuilder(); foreach (DataWndItem dataWndItem in userData.UserContent.DataWndItems) { DataWndSpec dataWndSpec = dataWndItem.DataWndSpec; if (dataWndSpec == null) sbHtml.AppendFormat(TabTemplate, " disabled", "", "", "", dataWndItem.Text); else sbHtml.AppendFormat(TabTemplate, "", dataWndSpec.TypeCode, ResolveUrl(dataWndItem.Url), dataWndSpec.DependsOnView ? "true" : "false", dataWndItem.Text); } return sbHtml.ToString(); } protected void Page_Load(object sender, EventArgs e) { userData = UserData.GetUserData(); userData.CheckLoggedOn(true); // перевод веб-страницы Translator.TranslatePage(Page, "Scada.Web.WFrmView"); // получение ид. и ссылки представления для загрузки initialViewID = Request.QueryString.GetParamAsInt("viewID"); ViewNode viewNode; if (initialViewID > 0) { viewNode = userData.UserViews.GetViewNode(initialViewID); } else { viewNode = userData.UserViews.GetFirstViewNode(); initialViewID = viewNode == null ? 0 : viewNode.ViewID; } initialViewUrl = viewNode == null || string.IsNullOrEmpty(viewNode.ViewUrl) ? ResolveUrl(UrlTemplates.NoView) : viewNode.ViewUrl; ((MasterMain)Master).SelectedViewID = initialViewID; } } }
33.510417
107
0.609263
[ "Apache-2.0" ]
Arvid-new/scada
ScadaWeb/ScadaWeb/ScadaWebShell/View.aspx.cs
3,421
C#
namespace SpaceInvaders.Models { public class ScoreValueDto { public int PlayerId { get; set; } public int score { get; set; } } }
17.777778
41
0.59375
[ "Unlicense" ]
BjarniPeturFridjonsson/SpaceInvaders
SpaceInvadersDotNet/Models/ScoreValueDto.cs
162
C#
namespace BDInSelfLove.Common { using System; using TimeZoneConverter; public static class TimezoneHelper { public static TimeZoneInfo GetUserWindowsTimezone(string timezone) { if (timezone == null) { return null; } return TZConvert.GetTimeZoneInfo(timezone); } public static DateTime ToUTCTime(DateTime localTime, string timezone) { if (timezone == null) { return localTime; } return TimeZoneInfo.ConvertTimeToUtc(localTime, GetUserWindowsTimezone(timezone)); } public static DateTime ToLocalTime(DateTime utcTime, string timezone) { if (timezone == null) { return utcTime; } TimeZoneInfo userWindowsTimezone = TZConvert.GetTimeZoneInfo(GetUserWindowsTimezone(timezone).Id); DateTime userLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, userWindowsTimezone); return userLocalTime; } } }
26.380952
110
0.58213
[ "MIT" ]
ivanBalev/InSelfLove
BDInSelfLove.Common/TimezoneHelper.cs
1,110
C#
 namespace mrHelper.App.Forms { partial class ConfigureNotificationsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBoxNotifications = new System.Windows.Forms.GroupBox(); this.checkBoxShowMergedMergeRequests = new System.Windows.Forms.CheckBox(); this.checkBoxShowServiceNotifications = new System.Windows.Forms.CheckBox(); this.checkBoxShowNewMergeRequests = new System.Windows.Forms.CheckBox(); this.checkBoxShowMyActivity = new System.Windows.Forms.CheckBox(); this.checkBoxShowUpdatedMergeRequests = new System.Windows.Forms.CheckBox(); this.checkBoxShowKeywords = new System.Windows.Forms.CheckBox(); this.checkBoxShowResolvedAll = new System.Windows.Forms.CheckBox(); this.checkBoxShowOnMention = new System.Windows.Forms.CheckBox(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.groupBoxNotifications.SuspendLayout(); this.SuspendLayout(); // // groupBoxNotifications // this.groupBoxNotifications.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.groupBoxNotifications.Controls.Add(this.checkBoxShowMergedMergeRequests); this.groupBoxNotifications.Controls.Add(this.checkBoxShowServiceNotifications); this.groupBoxNotifications.Controls.Add(this.checkBoxShowNewMergeRequests); this.groupBoxNotifications.Controls.Add(this.checkBoxShowMyActivity); this.groupBoxNotifications.Controls.Add(this.checkBoxShowUpdatedMergeRequests); this.groupBoxNotifications.Controls.Add(this.checkBoxShowKeywords); this.groupBoxNotifications.Controls.Add(this.checkBoxShowResolvedAll); this.groupBoxNotifications.Controls.Add(this.checkBoxShowOnMention); this.groupBoxNotifications.Location = new System.Drawing.Point(12, 12); this.groupBoxNotifications.Name = "groupBoxNotifications"; this.groupBoxNotifications.Size = new System.Drawing.Size(486, 145); this.groupBoxNotifications.TabIndex = 0; this.groupBoxNotifications.TabStop = false; this.groupBoxNotifications.Text = "Notifications"; // // checkBoxShowMergedMergeRequests // this.checkBoxShowMergedMergeRequests.AutoSize = true; this.checkBoxShowMergedMergeRequests.Location = new System.Drawing.Point(6, 41); this.checkBoxShowMergedMergeRequests.Name = "checkBoxShowMergedMergeRequests"; this.checkBoxShowMergedMergeRequests.Size = new System.Drawing.Size(189, 17); this.checkBoxShowMergedMergeRequests.TabIndex = 1; this.checkBoxShowMergedMergeRequests.Text = "Merged or closed Merge Requests"; this.checkBoxShowMergedMergeRequests.UseVisualStyleBackColor = true; // // checkBoxShowServiceNotifications // this.checkBoxShowServiceNotifications.AutoSize = true; this.checkBoxShowServiceNotifications.Location = new System.Drawing.Point(228, 120); this.checkBoxShowServiceNotifications.Name = "checkBoxShowServiceNotifications"; this.checkBoxShowServiceNotifications.Size = new System.Drawing.Size(149, 17); this.checkBoxShowServiceNotifications.TabIndex = 7; this.checkBoxShowServiceNotifications.Text = "Show service notifications"; this.checkBoxShowServiceNotifications.UseVisualStyleBackColor = true; // // checkBoxShowNewMergeRequests // this.checkBoxShowNewMergeRequests.AutoSize = true; this.checkBoxShowNewMergeRequests.Location = new System.Drawing.Point(6, 18); this.checkBoxShowNewMergeRequests.Name = "checkBoxShowNewMergeRequests"; this.checkBoxShowNewMergeRequests.Size = new System.Drawing.Size(129, 17); this.checkBoxShowNewMergeRequests.TabIndex = 0; this.checkBoxShowNewMergeRequests.Text = "New Merge Requests"; this.checkBoxShowNewMergeRequests.UseVisualStyleBackColor = true; // // checkBoxShowMyActivity // this.checkBoxShowMyActivity.AutoSize = true; this.checkBoxShowMyActivity.Location = new System.Drawing.Point(6, 120); this.checkBoxShowMyActivity.Name = "checkBoxShowMyActivity"; this.checkBoxShowMyActivity.Size = new System.Drawing.Size(113, 17); this.checkBoxShowMyActivity.TabIndex = 6; this.checkBoxShowMyActivity.Text = "Include my activity"; this.checkBoxShowMyActivity.UseVisualStyleBackColor = true; // // checkBoxShowUpdatedMergeRequests // this.checkBoxShowUpdatedMergeRequests.AutoSize = true; this.checkBoxShowUpdatedMergeRequests.Location = new System.Drawing.Point(6, 64); this.checkBoxShowUpdatedMergeRequests.Name = "checkBoxShowUpdatedMergeRequests"; this.checkBoxShowUpdatedMergeRequests.Size = new System.Drawing.Size(181, 17); this.checkBoxShowUpdatedMergeRequests.TabIndex = 2; this.checkBoxShowUpdatedMergeRequests.Text = "New commits in Merge Requests"; this.checkBoxShowUpdatedMergeRequests.UseVisualStyleBackColor = true; // // checkBoxShowKeywords // this.checkBoxShowKeywords.AutoSize = true; this.checkBoxShowKeywords.Location = new System.Drawing.Point(6, 87); this.checkBoxShowKeywords.Name = "checkBoxShowKeywords"; this.checkBoxShowKeywords.Size = new System.Drawing.Size(75, 17); this.checkBoxShowKeywords.TabIndex = 5; this.checkBoxShowKeywords.Text = "Keywords:"; this.checkBoxShowKeywords.UseVisualStyleBackColor = true; // // checkBoxShowResolvedAll // this.checkBoxShowResolvedAll.AutoSize = true; this.checkBoxShowResolvedAll.Location = new System.Drawing.Point(228, 18); this.checkBoxShowResolvedAll.Name = "checkBoxShowResolvedAll"; this.checkBoxShowResolvedAll.Size = new System.Drawing.Size(127, 17); this.checkBoxShowResolvedAll.TabIndex = 3; this.checkBoxShowResolvedAll.Text = "Resolved All Threads"; this.checkBoxShowResolvedAll.UseVisualStyleBackColor = true; // // checkBoxShowOnMention // this.checkBoxShowOnMention.AutoSize = true; this.checkBoxShowOnMention.Location = new System.Drawing.Point(228, 41); this.checkBoxShowOnMention.Name = "checkBoxShowOnMention"; this.checkBoxShowOnMention.Size = new System.Drawing.Size(170, 17); this.checkBoxShowOnMention.TabIndex = 4; this.checkBoxShowOnMention.Text = "When someone mentioned me"; this.checkBoxShowOnMention.UseVisualStyleBackColor = true; // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Location = new System.Drawing.Point(12, 163); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 1; this.buttonOK.Text = "OK"; this.buttonOK.UseVisualStyleBackColor = true; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(93, 163); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 2; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // ConfigureNotificationsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(510, 195); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOK); this.Controls.Add(this.groupBoxNotifications); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = global::mrHelper.App.Properties.Resources.DefaultAppIcon; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ConfigureNotificationsForm"; this.Text = "Configure Notifications"; this.groupBoxNotifications.ResumeLayout(false); this.groupBoxNotifications.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBoxNotifications; private System.Windows.Forms.CheckBox checkBoxShowMergedMergeRequests; private System.Windows.Forms.CheckBox checkBoxShowServiceNotifications; private System.Windows.Forms.CheckBox checkBoxShowNewMergeRequests; private System.Windows.Forms.CheckBox checkBoxShowMyActivity; private System.Windows.Forms.CheckBox checkBoxShowUpdatedMergeRequests; private System.Windows.Forms.CheckBox checkBoxShowKeywords; private System.Windows.Forms.CheckBox checkBoxShowResolvedAll; private System.Windows.Forms.CheckBox checkBoxShowOnMention; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; } }
52.960396
166
0.696298
[ "MIT" ]
denis-adamchuk/mrHelper
src/App/src/Forms/ConfigureNotificationsForm.Designer.cs
10,700
C#
using System; using System.Windows.Forms; using DevOps.ReportsScreen; using GameManagement; using LibCore; namespace DevOps.OpsScreen.SecondaryDisplay { internal partial class SecondaryDisplayForm : Form { public SecondaryDisplayForm(NetworkProgressionGameFile gameFile) { FormBorderStyle = FormBorderStyle.None; displayPanel = new SecondaryDisplayPanel(gameFile); Controls.Add(displayPanel); InitializeComponent(); } public NetworkProgressionGameFile GameFile { set => displayPanel.GameFile = value; } public void ShowGameScreen (GameScreenPanel newGameScreen) { displayPanel.ShowGameScreen(newGameScreen); } public void ShowReportScreen (ReportsScreenPanel newReportsScreen) { displayPanel.ShowReportsScreen(newReportsScreen); } protected override CreateParams CreateParams { get { var createParams = base.CreateParams; createParams.Style &= ~0x00C0000; // remove WS_CAPTION createParams.Style |= 0x00040000; // include WS_SIZEBOX return createParams; } } protected override void OnVisibleChanged (EventArgs e) { base.OnVisibleChanged(e); if (Visible) { DoSize(); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { ((Form)TopLevelControl).DragMove(); } } protected override void OnSizeChanged (EventArgs e) { DoSize(); } void DoSize () { displayPanel.Size = ClientSize; } readonly SecondaryDisplayPanel displayPanel; } }
23.517647
74
0.56078
[ "MIT-0" ]
business-sims-toolkit/business-sims-toolkit
dev/products/eboards/DevOps/DevOps/DevOps.OpsScreen/SecondaryDisplay/SecondaryDisplayForm.cs
2,001
C#
using System; using UMapx.Core; namespace UMapx.Distribution { /// <summary> /// Defines the log-logistic distribution. /// <remarks> /// More information can be found on the website: /// https://en.wikipedia.org/wiki/Log-logistic_distribution /// </remarks> /// </summary> [Serializable] public class LogLogistic : IDistribution { #region Private data private float a = 1; private float b = 1; #endregion #region LogLogistic components /// <summary> /// Initializes the log-logistic distribution. /// </summary> public LogLogistic() { } /// <summary> /// Initializes the log-logistic distribution. /// </summary> /// <param name="a">Parameter a</param> /// <param name="b">Parameter b</param> public LogLogistic(float a, float b) { A = a; B = b; } /// <summary> /// Gets or sets the value of parameter a. /// </summary> public float A { get { return this.a; } set { if (value <= 0) throw new Exception("Invalid argument value"); this.a = value; } } /// <summary> /// Gets or sets the value of parameter b. /// </summary> public float B { get { return this.b; } set { if (value <= 0) throw new Exception("Invalid argument value"); this.b = value; } } /// <summary> /// Gets the support interval of the argument. /// </summary> public RangeFloat Support { get { return new RangeFloat(0, float.PositiveInfinity); } } /// <summary> /// Gets the mean value. /// </summary> public float Mean { get { throw new NotSupportedException(); } } /// <summary> /// Gets the variance value. /// </summary> public float Variance { get { throw new NotSupportedException(); } } /// <summary> /// Gets the mode value. /// </summary> public float Mode { get { if (b > 1) { return a * (float)Math.Pow((b - 1) / (b + 1), 1 / b); } return 0; } } /// <summary> /// Gets the median value. /// </summary> public float Median { get { throw new NotSupportedException(); } } /// <summary> /// Gets the value of the asymmetry coefficient. /// </summary> public float Skewness { get { throw new NotSupportedException(); } } /// <summary> /// Gets the kurtosis coefficient. /// </summary> public float Excess { get { throw new NotSupportedException(); } } /// <summary> /// Returns the value of the probability density function. /// </summary> /// <param name="x">Value</param> /// <returns>float precision floating point number</returns> public float Function(float x) { return (b / a) * (float)Math.Pow(x / a, b - 1) / (1.0f + (float)Math.Pow(Math.Pow(x / a, b), 2)); } /// <summary> /// Returns the value of the probability distribution function. /// </summary> /// <param name="x">Value</param> /// <returns>float precision floating point number</returns> public float Distribution(float x) { return 1.0f / (1 + (float)Math.Pow(x / a, -b)); } /// <summary> /// Returns the value of differential entropy. /// </summary> /// <returns>float precision floating point number</returns> public float Entropy { get { throw new NotSupportedException(); } } #endregion } }
27.420382
109
0.455285
[ "MIT" ]
UMapx/UMapx
sources/Distribution/LogLogistic.cs
4,307
C#
// <copyright file="AllureReportingSettings.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System; using System.Collections.Generic; using System.Text; namespace Bellatrix.Results.Allure { public class AllureReportingSettings { public bool IsEnabled { get; set; } } }
38.76
85
0.74613
[ "Apache-2.0" ]
48x16/BELLATRIX
src/Bellatrix.Allure/AllureReportingSettings.cs
971
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Player : MonoBehaviour, IDropHandler { public Image playerImage = null; public Image mirrorImage = null; public Image healthNumberImage = null; public Image glowImage = null; public int maxHealth = 5; public int health = 5; // current health public int mana = 1; public bool isPlayer; public bool isFire; public GameObject[] manaBalls = new GameObject[5]; private Animator animator = null; public AudioSource dealAudio = null; public AudioSource healAudio = null; public AudioSource mirrorAudio = null; public AudioSource smashAudio = null; void Start() { animator = GetComponent<Animator>(); UpdateHealth(); UpdateManaBalls(); } internal void PlayHitAnim() { if (animator != null) animator.SetTrigger("Hit"); } public void OnDrop(PointerEventData eventData) { if (!GameController.instance.isPlayable) return; GameObject obj = eventData.pointerDrag; if (obj != null) { Card card = obj.GetComponent<Card>(); if (card!=null) { GameController.instance.UseCard(card, this, GameController.instance.playersHand); } } } internal void UpdateHealth() { if (health>=0 && health< GameController.instance.healthNumbers.Length) { healthNumberImage.sprite = GameController.instance.healthNumbers[health]; } else { Debug.LogWarning("Health is not a valid number," + health.ToString()); } } internal void SetMirror(bool on) { mirrorImage.gameObject.SetActive(on); } internal bool hasMirror() { return mirrorImage.gameObject.activeInHierarchy; } internal void UpdateManaBalls() { for(int m = 0; m < 5; m++) { if (mana > m) manaBalls[m].SetActive(true); else manaBalls[m].SetActive(false); } } internal void PlayMirrorSound() { mirrorAudio.Play(); } internal void PlaySmashSound() { smashAudio.Play(); } internal void PlayHealSound() { healAudio.Play(); } internal void PlayCardSound() { dealAudio.Play(); } }
21.801724
97
0.584421
[ "MIT" ]
r00tMakesGames/XAMK-Card-Game
Assets/Scripts/Player.cs
2,531
C#
// Copyright (c) 2021 OPEN CASCADE SAS // // This file is part of the examples of the Open CASCADE Technology software library. // // 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 // include required OCCT headers using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]
45.444444
90
0.708775
[ "MIT" ]
Open-Cascade-SAS/OCCT-samples-.NET
WinForms/AssemblyInfo.cs
3,601
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotwireless-2020-11-22.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Net; using Amazon.IoTWireless.Model; using Amazon.IoTWireless.Model.Internal.MarshallTransformations; using Amazon.IoTWireless.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.IoTWireless { /// <summary> /// Implementation for accessing IoTWireless /// /// AWS IoT Wireless API documentation /// </summary> public partial class AmazonIoTWirelessClient : AmazonServiceClient, IAmazonIoTWireless { private static IServiceMetadata serviceMetadata = new AmazonIoTWirelessMetadata(); private IIoTWirelessPaginatorFactory _paginators; /// <summary> /// Paginators for the service /// </summary> public IIoTWirelessPaginatorFactory Paginators { get { if (this._paginators == null) { this._paginators = new IoTWirelessPaginatorFactory(this); } return this._paginators; } } #region Constructors /// <summary> /// Constructs AmazonIoTWirelessClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonIoTWirelessClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTWirelessConfig()) { } /// <summary> /// Constructs AmazonIoTWirelessClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonIoTWirelessClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTWirelessConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTWirelessClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonIoTWirelessClient Configuration Object</param> public AmazonIoTWirelessClient(AmazonIoTWirelessConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonIoTWirelessClient(AWSCredentials credentials) : this(credentials, new AmazonIoTWirelessConfig()) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonIoTWirelessClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonIoTWirelessConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Credentials and an /// AmazonIoTWirelessClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonIoTWirelessClient Configuration Object</param> public AmazonIoTWirelessClient(AWSCredentials credentials, AmazonIoTWirelessConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTWirelessConfig()) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTWirelessConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID, AWS Secret Key and an /// AmazonIoTWirelessClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonIoTWirelessClient Configuration Object</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonIoTWirelessConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTWirelessConfig()) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTWirelessConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTWirelessClient with AWS Access Key ID, AWS Secret Key and an /// AmazonIoTWirelessClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonIoTWirelessClient Configuration Object</param> public AmazonIoTWirelessClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonIoTWirelessConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AssociateAwsAccountWithPartnerAccount /// <summary> /// Associates a partner account with your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateAwsAccountWithPartnerAccount service method.</param> /// /// <returns>The response from the AssociateAwsAccountWithPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateAwsAccountWithPartnerAccount">REST API Reference for AssociateAwsAccountWithPartnerAccount Operation</seealso> public virtual AssociateAwsAccountWithPartnerAccountResponse AssociateAwsAccountWithPartnerAccount(AssociateAwsAccountWithPartnerAccountRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateAwsAccountWithPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateAwsAccountWithPartnerAccountResponseUnmarshaller.Instance; return Invoke<AssociateAwsAccountWithPartnerAccountResponse>(request, options); } /// <summary> /// Associates a partner account with your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateAwsAccountWithPartnerAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AssociateAwsAccountWithPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateAwsAccountWithPartnerAccount">REST API Reference for AssociateAwsAccountWithPartnerAccount Operation</seealso> public virtual Task<AssociateAwsAccountWithPartnerAccountResponse> AssociateAwsAccountWithPartnerAccountAsync(AssociateAwsAccountWithPartnerAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateAwsAccountWithPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateAwsAccountWithPartnerAccountResponseUnmarshaller.Instance; return InvokeAsync<AssociateAwsAccountWithPartnerAccountResponse>(request, options, cancellationToken); } #endregion #region AssociateWirelessDeviceWithThing /// <summary> /// Associates a wireless device with a thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessDeviceWithThing service method.</param> /// /// <returns>The response from the AssociateWirelessDeviceWithThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessDeviceWithThing">REST API Reference for AssociateWirelessDeviceWithThing Operation</seealso> public virtual AssociateWirelessDeviceWithThingResponse AssociateWirelessDeviceWithThing(AssociateWirelessDeviceWithThingRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessDeviceWithThingRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessDeviceWithThingResponseUnmarshaller.Instance; return Invoke<AssociateWirelessDeviceWithThingResponse>(request, options); } /// <summary> /// Associates a wireless device with a thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessDeviceWithThing service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AssociateWirelessDeviceWithThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessDeviceWithThing">REST API Reference for AssociateWirelessDeviceWithThing Operation</seealso> public virtual Task<AssociateWirelessDeviceWithThingResponse> AssociateWirelessDeviceWithThingAsync(AssociateWirelessDeviceWithThingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessDeviceWithThingRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessDeviceWithThingResponseUnmarshaller.Instance; return InvokeAsync<AssociateWirelessDeviceWithThingResponse>(request, options, cancellationToken); } #endregion #region AssociateWirelessGatewayWithCertificate /// <summary> /// Associates a wireless gateway with a certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessGatewayWithCertificate service method.</param> /// /// <returns>The response from the AssociateWirelessGatewayWithCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessGatewayWithCertificate">REST API Reference for AssociateWirelessGatewayWithCertificate Operation</seealso> public virtual AssociateWirelessGatewayWithCertificateResponse AssociateWirelessGatewayWithCertificate(AssociateWirelessGatewayWithCertificateRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessGatewayWithCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessGatewayWithCertificateResponseUnmarshaller.Instance; return Invoke<AssociateWirelessGatewayWithCertificateResponse>(request, options); } /// <summary> /// Associates a wireless gateway with a certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessGatewayWithCertificate service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AssociateWirelessGatewayWithCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessGatewayWithCertificate">REST API Reference for AssociateWirelessGatewayWithCertificate Operation</seealso> public virtual Task<AssociateWirelessGatewayWithCertificateResponse> AssociateWirelessGatewayWithCertificateAsync(AssociateWirelessGatewayWithCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessGatewayWithCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessGatewayWithCertificateResponseUnmarshaller.Instance; return InvokeAsync<AssociateWirelessGatewayWithCertificateResponse>(request, options, cancellationToken); } #endregion #region AssociateWirelessGatewayWithThing /// <summary> /// Associates a wireless gateway with a thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessGatewayWithThing service method.</param> /// /// <returns>The response from the AssociateWirelessGatewayWithThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessGatewayWithThing">REST API Reference for AssociateWirelessGatewayWithThing Operation</seealso> public virtual AssociateWirelessGatewayWithThingResponse AssociateWirelessGatewayWithThing(AssociateWirelessGatewayWithThingRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessGatewayWithThingRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessGatewayWithThingResponseUnmarshaller.Instance; return Invoke<AssociateWirelessGatewayWithThingResponse>(request, options); } /// <summary> /// Associates a wireless gateway with a thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateWirelessGatewayWithThing service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AssociateWirelessGatewayWithThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/AssociateWirelessGatewayWithThing">REST API Reference for AssociateWirelessGatewayWithThing Operation</seealso> public virtual Task<AssociateWirelessGatewayWithThingResponse> AssociateWirelessGatewayWithThingAsync(AssociateWirelessGatewayWithThingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateWirelessGatewayWithThingRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateWirelessGatewayWithThingResponseUnmarshaller.Instance; return InvokeAsync<AssociateWirelessGatewayWithThingResponse>(request, options, cancellationToken); } #endregion #region CreateDestination /// <summary> /// Creates a new destination that maps a device message to an AWS IoT rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDestination service method.</param> /// /// <returns>The response from the CreateDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateDestination">REST API Reference for CreateDestination Operation</seealso> public virtual CreateDestinationResponse CreateDestination(CreateDestinationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDestinationResponseUnmarshaller.Instance; return Invoke<CreateDestinationResponse>(request, options); } /// <summary> /// Creates a new destination that maps a device message to an AWS IoT rule. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateDestination">REST API Reference for CreateDestination Operation</seealso> public virtual Task<CreateDestinationResponse> CreateDestinationAsync(CreateDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDestinationResponseUnmarshaller.Instance; return InvokeAsync<CreateDestinationResponse>(request, options, cancellationToken); } #endregion #region CreateDeviceProfile /// <summary> /// Creates a new device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDeviceProfile service method.</param> /// /// <returns>The response from the CreateDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateDeviceProfile">REST API Reference for CreateDeviceProfile Operation</seealso> public virtual CreateDeviceProfileResponse CreateDeviceProfile(CreateDeviceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDeviceProfileResponseUnmarshaller.Instance; return Invoke<CreateDeviceProfileResponse>(request, options); } /// <summary> /// Creates a new device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDeviceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateDeviceProfile">REST API Reference for CreateDeviceProfile Operation</seealso> public virtual Task<CreateDeviceProfileResponse> CreateDeviceProfileAsync(CreateDeviceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDeviceProfileResponseUnmarshaller.Instance; return InvokeAsync<CreateDeviceProfileResponse>(request, options, cancellationToken); } #endregion #region CreateServiceProfile /// <summary> /// Creates a new service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateServiceProfile service method.</param> /// /// <returns>The response from the CreateServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateServiceProfile">REST API Reference for CreateServiceProfile Operation</seealso> public virtual CreateServiceProfileResponse CreateServiceProfile(CreateServiceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateServiceProfileResponseUnmarshaller.Instance; return Invoke<CreateServiceProfileResponse>(request, options); } /// <summary> /// Creates a new service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateServiceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateServiceProfile">REST API Reference for CreateServiceProfile Operation</seealso> public virtual Task<CreateServiceProfileResponse> CreateServiceProfileAsync(CreateServiceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateServiceProfileResponseUnmarshaller.Instance; return InvokeAsync<CreateServiceProfileResponse>(request, options, cancellationToken); } #endregion #region CreateWirelessDevice /// <summary> /// Provisions a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessDevice service method.</param> /// /// <returns>The response from the CreateWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessDevice">REST API Reference for CreateWirelessDevice Operation</seealso> public virtual CreateWirelessDeviceResponse CreateWirelessDevice(CreateWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessDeviceResponseUnmarshaller.Instance; return Invoke<CreateWirelessDeviceResponse>(request, options); } /// <summary> /// Provisions a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessDevice">REST API Reference for CreateWirelessDevice Operation</seealso> public virtual Task<CreateWirelessDeviceResponse> CreateWirelessDeviceAsync(CreateWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<CreateWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region CreateWirelessGateway /// <summary> /// Provisions a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGateway service method.</param> /// /// <returns>The response from the CreateWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGateway">REST API Reference for CreateWirelessGateway Operation</seealso> public virtual CreateWirelessGatewayResponse CreateWirelessGateway(CreateWirelessGatewayRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayResponseUnmarshaller.Instance; return Invoke<CreateWirelessGatewayResponse>(request, options); } /// <summary> /// Provisions a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGateway service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGateway">REST API Reference for CreateWirelessGateway Operation</seealso> public virtual Task<CreateWirelessGatewayResponse> CreateWirelessGatewayAsync(CreateWirelessGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayResponseUnmarshaller.Instance; return InvokeAsync<CreateWirelessGatewayResponse>(request, options, cancellationToken); } #endregion #region CreateWirelessGatewayTask /// <summary> /// Creates a task for a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGatewayTask service method.</param> /// /// <returns>The response from the CreateWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGatewayTask">REST API Reference for CreateWirelessGatewayTask Operation</seealso> public virtual CreateWirelessGatewayTaskResponse CreateWirelessGatewayTask(CreateWirelessGatewayTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayTaskResponseUnmarshaller.Instance; return Invoke<CreateWirelessGatewayTaskResponse>(request, options); } /// <summary> /// Creates a task for a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGatewayTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGatewayTask">REST API Reference for CreateWirelessGatewayTask Operation</seealso> public virtual Task<CreateWirelessGatewayTaskResponse> CreateWirelessGatewayTaskAsync(CreateWirelessGatewayTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayTaskResponseUnmarshaller.Instance; return InvokeAsync<CreateWirelessGatewayTaskResponse>(request, options, cancellationToken); } #endregion #region CreateWirelessGatewayTaskDefinition /// <summary> /// Creates a gateway task definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGatewayTaskDefinition service method.</param> /// /// <returns>The response from the CreateWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGatewayTaskDefinition">REST API Reference for CreateWirelessGatewayTaskDefinition Operation</seealso> public virtual CreateWirelessGatewayTaskDefinitionResponse CreateWirelessGatewayTaskDefinition(CreateWirelessGatewayTaskDefinitionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return Invoke<CreateWirelessGatewayTaskDefinitionResponse>(request, options); } /// <summary> /// Creates a gateway task definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWirelessGatewayTaskDefinition service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/CreateWirelessGatewayTaskDefinition">REST API Reference for CreateWirelessGatewayTaskDefinition Operation</seealso> public virtual Task<CreateWirelessGatewayTaskDefinitionResponse> CreateWirelessGatewayTaskDefinitionAsync(CreateWirelessGatewayTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<CreateWirelessGatewayTaskDefinitionResponse>(request, options, cancellationToken); } #endregion #region DeleteDestination /// <summary> /// Deletes a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDestination service method.</param> /// /// <returns>The response from the DeleteDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteDestination">REST API Reference for DeleteDestination Operation</seealso> public virtual DeleteDestinationResponse DeleteDestination(DeleteDestinationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDestinationResponseUnmarshaller.Instance; return Invoke<DeleteDestinationResponse>(request, options); } /// <summary> /// Deletes a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteDestination">REST API Reference for DeleteDestination Operation</seealso> public virtual Task<DeleteDestinationResponse> DeleteDestinationAsync(DeleteDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDestinationResponseUnmarshaller.Instance; return InvokeAsync<DeleteDestinationResponse>(request, options, cancellationToken); } #endregion #region DeleteDeviceProfile /// <summary> /// Deletes a device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDeviceProfile service method.</param> /// /// <returns>The response from the DeleteDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteDeviceProfile">REST API Reference for DeleteDeviceProfile Operation</seealso> public virtual DeleteDeviceProfileResponse DeleteDeviceProfile(DeleteDeviceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDeviceProfileResponseUnmarshaller.Instance; return Invoke<DeleteDeviceProfileResponse>(request, options); } /// <summary> /// Deletes a device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDeviceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteDeviceProfile">REST API Reference for DeleteDeviceProfile Operation</seealso> public virtual Task<DeleteDeviceProfileResponse> DeleteDeviceProfileAsync(DeleteDeviceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDeviceProfileResponseUnmarshaller.Instance; return InvokeAsync<DeleteDeviceProfileResponse>(request, options, cancellationToken); } #endregion #region DeleteServiceProfile /// <summary> /// Deletes a service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteServiceProfile service method.</param> /// /// <returns>The response from the DeleteServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteServiceProfile">REST API Reference for DeleteServiceProfile Operation</seealso> public virtual DeleteServiceProfileResponse DeleteServiceProfile(DeleteServiceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteServiceProfileResponseUnmarshaller.Instance; return Invoke<DeleteServiceProfileResponse>(request, options); } /// <summary> /// Deletes a service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteServiceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteServiceProfile">REST API Reference for DeleteServiceProfile Operation</seealso> public virtual Task<DeleteServiceProfileResponse> DeleteServiceProfileAsync(DeleteServiceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteServiceProfileResponseUnmarshaller.Instance; return InvokeAsync<DeleteServiceProfileResponse>(request, options, cancellationToken); } #endregion #region DeleteWirelessDevice /// <summary> /// Deletes a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessDevice service method.</param> /// /// <returns>The response from the DeleteWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessDevice">REST API Reference for DeleteWirelessDevice Operation</seealso> public virtual DeleteWirelessDeviceResponse DeleteWirelessDevice(DeleteWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessDeviceResponseUnmarshaller.Instance; return Invoke<DeleteWirelessDeviceResponse>(request, options); } /// <summary> /// Deletes a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessDevice">REST API Reference for DeleteWirelessDevice Operation</seealso> public virtual Task<DeleteWirelessDeviceResponse> DeleteWirelessDeviceAsync(DeleteWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<DeleteWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region DeleteWirelessGateway /// <summary> /// Deletes a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGateway service method.</param> /// /// <returns>The response from the DeleteWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGateway">REST API Reference for DeleteWirelessGateway Operation</seealso> public virtual DeleteWirelessGatewayResponse DeleteWirelessGateway(DeleteWirelessGatewayRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayResponseUnmarshaller.Instance; return Invoke<DeleteWirelessGatewayResponse>(request, options); } /// <summary> /// Deletes a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGateway service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGateway">REST API Reference for DeleteWirelessGateway Operation</seealso> public virtual Task<DeleteWirelessGatewayResponse> DeleteWirelessGatewayAsync(DeleteWirelessGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayResponseUnmarshaller.Instance; return InvokeAsync<DeleteWirelessGatewayResponse>(request, options, cancellationToken); } #endregion #region DeleteWirelessGatewayTask /// <summary> /// Deletes a wireless gateway task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGatewayTask service method.</param> /// /// <returns>The response from the DeleteWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGatewayTask">REST API Reference for DeleteWirelessGatewayTask Operation</seealso> public virtual DeleteWirelessGatewayTaskResponse DeleteWirelessGatewayTask(DeleteWirelessGatewayTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayTaskResponseUnmarshaller.Instance; return Invoke<DeleteWirelessGatewayTaskResponse>(request, options); } /// <summary> /// Deletes a wireless gateway task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGatewayTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGatewayTask">REST API Reference for DeleteWirelessGatewayTask Operation</seealso> public virtual Task<DeleteWirelessGatewayTaskResponse> DeleteWirelessGatewayTaskAsync(DeleteWirelessGatewayTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayTaskResponseUnmarshaller.Instance; return InvokeAsync<DeleteWirelessGatewayTaskResponse>(request, options, cancellationToken); } #endregion #region DeleteWirelessGatewayTaskDefinition /// <summary> /// Deletes a wireless gateway task definition. Deleting this task definition does not /// affect tasks that are currently in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGatewayTaskDefinition service method.</param> /// /// <returns>The response from the DeleteWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGatewayTaskDefinition">REST API Reference for DeleteWirelessGatewayTaskDefinition Operation</seealso> public virtual DeleteWirelessGatewayTaskDefinitionResponse DeleteWirelessGatewayTaskDefinition(DeleteWirelessGatewayTaskDefinitionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return Invoke<DeleteWirelessGatewayTaskDefinitionResponse>(request, options); } /// <summary> /// Deletes a wireless gateway task definition. Deleting this task definition does not /// affect tasks that are currently in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteWirelessGatewayTaskDefinition service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DeleteWirelessGatewayTaskDefinition">REST API Reference for DeleteWirelessGatewayTaskDefinition Operation</seealso> public virtual Task<DeleteWirelessGatewayTaskDefinitionResponse> DeleteWirelessGatewayTaskDefinitionAsync(DeleteWirelessGatewayTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<DeleteWirelessGatewayTaskDefinitionResponse>(request, options, cancellationToken); } #endregion #region DisassociateAwsAccountFromPartnerAccount /// <summary> /// Disassociates your AWS account from a partner account. If <code>PartnerAccountId</code> /// and <code>PartnerType</code> are <code>null</code>, disassociates your AWS account /// from all partner accounts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateAwsAccountFromPartnerAccount service method.</param> /// /// <returns>The response from the DisassociateAwsAccountFromPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateAwsAccountFromPartnerAccount">REST API Reference for DisassociateAwsAccountFromPartnerAccount Operation</seealso> public virtual DisassociateAwsAccountFromPartnerAccountResponse DisassociateAwsAccountFromPartnerAccount(DisassociateAwsAccountFromPartnerAccountRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateAwsAccountFromPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateAwsAccountFromPartnerAccountResponseUnmarshaller.Instance; return Invoke<DisassociateAwsAccountFromPartnerAccountResponse>(request, options); } /// <summary> /// Disassociates your AWS account from a partner account. If <code>PartnerAccountId</code> /// and <code>PartnerType</code> are <code>null</code>, disassociates your AWS account /// from all partner accounts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateAwsAccountFromPartnerAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisassociateAwsAccountFromPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateAwsAccountFromPartnerAccount">REST API Reference for DisassociateAwsAccountFromPartnerAccount Operation</seealso> public virtual Task<DisassociateAwsAccountFromPartnerAccountResponse> DisassociateAwsAccountFromPartnerAccountAsync(DisassociateAwsAccountFromPartnerAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateAwsAccountFromPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateAwsAccountFromPartnerAccountResponseUnmarshaller.Instance; return InvokeAsync<DisassociateAwsAccountFromPartnerAccountResponse>(request, options, cancellationToken); } #endregion #region DisassociateWirelessDeviceFromThing /// <summary> /// Disassociates a wireless device from its currently associated thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessDeviceFromThing service method.</param> /// /// <returns>The response from the DisassociateWirelessDeviceFromThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessDeviceFromThing">REST API Reference for DisassociateWirelessDeviceFromThing Operation</seealso> public virtual DisassociateWirelessDeviceFromThingResponse DisassociateWirelessDeviceFromThing(DisassociateWirelessDeviceFromThingRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessDeviceFromThingRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessDeviceFromThingResponseUnmarshaller.Instance; return Invoke<DisassociateWirelessDeviceFromThingResponse>(request, options); } /// <summary> /// Disassociates a wireless device from its currently associated thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessDeviceFromThing service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisassociateWirelessDeviceFromThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessDeviceFromThing">REST API Reference for DisassociateWirelessDeviceFromThing Operation</seealso> public virtual Task<DisassociateWirelessDeviceFromThingResponse> DisassociateWirelessDeviceFromThingAsync(DisassociateWirelessDeviceFromThingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessDeviceFromThingRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessDeviceFromThingResponseUnmarshaller.Instance; return InvokeAsync<DisassociateWirelessDeviceFromThingResponse>(request, options, cancellationToken); } #endregion #region DisassociateWirelessGatewayFromCertificate /// <summary> /// Disassociates a wireless gateway from its currently associated certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessGatewayFromCertificate service method.</param> /// /// <returns>The response from the DisassociateWirelessGatewayFromCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessGatewayFromCertificate">REST API Reference for DisassociateWirelessGatewayFromCertificate Operation</seealso> public virtual DisassociateWirelessGatewayFromCertificateResponse DisassociateWirelessGatewayFromCertificate(DisassociateWirelessGatewayFromCertificateRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessGatewayFromCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessGatewayFromCertificateResponseUnmarshaller.Instance; return Invoke<DisassociateWirelessGatewayFromCertificateResponse>(request, options); } /// <summary> /// Disassociates a wireless gateway from its currently associated certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessGatewayFromCertificate service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisassociateWirelessGatewayFromCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessGatewayFromCertificate">REST API Reference for DisassociateWirelessGatewayFromCertificate Operation</seealso> public virtual Task<DisassociateWirelessGatewayFromCertificateResponse> DisassociateWirelessGatewayFromCertificateAsync(DisassociateWirelessGatewayFromCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessGatewayFromCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessGatewayFromCertificateResponseUnmarshaller.Instance; return InvokeAsync<DisassociateWirelessGatewayFromCertificateResponse>(request, options, cancellationToken); } #endregion #region DisassociateWirelessGatewayFromThing /// <summary> /// Disassociates a wireless gateway from its currently associated thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessGatewayFromThing service method.</param> /// /// <returns>The response from the DisassociateWirelessGatewayFromThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessGatewayFromThing">REST API Reference for DisassociateWirelessGatewayFromThing Operation</seealso> public virtual DisassociateWirelessGatewayFromThingResponse DisassociateWirelessGatewayFromThing(DisassociateWirelessGatewayFromThingRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessGatewayFromThingRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessGatewayFromThingResponseUnmarshaller.Instance; return Invoke<DisassociateWirelessGatewayFromThingResponse>(request, options); } /// <summary> /// Disassociates a wireless gateway from its currently associated thing. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateWirelessGatewayFromThing service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisassociateWirelessGatewayFromThing service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/DisassociateWirelessGatewayFromThing">REST API Reference for DisassociateWirelessGatewayFromThing Operation</seealso> public virtual Task<DisassociateWirelessGatewayFromThingResponse> DisassociateWirelessGatewayFromThingAsync(DisassociateWirelessGatewayFromThingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateWirelessGatewayFromThingRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateWirelessGatewayFromThingResponseUnmarshaller.Instance; return InvokeAsync<DisassociateWirelessGatewayFromThingResponse>(request, options, cancellationToken); } #endregion #region GetDestination /// <summary> /// Gets information about a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDestination service method.</param> /// /// <returns>The response from the GetDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetDestination">REST API Reference for GetDestination Operation</seealso> public virtual GetDestinationResponse GetDestination(GetDestinationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetDestinationResponseUnmarshaller.Instance; return Invoke<GetDestinationResponse>(request, options); } /// <summary> /// Gets information about a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetDestination">REST API Reference for GetDestination Operation</seealso> public virtual Task<GetDestinationResponse> GetDestinationAsync(GetDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetDestinationResponseUnmarshaller.Instance; return InvokeAsync<GetDestinationResponse>(request, options, cancellationToken); } #endregion #region GetDeviceProfile /// <summary> /// Gets information about a device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDeviceProfile service method.</param> /// /// <returns>The response from the GetDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetDeviceProfile">REST API Reference for GetDeviceProfile Operation</seealso> public virtual GetDeviceProfileResponse GetDeviceProfile(GetDeviceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = GetDeviceProfileResponseUnmarshaller.Instance; return Invoke<GetDeviceProfileResponse>(request, options); } /// <summary> /// Gets information about a device profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDeviceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDeviceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetDeviceProfile">REST API Reference for GetDeviceProfile Operation</seealso> public virtual Task<GetDeviceProfileResponse> GetDeviceProfileAsync(GetDeviceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetDeviceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = GetDeviceProfileResponseUnmarshaller.Instance; return InvokeAsync<GetDeviceProfileResponse>(request, options, cancellationToken); } #endregion #region GetPartnerAccount /// <summary> /// Gets information about a partner account. If <code>PartnerAccountId</code> and <code>PartnerType</code> /// are <code>null</code>, returns all partner accounts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetPartnerAccount service method.</param> /// /// <returns>The response from the GetPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetPartnerAccount">REST API Reference for GetPartnerAccount Operation</seealso> public virtual GetPartnerAccountResponse GetPartnerAccount(GetPartnerAccountRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = GetPartnerAccountResponseUnmarshaller.Instance; return Invoke<GetPartnerAccountResponse>(request, options); } /// <summary> /// Gets information about a partner account. If <code>PartnerAccountId</code> and <code>PartnerType</code> /// are <code>null</code>, returns all partner accounts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetPartnerAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetPartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetPartnerAccount">REST API Reference for GetPartnerAccount Operation</seealso> public virtual Task<GetPartnerAccountResponse> GetPartnerAccountAsync(GetPartnerAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetPartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = GetPartnerAccountResponseUnmarshaller.Instance; return InvokeAsync<GetPartnerAccountResponse>(request, options, cancellationToken); } #endregion #region GetServiceEndpoint /// <summary> /// Gets the account-specific endpoint for Configuration and Update Server (CUPS) protocol /// or LoRaWAN Network Server (LNS) connections. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetServiceEndpoint service method.</param> /// /// <returns>The response from the GetServiceEndpoint service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetServiceEndpoint">REST API Reference for GetServiceEndpoint Operation</seealso> public virtual GetServiceEndpointResponse GetServiceEndpoint(GetServiceEndpointRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetServiceEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = GetServiceEndpointResponseUnmarshaller.Instance; return Invoke<GetServiceEndpointResponse>(request, options); } /// <summary> /// Gets the account-specific endpoint for Configuration and Update Server (CUPS) protocol /// or LoRaWAN Network Server (LNS) connections. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetServiceEndpoint service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetServiceEndpoint service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetServiceEndpoint">REST API Reference for GetServiceEndpoint Operation</seealso> public virtual Task<GetServiceEndpointResponse> GetServiceEndpointAsync(GetServiceEndpointRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetServiceEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = GetServiceEndpointResponseUnmarshaller.Instance; return InvokeAsync<GetServiceEndpointResponse>(request, options, cancellationToken); } #endregion #region GetServiceProfile /// <summary> /// Gets information about a service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetServiceProfile service method.</param> /// /// <returns>The response from the GetServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetServiceProfile">REST API Reference for GetServiceProfile Operation</seealso> public virtual GetServiceProfileResponse GetServiceProfile(GetServiceProfileRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = GetServiceProfileResponseUnmarshaller.Instance; return Invoke<GetServiceProfileResponse>(request, options); } /// <summary> /// Gets information about a service profile. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetServiceProfile service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetServiceProfile service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetServiceProfile">REST API Reference for GetServiceProfile Operation</seealso> public virtual Task<GetServiceProfileResponse> GetServiceProfileAsync(GetServiceProfileRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetServiceProfileRequestMarshaller.Instance; options.ResponseUnmarshaller = GetServiceProfileResponseUnmarshaller.Instance; return InvokeAsync<GetServiceProfileResponse>(request, options, cancellationToken); } #endregion #region GetWirelessDevice /// <summary> /// Gets information about a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessDevice service method.</param> /// /// <returns>The response from the GetWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessDevice">REST API Reference for GetWirelessDevice Operation</seealso> public virtual GetWirelessDeviceResponse GetWirelessDevice(GetWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessDeviceResponseUnmarshaller.Instance; return Invoke<GetWirelessDeviceResponse>(request, options); } /// <summary> /// Gets information about a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessDevice">REST API Reference for GetWirelessDevice Operation</seealso> public virtual Task<GetWirelessDeviceResponse> GetWirelessDeviceAsync(GetWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region GetWirelessDeviceStatistics /// <summary> /// Gets operating information about a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessDeviceStatistics service method.</param> /// /// <returns>The response from the GetWirelessDeviceStatistics service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessDeviceStatistics">REST API Reference for GetWirelessDeviceStatistics Operation</seealso> public virtual GetWirelessDeviceStatisticsResponse GetWirelessDeviceStatistics(GetWirelessDeviceStatisticsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessDeviceStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessDeviceStatisticsResponseUnmarshaller.Instance; return Invoke<GetWirelessDeviceStatisticsResponse>(request, options); } /// <summary> /// Gets operating information about a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessDeviceStatistics service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessDeviceStatistics service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessDeviceStatistics">REST API Reference for GetWirelessDeviceStatistics Operation</seealso> public virtual Task<GetWirelessDeviceStatisticsResponse> GetWirelessDeviceStatisticsAsync(GetWirelessDeviceStatisticsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessDeviceStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessDeviceStatisticsResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessDeviceStatisticsResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGateway /// <summary> /// Gets information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGateway service method.</param> /// /// <returns>The response from the GetWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGateway">REST API Reference for GetWirelessGateway Operation</seealso> public virtual GetWirelessGatewayResponse GetWirelessGateway(GetWirelessGatewayRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayResponse>(request, options); } /// <summary> /// Gets information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGateway service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGateway">REST API Reference for GetWirelessGateway Operation</seealso> public virtual Task<GetWirelessGatewayResponse> GetWirelessGatewayAsync(GetWirelessGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGatewayCertificate /// <summary> /// Gets the ID of the certificate that is currently associated with a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayCertificate service method.</param> /// /// <returns>The response from the GetWirelessGatewayCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayCertificate">REST API Reference for GetWirelessGatewayCertificate Operation</seealso> public virtual GetWirelessGatewayCertificateResponse GetWirelessGatewayCertificate(GetWirelessGatewayCertificateRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayCertificateResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayCertificateResponse>(request, options); } /// <summary> /// Gets the ID of the certificate that is currently associated with a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayCertificate service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGatewayCertificate service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayCertificate">REST API Reference for GetWirelessGatewayCertificate Operation</seealso> public virtual Task<GetWirelessGatewayCertificateResponse> GetWirelessGatewayCertificateAsync(GetWirelessGatewayCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayCertificateResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayCertificateResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGatewayFirmwareInformation /// <summary> /// Gets the firmware version and other information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayFirmwareInformation service method.</param> /// /// <returns>The response from the GetWirelessGatewayFirmwareInformation service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayFirmwareInformation">REST API Reference for GetWirelessGatewayFirmwareInformation Operation</seealso> public virtual GetWirelessGatewayFirmwareInformationResponse GetWirelessGatewayFirmwareInformation(GetWirelessGatewayFirmwareInformationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayFirmwareInformationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayFirmwareInformationResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayFirmwareInformationResponse>(request, options); } /// <summary> /// Gets the firmware version and other information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayFirmwareInformation service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGatewayFirmwareInformation service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayFirmwareInformation">REST API Reference for GetWirelessGatewayFirmwareInformation Operation</seealso> public virtual Task<GetWirelessGatewayFirmwareInformationResponse> GetWirelessGatewayFirmwareInformationAsync(GetWirelessGatewayFirmwareInformationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayFirmwareInformationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayFirmwareInformationResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayFirmwareInformationResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGatewayStatistics /// <summary> /// Gets operating information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayStatistics service method.</param> /// /// <returns>The response from the GetWirelessGatewayStatistics service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayStatistics">REST API Reference for GetWirelessGatewayStatistics Operation</seealso> public virtual GetWirelessGatewayStatisticsResponse GetWirelessGatewayStatistics(GetWirelessGatewayStatisticsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayStatisticsResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayStatisticsResponse>(request, options); } /// <summary> /// Gets operating information about a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayStatistics service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGatewayStatistics service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayStatistics">REST API Reference for GetWirelessGatewayStatistics Operation</seealso> public virtual Task<GetWirelessGatewayStatisticsResponse> GetWirelessGatewayStatisticsAsync(GetWirelessGatewayStatisticsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayStatisticsResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayStatisticsResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGatewayTask /// <summary> /// Gets information about a wireless gateway task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayTask service method.</param> /// /// <returns>The response from the GetWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayTask">REST API Reference for GetWirelessGatewayTask Operation</seealso> public virtual GetWirelessGatewayTaskResponse GetWirelessGatewayTask(GetWirelessGatewayTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayTaskResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayTaskResponse>(request, options); } /// <summary> /// Gets information about a wireless gateway task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGatewayTask service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayTask">REST API Reference for GetWirelessGatewayTask Operation</seealso> public virtual Task<GetWirelessGatewayTaskResponse> GetWirelessGatewayTaskAsync(GetWirelessGatewayTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayTaskResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayTaskResponse>(request, options, cancellationToken); } #endregion #region GetWirelessGatewayTaskDefinition /// <summary> /// Gets information about a wireless gateway task definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayTaskDefinition service method.</param> /// /// <returns>The response from the GetWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayTaskDefinition">REST API Reference for GetWirelessGatewayTaskDefinition Operation</seealso> public virtual GetWirelessGatewayTaskDefinitionResponse GetWirelessGatewayTaskDefinition(GetWirelessGatewayTaskDefinitionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return Invoke<GetWirelessGatewayTaskDefinitionResponse>(request, options); } /// <summary> /// Gets information about a wireless gateway task definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetWirelessGatewayTaskDefinition service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetWirelessGatewayTaskDefinition service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/GetWirelessGatewayTaskDefinition">REST API Reference for GetWirelessGatewayTaskDefinition Operation</seealso> public virtual Task<GetWirelessGatewayTaskDefinitionResponse> GetWirelessGatewayTaskDefinitionAsync(GetWirelessGatewayTaskDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetWirelessGatewayTaskDefinitionRequestMarshaller.Instance; options.ResponseUnmarshaller = GetWirelessGatewayTaskDefinitionResponseUnmarshaller.Instance; return InvokeAsync<GetWirelessGatewayTaskDefinitionResponse>(request, options, cancellationToken); } #endregion #region ListDestinations /// <summary> /// Lists the destinations registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDestinations service method.</param> /// /// <returns>The response from the ListDestinations service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListDestinations">REST API Reference for ListDestinations Operation</seealso> public virtual ListDestinationsResponse ListDestinations(ListDestinationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListDestinationsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDestinationsResponseUnmarshaller.Instance; return Invoke<ListDestinationsResponse>(request, options); } /// <summary> /// Lists the destinations registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDestinations service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDestinations service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListDestinations">REST API Reference for ListDestinations Operation</seealso> public virtual Task<ListDestinationsResponse> ListDestinationsAsync(ListDestinationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListDestinationsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDestinationsResponseUnmarshaller.Instance; return InvokeAsync<ListDestinationsResponse>(request, options, cancellationToken); } #endregion #region ListDeviceProfiles /// <summary> /// Lists the device profiles registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDeviceProfiles service method.</param> /// /// <returns>The response from the ListDeviceProfiles service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListDeviceProfiles">REST API Reference for ListDeviceProfiles Operation</seealso> public virtual ListDeviceProfilesResponse ListDeviceProfiles(ListDeviceProfilesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListDeviceProfilesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDeviceProfilesResponseUnmarshaller.Instance; return Invoke<ListDeviceProfilesResponse>(request, options); } /// <summary> /// Lists the device profiles registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDeviceProfiles service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDeviceProfiles service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListDeviceProfiles">REST API Reference for ListDeviceProfiles Operation</seealso> public virtual Task<ListDeviceProfilesResponse> ListDeviceProfilesAsync(ListDeviceProfilesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListDeviceProfilesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDeviceProfilesResponseUnmarshaller.Instance; return InvokeAsync<ListDeviceProfilesResponse>(request, options, cancellationToken); } #endregion #region ListPartnerAccounts /// <summary> /// Lists the partner accounts associated with your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPartnerAccounts service method.</param> /// /// <returns>The response from the ListPartnerAccounts service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListPartnerAccounts">REST API Reference for ListPartnerAccounts Operation</seealso> public virtual ListPartnerAccountsResponse ListPartnerAccounts(ListPartnerAccountsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListPartnerAccountsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPartnerAccountsResponseUnmarshaller.Instance; return Invoke<ListPartnerAccountsResponse>(request, options); } /// <summary> /// Lists the partner accounts associated with your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPartnerAccounts service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPartnerAccounts service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListPartnerAccounts">REST API Reference for ListPartnerAccounts Operation</seealso> public virtual Task<ListPartnerAccountsResponse> ListPartnerAccountsAsync(ListPartnerAccountsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListPartnerAccountsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPartnerAccountsResponseUnmarshaller.Instance; return InvokeAsync<ListPartnerAccountsResponse>(request, options, cancellationToken); } #endregion #region ListServiceProfiles /// <summary> /// Lists the service profiles registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListServiceProfiles service method.</param> /// /// <returns>The response from the ListServiceProfiles service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListServiceProfiles">REST API Reference for ListServiceProfiles Operation</seealso> public virtual ListServiceProfilesResponse ListServiceProfiles(ListServiceProfilesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListServiceProfilesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListServiceProfilesResponseUnmarshaller.Instance; return Invoke<ListServiceProfilesResponse>(request, options); } /// <summary> /// Lists the service profiles registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListServiceProfiles service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListServiceProfiles service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListServiceProfiles">REST API Reference for ListServiceProfiles Operation</seealso> public virtual Task<ListServiceProfilesResponse> ListServiceProfilesAsync(ListServiceProfilesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListServiceProfilesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListServiceProfilesResponseUnmarshaller.Instance; return InvokeAsync<ListServiceProfilesResponse>(request, options, cancellationToken); } #endregion #region ListTagsForResource /// <summary> /// Lists the tags (metadata) you have assigned to the resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// /// <returns>The response from the ListTagsForResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return Invoke<ListTagsForResourceResponse>(request, options); } /// <summary> /// Lists the tags (metadata) you have assigned to the resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsForResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return InvokeAsync<ListTagsForResourceResponse>(request, options, cancellationToken); } #endregion #region ListWirelessDevices /// <summary> /// Lists the wireless devices registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessDevices service method.</param> /// /// <returns>The response from the ListWirelessDevices service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessDevices">REST API Reference for ListWirelessDevices Operation</seealso> public virtual ListWirelessDevicesResponse ListWirelessDevices(ListWirelessDevicesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessDevicesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessDevicesResponseUnmarshaller.Instance; return Invoke<ListWirelessDevicesResponse>(request, options); } /// <summary> /// Lists the wireless devices registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessDevices service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListWirelessDevices service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessDevices">REST API Reference for ListWirelessDevices Operation</seealso> public virtual Task<ListWirelessDevicesResponse> ListWirelessDevicesAsync(ListWirelessDevicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessDevicesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessDevicesResponseUnmarshaller.Instance; return InvokeAsync<ListWirelessDevicesResponse>(request, options, cancellationToken); } #endregion #region ListWirelessGateways /// <summary> /// Lists the wireless gateways registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessGateways service method.</param> /// /// <returns>The response from the ListWirelessGateways service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessGateways">REST API Reference for ListWirelessGateways Operation</seealso> public virtual ListWirelessGatewaysResponse ListWirelessGateways(ListWirelessGatewaysRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessGatewaysRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessGatewaysResponseUnmarshaller.Instance; return Invoke<ListWirelessGatewaysResponse>(request, options); } /// <summary> /// Lists the wireless gateways registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessGateways service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListWirelessGateways service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessGateways">REST API Reference for ListWirelessGateways Operation</seealso> public virtual Task<ListWirelessGatewaysResponse> ListWirelessGatewaysAsync(ListWirelessGatewaysRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessGatewaysRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessGatewaysResponseUnmarshaller.Instance; return InvokeAsync<ListWirelessGatewaysResponse>(request, options, cancellationToken); } #endregion #region ListWirelessGatewayTaskDefinitions /// <summary> /// List the wireless gateway tasks definitions registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessGatewayTaskDefinitions service method.</param> /// /// <returns>The response from the ListWirelessGatewayTaskDefinitions service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessGatewayTaskDefinitions">REST API Reference for ListWirelessGatewayTaskDefinitions Operation</seealso> public virtual ListWirelessGatewayTaskDefinitionsResponse ListWirelessGatewayTaskDefinitions(ListWirelessGatewayTaskDefinitionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessGatewayTaskDefinitionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessGatewayTaskDefinitionsResponseUnmarshaller.Instance; return Invoke<ListWirelessGatewayTaskDefinitionsResponse>(request, options); } /// <summary> /// List the wireless gateway tasks definitions registered to your AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListWirelessGatewayTaskDefinitions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListWirelessGatewayTaskDefinitions service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListWirelessGatewayTaskDefinitions">REST API Reference for ListWirelessGatewayTaskDefinitions Operation</seealso> public virtual Task<ListWirelessGatewayTaskDefinitionsResponse> ListWirelessGatewayTaskDefinitionsAsync(ListWirelessGatewayTaskDefinitionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListWirelessGatewayTaskDefinitionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListWirelessGatewayTaskDefinitionsResponseUnmarshaller.Instance; return InvokeAsync<ListWirelessGatewayTaskDefinitionsResponse>(request, options, cancellationToken); } #endregion #region SendDataToWirelessDevice /// <summary> /// Sends a decrypted application data frame to a device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SendDataToWirelessDevice service method.</param> /// /// <returns>The response from the SendDataToWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/SendDataToWirelessDevice">REST API Reference for SendDataToWirelessDevice Operation</seealso> public virtual SendDataToWirelessDeviceResponse SendDataToWirelessDevice(SendDataToWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = SendDataToWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = SendDataToWirelessDeviceResponseUnmarshaller.Instance; return Invoke<SendDataToWirelessDeviceResponse>(request, options); } /// <summary> /// Sends a decrypted application data frame to a device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SendDataToWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the SendDataToWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/SendDataToWirelessDevice">REST API Reference for SendDataToWirelessDevice Operation</seealso> public virtual Task<SendDataToWirelessDeviceResponse> SendDataToWirelessDeviceAsync(SendDataToWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = SendDataToWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = SendDataToWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<SendDataToWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region TagResource /// <summary> /// Adds a tag to a resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// /// <returns>The response from the TagResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.TooManyTagsException"> /// The request was denied because the resource can't have any more tags. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse TagResource(TagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return Invoke<TagResourceResponse>(request, options); } /// <summary> /// Adds a tag to a resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.TooManyTagsException"> /// The request was denied because the resource can't have any more tags. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/TagResource">REST API Reference for TagResource Operation</seealso> public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return InvokeAsync<TagResourceResponse>(request, options, cancellationToken); } #endregion #region TestWirelessDevice /// <summary> /// Simulates a provisioned device by sending an uplink data payload of <code>Hello</code>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TestWirelessDevice service method.</param> /// /// <returns>The response from the TestWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/TestWirelessDevice">REST API Reference for TestWirelessDevice Operation</seealso> public virtual TestWirelessDeviceResponse TestWirelessDevice(TestWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TestWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = TestWirelessDeviceResponseUnmarshaller.Instance; return Invoke<TestWirelessDeviceResponse>(request, options); } /// <summary> /// Simulates a provisioned device by sending an uplink data payload of <code>Hello</code>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TestWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TestWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/TestWirelessDevice">REST API Reference for TestWirelessDevice Operation</seealso> public virtual Task<TestWirelessDeviceResponse> TestWirelessDeviceAsync(TestWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = TestWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = TestWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<TestWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region UntagResource /// <summary> /// Removes one or more tags from a resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// /// <returns>The response from the UntagResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse UntagResource(UntagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return Invoke<UntagResourceResponse>(request, options); } /// <summary> /// Removes one or more tags from a resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.ConflictException"> /// Adding, updating, or deleting the resource can cause an inconsistent state. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken); } #endregion #region UpdateDestination /// <summary> /// Updates properties of a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateDestination service method.</param> /// /// <returns>The response from the UpdateDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateDestination">REST API Reference for UpdateDestination Operation</seealso> public virtual UpdateDestinationResponse UpdateDestination(UpdateDestinationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateDestinationResponseUnmarshaller.Instance; return Invoke<UpdateDestinationResponse>(request, options); } /// <summary> /// Updates properties of a destination. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateDestination service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateDestination">REST API Reference for UpdateDestination Operation</seealso> public virtual Task<UpdateDestinationResponse> UpdateDestinationAsync(UpdateDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateDestinationRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateDestinationResponseUnmarshaller.Instance; return InvokeAsync<UpdateDestinationResponse>(request, options, cancellationToken); } #endregion #region UpdatePartnerAccount /// <summary> /// Updates properties of a partner account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdatePartnerAccount service method.</param> /// /// <returns>The response from the UpdatePartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdatePartnerAccount">REST API Reference for UpdatePartnerAccount Operation</seealso> public virtual UpdatePartnerAccountResponse UpdatePartnerAccount(UpdatePartnerAccountRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdatePartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdatePartnerAccountResponseUnmarshaller.Instance; return Invoke<UpdatePartnerAccountResponse>(request, options); } /// <summary> /// Updates properties of a partner account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdatePartnerAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdatePartnerAccount service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdatePartnerAccount">REST API Reference for UpdatePartnerAccount Operation</seealso> public virtual Task<UpdatePartnerAccountResponse> UpdatePartnerAccountAsync(UpdatePartnerAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdatePartnerAccountRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdatePartnerAccountResponseUnmarshaller.Instance; return InvokeAsync<UpdatePartnerAccountResponse>(request, options, cancellationToken); } #endregion #region UpdateWirelessDevice /// <summary> /// Updates properties of a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateWirelessDevice service method.</param> /// /// <returns>The response from the UpdateWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateWirelessDevice">REST API Reference for UpdateWirelessDevice Operation</seealso> public virtual UpdateWirelessDeviceResponse UpdateWirelessDevice(UpdateWirelessDeviceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateWirelessDeviceResponseUnmarshaller.Instance; return Invoke<UpdateWirelessDeviceResponse>(request, options); } /// <summary> /// Updates properties of a wireless device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateWirelessDevice service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateWirelessDevice service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateWirelessDevice">REST API Reference for UpdateWirelessDevice Operation</seealso> public virtual Task<UpdateWirelessDeviceResponse> UpdateWirelessDeviceAsync(UpdateWirelessDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateWirelessDeviceRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateWirelessDeviceResponseUnmarshaller.Instance; return InvokeAsync<UpdateWirelessDeviceResponse>(request, options, cancellationToken); } #endregion #region UpdateWirelessGateway /// <summary> /// Updates properties of a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateWirelessGateway service method.</param> /// /// <returns>The response from the UpdateWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateWirelessGateway">REST API Reference for UpdateWirelessGateway Operation</seealso> public virtual UpdateWirelessGatewayResponse UpdateWirelessGateway(UpdateWirelessGatewayRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateWirelessGatewayResponseUnmarshaller.Instance; return Invoke<UpdateWirelessGatewayResponse>(request, options); } /// <summary> /// Updates properties of a wireless gateway. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateWirelessGateway service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateWirelessGateway service method, as returned by IoTWireless.</returns> /// <exception cref="Amazon.IoTWireless.Model.AccessDeniedException"> /// User does not have permission to perform this action. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.InternalServerException"> /// An unexpected error occurred while processing a request. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ResourceNotFoundException"> /// Resource does not exist. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ThrottlingException"> /// The request was denied because it exceeded the allowed API request rate. /// </exception> /// <exception cref="Amazon.IoTWireless.Model.ValidationException"> /// The input did not meet the specified constraints. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/UpdateWirelessGateway">REST API Reference for UpdateWirelessGateway Operation</seealso> public virtual Task<UpdateWirelessGatewayResponse> UpdateWirelessGatewayAsync(UpdateWirelessGatewayRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateWirelessGatewayRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateWirelessGatewayResponseUnmarshaller.Instance; return InvokeAsync<UpdateWirelessGatewayResponse>(request, options, cancellationToken); } #endregion } }
56.880873
269
0.682971
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/_bcl45/AmazonIoTWirelessClient.cs
221,551
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Text; using System.Reflection; using System.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace System.ComponentModel.Composition.Registration { public interface IController {} public interface IAuthentication {} public interface IFormsAuthenticationService {} public interface IMembershipService {} public class FormsAuthenticationServiceImpl : IFormsAuthenticationService {} public class MembershipServiceImpl : IMembershipService {} public class SpecificMembershipServiceImpl : IMembershipService {} public class HttpDigestAuthentication : IAuthentication {} public class AmbiguousConstructors { public AmbiguousConstructors(string first, int second) { StringArg = first; IntArg = second; } public AmbiguousConstructors(int first, string second) { IntArg = first; StringArg = second; } public int IntArg { get; set ; } public string StringArg { get; set ; } } public class AmbiguousConstructorsWithAttribute { [ImportingConstructorAttribute] public AmbiguousConstructorsWithAttribute(string first, int second) { StringArg = first; IntArg = second; } public AmbiguousConstructorsWithAttribute(int first, string second) { IntArg = first; StringArg = second; } public int IntArg { get; set ; } public string StringArg { get; set ; } } public class LongestConstructorWithAttribute { [ImportingConstructorAttribute] public LongestConstructorWithAttribute(string first, int second) { StringArg = first; IntArg = second; } public LongestConstructorWithAttribute(int first) { IntArg = first; } public int IntArg { get; set ; } public string StringArg { get; set ; } } public class LongestConstructorShortestWithAttribute { public LongestConstructorShortestWithAttribute(string first, int second) { StringArg = first; IntArg = second; } [ImportingConstructorAttribute] public LongestConstructorShortestWithAttribute(int first) { IntArg = first; } public int IntArg { get; set ; } public string StringArg { get; set ; } } public class ConstructorArgs { public ConstructorArgs() { IntArg = 10; StringArg = "Hello, World"; } public int IntArg { get; set ; } public string StringArg { get; set ; } } public class AccountController : IController { public IMembershipService MembershipService { get; private set; } public AccountController(IMembershipService membershipService) { this.MembershipService = membershipService; } public AccountController(IAuthentication auth) { } } public class HttpRequestValidator { public IAuthentication authenticator; public HttpRequestValidator(IAuthentication authenticator) {} } public class ManyConstructorsController : IController { public IFormsAuthenticationService FormsService { get; set; } public IMembershipService MembershipService { get; set; } public HttpRequestValidator Validator { get; set; } public ManyConstructorsController() {} public ManyConstructorsController( IFormsAuthenticationService formsService) { FormsService = formsService; } public ManyConstructorsController( IFormsAuthenticationService formsService, IMembershipService membershipService) { FormsService = formsService; MembershipService = MembershipService; } public ManyConstructorsController( IFormsAuthenticationService formsService, IMembershipService membershipService, HttpRequestValidator validator) { FormsService = formsService; MembershipService = membershipService; Validator = validator; } } [TestClass] public class PartBuilderUnitTests { [TestMethod] public void ManyConstructorsControllerFindLongestConstructor_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<FormsAuthenticationServiceImpl>().Export<IFormsAuthenticationService>(); ctx.ForType<HttpDigestAuthentication>().Export<IAuthentication>(); ctx.ForType<MembershipServiceImpl>().Export<IMembershipService>(); ctx.ForType<HttpRequestValidator>().Export(); ctx.ForType<ManyConstructorsController>().Export(); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(FormsAuthenticationServiceImpl), typeof(HttpDigestAuthentication), typeof(MembershipServiceImpl), typeof(HttpRequestValidator), typeof(ManyConstructorsController)), ctx); Assert.IsTrue(catalog.Parts.Count() == 5); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); var item = container.GetExportedValue<ManyConstructorsController>(); Assert.IsTrue(item.Validator != null); Assert.IsTrue(item.FormsService != null); Assert.IsTrue(item.MembershipService != null); } [TestMethod] public void ManyConstructorsControllerFindLongestConstructorAndImportByName_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<FormsAuthenticationServiceImpl>().Export<IFormsAuthenticationService>(); ctx.ForType<HttpDigestAuthentication>().Export<IAuthentication>(); ctx.ForType<MembershipServiceImpl>().Export<IMembershipService>(); ctx.ForType<SpecificMembershipServiceImpl>().Export<IMembershipService>( (c) => c.AsContractName("membershipService") ); ctx.ForType<HttpRequestValidator>().Export(); ctx.ForType<ManyConstructorsController>().SelectConstructor( null, (pi, import) => { if(typeof(IMembershipService).IsAssignableFrom(pi.ParameterType)) import.AsContractName("membershipService"); }).Export(); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(FormsAuthenticationServiceImpl), typeof(HttpDigestAuthentication), typeof(MembershipServiceImpl), typeof(SpecificMembershipServiceImpl), typeof(HttpRequestValidator), typeof(ManyConstructorsController)), ctx); Assert.IsTrue(catalog.Parts.Count() == 6); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); var item = container.GetExportedValue<ManyConstructorsController>(); Assert.IsTrue(item.Validator != null); Assert.IsTrue(item.FormsService != null); Assert.IsTrue(item.MembershipService != null); Assert.IsTrue(item.MembershipService.GetType() == typeof(SpecificMembershipServiceImpl)); } [TestMethod] public void LongestConstructorWithAttribute_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<LongestConstructorWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "IntArg" ); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "StringArg" ); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(LongestConstructorWithAttribute), typeof(ConstructorArgs)), ctx); Assert.AreEqual(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); var item = container.GetExportedValue<LongestConstructorWithAttribute>(); Assert.AreEqual(10, item.IntArg); Assert.AreEqual("Hello, World", item.StringArg); } [TestMethod] public void LongestConstructorShortestWithAttribute_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<LongestConstructorShortestWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "IntArg" ); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "StringArg" ); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(LongestConstructorShortestWithAttribute), typeof(ConstructorArgs)), ctx); Assert.AreEqual(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); var item = container.GetExportedValue<LongestConstructorShortestWithAttribute>(); Assert.AreEqual(10, item.IntArg); Assert.AreEqual(null, item.StringArg); } [TestMethod] public void AmbiguousConstructorWithAttributeAppliedToOne_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<AmbiguousConstructorsWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "IntArg" ); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "StringArg" ); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(AmbiguousConstructorsWithAttribute), typeof(ConstructorArgs)), ctx); Assert.AreEqual(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); var item = container.GetExportedValue<AmbiguousConstructorsWithAttribute>(); Assert.AreEqual(10, item.IntArg); Assert.AreEqual("Hello, World", item.StringArg); } [TestMethod] public void AmbiguousConstructor_ShouldFail() { var ctx = new RegistrationBuilder(); ctx.ForType<AmbiguousConstructors>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "IntArg" ); ctx.ForType<ConstructorArgs>().ExportProperties( (m) => m.Name == "StringArg" ); var catalog = new TypeCatalog(Helpers.GetEnumerableOfTypes( typeof(AmbiguousConstructors), typeof(ConstructorArgs)), ctx); Assert.AreEqual(catalog.Parts.Count(), 2); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); ExceptionAssert.Throws<CompositionException>(() => { var item = container.GetExportedValue<AmbiguousConstructors>(); }); } } }
40.304659
132
0.651578
[ "MIT" ]
zhy29563/MyMEF
redist/test/RegistrationModelUnitTest/System/ComponentModel/Composition/PartBuilderUnitTests.cs
11,245
C#
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using XenAdmin; namespace XenAPI { partial class VGPU_type : IComparable<VGPU_type>, IEquatable<VGPU_type> { public override string Name { get { if (IsPassthrough) return Messages.VGPU_PASSTHRU_TOSTRING; return string.Format(Messages.VGPU_TOSTRING, model_name, Capacity); } } public override string Description { get { if (IsPassthrough) return Messages.VGPU_PASSTHRU_TOSTRING; return string.Format(Messages.VGPU_DESCRIPTION, model_name, Capacity, MaxResolution, max_heads); } } public string MaxResolution { get { return max_resolution_x + "x" + max_resolution_y; } } #region IEquatable<VGPU_type> Members /// <summary> /// Indicates whether the current object is equal to the specified object. /// This calls the implementation from XenObject. /// This implementation is required for ToStringWrapper. /// </summary> public bool Equals(VGPU_type other) { return base.Equals(other); } #endregion // CA-166091: Default sort order for VGPU types is: // * Pass-through is "biggest" // * Then others in capacity order, lowest capacity is biggest // * In case of ties, highest resolution is biggest public override int CompareTo(VGPU_type other) { if (this.IsPassthrough != other.IsPassthrough) return this.IsPassthrough ? 1 : -1; long thisCapacity = this.Capacity; long otherCapacity = other.Capacity; if (thisCapacity != otherCapacity) return (int)(otherCapacity - thisCapacity); long thisResolution = this.max_resolution_x * this.max_resolution_y; long otherResolution = other.max_resolution_x * other.max_resolution_y; if (thisResolution != otherResolution) return (int)(thisResolution - otherResolution); return base.CompareTo(other); } /// <summary> /// vGPUs per GPU /// </summary> public long Capacity { get { long capacity = 0; if (supported_on_PGPUs != null && supported_on_PGPUs.Count > 0) { PGPU pgpu = Connection.Resolve(supported_on_PGPUs[0]); if (pgpu != null && pgpu.supported_VGPU_max_capacities != null && pgpu.supported_VGPU_max_capacities.Count > 0) { var vgpuTypeRef = new XenRef<VGPU_type>(this); if (pgpu.supported_VGPU_max_capacities.ContainsKey(vgpuTypeRef)) capacity = pgpu.supported_VGPU_max_capacities[vgpuTypeRef]; } } return capacity; } } public bool IsPassthrough { get { return max_heads == 0; } } } }
34.540741
131
0.597469
[ "BSD-2-Clause" ]
wdxgy136/xenadmin-yeesan
XenModel/XenAPI-Extensions/VGPU_type.cs
4,665
C#
namespace GW2Api.NET.V2.Items.Dto.ItemTypes.Tool { public record ToolDetails( ToolType Type, int Charges ); }
17.75
50
0.605634
[ "MIT" ]
RyanClementsHax/GW2Api.NET
GW2Api.NET/V2/Items/Dto/ItemTypes/Tool/ToolDetails.cs
144
C#
using MTools.Identifier; using System.Collections.Generic; using System.Diagnostics; namespace MTools.Trigger { public interface ITriggerEvent { } }
14.818182
34
0.748466
[ "MIT" ]
Swipeu/memma-tools
Assets/Plugins/MTools/Trigger/ITriggerEvent.cs
165
C#
using System.Threading.Tasks; using GovUk.Education.ExploreEducationStatistics.Admin.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace GovUk.Education.ExploreEducationStatistics.Admin.Areas.Identity.Pages.Account { [AllowAnonymous] public class LogoutModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<LogoutModel> _logger; public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger) { _signInManager = signInManager; _logger = logger; } public void OnGet() { } public async Task<IActionResult> OnPost(string returnUrl = null) { await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out"); if (returnUrl != null) { return LocalRedirect(returnUrl); } else { return RedirectToPage(); } } } }
29.02381
101
0.646432
[ "MIT" ]
benoutram/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Admin/Areas/Identity/Pages/Account/Logout.cshtml.cs
1,219
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityCustomization.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace IdentityCustomization.Areas.Identity.Pages.Account.Manage { public class Disable2faModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<Disable2faModel> _logger; public Disable2faModel( UserManager<ApplicationUser> userManager, ILogger<Disable2faModel> logger) { _userManager = userManager; _logger = logger; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGet() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!await _userManager.GetTwoFactorEnabledAsync(user)) { throw new InvalidOperationException($"Cannot disable 2FA for user with ID '{_userManager.GetUserId(User)}' as it's not currently enabled."); } return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false); if (!disable2faResult.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'."); } _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User)); StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app"; return RedirectToPage("./TwoFactorAuthentication"); } } }
35.90625
156
0.632724
[ "MIT" ]
235u/proposals
IdentityCustomization/IdentityCustomization/Areas/Identity/Pages/Account/Manage/Disable2fa.cshtml.cs
2,300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NMR { public class SignalDisplayView : View { } }
13.333333
41
0.7125
[ "MIT" ]
boba761/Amos_config
Src/Amos/Views/SignalDisplayView.cs
162
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { public partial class SourceVault : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Id)) { writer.WritePropertyName("id"); writer.WriteStringValue(Id); } writer.WriteEndObject(); } internal static SourceVault DeserializeSourceVault(JsonElement element) { Optional<string> id = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } } return new SourceVault(id.Value); } } }
26.195122
79
0.557728
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/SourceVault.Serialization.cs
1,074
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RuralAPI.Models; using RuralAPI.Services; namespace RuralAPI.Controllers { [Route("api/[controller]")] [ApiController] public class PersonController : ControllerBase { private readonly IPersonService _personService; public PersonController(IPersonService personService) { _personService = personService; } // GET: api/People [HttpGet] public ActionResult<Person> GetAll() { var persons = _personService.GetAll(); return new JsonResult(persons); } // GET: api/People/5 [HttpGet("{id}")] public ActionResult<Person> Get(long id) { var person = _personService.Get(id); return person; } // POST: api/People [HttpPost] public ActionResult<Person> Post(Person person) { var newPerson = _personService.Create(person); return newPerson; } // PUT: api/People/5 [HttpPut("{id}")] public ActionResult<Person> Put(long id, Person person) { var updatedPerson = _personService.Update(id, person); return updatedPerson; } } }
24.864407
70
0.593729
[ "MIT" ]
e310905-Saimia/rural-api
RuralAPI/RuralAPI/Controllers/PersonController.cs
1,469
C#
// http://careercup.com/question?id=4816567298686976 // // (Careercup really needs to step up their copy-paste game) // // Given a prime set, we call "prime expressible" if a number can be factorized only using given prime numbers. // Find n-th big expressible number. // // Example: // Set = { 2, 3 } // // Expressible numbers = { 1, 2, 3, 4, 6, 8, 9, 12, ... } // using System; using System.Linq; static class Program { static int[] NthExpressibleNumber(this int[] a, int n) { var result = new int[n]; var indexes = Enumerable. Repeat(0, a.Length).ToArray(); result[0] = 1; for (int i = 1; i < n; i++) { result[i] = indexes.Select((x, index) => result[x] * a[index]).Min(); indexes. Select((val, index) => new { val, index}). Where(x => result[x.val] * a[x.index] == result[i]). ToList(). ForEach(y => indexes[y.index] ++); } return result; } static void Main() { Console.WriteLine(String.Join(",", new [] {2, 3}.NthExpressibleNumber(20))); } }
25.933333
111
0.523565
[ "MIT" ]
Gerula/interviews
CareerCup/Google/prime_expressible.cs
1,167
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("p365 - Retired Jersey Numbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("p365 - Retired Jersey Numbers")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("138fe29b-4b8b-4b07-b9c6-273059367fc2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.135135
85
0.729293
[ "MIT" ]
head-first-csharp/second-edition
Chapter 8/p365 - Retired Jersey Numbers/p365 - Retired Jersey Numbers/Properties/AssemblyInfo.cs
1,488
C#
using Newtonsoft.Json; namespace LDtkUnity { /// <summary> /// This complex section isn't meant to be used by game devs at all, as these rules are /// completely resolved internally by the editor before any saving. You should just ignore /// this part. /// </summary> public partial class AutoLayerRuleDefinition { /// <summary> /// If FALSE, the rule effect isn't applied, and no tiles are generated. /// </summary> [JsonProperty("active")] public bool Active { get; set; } /// <summary> /// When TRUE, the rule will prevent other rules to be applied in the same cell if it matches /// (TRUE by default). /// </summary> [JsonProperty("breakOnMatch")] public bool BreakOnMatch { get; set; } /// <summary> /// Chances for this rule to be applied (0 to 1) /// </summary> [JsonProperty("chance")] public double Chance { get; set; } /// <summary> /// Checker mode Possible values: `None`, `Horizontal`, `Vertical` /// </summary> [JsonProperty("checker")] public Checker Checker { get; set; } /// <summary> /// If TRUE, allow rule to be matched by flipping its pattern horizontally /// </summary> [JsonProperty("flipX")] public bool FlipX { get; set; } /// <summary> /// If TRUE, allow rule to be matched by flipping its pattern vertically /// </summary> [JsonProperty("flipY")] public bool FlipY { get; set; } /// <summary> /// Default IntGrid value when checking cells outside of level bounds /// </summary> [JsonProperty("outOfBoundsValue")] public long? OutOfBoundsValue { get; set; } /// <summary> /// Rule pattern (size x size) /// </summary> [JsonProperty("pattern")] public long[] Pattern { get; set; } /// <summary> /// If TRUE, enable Perlin filtering to only apply rule on specific random area /// </summary> [JsonProperty("perlinActive")] public bool PerlinActive { get; set; } [JsonProperty("perlinOctaves")] public double PerlinOctaves { get; set; } [JsonProperty("perlinScale")] public double PerlinScale { get; set; } [JsonProperty("perlinSeed")] public double PerlinSeed { get; set; } /// <summary> /// X pivot of a tile stamp (0-1) /// </summary> [JsonProperty("pivotX")] public double PivotX { get; set; } /// <summary> /// Y pivot of a tile stamp (0-1) /// </summary> [JsonProperty("pivotY")] public double PivotY { get; set; } /// <summary> /// Pattern width & height. Should only be 1,3,5 or 7. /// </summary> [JsonProperty("size")] public long Size { get; set; } /// <summary> /// Array of all the tile IDs. They are used randomly or as stamps, based on `tileMode` value. /// </summary> [JsonProperty("tileIds")] public long[] TileIds { get; set; } /// <summary> /// Defines how tileIds array is used Possible values: `Single`, `Stamp` /// </summary> [JsonProperty("tileMode")] public TileMode TileMode { get; set; } /// <summary> /// Unique Int identifier /// </summary> [JsonProperty("uid")] public long Uid { get; set; } /// <summary> /// X cell coord modulo /// </summary> [JsonProperty("xModulo")] public long XModulo { get; set; } /// <summary> /// Y cell coord modulo /// </summary> [JsonProperty("yModulo")] public long YModulo { get; set; } } }
31.129032
102
0.541192
[ "MIT" ]
tuanminh3395/LDtkUnity
Assets/LDtkUnity/Runtime/Data/Schema/Definition/AutoLayerRuleDefinition.cs
3,862
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using DemoSimpleApi.Areas.HelpPage.ModelDescriptions; namespace DemoSimpleApi.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private XPathNavigator _documentNavigator; private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); } public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return _documentNavigator.SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return _documentNavigator.SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
43.395062
160
0.632717
[ "MIT" ]
horseracer/cross-platform-with-cloud
DemoBackend/DemoSimpleApi/Areas/HelpPage/XmlDocumentationProvider.cs
7,030
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from include/vulkan/vulkan_core.h in the KhronosGroup/Vulkan-Headers repository for tag v1.2.198 // Original source is Copyright © 2015-2021 The Khronos Group Inc. namespace TerraFX.Interop.Vulkan { public enum VkImageTiling { VK_IMAGE_TILING_OPTIMAL = 0, VK_IMAGE_TILING_LINEAR = 1, VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT = 1000158000, VK_IMAGE_TILING_MAX_ENUM = 0x7FFFFFFF, } }
36.4375
145
0.746141
[ "MIT" ]
tannergooding/terrafx.interop.vulkan
sources/Interop/Vulkan/Vulkan/vulkan/vulkan_core/VkImageTiling.cs
585
C#
// // Authors: // Marek Habersack <grendel@twistedcode.net> // // Copyright (C) 2011 Novell, Inc (http://novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Web.Configuration { public enum CustomErrorsRedirectMode { ResponseRedirect, ResponseRewrite } }
35.315789
73
0.753353
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/System.Web.Configuration_2.0/CustomErrorsRedirectMode.cs
1,342
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Automation.Cmdlet; using Microsoft.Azure.Commands.Automation.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Moq; using System; namespace Microsoft.Azure.Commands.ResourceManager.Automation.Test.UnitTests { [TestClass] public class NewAzureAutomationWebhookTest : RMTestBase { private Mock<IAutomationPSClient> mockAutomationClient; private MockCommandRuntime mockCommandRuntime; private NewAzureAutomationWebhook cmdlet; [TestInitialize] public void SetupTest() { this.mockAutomationClient = new Mock<IAutomationPSClient>(); this.mockCommandRuntime = new MockCommandRuntime(); this.cmdlet = new NewAzureAutomationWebhook { AutomationClient = this.mockAutomationClient.Object, CommandRuntime = this.mockCommandRuntime }; } [TestMethod] public void NewAzureAutomationWebhookByNameSuccessful() { // Setup string resourceGroupName = "resourceGroup"; string accountName = "account"; string name = "webhookName"; string runbookName = "runbookName"; DateTimeOffset expiryTime = DateTimeOffset.Now.AddDays(1); this.mockAutomationClient.Setup( f => f.CreateWebhook(resourceGroupName, accountName, name, runbookName, true, expiryTime, null, null)); // Test this.cmdlet.ResourceGroupName = resourceGroupName; this.cmdlet.AutomationAccountName = accountName; this.cmdlet.Name = name; this.cmdlet.RunbookName = runbookName; this.cmdlet.ExpiryTime = expiryTime; this.cmdlet.IsEnabled = true; this.cmdlet.Parameters = null; this.cmdlet.ExecuteCmdlet(); // Assert this.mockAutomationClient.Verify( f => f.CreateWebhook(resourceGroupName, accountName, name, runbookName, true, expiryTime, null, null), Times.Once()); } } }
41.486486
120
0.619218
[ "MIT" ]
3quanfeng/azure-powershell
src/Automation/Automation.Test/UnitTests/NewAzureAutomationWebhookTest.cs
2,999
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Figuras_Geometricas { abstract class Triangulo : Figura { //Atributos de la clase private double altura; public double Altura { get; set; } public double Lado2 { get; internal set; } public double Lado3 { get; internal set; } public Triangulo() { Altura = 0; } public override void CalcularPerimetro() { } public override void CalcularArea() { } } }
17.153846
50
0.539611
[ "Apache-2.0" ]
Daniel-Soto2001/POO
UNIDAD 4/Figuras Geometricas/Triangulo.cs
671
C#
using System; class CpuInfo { public static void Main(string[] args) { /* Retrieve information about processor architecture */ Yeppp.CpuArchitecture architecture = Yeppp.Library.GetCpuArchitecture(); Console.WriteLine("Architecture: {0}", architecture.Description); /* Retrieve information about processor vendor */ Yeppp.CpuVendor vendor = Yeppp.Library.GetCpuVendor(); Console.WriteLine("Vendor: {0}", vendor.Description); /* Retrieve information about processor microarchitecture */ Yeppp.CpuMicroarchitecture microarchitecture = Yeppp.Library.GetCpuMicroarchitecture(); Console.WriteLine("Microarchitecture: {0}", microarchitecture.Description); /* Check if Yeppp! is aware of any ISA features on this architecture */ if (architecture.CpuIsaFeatures.GetEnumerator().MoveNext()) { Console.WriteLine("CPU ISA extensions:"); /* Iterate through ISA features */ foreach (Yeppp.CpuIsaFeature isaFeature in architecture.CpuIsaFeatures) { Console.WriteLine(String.Format("\t{0, -60}\t{1}", isaFeature.Description + ":", (Yeppp.Library.IsSupported(isaFeature) ? "Yes" : "No"))); } } /* Check if Yeppp! is aware of any SIMD features on this architecture */ if (architecture.CpuSimdFeatures.GetEnumerator().MoveNext()) { Console.WriteLine("CPU SIMD extensions:"); /* Iterate through SIMD features */ foreach (Yeppp.CpuSimdFeature simdFeature in architecture.CpuSimdFeatures) { Console.WriteLine(String.Format("\t{0, -60}\t{1}", simdFeature.Description + ":", (Yeppp.Library.IsSupported(simdFeature) ? "Yes" : "No"))); } } /* Check if Yeppp! is aware of any non-ISA CPU and system features on this architecture */ if (architecture.CpuSystemFeatures.GetEnumerator().MoveNext()) { Console.WriteLine("Non-ISA CPU and system features:"); /* Iterate through non-ISA CPU and system features */ foreach (Yeppp.CpuSystemFeature systemFeature in architecture.CpuSystemFeatures) { Console.WriteLine(String.Format("\t{0, -60}\t{1}", systemFeature.Description + ":", (Yeppp.Library.IsSupported(systemFeature) ? "Yes" : "No"))); } } } }
46.956522
149
0.711111
[ "BSD-3-Clause" ]
rguthrie3/Yeppp-Mirror
examples/csharp/sources/CpuInfo.cs
2,160
C#
/* Copyright (c) 2019 Reakain & Bandit Bots LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BroomRacing { public class InputContainer : MonoBehaviour { public static InputContainer instance; public string movementAxis = "Horizontal"; public string raceAxis = "Vertical"; public string boostButton = "Jump"; public string startRaceButton = "Submit"; public string endRaceButton = "Cancel"; public bool rightButton = false; public bool leftButton = false; [Range(0, 1)] public float analogueDeadzone = 0.05f; private void Update() { if (Input.GetAxis(movementAxis) > analogueDeadzone) { rightButton = true; leftButton = false; } else if (Input.GetAxis(movementAxis) < -analogueDeadzone) { rightButton = false; leftButton = true; } else { rightButton = false; leftButton = false; } } void Awake() { instance = this; } } }
31.361111
78
0.656333
[ "MIT" ]
reakain/Broom-Racing
Broom-Racing/Assets/Broom-Racing/Scripts/InputContainer.cs
2,260
C#
 #if !NET35 && NETFRAMEWORK using System; using System.Diagnostics; using System.Threading; using Eneter.Messaging.Diagnostic; namespace Eneter.Messaging.MessagingSystems.SharedMemoryMessagingSystem { internal class EventWaitHandleExt { // Note: if openTimeout <= 0 then infinite loop trying to open the handle. public static EventWaitHandle OpenExisting(string name, TimeSpan openTimeout) { using (EneterTrace.Entering()) { EventWaitHandle anEventWaitHandle = null; Stopwatch aStopWatch = new Stopwatch(); aStopWatch.Start(); try { while (true) { try { anEventWaitHandle = EventWaitHandle.OpenExisting(name); // No exception, so the handle was open. break; } catch (WaitHandleCannotBeOpenedException) { // The handle does not exist so check the timeout. if (openTimeout > TimeSpan.Zero && aStopWatch.Elapsed >= openTimeout) { throw; } } // Wait a moment and try again. The handle can be meanwhile created. Thread.Sleep(100); } } finally { aStopWatch.Stop(); } return anEventWaitHandle; } } } } #endif
31.155172
98
0.428888
[ "MIT" ]
ng-eneter/eneter-net
EneterMessaging/EneterMessagingFramework/MessagingSystems/SharedMemoryMessagingSystem/EventWaitHandleExt.cs
1,809
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("TygaSoft.MsmqMessaging")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TygaSoft")] [assembly: AssemblyProduct("TygaSoft.MsmqMessaging")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("1c207573-ae09-4ba4-9474-873396e2f86d")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.297297
56
0.720452
[ "MIT" ]
qq283335746/MyContentSystem
src/TygaSoft/MsmqMessaging/Properties/AssemblyInfo.cs
1,324
C#
namespace Orchard.Security { public static class MembershipSettingsExtensions { public static int GetMinimumPasswordLength(this IMembershipSettings membershipSettings) { return membershipSettings.EnableCustomPasswordPolicy ? membershipSettings.MinimumPasswordLength : 7; } public static bool GetPasswordLowercaseRequirement(this IMembershipSettings membershipSettings) { return membershipSettings.EnableCustomPasswordPolicy ? membershipSettings.EnablePasswordLowercaseRequirement : false; } public static bool GetPasswordUppercaseRequirement(this IMembershipSettings membershipSettings) { return membershipSettings.EnableCustomPasswordPolicy ? membershipSettings.EnablePasswordUppercaseRequirement : false; } public static bool GetPasswordNumberRequirement(this IMembershipSettings membershipSettings) { return membershipSettings.EnableCustomPasswordPolicy ? membershipSettings.EnablePasswordNumberRequirement : false; } public static bool GetPasswordSpecialRequirement(this IMembershipSettings membershipSettings) { return membershipSettings.EnableCustomPasswordPolicy ? membershipSettings.EnablePasswordSpecialRequirement : false; } public static bool GetPasswordHistoryRequirement(this IMembershipSettings membershipSettings) { return membershipSettings.EnablePasswordHistoryPolicy ? membershipSettings.EnablePasswordHistoryPolicy : false; } public static int GetPasswordReuseLimit(this IMembershipSettings membershipSettings) { return membershipSettings.EnablePasswordHistoryPolicy ? membershipSettings.PasswordReuseLimit : 5; } } }
69.64
129
0.781735
[ "BSD-3-Clause" ]
OrchardCMS/orchard
src/Orchard.Web/Modules/Orchard.Users/Extensions/MembershipSettingsExtensions.cs
1,743
C#
using Mimp.SeeSharper.DependencyInjection.Abstraction; namespace Mimp.SeeSharper.DependencyInjection { public class EmptyDependencyProvider : IDependencyProvider { public IDependency? Provide(IDependencyContext context) => null; } }
18.5
72
0.760618
[ "MIT" ]
DavenaHack/SeeSharper.DependencyInjection
src/Mimp.SeeSharper.DependencyInjection/EmptyDependencyProvider.cs
261
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Silk.NET.Core.Attributes; #pragma warning disable 1591 namespace Silk.NET.OpenGLES { [NativeName("Name", "PointParameterNameSGIS")] public enum PointParameterNameSGIS : int { [NativeName("Name", "GL_POINT_SIZE_MIN")] PointSizeMin = 0x8126, [NativeName("Name", "GL_POINT_SIZE_MIN_ARB")] PointSizeMinArb = 0x8126, [NativeName("Name", "GL_POINT_SIZE_MIN_EXT")] PointSizeMinExt = 0x8126, [NativeName("Name", "GL_POINT_SIZE_MIN_SGIS")] PointSizeMinSgis = 0x8126, [NativeName("Name", "GL_POINT_SIZE_MAX")] PointSizeMax = 0x8127, [NativeName("Name", "GL_POINT_SIZE_MAX_ARB")] PointSizeMaxArb = 0x8127, [NativeName("Name", "GL_POINT_SIZE_MAX_EXT")] PointSizeMaxExt = 0x8127, [NativeName("Name", "GL_POINT_SIZE_MAX_SGIS")] PointSizeMaxSgis = 0x8127, [NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE")] PointFadeThresholdSize = 0x8128, [NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE_ARB")] PointFadeThresholdSizeArb = 0x8128, [NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE_EXT")] PointFadeThresholdSizeExt = 0x8128, [NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE_SGIS")] PointFadeThresholdSizeSgis = 0x8128, [NativeName("Name", "GL_DISTANCE_ATTENUATION_EXT")] DistanceAttenuationExt = 0x8129, [NativeName("Name", "GL_DISTANCE_ATTENUATION_SGIS")] DistanceAttenuationSgis = 0x8129, [NativeName("Name", "GL_POINT_DISTANCE_ATTENUATION")] PointDistanceAttenuation = 0x8129, [NativeName("Name", "GL_POINT_DISTANCE_ATTENUATION_ARB")] PointDistanceAttenuationArb = 0x8129, } }
38.816327
71
0.680862
[ "MIT" ]
Ar37-rs/Silk.NET
src/OpenGL/Silk.NET.OpenGLES/Enums/PointParameterNameSGIS.gen.cs
1,902
C#
using System.Collections.Generic; using StockportContentApi.ContentfulModels; using StockportContentApiTests.Unit.Builders; namespace StockportContentApiTests.Builders { public class ContentfulStartPageBuilder { private string _title { get; set; } = "Start Page"; private string _slug { get; set; } = "startPageSlug"; private string _teaser { get; set; } = "this is a teaser"; private string _summary { get; set; } = "This is a summary"; private string _upperBody { get; set; } = "An upper body"; private string _formLinkLabel { get; set; } = "Start now"; private string _formLink { get; set; } = "http://start.com"; private string _lowerBody { get; set; } = "Lower body"; private string _backgroundImage { get; set; } = "image.jpg"; private string _icon { get; set; } = "icon"; private List<ContentfulReference> _breadcrumbs = new List<ContentfulReference> { new ContentfulReferenceBuilder().Build() }; private List<ContentfulAlert> _alerts = new List<ContentfulAlert> { new ContentfulAlertBuilder().Build() }; public ContentfulStartPage Build() { return new ContentfulStartPage() { Title = _title, Slug = _slug, Teaser = _teaser, Summary = _summary, UpperBody = _upperBody, FormLinkLabel = _formLinkLabel, FormLink = _formLink, LowerBody = _lowerBody, BackgroundImage = _backgroundImage, Icon = _icon, Breadcrumbs = _breadcrumbs, Alerts = _alerts }; } public ContentfulStartPageBuilder Slug(string slug) { _slug = slug; return this; } public ContentfulStartPageBuilder Title(string title) { _title = title; return this; } public ContentfulStartPageBuilder Teaser(string teaser) { _teaser = teaser; return this; } } }
32.671642
86
0.56053
[ "MIT" ]
smbc-digital/iag-contentapi
test/StockportContentApiTests/Unit/Builders/ContentfulStartPageBuilder.cs
2,189
C#
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace DevOpsDashboard.Web.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "DevOpsDashboard.Web.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
57.60177
149
0.666462
[ "Apache-2.0" ]
jkruza/DevOpsDashboard
DevOpsDashboard.Web/Areas/HelpPage/App_Start/HelpPageConfig.cs
6,509
C#
using System; using UnityEngine; [Serializable] public class VCollisionCylinderSector : VCollisionShape { [HideInInspector, SerializeField] private VInt3 localPos = VInt3.zero; [HideInInspector, SerializeField] private int radius = 500; [HideInInspector, SerializeField] private int degree = 90; [HideInInspector, SerializeField] private int rotation; [HideInInspector, SerializeField] private int height = 500; private VInt3 worldPos = VInt3.zero; private VInt3 rightDir = VInt3.forward; private VInt3 leftDir = VInt3.forward; /* [CollisionProperty]*/ public VInt3 Pos { get { return this.localPos; } set { this.localPos = value; this.dirty = false; } } public VInt3 WorldPos { get { base.ConditionalUpdateShape(); return this.worldPos; } } /* [CollisionProperty]*/ public int Radius { get { return this.radius; } set { this.radius = value; this.dirty = true; } } /* [CollisionProperty]*/ public int Degree { get { return this.degree; } set { this.degree = Mathf.Clamp(value, 1, 360); this.dirty = true; } } /* [CollisionProperty]*/ public int Height { get { return this.height; } set { this.height = Mathf.Max(0, value); this.dirty = true; } } /* [CollisionProperty]*/ public int Rotation { get { return this.rotation; } set { this.rotation = value; this.dirty = true; } } public override int AvgCollisionRadius { get { return this.radius; } } public VCollisionCylinderSector() { this.dirty = true; } private static VInt3 ClosestPoint(ref VInt3 point, ref VInt3 lineStart, ref VInt3 lineDir, int lineLen) { long num = VInt3.DotXZLong(point - lineStart, lineDir); num = IntMath.Clamp(num, 0L, (long)(lineLen * 1000)); return IntMath.Divide(lineDir, num, 1000000L) + lineStart; } private static int CalcSide(ref VInt3 point, ref VInt3 lineStart, ref VInt3 lineDir) { return lineDir.x * (point.z - lineStart.z) - (point.x - lineStart.x) * lineDir.z; } public override bool Intersects(VCollisionSphere s) { base.ConditionalUpdateShape(); s.ConditionalUpdateShape(); VInt3 rhs = s.WorldPos; int worldRadius = s.WorldRadius; int num = this.height >> 1; int num2 = this.worldPos.y - num; int num3 = this.worldPos.y + num; if (rhs.y + worldRadius <= num2 || rhs.y - worldRadius >= num3) { return false; } int num4 = worldRadius; if (rhs.y > num3 || rhs.y < num2) { int num5 = (rhs.y <= num3) ? (num2 - rhs.y) : (rhs.y - num3); int num6 = worldRadius * worldRadius - num5 * num5; //DebugHelper.Assert(num6 >= 0); num4 = IntMath.Sqrt((long)num6); } long num7 = (long)(num4 + this.radius); if ((this.worldPos - rhs).sqrMagnitudeLong2D >= num7 * num7) { return false; } int num8 = worldRadius * worldRadius; VInt3 lhs = VCollisionCylinderSector.ClosestPoint(ref rhs, ref this.worldPos, ref this.leftDir, this.radius); if ((lhs - rhs).sqrMagnitudeLong2D <= (long)num8) { return true; } lhs = VCollisionCylinderSector.ClosestPoint(ref rhs, ref this.worldPos, ref this.rightDir, this.radius); if ((lhs - rhs).sqrMagnitudeLong2D <= (long)num8) { return true; } if (this.degree <= 180) { if (VCollisionCylinderSector.CalcSide(ref rhs, ref this.worldPos, ref this.leftDir) <= 0 && VCollisionCylinderSector.CalcSide(ref rhs, ref this.worldPos, ref this.rightDir) >= 0) { return true; } } else if (VCollisionCylinderSector.CalcSide(ref rhs, ref this.worldPos, ref this.leftDir) <= 0 || VCollisionCylinderSector.CalcSide(ref rhs, ref this.worldPos, ref this.rightDir) >= 0) { return true; } return false; } public override bool Intersects(VCollisionBox obb) { return false; } public override bool Intersects(VCollisionCylinderSector s) { return false; } public override bool EdgeIntersects(VCollisionSphere s) { return this.Intersects(s); } public override bool EdgeIntersects(VCollisionBox s) { return false; } public override bool EdgeIntersects(VCollisionCylinderSector s) { return false; } public override CollisionShapeType GetShapeType() { return CollisionShapeType.CylinderSector; } public override void UpdateShape(VInt3 location, VInt3 forward) { VCollisionSphere.UpdatePosition(ref this.worldPos, ref this.localPos, ref location, ref forward); if (this.rotation != 0) { forward = forward.RotateY(this.rotation); } VFactor vFactor; VFactor vFactor2; IntMath.sincos(out vFactor, out vFactor2, (long)(314 * Mathf.Clamp(this.degree, 1, 360)), 36000L); long num = vFactor2.nom * vFactor.den; long num2 = vFactor2.den * vFactor.nom; long b = vFactor2.den * vFactor.den; this.rightDir.x = (int)IntMath.Divide((long)forward.x * num + (long)forward.z * num2, b); this.rightDir.z = (int)IntMath.Divide((long)(-(long)forward.x) * num2 + (long)forward.z * num, b); this.rightDir.y = 0; num2 = -num2; this.leftDir.x = (int)IntMath.Divide((long)forward.x * num + (long)forward.z * num2, b); this.leftDir.z = (int)IntMath.Divide((long)(-(long)forward.x) * num2 + (long)forward.z * num, b); this.leftDir.y = 0; this.rightDir.Normalize(); this.leftDir.Normalize(); this.dirty = false; } public override void UpdateShape(VInt3 location, VInt3 forward, int moveDelta) { } public override void GetAabb2D(out VInt2 origin, out VInt2 size) { origin = this.worldPos.xz; origin.x -= this.radius; origin.y -= this.radius; size.x = this.radius + this.radius; size.y = size.x; } // public override bool AcceptFowVisibilityCheck(COM_PLAYERCAMP inHostCamp, GameFowManager fowMgr) // { // return GameFowCollector.VisitFowVisibilityCheck(this, this.owner, inHostCamp, fowMgr); // } }
22.523438
185
0.682449
[ "MIT" ]
lim1992/ET
Unity/Assets/Scripts/Base/Physics/VCollisionCylinderSector.cs
5,766
C#
// This code is distributed under MIT license. // Copyright (c) 2015 George Mamaladze // See license.txt or https://mit-license.org/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using WindowsInput.Native; namespace WindowsInput.Events.Sources { public abstract class HookEventSource : EventSourceBase { protected abstract HookHandle Subscribe(); protected abstract bool Callback(CallbackData data); protected override void Enable() { Handle = Subscribe(); } protected override void Disable() { if (Handle != default) { Handle?.Dispose(); Handle = null; } } protected HookHandle Handle { get; set; } protected IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam) { var ret = new IntPtr(-1); var passThrough = nCode != 0; if (passThrough) { ret = CallNextHookEx(nCode, wParam, lParam); } else { var callbackData = new CallbackData(wParam, lParam); var continueProcessing = Callback(callbackData); if (continueProcessing) { ret = CallNextHookEx(nCode, wParam, lParam); } else { } } return ret; } private static IntPtr CallNextHookEx(int nCode, IntPtr wParam, IntPtr lParam) { return HookNativeMethods.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam); } protected EventSourceEventArgs InvokeMany(params Func<EventSourceEventArgs, EventSourceEventArgs>[] Actions) { var ret = new EventSourceEventArgs(DateTimeOffset.UtcNow); ; foreach (var item in Actions) { if (ret.Next_Event_Enabled) { var tret = item(ret); ret.Next_Event_Enabled = tret.Next_Event_Enabled; ret.Next_Hook_Enabled = tret.Next_Hook_Enabled; } } return ret; } protected EventSourceEventArgs InvokeEvent<T>(EventSourceEventArgs args, EventHandler<EventSourceEventArgs<T>> Event, T Data, object RawData, DateTimeOffset Timestamp) { var ret = new EventSourceEventArgs(Timestamp); ret.Next_Event_Enabled = args.Next_Event_Enabled; ret.Next_Hook_Enabled = args.Next_Hook_Enabled; if (!EqualityComparer<T>.Default.Equals(Data, default)) { var Args = new EventSourceEventArgs<T>(Timestamp, Data, RawData) { Next_Event_Enabled = args.Next_Event_Enabled, Next_Hook_Enabled = args.Next_Hook_Enabled, }; Event?.Invoke(this, Args); ret.Next_Event_Enabled = Args.Next_Event_Enabled; ret.Next_Hook_Enabled = Args.Next_Hook_Enabled; } return ret; } } }
32.623656
177
0.591958
[ "MIT" ]
AlexCSDev/WindowsInput
WindowsInput/EventsSources/HookEventSource.cs
3,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dental.Entities.Interface { public interface IEntity { } }
14.285714
35
0.745
[ "MIT" ]
hkmky/DentalProject
Back-End/Dental.Entities/Interface/IEntity.cs
202
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datasync-2018-11-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DataSync.Model { /// <summary> /// CreateLocationS3Response /// </summary> public partial class CreateLocationS3Response : AmazonWebServiceResponse { private string _locationArn; /// <summary> /// Gets and sets the property LocationArn. /// <para> /// The Amazon Resource Name (ARN) of the source Amazon S3 bucket location that is created. /// </para> /// </summary> [AWSProperty(Max=128)] public string LocationArn { get { return this._locationArn; } set { this._locationArn = value; } } // Check to see if LocationArn property is set internal bool IsSetLocationArn() { return this._locationArn != null; } } }
29.362069
106
0.661186
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/DataSync/Generated/Model/CreateLocationS3Response.cs
1,703
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace WizBot.Migrations { public partial class unbantimerreset : Migration { protected override void Up(MigrationBuilder migrationBuilder) { // I have to remove everything as it has been piling up for a year. migrationBuilder.Sql(@"DELETE FROM UnbanTimer;"); } protected override void Down(MigrationBuilder migrationBuilder) { } } }
24.842105
79
0.658898
[ "MIT" ]
fossabot/WizBot
WizBot.Core/Migrations/20181102094215_unban-timer-reset.cs
472
C#
// Copyright (c) 2017 Gwaredd Mountain, https://opensource.org/licenses/MIT #if !UNIUM_DISABLE && ( DEVELOPMENT_BUILD || UNITY_EDITOR || UNIUM_ENABLE ) using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace gw.gql { //////////////////////////////////////////////////////////////////////////////////////////////////// public partial class Query { List<object> ActionInvoke() { var actionName = SearchPath.Target; if( string.IsNullOrEmpty( actionName ) ) { UniumComponent.Warn( "No function name given for Invoke() call" ); return null; } var strArgs = SearchPath.Arguments; object[] cachedValues = new object[ strArgs.Length ]; Type[] cachedTypes = new Type[ strArgs.Length ]; object[] args = new object[ strArgs.Length ]; var results = new List<object>(); foreach( var current in Selected ) { try { // find something to invoke - either a method, event or field/property with an Invoke function (e.g. UnityEvent or Button) var target = current; var targetType = target.GetType(); var method = null as MethodInfo; var multicast = null as MulticastDelegate; var member = targetType.GetMember( actionName ); var memberType = member.Length > 0 ? member[ 0 ].MemberType : 0; if( ( memberType & MemberTypes.Method ) == MemberTypes.Method ) { method = targetType.GetMethods().Where( m => m.Name == actionName && m.GetParameters().Length == args.Length ).FirstOrDefault(); } else if( ( memberType & MemberTypes.Event ) == MemberTypes.Event ) { var field = targetType.GetField( actionName, BindingFlags.Instance | BindingFlags.NonPublic ); multicast = field == null ? null : field.GetValue( target ) as MulticastDelegate; if( multicast != null ) { var delegateList = multicast.GetInvocationList(); method = delegateList.Length > 0 ? delegateList[ 0 ].Method : null; } } else if( ( memberType & MemberTypes.Field ) == MemberTypes.Field ) { var field = targetType.GetField( actionName ); target = field == null ? null : field.GetValue( target ); method = target == null ? null : target.GetType().GetMethod( "Invoke" ); } else if( ( memberType & MemberTypes.Property ) == MemberTypes.Property ) { var prop = targetType.GetProperty( actionName ); target = prop == null ? null : prop.GetValue( target, null ); method = target == null ? null : target.GetType().GetMethod( "Invoke" ); } // if we didn't find anything invokable then skip this object if( method == null ) { continue; } // otherwise, convert arguments passed in to the appropriate types if( strArgs != null ) { var argInfo = method.GetParameters(); if( argInfo.Length != strArgs.Length ) { //Unium.Instance.Log.Warn( "Can't invoke function {0} - parameters do not match", func ); continue; } for( int i=0; i < args.Length; i++ ) { // convert string to value var argType = argInfo[ i ].ParameterType; if( argType != cachedTypes[ i ] ) { cachedTypes[ i ] = argType; cachedValues[ i ] = ConvertType.FromString( strArgs[ i ], argType ); } args[ i ] = cachedValues[ i ]; } } // invoke method object result = null; if( multicast != null ) { result = multicast.DynamicInvoke( args ); } else { result = method.Invoke( target, args ); } results.Add( result ); } catch( Exception e ) { if( UniumComponent.IsDebug ) { UniumComponent.Warn( string.Format( "Failed to invoke '{0}' - {1}", actionName, e.Message ) ); } } } return results; } } } #endif
39.624113
153
0.410954
[ "MIT" ]
DragonBox/unium
Assets/Unium/GQL/Query/ActionInvoke.cs
5,589
C#