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
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: ReferenceAssembly] [assembly: AssemblyTitle("System.Runtime")] [assembly: AssemblyDescription("System.Runtime")] [assembly: AssemblyDefaultAlias("System.Runtime")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.27406.03")] [assembly: AssemblyInformationalVersion("4.6.27406.03 built by: SOURCEBUILD")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("", "")] [assembly: AssemblyVersion("4.1.1.1")] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandle))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandleType))] [assembly: TypeForwardedTo(typeof(System.Action))] [assembly: TypeForwardedTo(typeof(System.Action<>))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, >))] [assembly: TypeForwardedTo(typeof(System.Action<, , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Action<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Activator))] [assembly: TypeForwardedTo(typeof(System.ArgumentException))] [assembly: TypeForwardedTo(typeof(System.ArgumentNullException))] [assembly: TypeForwardedTo(typeof(System.ArgumentOutOfRangeException))] [assembly: TypeForwardedTo(typeof(System.ArithmeticException))] [assembly: TypeForwardedTo(typeof(System.Array))] [assembly: TypeForwardedTo(typeof(System.ArraySegment<>))] [assembly: TypeForwardedTo(typeof(System.ArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(System.AsyncCallback))] [assembly: TypeForwardedTo(typeof(System.Attribute))] [assembly: TypeForwardedTo(typeof(System.AttributeTargets))] [assembly: TypeForwardedTo(typeof(System.AttributeUsageAttribute))] [assembly: TypeForwardedTo(typeof(System.BadImageFormatException))] [assembly: TypeForwardedTo(typeof(System.Boolean))] [assembly: TypeForwardedTo(typeof(System.Buffer))] [assembly: TypeForwardedTo(typeof(System.Byte))] [assembly: TypeForwardedTo(typeof(System.Char))] [assembly: TypeForwardedTo(typeof(System.CLSCompliantAttribute))] [assembly: TypeForwardedTo(typeof(System.Collections.DictionaryEntry))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.ICollection<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IComparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IDictionary<, >))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEnumerator<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEqualityComparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IList<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IReadOnlyDictionary<, >))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IReadOnlyList<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.ISet<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.KeyNotFoundException))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.KeyValuePair<, >))] [assembly: TypeForwardedTo(typeof(System.Collections.ICollection))] [assembly: TypeForwardedTo(typeof(System.Collections.IComparer))] [assembly: TypeForwardedTo(typeof(System.Collections.IDictionary))] [assembly: TypeForwardedTo(typeof(System.Collections.IDictionaryEnumerator))] [assembly: TypeForwardedTo(typeof(System.Collections.IEnumerable))] [assembly: TypeForwardedTo(typeof(System.Collections.IEnumerator))] [assembly: TypeForwardedTo(typeof(System.Collections.IEqualityComparer))] [assembly: TypeForwardedTo(typeof(System.Collections.IList))] [assembly: TypeForwardedTo(typeof(System.Collections.IStructuralComparable))] [assembly: TypeForwardedTo(typeof(System.Collections.IStructuralEquatable))] [assembly: TypeForwardedTo(typeof(System.Collections.ObjectModel.Collection<>))] [assembly: TypeForwardedTo(typeof(System.Collections.ObjectModel.ReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(System.Comparison<>))] [assembly: TypeForwardedTo(typeof(System.ComponentModel.DefaultValueAttribute))] [assembly: TypeForwardedTo(typeof(System.ComponentModel.EditorBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(System.ComponentModel.EditorBrowsableState))] [assembly: TypeForwardedTo(typeof(System.DateTime))] [assembly: TypeForwardedTo(typeof(System.DateTimeKind))] [assembly: TypeForwardedTo(typeof(System.DateTimeOffset))] [assembly: TypeForwardedTo(typeof(System.DayOfWeek))] [assembly: TypeForwardedTo(typeof(System.Decimal))] [assembly: TypeForwardedTo(typeof(System.Delegate))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ConditionalAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggableAttribute))] [assembly: TypeForwardedTo(typeof(System.DivideByZeroException))] [assembly: TypeForwardedTo(typeof(System.Double))] [assembly: TypeForwardedTo(typeof(System.Enum))] [assembly: TypeForwardedTo(typeof(System.EventArgs))] [assembly: TypeForwardedTo(typeof(System.EventHandler))] [assembly: TypeForwardedTo(typeof(System.EventHandler<>))] [assembly: TypeForwardedTo(typeof(System.Exception))] [assembly: TypeForwardedTo(typeof(System.FieldAccessException))] [assembly: TypeForwardedTo(typeof(System.FlagsAttribute))] [assembly: TypeForwardedTo(typeof(System.FormatException))] [assembly: TypeForwardedTo(typeof(System.FormattableString))] [assembly: TypeForwardedTo(typeof(System.Func<>))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, >))] [assembly: TypeForwardedTo(typeof(System.Func<, , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Func<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.GC))] [assembly: TypeForwardedTo(typeof(System.GCCollectionMode))] [assembly: TypeForwardedTo(typeof(System.Globalization.DateTimeStyles))] [assembly: TypeForwardedTo(typeof(System.Globalization.NumberStyles))] [assembly: TypeForwardedTo(typeof(System.Globalization.TimeSpanStyles))] [assembly: TypeForwardedTo(typeof(System.Guid))] [assembly: TypeForwardedTo(typeof(System.IAsyncResult))] [assembly: TypeForwardedTo(typeof(System.IComparable))] [assembly: TypeForwardedTo(typeof(System.IComparable<>))] [assembly: TypeForwardedTo(typeof(System.IConvertible))] [assembly: TypeForwardedTo(typeof(System.ICustomFormatter))] [assembly: TypeForwardedTo(typeof(System.IDisposable))] [assembly: TypeForwardedTo(typeof(System.IEquatable<>))] [assembly: TypeForwardedTo(typeof(System.IFormatProvider))] [assembly: TypeForwardedTo(typeof(System.IFormattable))] [assembly: TypeForwardedTo(typeof(System.IndexOutOfRangeException))] [assembly: TypeForwardedTo(typeof(System.InsufficientExecutionStackException))] [assembly: TypeForwardedTo(typeof(System.Int16))] [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(System.Int64))] [assembly: TypeForwardedTo(typeof(System.IntPtr))] [assembly: TypeForwardedTo(typeof(System.InvalidCastException))] [assembly: TypeForwardedTo(typeof(System.InvalidOperationException))] [assembly: TypeForwardedTo(typeof(System.InvalidProgramException))] [assembly: TypeForwardedTo(typeof(System.InvalidTimeZoneException))] [assembly: TypeForwardedTo(typeof(System.IO.DirectoryNotFoundException))] [assembly: TypeForwardedTo(typeof(System.IO.FileLoadException))] [assembly: TypeForwardedTo(typeof(System.IO.FileNotFoundException))] [assembly: TypeForwardedTo(typeof(System.IO.IOException))] [assembly: TypeForwardedTo(typeof(System.IO.PathTooLongException))] [assembly: TypeForwardedTo(typeof(System.IObservable<>))] [assembly: TypeForwardedTo(typeof(System.IObserver<>))] [assembly: TypeForwardedTo(typeof(System.IProgress<>))] [assembly: TypeForwardedTo(typeof(System.Lazy<>))] [assembly: TypeForwardedTo(typeof(System.Lazy<, >))] [assembly: TypeForwardedTo(typeof(System.MemberAccessException))] [assembly: TypeForwardedTo(typeof(System.MethodAccessException))] [assembly: TypeForwardedTo(typeof(System.MissingFieldException))] [assembly: TypeForwardedTo(typeof(System.MissingMemberException))] [assembly: TypeForwardedTo(typeof(System.MissingMethodException))] [assembly: TypeForwardedTo(typeof(System.MTAThreadAttribute))] [assembly: TypeForwardedTo(typeof(System.MulticastDelegate))] [assembly: TypeForwardedTo(typeof(System.NotImplementedException))] [assembly: TypeForwardedTo(typeof(System.NotSupportedException))] [assembly: TypeForwardedTo(typeof(System.Nullable))] [assembly: TypeForwardedTo(typeof(System.Nullable<>))] [assembly: TypeForwardedTo(typeof(System.NullReferenceException))] [assembly: TypeForwardedTo(typeof(System.Object))] [assembly: TypeForwardedTo(typeof(System.ObjectDisposedException))] [assembly: TypeForwardedTo(typeof(System.ObsoleteAttribute))] [assembly: TypeForwardedTo(typeof(System.OutOfMemoryException))] [assembly: TypeForwardedTo(typeof(System.OverflowException))] [assembly: TypeForwardedTo(typeof(System.ParamArrayAttribute))] [assembly: TypeForwardedTo(typeof(System.PlatformNotSupportedException))] [assembly: TypeForwardedTo(typeof(System.Predicate<>))] [assembly: TypeForwardedTo(typeof(System.RankException))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCompanyAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyConfigurationAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCopyrightAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCultureAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDefaultAliasAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDelaySignAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyFileVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyFlagsAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyInformationalVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyKeyFileAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyKeyNameAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyMetadataAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyNameFlags))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyProductAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblySignatureKeyAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyTitleAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyTrademarkAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.DefaultMemberAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.ProcessorArchitecture))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AccessedThroughPropertyAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CallerFilePathAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CallerLineNumberAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CallerMemberNameAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConditionalWeakTable<, >))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CustomConstantAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DateTimeConstantAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DecimalConstantAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DisablePrivateReflectionAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ExtensionAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.FixedBufferAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.FormattableStringFactory))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IndexerNameAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsConst))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IStrongBox))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsVolatile))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.MethodImplAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.MethodImplOptions))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.RuntimeHelpers))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.StateMachineAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.StrongBox<>))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.TypeForwardedFromAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.UnsafeValueTypeAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo))] [assembly: TypeForwardedTo(typeof(System.Runtime.GCLargeObjectHeapCompactionMode))] [assembly: TypeForwardedTo(typeof(System.Runtime.GCLatencyMode))] [assembly: TypeForwardedTo(typeof(System.Runtime.GCSettings))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.CharSet))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.ComVisibleAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.FieldOffsetAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.LayoutKind))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.OutAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.StructLayoutAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.TargetFrameworkAttribute))] [assembly: TypeForwardedTo(typeof(System.RuntimeFieldHandle))] [assembly: TypeForwardedTo(typeof(System.RuntimeMethodHandle))] [assembly: TypeForwardedTo(typeof(System.RuntimeTypeHandle))] [assembly: TypeForwardedTo(typeof(System.SByte))] [assembly: TypeForwardedTo(typeof(System.Security.AllowPartiallyTrustedCallersAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.SecurityCriticalAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.SecurityException))] [assembly: TypeForwardedTo(typeof(System.Security.SecuritySafeCriticalAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.SecurityTransparentAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.VerificationException))] [assembly: TypeForwardedTo(typeof(System.Single))] [assembly: TypeForwardedTo(typeof(System.STAThreadAttribute))] [assembly: TypeForwardedTo(typeof(System.String))] [assembly: TypeForwardedTo(typeof(System.StringComparison))] [assembly: TypeForwardedTo(typeof(System.StringSplitOptions))] [assembly: TypeForwardedTo(typeof(System.Text.StringBuilder))] [assembly: TypeForwardedTo(typeof(System.Threading.LazyThreadSafetyMode))] [assembly: TypeForwardedTo(typeof(System.Threading.Timeout))] [assembly: TypeForwardedTo(typeof(System.Threading.WaitHandle))] [assembly: TypeForwardedTo(typeof(System.ThreadStaticAttribute))] [assembly: TypeForwardedTo(typeof(System.TimeoutException))] [assembly: TypeForwardedTo(typeof(System.TimeSpan))] [assembly: TypeForwardedTo(typeof(System.TimeZoneInfo))] [assembly: TypeForwardedTo(typeof(System.Tuple))] [assembly: TypeForwardedTo(typeof(System.Tuple<>))] [assembly: TypeForwardedTo(typeof(System.Tuple<, >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , , >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , , , >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , , , , >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Tuple<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(System.Type))] [assembly: TypeForwardedTo(typeof(System.TypeAccessException))] [assembly: TypeForwardedTo(typeof(System.TypeCode))] [assembly: TypeForwardedTo(typeof(System.TypeInitializationException))] [assembly: TypeForwardedTo(typeof(System.TypeLoadException))] [assembly: TypeForwardedTo(typeof(System.UInt16))] [assembly: TypeForwardedTo(typeof(System.UInt32))] [assembly: TypeForwardedTo(typeof(System.UInt64))] [assembly: TypeForwardedTo(typeof(System.UIntPtr))] [assembly: TypeForwardedTo(typeof(System.UnauthorizedAccessException))] [assembly: TypeForwardedTo(typeof(System.Uri))] [assembly: TypeForwardedTo(typeof(System.UriComponents))] [assembly: TypeForwardedTo(typeof(System.UriFormat))] [assembly: TypeForwardedTo(typeof(System.UriFormatException))] [assembly: TypeForwardedTo(typeof(System.UriHostNameType))] [assembly: TypeForwardedTo(typeof(System.UriKind))] [assembly: TypeForwardedTo(typeof(System.ValueType))] [assembly: TypeForwardedTo(typeof(System.Version))] [assembly: TypeForwardedTo(typeof(void))] [assembly: TypeForwardedTo(typeof(System.WeakReference))] [assembly: TypeForwardedTo(typeof(System.WeakReference<>))]
64.877743
102
0.802087
[ "MIT" ]
chsienki/source-build-reference-packages
src/referencePackages/src/system.runtime/4.3.1/ref/net462/System.Runtime.cs
20,698
C#
namespace ImportCsvToGraphite { using System; using System.IO; using System.Linq; using System.Net.Sockets; internal class Program { private static string _hostname = "localhost"; private static string _directory = "c:\\temp\\metrics"; private static int _port = 2003; private static int _rebaseSeconds; private static string _prefix = "Neo4j"; private static int _incrementRebaseSeconds = 5; private static bool _convertToDt; private static string _convertToDtOutputFolder; private static bool _verbose; private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1); private static bool AreParametersOk(string[] args) { for (var i = 0; i < args.Length; i++) switch (args[i].ToLowerInvariant()) { case "-verbose": case "-v": _verbose = true; break; case "-hostname": case "-host": _hostname = args[++i]; break; case "-port": if (int.TryParse(args[++i], out var port)) _port = port; // ReSharper disable once NotResolvedInText else throw new ArgumentOutOfRangeException("port", args[i], "Port isn't a number!"); break; case "-directory": case "-d": _directory = args[++i]; break; case "-rebaseseconds": case "-rs": if (int.TryParse(args[++i], out var rebaseSeconds)) _rebaseSeconds = rebaseSeconds; else // ReSharper disable once NotResolvedInText throw new ArgumentOutOfRangeException("rebaseSeconds", args[i], "Seconds provided for RebaseSeconds wasn't a number"); break; case "-rebasesecondsincrement": case "-rsi": if (int.TryParse(args[++i], out var rebaseIncrement)) _incrementRebaseSeconds = rebaseIncrement; else // ReSharper disable once NotResolvedInText throw new ArgumentOutOfRangeException("rebaseIncrementSeconds", args[i], "Seconds provided to increment RebaseSeconds wasn't a number."); break; case "-prefix": _prefix = args[++i]; break; case "-converttodt": _convertToDt = true; _convertToDtOutputFolder = args[++i]; break; default: Console.WriteLine($"Unknown parameter supplied: '{args[i]}'"); ShowUsageMessage(); return false; } if (!_convertToDt && (string.IsNullOrWhiteSpace(_hostname) || string.IsNullOrWhiteSpace(_prefix) || string.IsNullOrWhiteSpace(_directory))) return false; return true; } private static void Main(string[] args) { if (!AreParametersOk(args)) { ShowUsageMessage(); return; } DateTime start = DateTime.Now; if (_convertToDt) ConvertToDateTime(); else ImportToGraphite(); Console.WriteLine($"All done!! (Took {(DateTime.Now - start).TotalMilliseconds} ms)"); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); } private static void ImportToGraphite() { var client = new TcpClient(); client.Connect(_hostname, _port); Console.WriteLine($"Connected to the Graphite end point ({client.Connected})."); var stream = new StreamWriter(client.GetStream()); var files = Directory.GetFiles(_directory, "*.csv"); foreach (var file in files) { var fInfo = new FileInfo(file); Console.WriteLine($"Inserting {fInfo.Name} to Graphite...."); var secondsSinceEpoch = SecondsSinceEpoch(TimeSpan.FromSeconds(_rebaseSeconds)); var stat = fInfo.Name.Replace(".csv", ""); var lines = File.ReadAllLines(file).Skip(1); foreach (var line in lines) { if (line.StartsWith("t,")) continue; var split = line.Split(",".ToCharArray()); var newLine = _rebaseSeconds != 0 ? $"{_prefix}.{stat} {split[1]} {secondsSinceEpoch}" : $"{_prefix}.{stat} {split[1]} {split[0]} "; if (_rebaseSeconds != 0) secondsSinceEpoch += _incrementRebaseSeconds; if (_verbose) Console.WriteLine($"\tWriting {newLine} to Stream (which is: {new DateTime(1970, 1, 1).AddSeconds(secondsSinceEpoch):yyyy-MM-dd HH:mm:ss})"); stream.WriteLine($"{newLine}"); } Console.WriteLine($"Inserted {fInfo.Name} to Graphite."); } stream.Dispose(); client.Dispose(); } private static void ConvertToDateTime() { var files = Directory.GetFiles(_directory, "*.csv"); var outputDirectory = string.IsNullOrWhiteSpace(_convertToDtOutputFolder) ? new DirectoryInfo(_directory) : Directory.CreateDirectory(_convertToDtOutputFolder); foreach (var file in files) { var inputFile = new FileInfo(file); var outputFile = File.Create(Path.Combine(outputDirectory.FullName, inputFile.Name)); var stat = inputFile.Name.Replace(".csv", ""); var start = DateTime.Now; Console.WriteLine($"Writing {inputFile.Name} to {outputFile.Name}."); var outputWriter = new StreamWriter(outputFile); outputWriter.WriteLine($"DateTime,{_prefix}.{stat}"); var secondsSinceEpoch = SecondsSinceEpoch(TimeSpan.FromSeconds(_rebaseSeconds)); var lines = File.ReadAllLines(file).Skip(1); foreach (var line in lines) { if (line.StartsWith("t,")) continue; var split = line.Split(",".ToCharArray()); var newLine = _rebaseSeconds != 0 ? $"{UnixEpoch.AddSeconds(secondsSinceEpoch)},{split[1]}" : $"{UnixEpoch.AddSeconds(Convert.ToInt32(split[0]))},{split[1]}"; if (_rebaseSeconds != 0) secondsSinceEpoch += _incrementRebaseSeconds; if (_verbose) Console.WriteLine($"Writing {newLine} to {outputFile.Name} (which is: {new DateTime(1970, 1, 1).AddSeconds(secondsSinceEpoch):yyyy-MM-dd HH:mm:ss})"); outputWriter.WriteLine(newLine); } outputFile.Close(); Console.WriteLine($"Wrote {inputFile.Name} to {outputFile.Name} ({(DateTime.Now - start).TotalMilliseconds} ms)."); } } private static void ShowUsageMessage() { Console.WriteLine("Importer / Converter"); Console.WriteLine("usage: dotnet run -d DIRECTORY [-host HOST -port PORT] [-convertToDt FOLDER] [-rs REBASE] [-rsi REBASE_INCREMENT] [-prefix PREFIX] [-verbose]"); Console.WriteLine(); Console.WriteLine("Args:"); Console.WriteLine("-d / -directory :: The directory to read the metrics files from [REQUIRED]"); Console.WriteLine("-host HOST :: the host of the graphite server (IP/DNS name) [OPTIONAL]"); Console.WriteLine("-port PORT :: the port of the graphite server [OPTIONAL - REQUIRED if using '-host']"); Console.WriteLine("-prefix :: a prefix to append to the stream to graphite to organise your metrics (typically something like 'neo4j') [OPTIONAL]"); Console.WriteLine("-convertToDt FOLDER :: the folder to output converted CSV files to. [OPTIONAL]"); Console.WriteLine("-rs REBASE :: the point to rebase the metrics files from in seconds [OPTIONAL]"); Console.WriteLine("-rsi REBASE INCREMENT :: the number of seconds to incremement each metric by when reading in the data [OPTIONAL]"); Console.WriteLine("-verbose :: Outputs verbose info about things happening (due to writing to the screen this will significantly slow down the process)."); Console.WriteLine("---------------------------------------------------------------------------"); Console.WriteLine("Import to Graphite Example:"); Console.WriteLine("dotnet run -host localhost -port 2003 -rs 3600 -d c:\\temp\\metrics"); Console.WriteLine(); Console.WriteLine("Convert To DT example:"); Console.WriteLine("dotnet run -d c:\\temp\\metrics -convertToDt c:\\temp\\metrics\\dt -verbose"); } private static int SecondsSinceEpoch(TimeSpan? hoursToSubtract = null) { if (hoursToSubtract == null) hoursToSubtract = TimeSpan.Zero; var t = (DateTime.Now - new DateTime(1970, 1, 1)).Subtract(hoursToSubtract.Value); return (int) t.TotalSeconds; } } }
45.780269
176
0.508767
[ "MIT" ]
cskardon/ImportCsvToGraphite
ImportCsvToGraphite/ImportCsvToGraphite/Program.cs
10,211
C#
using CsvHelper; using LazyCache; using LiveCharts; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; namespace CovidItalia { public static class Parser { public class Dati { public DateTime data { get; set; } public string regione { get; set; } public int nuoviPositivi { get; set; } public int totaleCasi { get; set; } public int totaleDeceduti { get; set; } public int totaleTamponi { get; set; } public int nuoviGuariti { get; set; } public int totaleGuariti { get; set; } public int totalePositivi { get; set; } public int nuoviDeceduti { get; set; } public int nuoviTamponi { get; set; } } public static List<Dati> ReadCSV() { string source = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv"; StringReader rawFile = new StringReader(new WebClient().DownloadString(source)); using (var reader = rawFile) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { List<Dati> records = new List<Dati>(); csv.Read(); csv.ReadHeader(); while (csv.Read()) { Dati regionep = new Dati(); regionep.totaleTamponi = 0; regionep.totaleDeceduti = 0; if (records.Count > 1) { regionep.totaleTamponi = records[records.Count - 1].totaleTamponi; regionep.totaleDeceduti = records[records.Count - 1].totaleDeceduti; regionep.totaleGuariti = records[records.Count - 1].totaleGuariti; } var record = new Dati { data = csv.GetField<DateTime>("data"), regione = "Italia", nuoviPositivi = csv.GetField<int>("nuovi_positivi"), totaleCasi = csv.GetField<int>("totale_casi"), totaleDeceduti = csv.GetField<int>("deceduti"), totaleTamponi = csv.GetField<int>("tamponi"), totaleGuariti = csv.GetField<int>("dimessi_guariti"), totalePositivi = csv.GetField<int>("totale_positivi"), nuoviGuariti = csv.GetField<int>("dimessi_guariti") - regionep.totaleGuariti, nuoviDeceduti = csv.GetField<int>("deceduti") - regionep.totaleDeceduti, nuoviTamponi = csv.GetField<int>("tamponi") - regionep.totaleTamponi }; records.Add(record); } return records; } } public static List<Dati> ReadCSVRegioni() { string source = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv"; StringReader rawFile = new StringReader(new WebClient().DownloadString(source)); using (var reader = rawFile) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { List<Dati> records = new List<Dati>(); csv.Read(); csv.ReadHeader(); while (csv.Read()) { Dati regionep = new Dati(); regionep.totaleTamponi = 0; regionep.totaleDeceduti = 0; if (records.Count > 21) { regionep.totaleTamponi = records[records.Count - 21].totaleTamponi; regionep.totaleDeceduti = records[records.Count - 21].totaleDeceduti; regionep.totaleGuariti = records[records.Count - 21].totaleGuariti; } var record = new Dati { data = csv.GetField<DateTime>("data"), regione = csv.GetField("denominazione_regione").ToString(), nuoviPositivi = csv.GetField<int>("nuovi_positivi"), totaleCasi = csv.GetField<int>("totale_casi"), totaleDeceduti = csv.GetField<int>("deceduti"), totaleTamponi = csv.GetField<int>("tamponi"), totaleGuariti = csv.GetField<int>("dimessi_guariti"), totalePositivi = csv.GetField<int>("totale_positivi"), nuoviGuariti = csv.GetField<int>("dimessi_guariti") - regionep.totaleGuariti, nuoviDeceduti = csv.GetField<int>("deceduti") - regionep.totaleDeceduti, nuoviTamponi = csv.GetField<int>("tamponi") - regionep.totaleTamponi }; records.Add(record); } return records; } } public static List<Dati> Filtered(DateTime date) { List<Dati> filtered = new List<Dati>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData, TimeSpan.FromMinutes(10)); foreach (var record in records) { var filter = records[records.Count - 1]; filtered.Add(filter); if (record.data.ToString("dd MMMM yyyy") == date.ToString("dd MMMM yyyy")) { filter = record; filtered.Clear(); filtered.Add(filter); } } return filtered; } public static List<Dati> FilteredRegioni(DateTime date, string regione) { List<Dati> filtered = new List<Dati>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSVRegioni(); var records = cache.GetOrAdd("regioni.Get", getData, TimeSpan.FromMinutes(10)); if (records[records.Count - 1].data.ToString("dd MMMM yyyy") != DateTime.Now.ToString("dd MMMM yyyy") & date.ToString("dd MMMM yyyy") == DateTime.Now.ToString("dd MMMM yyyy")) { foreach (var record in records) { if (record.data.ToString("dd MMMM yyyy") == records[records.Count - 1].data.ToString("dd MMMM yyyy")) { if (record.regione == regione) { var filter = record; filtered.Clear(); filtered.Add(filter); } } } } else { foreach (var record in records) { if (record.data.ToString("dd MMMM yyyy") == date.ToString("dd MMMM yyyy")) { if (record.regione == regione) { var filter = record; filtered.Clear(); filtered.Add(filter); } } } } return filtered; } public class ChartSelector { public static ChartValues<string> data(DateTime start, DateTime end) { ChartValues<string> filtered = new ChartValues<string>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { filtered.Add(record.data.ToString("dd MMM")); } } } return filtered; } public static ChartValues<int> nuoviPositivi(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.nuoviPositivi); } } } } return filtered; } public static ChartValues<int> nuoviDeceduti(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.nuoviDeceduti); } } } } return filtered; } public static ChartValues<int> totalePositivi(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totalePositivi); } } } } return filtered; } public static ChartValues<int> totaleDeceduti(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totaleDeceduti); } } } } return filtered; } public static ChartValues<int> nuoviTamponi(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.nuoviTamponi); } } } } return filtered; } public static ChartValues<int> totaleTamponi(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totaleTamponi); } } } } return filtered; } public static ChartValues<int> nuoviGuariti(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.nuoviGuariti); } } } } return filtered; } public static ChartValues<int> totaleGuariti(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totaleGuariti); } } } } return filtered; } public static ChartValues<int> totaleCasi(DateTime start, DateTime end, string region) { ChartValues<int> filtered = new ChartValues<int>(); IAppCache cache = new CachingService(); Func<List<Dati>> getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totaleCasi); } } } } return filtered; } } } }
40.772727
187
0.437497
[ "CC0-1.0" ]
apd911/CovidUpdates
CovidItalia/Parser.cs
20,633
C#
using System; using System.IO; using System.Text; using System.Collections.Generic; using InvokeIR.Win32; namespace PowerForensics.Ntfs { #region AttrDefClass public class AttrDef { #region Constants internal const int ATTRDEF_INDEX = 4; #endregion Constants #region Enums [FlagsAttribute] public enum ATTR_DEF_ENTRY { INDEX = 0x02, ALWAYS_RESIDENT = 0x40, ALWAYS_NONRESIDENT = 0x80 } #endregion Enums #region Properties public readonly string Name; public readonly uint Type; public readonly uint DisplayRule; public readonly string CollationRule; public readonly ATTR_DEF_ENTRY Flags; public readonly ulong MinSize; public readonly ulong MaxSize; #endregion Properties #region Constructors private AttrDef(byte[] bytes) { Name = Encoding.Unicode.GetString(bytes, 0x00, 0x80).TrimEnd('\0'); Type = BitConverter.ToUInt32(bytes, 0x80); DisplayRule = BitConverter.ToUInt32(bytes, 0x84); #region CollationRuleSwitch switch (BitConverter.ToUInt32(bytes, 0x88)) { case 0x00: CollationRule = "Binary"; break; case 0x01: CollationRule = "Filename"; break; case 0x02: CollationRule = "Unicode String"; break; case 0x10: CollationRule = "Unsigned Long"; break; case 0x11: CollationRule = "SID"; break; case 0x12: CollationRule = "Security Hash"; break; case 0x13: CollationRule = "Multiple Unsigned Longs"; break; default: CollationRule = "unknown"; break; } #endregion CollationRuleSwitch Flags = (ATTR_DEF_ENTRY)BitConverter.ToUInt32(bytes, 0x8C); MinSize = BitConverter.ToUInt64(bytes, 0x90); MaxSize = BitConverter.ToUInt64(bytes, 0x98); } #endregion Constructors #region StaticMethods internal static AttrDef[] GetInstances(byte[] bytes) { // Instantiate a List of AttrDef objects for output List<AttrDef> adList = new List<AttrDef>(); // Iterate through 160 byte chunks (representing an AttrDef object) for (uint i = 0; (i < bytes.Length) && (bytes[i] != 0); i += 160) { // Intantiate a new AttrDef object and add it to the adList List of AttrDef objects adList.Add(new AttrDef(NativeMethods.GetSubArray(bytes, i, 0xA0))); } return adList.ToArray(); } public static AttrDef[] GetInstances(string volume) { FileRecord record = FileRecord.Get(volume, ATTRDEF_INDEX, true); return AttrDef.GetInstances(record.GetBytes()); } public static AttrDef[] GetInstancesByPath(string path) { FileRecord record = FileRecord.Get(path, true); return AttrDef.GetInstances(record.GetBytes()); } #endregion StaticMethods } #endregion AttrDefClass }
29.305785
99
0.533277
[ "Apache-2.0" ]
darkoperator/PowerForensics_Source
Invoke-IR.PowerForensics/PowerForensics/FileSystems/NTFS/MetadataFiles/AttrDef.cs
3,548
C#
using System.Collections.Generic; using System.Numerics; namespace Raytracing { public record Triangle(IReadOnlyList<Vector3> Points) { public Vector3 A { get; } = Points[0]; public Vector3 B { get; } = Points[1]; public Vector3 C { get; } = Points[2]; public Vector3 Normal { get; } = Vector3.Cross(Points[0], Points[1]); } }
24.933333
77
0.622995
[ "MIT" ]
sqeezy/raytracing
src/Raytracing/Triangle.cs
376
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("5Butterfly")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("5Butterfly")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("afdab016-84b0-4cf5-bb86-9b30f5c948c2")] // 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")]
37.648649
84
0.744436
[ "MIT" ]
Avarea/Programming-Basics
Exams/5Butterfly/Properties/AssemblyInfo.cs
1,396
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 lookoutvision-2020-11-20.normal.json service model. */ using System; using System.Collections.Generic; using System.Net; using Amazon.LookoutforVision.Model; using Amazon.LookoutforVision.Model.Internal.MarshallTransformations; using Amazon.LookoutforVision.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.LookoutforVision { /// <summary> /// Implementation for accessing LookoutforVision /// /// This is the Amazon Lookout for Vision API Reference. It provides descriptions of actions, /// data types, common parameters, and common errors. /// /// /// <para> /// Amazon Lookout for Vision enables you to find visual defects in industrial products, /// accurately and at scale. It uses computer vision to identify missing components in /// an industrial product, damage to vehicles or structures, irregularities in production /// lines, and even minuscule defects in silicon wafers — or any other physical item where /// quality is important such as a missing capacitor on printed circuit boards. /// </para> /// </summary> public partial class AmazonLookoutforVisionClient : AmazonServiceClient, IAmazonLookoutforVision { private static IServiceMetadata serviceMetadata = new AmazonLookoutforVisionMetadata(); #if BCL45 || AWS_ASYNC_ENUMERABLES_API private ILookoutforVisionPaginatorFactory _paginators; /// <summary> /// Paginators for the service /// </summary> public ILookoutforVisionPaginatorFactory Paginators { get { if (this._paginators == null) { this._paginators = new LookoutforVisionPaginatorFactory(this); } return this._paginators; } } #endif #region Constructors /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonLookoutforVisionConfig()) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonLookoutforVisionConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient Configuration Object</param> public AmazonLookoutforVisionClient(AmazonLookoutforVisionConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonLookoutforVisionClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonLookoutforVisionClient(AWSCredentials credentials) : this(credentials, new AmazonLookoutforVisionConfig()) { } /// <summary> /// Constructs AmazonLookoutforVisionClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonLookoutforVisionClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonLookoutforVisionConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLookoutforVisionClient with AWS Credentials and an /// AmazonLookoutforVisionClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonLookoutforVisionClient Configuration Object</param> public AmazonLookoutforVisionClient(AWSCredentials credentials, AmazonLookoutforVisionConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonLookoutforVisionConfig()) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonLookoutforVisionConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonLookoutforVisionClient with AWS Access Key ID, AWS Secret Key and an /// AmazonLookoutforVisionClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonLookoutforVisionClient Configuration Object</param> public AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonLookoutforVisionConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLookoutforVisionConfig()) { } /// <summary> /// Constructs AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLookoutforVisionConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLookoutforVisionClient with AWS Access Key ID, AWS Secret Key and an /// AmazonLookoutforVisionClient 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 AmazonLookoutforVisionClient Configuration Object</param> public AmazonLookoutforVisionClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonLookoutforVisionConfig 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 CreateDataset /// <summary> /// Creates a new dataset in an Amazon Lookout for Vision project. <code>CreateDataset</code> /// can create a training or a test dataset from a valid dataset source (<code>DatasetSource</code>). /// /// /// <para> /// If you want a single dataset project, specify <code>train</code> for the value of /// <code>DatasetType</code>. /// </para> /// /// <para> /// To have a project with separate training and test datasets, call <code>CreateDataset</code> /// twice. On the first call, specify <code>train</code> for the value of <code>DatasetType</code>. /// On the second call, specify <code>test</code> for the value of <code>DatasetType</code>. /// /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:CreateDataset</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDataset service method.</param> /// /// <returns>The response from the CreateDataset service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateDataset">REST API Reference for CreateDataset Operation</seealso> public virtual CreateDatasetResponse CreateDataset(CreateDatasetRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDatasetResponseUnmarshaller.Instance; return Invoke<CreateDatasetResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateDataset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDataset operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateDataset /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateDataset">REST API Reference for CreateDataset Operation</seealso> public virtual IAsyncResult BeginCreateDataset(CreateDatasetRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateDatasetResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateDataset operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateDataset.</param> /// /// <returns>Returns a CreateDatasetResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateDataset">REST API Reference for CreateDataset Operation</seealso> public virtual CreateDatasetResponse EndCreateDataset(IAsyncResult asyncResult) { return EndInvoke<CreateDatasetResponse>(asyncResult); } #endregion #region CreateModel /// <summary> /// Creates a new version of a model within an an Amazon Lookout for Vision project. <code>CreateModel</code> /// is an asynchronous operation in which Amazon Lookout for Vision trains, tests, and /// evaluates a new version of a model. /// /// /// <para> /// To get the current status, check the <code>Status</code> field returned in the response /// from <a>DescribeModel</a>. /// </para> /// /// <para> /// If the project has a single dataset, Amazon Lookout for Vision internally splits the /// dataset to create a training and a test dataset. If the project has a training and /// a test dataset, Lookout for Vision uses the respective datasets to train and test /// the model. /// </para> /// /// <para> /// After training completes, the evaluation metrics are stored at the location specified /// in <code>OutputConfig</code>. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:CreateModel</code> /// operation. If you want to tag your model, you also require permission to the <code>lookoutvision:TagResource</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateModel service method.</param> /// /// <returns>The response from the CreateModel service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateModel">REST API Reference for CreateModel Operation</seealso> public virtual CreateModelResponse CreateModel(CreateModelRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateModelRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateModelResponseUnmarshaller.Instance; return Invoke<CreateModelResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateModel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateModel operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateModel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateModel">REST API Reference for CreateModel Operation</seealso> public virtual IAsyncResult BeginCreateModel(CreateModelRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateModelRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateModelResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateModel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateModel.</param> /// /// <returns>Returns a CreateModelResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateModel">REST API Reference for CreateModel Operation</seealso> public virtual CreateModelResponse EndCreateModel(IAsyncResult asyncResult) { return EndInvoke<CreateModelResponse>(asyncResult); } #endregion #region CreateProject /// <summary> /// Creates an empty Amazon Lookout for Vision project. After you create the project, /// add a dataset by calling <a>CreateDataset</a>. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:CreateProject</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateProject service method.</param> /// /// <returns>The response from the CreateProject service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateProject">REST API Reference for CreateProject Operation</seealso> public virtual CreateProjectResponse CreateProject(CreateProjectRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateProjectResponseUnmarshaller.Instance; return Invoke<CreateProjectResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateProject operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateProject operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateProject /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateProject">REST API Reference for CreateProject Operation</seealso> public virtual IAsyncResult BeginCreateProject(CreateProjectRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateProjectResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateProject operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateProject.</param> /// /// <returns>Returns a CreateProjectResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/CreateProject">REST API Reference for CreateProject Operation</seealso> public virtual CreateProjectResponse EndCreateProject(IAsyncResult asyncResult) { return EndInvoke<CreateProjectResponse>(asyncResult); } #endregion #region DeleteDataset /// <summary> /// Deletes an existing Amazon Lookout for Vision <code>dataset</code>. /// /// /// <para> /// If your the project has a single dataset, you must create a new dataset before you /// can create a model. /// </para> /// /// <para> /// If you project has a training dataset and a test dataset consider the following. /// </para> /// <ul> <li> /// <para> /// If you delete the test dataset, your project reverts to a single dataset project. /// If you then train the model, Amazon Lookout for Vision internally splits the remaining /// dataset into a training and test dataset. /// </para> /// </li> <li> /// <para> /// If you delete the training dataset, you must create a training dataset before you /// can create a model. /// </para> /// </li> </ul> /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DeleteDataset</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDataset service method.</param> /// /// <returns>The response from the DeleteDataset service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteDataset">REST API Reference for DeleteDataset Operation</seealso> public virtual DeleteDatasetResponse DeleteDataset(DeleteDatasetRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDatasetResponseUnmarshaller.Instance; return Invoke<DeleteDatasetResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteDataset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDataset operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDataset /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteDataset">REST API Reference for DeleteDataset Operation</seealso> public virtual IAsyncResult BeginDeleteDataset(DeleteDatasetRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteDatasetResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteDataset operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDataset.</param> /// /// <returns>Returns a DeleteDatasetResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteDataset">REST API Reference for DeleteDataset Operation</seealso> public virtual DeleteDatasetResponse EndDeleteDataset(IAsyncResult asyncResult) { return EndInvoke<DeleteDatasetResponse>(asyncResult); } #endregion #region DeleteModel /// <summary> /// Deletes an Amazon Lookout for Vision model. You can't delete a running model. To stop /// a running model, use the <a>StopModel</a> operation. /// /// /// <para> /// It might take a few seconds to delete a model. To determine if a model has been deleted, /// call <a>ListModels</a> and check if the version of the model (<code>ModelVersion</code>) /// is in the <code>Models</code> array. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DeleteModel</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteModel service method.</param> /// /// <returns>The response from the DeleteModel service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteModel">REST API Reference for DeleteModel Operation</seealso> public virtual DeleteModelResponse DeleteModel(DeleteModelRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteModelRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteModelResponseUnmarshaller.Instance; return Invoke<DeleteModelResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteModel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteModel operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteModel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteModel">REST API Reference for DeleteModel Operation</seealso> public virtual IAsyncResult BeginDeleteModel(DeleteModelRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteModelRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteModelResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteModel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteModel.</param> /// /// <returns>Returns a DeleteModelResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteModel">REST API Reference for DeleteModel Operation</seealso> public virtual DeleteModelResponse EndDeleteModel(IAsyncResult asyncResult) { return EndInvoke<DeleteModelResponse>(asyncResult); } #endregion #region DeleteProject /// <summary> /// Deletes an Amazon Lookout for Vision project. /// /// /// <para> /// To delete a project, you must first delete each version of the model associated with /// the project. To delete a model use the <a>DeleteModel</a> operation. /// </para> /// /// <para> /// You also have to delete the dataset(s) associated with the model. For more information, /// see <a>DeleteDataset</a>. The images referenced by the training and test datasets /// aren't deleted. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DeleteProject</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteProject service method.</param> /// /// <returns>The response from the DeleteProject service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteProject">REST API Reference for DeleteProject Operation</seealso> public virtual DeleteProjectResponse DeleteProject(DeleteProjectRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteProjectResponseUnmarshaller.Instance; return Invoke<DeleteProjectResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteProject operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteProject operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteProject /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteProject">REST API Reference for DeleteProject Operation</seealso> public virtual IAsyncResult BeginDeleteProject(DeleteProjectRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteProjectResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteProject operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteProject.</param> /// /// <returns>Returns a DeleteProjectResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DeleteProject">REST API Reference for DeleteProject Operation</seealso> public virtual DeleteProjectResponse EndDeleteProject(IAsyncResult asyncResult) { return EndInvoke<DeleteProjectResponse>(asyncResult); } #endregion #region DescribeDataset /// <summary> /// Describe an Amazon Lookout for Vision dataset. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DescribeDataset</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDataset service method.</param> /// /// <returns>The response from the DescribeDataset service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeDataset">REST API Reference for DescribeDataset Operation</seealso> public virtual DescribeDatasetResponse DescribeDataset(DescribeDatasetRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeDatasetResponseUnmarshaller.Instance; return Invoke<DescribeDatasetResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeDataset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDataset operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDataset /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeDataset">REST API Reference for DescribeDataset Operation</seealso> public virtual IAsyncResult BeginDescribeDataset(DescribeDatasetRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeDatasetRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeDatasetResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeDataset operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDataset.</param> /// /// <returns>Returns a DescribeDatasetResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeDataset">REST API Reference for DescribeDataset Operation</seealso> public virtual DescribeDatasetResponse EndDescribeDataset(IAsyncResult asyncResult) { return EndInvoke<DescribeDatasetResponse>(asyncResult); } #endregion #region DescribeModel /// <summary> /// Describes a version of an Amazon Lookout for Vision model. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DescribeModel</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeModel service method.</param> /// /// <returns>The response from the DescribeModel service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModel">REST API Reference for DescribeModel Operation</seealso> public virtual DescribeModelResponse DescribeModel(DescribeModelRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeModelRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeModelResponseUnmarshaller.Instance; return Invoke<DescribeModelResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeModel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeModel operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeModel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModel">REST API Reference for DescribeModel Operation</seealso> public virtual IAsyncResult BeginDescribeModel(DescribeModelRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeModelRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeModelResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeModel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeModel.</param> /// /// <returns>Returns a DescribeModelResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModel">REST API Reference for DescribeModel Operation</seealso> public virtual DescribeModelResponse EndDescribeModel(IAsyncResult asyncResult) { return EndInvoke<DescribeModelResponse>(asyncResult); } #endregion #region DescribeModelPackagingJob /// <summary> /// Describes an Amazon Lookout for Vision model packaging job. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DescribeModelPackagingJob</code> /// operation. /// </para> /// /// <para> /// For more information, see <i>Using your Amazon Lookout for Vision model on an edge /// device</i> in the Amazon Lookout for Vision Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeModelPackagingJob service method.</param> /// /// <returns>The response from the DescribeModelPackagingJob service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModelPackagingJob">REST API Reference for DescribeModelPackagingJob Operation</seealso> public virtual DescribeModelPackagingJobResponse DescribeModelPackagingJob(DescribeModelPackagingJobRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeModelPackagingJobRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeModelPackagingJobResponseUnmarshaller.Instance; return Invoke<DescribeModelPackagingJobResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeModelPackagingJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeModelPackagingJob operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeModelPackagingJob /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModelPackagingJob">REST API Reference for DescribeModelPackagingJob Operation</seealso> public virtual IAsyncResult BeginDescribeModelPackagingJob(DescribeModelPackagingJobRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeModelPackagingJobRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeModelPackagingJobResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeModelPackagingJob operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeModelPackagingJob.</param> /// /// <returns>Returns a DescribeModelPackagingJobResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeModelPackagingJob">REST API Reference for DescribeModelPackagingJob Operation</seealso> public virtual DescribeModelPackagingJobResponse EndDescribeModelPackagingJob(IAsyncResult asyncResult) { return EndInvoke<DescribeModelPackagingJobResponse>(asyncResult); } #endregion #region DescribeProject /// <summary> /// Describes an Amazon Lookout for Vision project. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DescribeProject</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeProject service method.</param> /// /// <returns>The response from the DescribeProject service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeProject">REST API Reference for DescribeProject Operation</seealso> public virtual DescribeProjectResponse DescribeProject(DescribeProjectRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeProjectResponseUnmarshaller.Instance; return Invoke<DescribeProjectResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeProject operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeProject operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeProject /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeProject">REST API Reference for DescribeProject Operation</seealso> public virtual IAsyncResult BeginDescribeProject(DescribeProjectRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeProjectRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeProjectResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeProject operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeProject.</param> /// /// <returns>Returns a DescribeProjectResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DescribeProject">REST API Reference for DescribeProject Operation</seealso> public virtual DescribeProjectResponse EndDescribeProject(IAsyncResult asyncResult) { return EndInvoke<DescribeProjectResponse>(asyncResult); } #endregion #region DetectAnomalies /// <summary> /// Detects anomalies in an image that you supply. /// /// /// <para> /// The response from <code>DetectAnomalies</code> includes a boolean prediction that /// the image contains one or more anomalies and a confidence value for the prediction. /// </para> /// <note> /// <para> /// Before calling <code>DetectAnomalies</code>, you must first start your model with /// the <a>StartModel</a> operation. You are charged for the amount of time, in minutes, /// that a model runs and for the number of anomaly detection units that your model uses. /// If you are not using a model, use the <a>StopModel</a> operation to stop your model. /// /// </para> /// </note> /// <para> /// This operation requires permissions to perform the <code>lookoutvision:DetectAnomalies</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DetectAnomalies service method.</param> /// /// <returns>The response from the DetectAnomalies service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DetectAnomalies">REST API Reference for DetectAnomalies Operation</seealso> public virtual DetectAnomaliesResponse DetectAnomalies(DetectAnomaliesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DetectAnomaliesRequestMarshaller.Instance; options.ResponseUnmarshaller = DetectAnomaliesResponseUnmarshaller.Instance; return Invoke<DetectAnomaliesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DetectAnomalies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DetectAnomalies operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDetectAnomalies /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DetectAnomalies">REST API Reference for DetectAnomalies Operation</seealso> public virtual IAsyncResult BeginDetectAnomalies(DetectAnomaliesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DetectAnomaliesRequestMarshaller.Instance; options.ResponseUnmarshaller = DetectAnomaliesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DetectAnomalies operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDetectAnomalies.</param> /// /// <returns>Returns a DetectAnomaliesResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/DetectAnomalies">REST API Reference for DetectAnomalies Operation</seealso> public virtual DetectAnomaliesResponse EndDetectAnomalies(IAsyncResult asyncResult) { return EndInvoke<DetectAnomaliesResponse>(asyncResult); } #endregion #region ListDatasetEntries /// <summary> /// Lists the JSON Lines within a dataset. An Amazon Lookout for Vision JSON Line contains /// the anomaly information for a single image, including the image location and the assigned /// label. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:ListDatasetEntries</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDatasetEntries service method.</param> /// /// <returns>The response from the ListDatasetEntries service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListDatasetEntries">REST API Reference for ListDatasetEntries Operation</seealso> public virtual ListDatasetEntriesResponse ListDatasetEntries(ListDatasetEntriesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListDatasetEntriesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDatasetEntriesResponseUnmarshaller.Instance; return Invoke<ListDatasetEntriesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListDatasetEntries operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDatasetEntries operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDatasetEntries /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListDatasetEntries">REST API Reference for ListDatasetEntries Operation</seealso> public virtual IAsyncResult BeginListDatasetEntries(ListDatasetEntriesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListDatasetEntriesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDatasetEntriesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListDatasetEntries operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDatasetEntries.</param> /// /// <returns>Returns a ListDatasetEntriesResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListDatasetEntries">REST API Reference for ListDatasetEntries Operation</seealso> public virtual ListDatasetEntriesResponse EndListDatasetEntries(IAsyncResult asyncResult) { return EndInvoke<ListDatasetEntriesResponse>(asyncResult); } #endregion #region ListModelPackagingJobs /// <summary> /// Lists the model packaging jobs created for an Amazon Lookout for Vision project. /// /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:ListModelPackagingJobs</code> /// operation. /// </para> /// /// <para> /// For more information, see <i>Using your Amazon Lookout for Vision model on an edge /// device</i> in the Amazon Lookout for Vision Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListModelPackagingJobs service method.</param> /// /// <returns>The response from the ListModelPackagingJobs service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModelPackagingJobs">REST API Reference for ListModelPackagingJobs Operation</seealso> public virtual ListModelPackagingJobsResponse ListModelPackagingJobs(ListModelPackagingJobsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListModelPackagingJobsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListModelPackagingJobsResponseUnmarshaller.Instance; return Invoke<ListModelPackagingJobsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListModelPackagingJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListModelPackagingJobs operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListModelPackagingJobs /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModelPackagingJobs">REST API Reference for ListModelPackagingJobs Operation</seealso> public virtual IAsyncResult BeginListModelPackagingJobs(ListModelPackagingJobsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListModelPackagingJobsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListModelPackagingJobsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListModelPackagingJobs operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListModelPackagingJobs.</param> /// /// <returns>Returns a ListModelPackagingJobsResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModelPackagingJobs">REST API Reference for ListModelPackagingJobs Operation</seealso> public virtual ListModelPackagingJobsResponse EndListModelPackagingJobs(IAsyncResult asyncResult) { return EndInvoke<ListModelPackagingJobsResponse>(asyncResult); } #endregion #region ListModels /// <summary> /// Lists the versions of a model in an Amazon Lookout for Vision project. /// /// /// <para> /// The <code>ListModels</code> operation is eventually consistent. Recent calls to <code>CreateModel</code> /// might take a while to appear in the response from <code>ListProjects</code>. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:ListModels</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListModels service method.</param> /// /// <returns>The response from the ListModels service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModels">REST API Reference for ListModels Operation</seealso> public virtual ListModelsResponse ListModels(ListModelsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListModelsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListModelsResponseUnmarshaller.Instance; return Invoke<ListModelsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListModels operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListModels operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListModels /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModels">REST API Reference for ListModels Operation</seealso> public virtual IAsyncResult BeginListModels(ListModelsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListModelsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListModelsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListModels operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListModels.</param> /// /// <returns>Returns a ListModelsResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListModels">REST API Reference for ListModels Operation</seealso> public virtual ListModelsResponse EndListModels(IAsyncResult asyncResult) { return EndInvoke<ListModelsResponse>(asyncResult); } #endregion #region ListProjects /// <summary> /// Lists the Amazon Lookout for Vision projects in your AWS account. /// /// /// <para> /// The <code>ListProjects</code> operation is eventually consistent. Recent calls to /// <code>CreateProject</code> and <code>DeleteProject</code> might take a while to appear /// in the response from <code>ListProjects</code>. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:ListProjects</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListProjects service method.</param> /// /// <returns>The response from the ListProjects service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListProjects">REST API Reference for ListProjects Operation</seealso> public virtual ListProjectsResponse ListProjects(ListProjectsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListProjectsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListProjectsResponseUnmarshaller.Instance; return Invoke<ListProjectsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListProjects operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListProjects operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListProjects /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListProjects">REST API Reference for ListProjects Operation</seealso> public virtual IAsyncResult BeginListProjects(ListProjectsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListProjectsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListProjectsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListProjects operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListProjects.</param> /// /// <returns>Returns a ListProjectsResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListProjects">REST API Reference for ListProjects Operation</seealso> public virtual ListProjectsResponse EndListProjects(IAsyncResult asyncResult) { return EndInvoke<ListProjectsResponse>(asyncResult); } #endregion #region ListTagsForResource /// <summary> /// Returns a list of tags attached to the specified Amazon Lookout for Vision model. /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:ListTagsForResource</code> /// operation. /// </para> /// </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 LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/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> /// Initiates the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param> /// /// <returns>Returns a ListTagsForResourceResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult) { return EndInvoke<ListTagsForResourceResponse>(asyncResult); } #endregion #region StartModel /// <summary> /// Starts the running of the version of an Amazon Lookout for Vision model. Starting /// a model takes a while to complete. To check the current state of the model, use <a>DescribeModel</a>. /// /// /// <para> /// A model is ready to use when its status is <code>HOSTED</code>. /// </para> /// /// <para> /// Once the model is running, you can detect custom labels in new images by calling <a>DetectAnomalies</a>. /// </para> /// <note> /// <para> /// You are charged for the amount of time that the model is running. To stop a running /// model, call <a>StopModel</a>. /// </para> /// </note> /// <para> /// This operation requires permissions to perform the <code>lookoutvision:StartModel</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartModel service method.</param> /// /// <returns>The response from the StartModel service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModel">REST API Reference for StartModel Operation</seealso> public virtual StartModelResponse StartModel(StartModelRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartModelRequestMarshaller.Instance; options.ResponseUnmarshaller = StartModelResponseUnmarshaller.Instance; return Invoke<StartModelResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartModel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartModel operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartModel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModel">REST API Reference for StartModel Operation</seealso> public virtual IAsyncResult BeginStartModel(StartModelRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartModelRequestMarshaller.Instance; options.ResponseUnmarshaller = StartModelResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartModel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartModel.</param> /// /// <returns>Returns a StartModelResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModel">REST API Reference for StartModel Operation</seealso> public virtual StartModelResponse EndStartModel(IAsyncResult asyncResult) { return EndInvoke<StartModelResponse>(asyncResult); } #endregion #region StartModelPackagingJob /// <summary> /// Starts an Amazon Lookout for Vision model packaging job. A model packaging job creates /// an AWS IoT Greengrass component for a Lookout for Vision model. You can use the component /// to deploy your model to an edge device managed by Greengrass. /// /// /// <para> /// Use the <a>DescribeModelPackagingJob</a> API to determine the current status of the /// job. The model packaging job is complete if the value of <code>Status</code> is <code>SUCCEEDED</code>. /// </para> /// /// <para> /// To deploy the component to the target device, use the component name and component /// version with the AWS IoT Greengrass <a href="https://docs.aws.amazon.com/greengrass/v2/APIReference/API_CreateDeployment.html">CreateDeployment</a> /// API. /// </para> /// /// <para> /// This operation requires the following permissions: /// </para> /// <ul> <li> /// <para> /// <code>lookoutvision:StartModelPackagingJobs</code> /// </para> /// </li> <li> /// <para> /// <code>s3:PutObject</code> /// </para> /// </li> <li> /// <para> /// <code>s3:GetBucketLocation</code> /// </para> /// </li> <li> /// <para> /// <code>greengrass:CreateComponentVersion</code> /// </para> /// </li> <li> /// <para> /// <code>greengrass:DescribeComponent</code> /// </para> /// </li> <li> /// <para> /// (Optional) <code>greengrass:TagResource</code>. Only required if you want to tag the /// component. /// </para> /// </li> </ul> /// <para> /// For more information, see <i>Using your Amazon Lookout for Vision model on an edge /// device</i> in the Amazon Lookout for Vision Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartModelPackagingJob service method.</param> /// /// <returns>The response from the StartModelPackagingJob service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModelPackagingJob">REST API Reference for StartModelPackagingJob Operation</seealso> public virtual StartModelPackagingJobResponse StartModelPackagingJob(StartModelPackagingJobRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartModelPackagingJobRequestMarshaller.Instance; options.ResponseUnmarshaller = StartModelPackagingJobResponseUnmarshaller.Instance; return Invoke<StartModelPackagingJobResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartModelPackagingJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartModelPackagingJob operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartModelPackagingJob /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModelPackagingJob">REST API Reference for StartModelPackagingJob Operation</seealso> public virtual IAsyncResult BeginStartModelPackagingJob(StartModelPackagingJobRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartModelPackagingJobRequestMarshaller.Instance; options.ResponseUnmarshaller = StartModelPackagingJobResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartModelPackagingJob operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartModelPackagingJob.</param> /// /// <returns>Returns a StartModelPackagingJobResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StartModelPackagingJob">REST API Reference for StartModelPackagingJob Operation</seealso> public virtual StartModelPackagingJobResponse EndStartModelPackagingJob(IAsyncResult asyncResult) { return EndInvoke<StartModelPackagingJobResponse>(asyncResult); } #endregion #region StopModel /// <summary> /// Stops the hosting of a running model. The operation might take a while to complete. /// To check the current status, call <a>DescribeModel</a>. /// /// /// <para> /// After the model hosting stops, the <code>Status</code> of the model is <code>TRAINED</code>. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:StopModel</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopModel service method.</param> /// /// <returns>The response from the StopModel service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StopModel">REST API Reference for StopModel Operation</seealso> public virtual StopModelResponse StopModel(StopModelRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StopModelRequestMarshaller.Instance; options.ResponseUnmarshaller = StopModelResponseUnmarshaller.Instance; return Invoke<StopModelResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StopModel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopModel operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStopModel /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StopModel">REST API Reference for StopModel Operation</seealso> public virtual IAsyncResult BeginStopModel(StopModelRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StopModelRequestMarshaller.Instance; options.ResponseUnmarshaller = StopModelResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StopModel operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopModel.</param> /// /// <returns>Returns a StopModelResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/StopModel">REST API Reference for StopModel Operation</seealso> public virtual StopModelResponse EndStopModel(IAsyncResult asyncResult) { return EndInvoke<StopModelResponse>(asyncResult); } #endregion #region TagResource /// <summary> /// Adds one or more key-value tags to an Amazon Lookout for Vision model. For more information, /// see <i>Tagging a model</i> in the <i>Amazon Lookout for Vision Developer Guide</i>. /// /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:TagResource</code> /// operation. /// </para> /// </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 LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ServiceQuotaExceededException"> /// A service quota was exceeded the allowed limit. For more information, see Limits in /// Amazon Lookout for Vision in the Amazon Lookout for Vision Developer Guide. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/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> /// Initiates the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/TagResource">REST API Reference for TagResource Operation</seealso> public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param> /// /// <returns>Returns a TagResourceResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult) { return EndInvoke<TagResourceResponse>(asyncResult); } #endregion #region UntagResource /// <summary> /// Removes one or more tags from an Amazon Lookout for Vision model. For more information, /// see <i>Tagging a model</i> in the <i>Amazon Lookout for Vision Developer Guide</i>. /// /// /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:UntagResource</code> /// operation. /// </para> /// </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 LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/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> /// Initiates the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param> /// /// <returns>Returns a UntagResourceResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult) { return EndInvoke<UntagResourceResponse>(asyncResult); } #endregion #region UpdateDatasetEntries /// <summary> /// Adds or updates one or more JSON Line entries in a dataset. A JSON Line includes information /// about an image used for training or testing an Amazon Lookout for Vision model. /// /// /// <para> /// To update an existing JSON Line, use the <code>source-ref</code> field to identify /// the JSON Line. The JSON line that you supply replaces the existing JSON line. Any /// existing annotations that are not in the new JSON line are removed from the dataset. /// /// </para> /// /// <para> /// For more information, see <i>Defining JSON lines for anomaly classification</i> in /// the Amazon Lookout for Vision Developer Guide. /// </para> /// <note> /// <para> /// The images you reference in the <code>source-ref</code> field of a JSON line, must /// be in the same S3 bucket as the existing images in the dataset. /// </para> /// </note> /// <para> /// Updating a dataset might take a while to complete. To check the current status, call /// <a>DescribeDataset</a> and check the <code>Status</code> field in the response. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lookoutvision:UpdateDatasetEntries</code> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateDatasetEntries service method.</param> /// /// <returns>The response from the UpdateDatasetEntries service method, as returned by LookoutforVision.</returns> /// <exception cref="Amazon.LookoutforVision.Model.AccessDeniedException"> /// You are not authorized to perform the action. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ConflictException"> /// The update or deletion of a resource caused an inconsistent state. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.InternalServerException"> /// Amazon Lookout for Vision experienced a service issue. Try your call again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ThrottlingException"> /// Amazon Lookout for Vision is temporarily unable to process the request. Try your call /// again. /// </exception> /// <exception cref="Amazon.LookoutforVision.Model.ValidationException"> /// An input validation error occured. For example, invalid characters in a project name, /// or if a pagination token is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/UpdateDatasetEntries">REST API Reference for UpdateDatasetEntries Operation</seealso> public virtual UpdateDatasetEntriesResponse UpdateDatasetEntries(UpdateDatasetEntriesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateDatasetEntriesRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateDatasetEntriesResponseUnmarshaller.Instance; return Invoke<UpdateDatasetEntriesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the UpdateDatasetEntries operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateDatasetEntries operation on AmazonLookoutforVisionClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateDatasetEntries /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/UpdateDatasetEntries">REST API Reference for UpdateDatasetEntries Operation</seealso> public virtual IAsyncResult BeginUpdateDatasetEntries(UpdateDatasetEntriesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateDatasetEntriesRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateDatasetEntriesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the UpdateDatasetEntries operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateDatasetEntries.</param> /// /// <returns>Returns a UpdateDatasetEntriesResult from LookoutforVision.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lookoutvision-2020-11-20/UpdateDatasetEntries">REST API Reference for UpdateDatasetEntries Operation</seealso> public virtual UpdateDatasetEntriesResponse EndUpdateDatasetEntries(IAsyncResult asyncResult) { return EndInvoke<UpdateDatasetEntriesResponse>(asyncResult); } #endregion } }
54.106952
186
0.659024
[ "Apache-2.0" ]
aws/aws-sdk-net
sdk/src/Services/LookoutforVision/Generated/_bcl35/AmazonLookoutforVisionClient.cs
121,418
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Angle.Controllers { public class BlogController : Controller { public ActionResult Blog() { return View(); } public ActionResult BlogArticles() { return View(); } public ActionResult BlogArticleView() { return View(); } public ActionResult BlogPost() { return View(); } } }
20.535714
46
0.516522
[ "MIT" ]
saifabushamma/laravelTask
WB04HF123/mvc5/Angle/Angle/Controllers/BlogController.cs
577
C#
using System.Collections.Generic; using System.Text; public class SpecialForce : Soldier { private const double OverallSkillMiltiplier = 3.5; private const int SpecialForceRegenerateValue = 30; public SpecialForce(string name, int age, double experience, double endurance) : base(name, age, experience, endurance) { } private readonly IReadOnlyList<string> weaponsAllowed = new List<string> { "Gun", "AutomaticMachine", "MachineGun", "RPG", "Helmet", "Knife", "NightVision" }; public override void Regenerate() => this.Endurance += this.Age + SpecialForceRegenerateValue; public override double OverallSkill => base.OverallSkill * OverallSkillMiltiplier; protected override IReadOnlyList<string> WeaponsAllowed { get { return weaponsAllowed; } } }
25.852941
98
0.668942
[ "MIT" ]
stoyanovmiroslav/CSharp-Fundamentals
CSharp OOP Advanced/CSharp Advanced Exams/C# OOP Advanced Exam - 20 August 2017/Last Army/Entities/Soldiers/SpecialForce.cs
881
C#
// // PricesEntity.cs // // Author: // Igor Guerrero <igorgue@protonmail.com> // // Copyright (c) 2022 HODL Wallet // // 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 Newtonsoft.Json; namespace Liviano.Services.Models { public class MetaEntity { [JsonProperty("high")] public HighEntity High { get; set; } [JsonProperty("low")] public LowEntity Low { get; set; } } public class PriceEntity { [JsonProperty("price")] public double Price { get; set; } [JsonProperty("time")] public DateTime Time { get; set; } } public class LowEntity : PriceEntity { } public class HighEntity : PriceEntity { } public class PricesEntity { [JsonProperty("meta")] public MetaEntity Meta { get; set; } [JsonProperty("prices")] public List<PriceEntity> Prices { get; set; } } }
31.555556
80
0.691147
[ "MIT" ]
hodlwallet/liviano
Liviano.Services/Models/PricesEntity.cs
1,990
C#
using Newtonsoft.Json.Linq; namespace TidalUSDK.Extensions { public static class JsonExtensions { public static bool IsNullOrEmpty(this JToken token) { return token == null || token.Type == JTokenType.Array && !token.HasValues || token.Type == JTokenType.Object && !token.HasValues || token.Type == JTokenType.String && token.ToString() == string.Empty || token.Type == JTokenType.Null; } } }
32.3125
89
0.560928
[ "MIT" ]
SacredSkull/dotnet-tidal-usdk
TidalUSDK/Extensions/JsonExtensions.cs
517
C#
namespace Gu.Localization.Analyzers.Tests.GULOC08DuplicateNeutralTests { using System.IO; using System.Linq; using Gu.Localization.Analyzers.Tests.Helpers; using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public class Diagnostic { private static readonly DiagnosticAnalyzer Analyzer = new ResourceAnalyzer(); #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. private FileInfo projectFile; private DirectoryInfo directory; #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. [SetUp] public void SetUp() { var original = ProjectFile.Find("Gu.Localization.TestStub.csproj"); this.directory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), original.Directory!.Name)); if (this.directory.Exists) { this.directory.Delete(recursive: true); } original.Directory.CopyTo(this.directory); this.projectFile = this.directory.FindFile(original.Name); } [Test] public void WhenDupe() { this.directory.FindFile("Properties\\Resources.resx").ReplaceText( "<value>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</value>", $"<value>Value</value>"); var sln = CodeFactory.CreateSolution(this.projectFile); var diagnostics = Analyze.GetDiagnostics(Analyzer, sln).Single(); Assert.AreEqual(4, diagnostics.AnalyzerDiagnostics.Length); CollectionAssert.AreEquivalent(new[] { "GULOC07", "GULOC07", "GULOC08", "GULOC08" }, diagnostics.AnalyzerDiagnostics.Select(x => x.Id).ToArray()); CollectionAssert.AreEquivalent(new[] { "Resources.Designer.cs", "Resources.Designer.cs", "Resources.Designer.cs", "Resources.Designer.cs" }, diagnostics.AnalyzerDiagnostics.Select(x => Path.GetFileName(x.Location.SourceTree!.FilePath)).ToArray()); } } }
45.25
259
0.672192
[ "MIT" ]
GuOrg/Gu.Localization
Gu.Localization.Analyzers.Tests/GULOC08DuplicateNeutralTests/Diagnostic.cs
2,174
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.Network.Models { public partial class TroubleshootingDetails { internal static TroubleshootingDetails DeserializeTroubleshootingDetails(JsonElement element) { Optional<string> reasonType = default; Optional<string> summary = default; Optional<string> detail = default; Optional<IReadOnlyList<TroubleshootingRecommendedActions>> recommendedActions = default; ResourceIdentifier id = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("reasonType")) { reasonType = property.Value.GetString(); continue; } if (property.NameEquals("summary")) { summary = property.Value.GetString(); continue; } if (property.NameEquals("detail")) { detail = property.Value.GetString(); continue; } if (property.NameEquals("recommendedActions")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<TroubleshootingRecommendedActions> array = new List<TroubleshootingRecommendedActions>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(TroubleshootingRecommendedActions.DeserializeTroubleshootingRecommendedActions(item)); } recommendedActions = array; continue; } if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } } return new TroubleshootingDetails(id, reasonType.Value, summary.Value, detail.Value, Optional.ToList(recommendedActions)); } } }
37
134
0.538084
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/TroubleshootingDetails.Serialization.cs
2,442
C#
using IntermediatorBotSample.CommandHandling; using IntermediatorBotSample.ConversationHistory; using IntermediatorBotSample.MessageRouting; using IntermediatorBotSample.Model; using Microsoft.Bot.Builder; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Underscore.Bot.MessageRouting; using Underscore.Bot.MessageRouting.DataStore; using Underscore.Bot.MessageRouting.DataStore.Azure; using Underscore.Bot.MessageRouting.DataStore.Local; using Underscore.Bot.MessageRouting.Results; namespace IntermediatorBotSample.Middleware { public class HandoffMiddleware : IMiddleware { private const string KeyAzureTableStorageConnectionString = "AzureTableStorageConnectionString"; private const string KeyRejectConnectionRequestIfNoAggregationChannel = "RejectConnectionRequestIfNoAggregationChannel"; private const string KeyPermittedAggregationChannels = "PermittedAggregationChannels"; private const string KeyNoDirectConversationsWithChannels = "NoDirectConversationsWithChannels"; private BotState _conversationState; private BotState _userState; public IConfiguration Configuration { get; protected set; } public MessageRouter MessageRouter { get; protected set; } public MessageRouterResultHandler MessageRouterResultHandler { get; protected set; } public CommandHandler CommandHandler { get; protected set; } public MessageLogs MessageLogs { get; protected set; } public HandoffMiddleware(IConfiguration configuration, ConversationState conversationState, UserState userState) { Configuration = configuration; _conversationState = conversationState; _userState = userState; string connectionString = Configuration[KeyAzureTableStorageConnectionString]; IRoutingDataStore routingDataStore = null; if (string.IsNullOrEmpty(connectionString)) { System.Diagnostics.Debug.WriteLine($"WARNING!!! No connection string found - using {nameof(InMemoryRoutingDataStore)}"); routingDataStore = new InMemoryRoutingDataStore(); } else { System.Diagnostics.Debug.WriteLine($"Found a connection string - using {nameof(AzureTableRoutingDataStore)}"); routingDataStore = new AzureTableRoutingDataStore(connectionString); } MessageRouter = new MessageRouter( routingDataStore, new MicrosoftAppCredentials(Configuration["MicrosoftAppId"], Configuration["MicrosoftAppPassword"])); //MessageRouter.Logger = new Logging.AggregationChannelLogger(MessageRouter); MessageRouterResultHandler = new MessageRouterResultHandler(MessageRouter); ConnectionRequestHandler connectionRequestHandler = new ConnectionRequestHandler(GetChannelList(KeyNoDirectConversationsWithChannels)); CommandHandler = new CommandHandler( MessageRouter, MessageRouterResultHandler, connectionRequestHandler, GetChannelList(KeyPermittedAggregationChannels)); MessageLogs = new MessageLogs(connectionString); } public async Task OnTurnAsync(ITurnContext context, NextDelegate next, CancellationToken ct) { Activity activity = context.Activity; var conversationStateAccessors = _conversationState.CreateProperty<Conversacion>(nameof(Conversacion)); var conversationData = await conversationStateAccessors.GetAsync(context, () => new Conversacion()); var userStateAccessors = _userState.CreateProperty<Conversacion>(nameof(Conversacion)); var conversacion = await userStateAccessors.GetAsync(context, () => new Conversacion()); if (activity.Type is ActivityTypes.Message) { bool.TryParse( Configuration[KeyRejectConnectionRequestIfNoAggregationChannel], out bool rejectConnectionRequestIfNoAggregationChannel); // Store the conversation references (identities of the sender and the recipient [bot]) // in the activity MessageRouter.StoreConversationReferences(activity); AbstractMessageRouterResult messageRouterResult = null; // Check the activity for commands if (await CommandHandler.HandleCommandAsync(context) == false) { // No command detected/handled // Let the message router route the activity, if the sender is connected with // another user/bot messageRouterResult = await MessageRouter.RouteMessageIfSenderIsConnectedAsync(activity); if (messageRouterResult is MessageRoutingResult && (messageRouterResult as MessageRoutingResult).Type == MessageRoutingResultType.NoActionTaken) { // No action was taken by the message router. This means that the user // is not connected (in a 1:1 conversation) with a human // (e.g. customer service agent) yet. // Check for cry for help (agent assistance) if (!string.IsNullOrWhiteSpace(activity.Text) && activity.Text.ToLower().Contains("agente")) { conversacion.Eleccion = activity.Text.ToLower(); await _conversationState.SaveChangesAsync(context, false, ct); await _userState.SaveChangesAsync(context, false, ct); // Create a connection request on behalf of the sender // Note that the returned result must be handled await context.SendActivityAsync($"{context.Activity.From.Name}, te voy a comunicar con un agente"); await context.SendActivityAsync("Por favor esperame unos segundos a que uno de nuestros agentes esté disponible para atenderte..."); messageRouterResult = MessageRouter.CreateConnectionRequest( MessageRouter.CreateSenderConversationReference(activity), rejectConnectionRequestIfNoAggregationChannel); } else { // No action taken - this middleware did not consume the activity so let it propagate await next(ct).ConfigureAwait(false); } } } // Uncomment to see the result in a reply (may be useful for debugging) //if (messageRouterResult != null) //{ // await MessageRouter.ReplyToActivityAsync(activity, messageRouterResult.ToString()); //} // Handle the result, if necessary await MessageRouterResultHandler.HandleResultAsync(messageRouterResult); } else { // No action taken - this middleware did not consume the activity so let it propagate await next(ct).ConfigureAwait(false); } } /// <summary> /// Extracts the channel list from the settings matching the given key. /// </summary> /// <returns>The list of channels or null, if none found.</returns> private IList<string> GetChannelList(string key) { IList<string> channelList = null; string channels = Configuration[key]; if (!string.IsNullOrWhiteSpace(channels)) { System.Diagnostics.Debug.WriteLine($"Channels by key \"{key}\": {channels}"); string[] channelArray = channels.Split(','); if (channelArray.Length > 0) { channelList = new List<string>(); foreach (string channel in channelArray) { channelList.Add(channel.Trim()); } } } else { System.Diagnostics.Debug.WriteLine($"No channels defined by key \"{key}\" in app settings"); } return channelList; } } }
44.480583
161
0.591618
[ "MIT" ]
jyapurv/botderivador
IntermediatorBotSample/Middleware/HandoffMiddleware.cs
9,166
C#
using Service.IndexPrices.Domain.Models.IndexInstructions; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Service.IndexPrices.Grpc.Models.IndexInstructions { [DataContract] public class IndexInstructionCreateResponse { [DataMember(Order = 1)] public IndexInstruction Item { get; set; } } }
24.388889
59
0.758542
[ "MIT" ]
MyJetWallet/Service.IndexPrices
src/Service.IndexPrices.Grpc/Models/IndexInstructions/IndexInstructionCreateResponse.cs
441
C#
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System.ComponentModel.Composition; using System.Windows.Controls; using ViewSwitchingNavigation.Email.ViewModels; namespace ViewSwitchingNavigation.Email.Views { [Export("ComposeEmailView")] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class ComposeEmailView : UserControl { public ComposeEmailView() { InitializeComponent(); } [Import] public ComposeEmailViewModel ViewModel { set { this.DataContext = value; } } } }
42.333333
86
0.560872
[ "MIT" ]
cointoss1973/Prism4.1-WPF
Quickstarts/View-Switching Navigation/Silverlight/View-Switching Navigation/ViewSwitchingNavigation.Email/Views/ComposeEmailView.xaml.cs
1,651
C#
/* Copyright 2019-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace MongoDB.Driver.Core.Events { /// <summary> /// Represents the reason a connection was closed. /// </summary> public enum ConnectionClosedReason { /// <summary> /// The pool was cleared, making the connection no longer valid. /// </summary> Stale, /// <summary> /// The connection became stale by being available for too long. /// </summary> Idle, /// <summary> /// The connection experienced an error, making it no longer valid. /// </summary> Error, /// <summary> /// The pool was closed, making the connection no longer valid. /// </summary> PoolClosed, /// <summary> /// The reason the connection was closed is unknown. /// </summary> Unknown } }
29.265306
75
0.629707
[ "Apache-2.0" ]
Anarh2404/mongo-csharp-driver
src/MongoDB.Driver.Core/Core/Events/ConnectionClosedReason.cs
1,436
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ContainerInstance.V20171001Preview { /// <summary> /// A container group. /// </summary> [AzureNativeResourceType("azure-native:containerinstance/v20171001preview:ContainerGroup")] public partial class ContainerGroup : Pulumi.CustomResource { /// <summary> /// The containers within the container group. /// </summary> [Output("containers")] public Output<ImmutableArray<Outputs.ContainerResponse>> Containers { get; private set; } = null!; /// <summary> /// The image registry credentials by which the container group is created from. /// </summary> [Output("imageRegistryCredentials")] public Output<ImmutableArray<Outputs.ImageRegistryCredentialResponse>> ImageRegistryCredentials { get; private set; } = null!; /// <summary> /// The instance view of the container group. Only valid in response. /// </summary> [Output("instanceView")] public Output<Outputs.ContainerGroupResponseInstanceView> InstanceView { get; private set; } = null!; /// <summary> /// The IP address type of the container group. /// </summary> [Output("ipAddress")] public Output<Outputs.IpAddressResponse?> IpAddress { get; private set; } = null!; /// <summary> /// The resource location. /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The operating system type required by the containers in the container group. /// </summary> [Output("osType")] public Output<string> OsType { get; private set; } = null!; /// <summary> /// The provisioning state of the container group. This only appears in the response. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Restart policy for all containers within the container group. /// - `Always` Always restart /// - `OnFailure` Restart on failure /// - `Never` Never restart /// </summary> [Output("restartPolicy")] public Output<string?> RestartPolicy { get; private set; } = null!; /// <summary> /// The resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The list of volumes that can be mounted by containers in this container group. /// </summary> [Output("volumes")] public Output<ImmutableArray<Outputs.VolumeResponse>> Volumes { get; private set; } = null!; /// <summary> /// Create a ContainerGroup resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ContainerGroup(string name, ContainerGroupArgs args, CustomResourceOptions? options = null) : base("azure-native:containerinstance/v20171001preview:ContainerGroup", name, args ?? new ContainerGroupArgs(), MakeResourceOptions(options, "")) { } private ContainerGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:containerinstance/v20171001preview:ContainerGroup", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20171001preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20170801preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20170801preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20171201preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20171201preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20180201preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180201preview:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20180401:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180401:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20180601:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180601:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20180901:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180901:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20181001:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20181001:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20191201:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20191201:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20201101:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20201101:ContainerGroup"}, new Pulumi.Alias { Type = "azure-native:containerinstance/v20210301:ContainerGroup"}, new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20210301:ContainerGroup"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ContainerGroup resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ContainerGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ContainerGroup(name, id, options); } } public sealed class ContainerGroupArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the container group. /// </summary> [Input("containerGroupName")] public Input<string>? ContainerGroupName { get; set; } [Input("containers", required: true)] private InputList<Inputs.ContainerArgs>? _containers; /// <summary> /// The containers within the container group. /// </summary> public InputList<Inputs.ContainerArgs> Containers { get => _containers ?? (_containers = new InputList<Inputs.ContainerArgs>()); set => _containers = value; } [Input("imageRegistryCredentials")] private InputList<Inputs.ImageRegistryCredentialArgs>? _imageRegistryCredentials; /// <summary> /// The image registry credentials by which the container group is created from. /// </summary> public InputList<Inputs.ImageRegistryCredentialArgs> ImageRegistryCredentials { get => _imageRegistryCredentials ?? (_imageRegistryCredentials = new InputList<Inputs.ImageRegistryCredentialArgs>()); set => _imageRegistryCredentials = value; } /// <summary> /// The IP address type of the container group. /// </summary> [Input("ipAddress")] public Input<Inputs.IpAddressArgs>? IpAddress { get; set; } /// <summary> /// The resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The operating system type required by the containers in the container group. /// </summary> [Input("osType", required: true)] public InputUnion<string, Pulumi.AzureNative.ContainerInstance.V20171001Preview.OperatingSystemTypes> OsType { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Restart policy for all containers within the container group. /// - `Always` Always restart /// - `OnFailure` Restart on failure /// - `Never` Never restart /// </summary> [Input("restartPolicy")] public InputUnion<string, Pulumi.AzureNative.ContainerInstance.V20171001Preview.ContainerGroupRestartPolicy>? RestartPolicy { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// The resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("volumes")] private InputList<Inputs.VolumeArgs>? _volumes; /// <summary> /// The list of volumes that can be mounted by containers in this container group. /// </summary> public InputList<Inputs.VolumeArgs> Volumes { get => _volumes ?? (_volumes = new InputList<Inputs.VolumeArgs>()); set => _volumes = value; } public ContainerGroupArgs() { } } }
44.777344
158
0.613103
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/ContainerInstance/V20171001Preview/ContainerGroup.cs
11,463
C#
using Sharpen; namespace android.telephony.@internal.test { [Sharpen.NakedStub] public interface SimulatedRadioControl { } }
13
42
0.776923
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/generated/android/telephony/internal/test/SimulatedRadioControl.cs
130
C#
using NBitcoin; using System.Net; using WalletWasabi.BitcoinCore.Configuration; using WalletWasabi.BitcoinCore.Configuration.Whitening; using Xunit; namespace WalletWasabi.Tests.UnitTests.BitcoinCore { public class ConfigTranslatorTests { [Fact] public void TryGetRpcUserTests() { var config = new CoreConfig(); var translatorMain = new CoreConfigTranslator(config, Network.Main); var translatorTest = new CoreConfigTranslator(config, Network.TestNet); var translatorReg = new CoreConfigTranslator(config, Network.RegTest); Assert.Null(translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("rpcuser"); Assert.Null(translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("rpcuser=foo"); Assert.Equal("foo", translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("rpcuser=boo"); Assert.Equal("boo", translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("main.rpcuser=ooh"); Assert.Equal("ooh", translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("rpcuser=boo"); Assert.Equal("boo", translatorMain.TryGetRpcUser()); Assert.Null(translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("test.rpcuser=boo"); Assert.Equal("boo", translatorMain.TryGetRpcUser()); Assert.Equal("boo", translatorTest.TryGetRpcUser()); Assert.Null(translatorReg.TryGetRpcUser()); config.AddOrUpdate("regtest.rpcuser=boo"); Assert.Equal("boo", translatorMain.TryGetRpcUser()); Assert.Equal("boo", translatorTest.TryGetRpcUser()); Assert.Equal("boo", translatorReg.TryGetRpcUser()); } [Fact] public void TryGetRpcPortTests() { var config = new CoreConfig(); var translator = new CoreConfigTranslator(config, Network.Main); Assert.Null(translator.TryGetRpcPort()); config.AddOrUpdate("rpcport"); Assert.Null(translator.TryGetRpcPort()); config.AddOrUpdate("main.rpcport=1"); Assert.Equal((ushort)1, translator.TryGetRpcPort()); config.AddOrUpdate("rpcport=2"); Assert.Equal((ushort)2, translator.TryGetRpcPort()); config.AddOrUpdate("main.rpcport=foo"); Assert.Null(translator.TryGetRpcPort()); } [Fact] public void TryGetWhiteBindTests() { var config = new CoreConfig(); var translator = new CoreConfigTranslator(config, Network.Main); Assert.Null(translator.TryGetWhiteBind()); config.AddOrUpdate("whitebind"); Assert.Null(translator.TryGetWhiteBind()); config.AddOrUpdate("main.whitebind=127.0.0.1:18444"); WhiteBind whiteBind = translator.TryGetWhiteBind(); var ipEndPoint = whiteBind.EndPoint as IPEndPoint; Assert.Equal(IPAddress.Loopback, ipEndPoint.Address); Assert.Equal(18444, ipEndPoint.Port); Assert.Equal("", whiteBind.Permissions); config.AddOrUpdate("whitebind=127.0.0.1:0"); whiteBind = translator.TryGetWhiteBind(); ipEndPoint = whiteBind.EndPoint as IPEndPoint; Assert.Equal(IPAddress.Loopback, ipEndPoint.Address); Assert.Equal(0, ipEndPoint.Port); Assert.Equal("", whiteBind.Permissions); config.AddOrUpdate("whitebind=127.0.0.1"); whiteBind = translator.TryGetWhiteBind(); ipEndPoint = whiteBind.EndPoint as IPEndPoint; Assert.Equal(IPAddress.Loopback, ipEndPoint.Address); // Default port. Assert.Equal(8333, ipEndPoint.Port); Assert.Equal("", whiteBind.Permissions); config.AddOrUpdate("whitebind=foo@127.0.0.1"); whiteBind = translator.TryGetWhiteBind(); ipEndPoint = whiteBind.EndPoint as IPEndPoint; Assert.Equal(IPAddress.Loopback, ipEndPoint.Address); Assert.Equal(8333, ipEndPoint.Port); Assert.Equal("foo", whiteBind.Permissions); config.AddOrUpdate("whitebind=foo,boo@127.0.0.1"); whiteBind = translator.TryGetWhiteBind(); ipEndPoint = whiteBind.EndPoint as IPEndPoint; Assert.Equal(IPAddress.Loopback, ipEndPoint.Address); Assert.Equal(8333, ipEndPoint.Port); Assert.Equal("foo,boo", whiteBind.Permissions); config.AddOrUpdate("main.whitebind=@@@"); Assert.Null(translator.TryGetWhiteBind()); } } }
36.040323
74
0.742672
[ "MIT" ]
Kixunil/WalletWasabi
WalletWasabi.Tests/UnitTests/BitcoinCore/ConfigTranslatorTests.cs
4,469
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UDPCommunication; namespace TestUDPCommunicationIA { class Program { static void Main(string[] args) { UDPCommunicationIA udpia = new UDPCommunicationIA(); udpia.MessageReceived += Udpia_MessageReceived; udpia.StartListening(8002); Console.WriteLine("Listening on port 8002"); Console.WriteLine("Type 'p' to listen on port 8003, 's' to send an ASCII message on port 8005, 'h' to send an Hex message to port 8005"); var c = Console.ReadKey().KeyChar; while (c != 'q') { //test change port if (c == 'p') { udpia.StartListening(8003); Console.WriteLine("UPDATE: Listening on port 8003"); } else if (c == 's') { udpia.SendMessage("127.0.0.1", 8005, "Hello World!"); } else if (c == 'h') { udpia.SendHexMessage("127.0.0.1", 8005, "48 65 6c 6c 6f 20 57 6f 72 6c 64 20 69 6e 20 48 65 78 21"); } c = Console.ReadKey().KeyChar; } } private static void Udpia_MessageReceived(object sender, UDPCommunication.Events.MessageEventArgs e) { Console.WriteLine("Message received: " + e.Message); } } }
31.4
149
0.51465
[ "MIT" ]
intuiface/UDPCommunicationIA
source/UDPCommunication/TestUDPCommunicationIA/Program.cs
1,572
C#
//--------------------------------------------------------------------------------- // Copyright 2013 Tomasz Cielecki (tomasz@ostebaronen.dk) // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, // INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing // permissions and limitations under the License. //--------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Windows.Input; using Cheesebaron.MvxPlugins.AzureAccessControl.ViewModels; using Cirrious.CrossCore.Platform; using Cirrious.CrossCore.WeakSubscription; using Cirrious.MvvmCross.Binding; using Cirrious.MvvmCross.Binding.Attributes; using Cirrious.MvvmCross.Binding.BindingContext; using Cirrious.MvvmCross.Dialog.Touch; using Cirrious.MvvmCross.ViewModels; using CrossUI.Touch.Dialog.Elements; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Cheesebaron.MvxPlugins.AzureAccessControl.Touch.Views { public class DefaultLoginIdentityProviderTableViewController : MvxDialogViewController { public DefaultLoginIdentityProviderTableViewController() : base(UITableViewStyle.Grouped, null, true) { } public new DefaultIdentityProviderCollectionViewModel ViewModel { get { return (DefaultIdentityProviderCollectionViewModel)base.ViewModel; } set { base.ViewModel = value; } } private Section _loginDetailSection; public override void ViewDidLoad() { base.ViewDidLoad(); var bindings = this.CreateInlineBindingTarget<DefaultIdentityProviderCollectionViewModel>(); if (_loginDetailSection == null) { _loginDetailSection = new Section("Log in details") { new StringElement("Logged in with: ") .Bind(bindings, element => element.Value, vm => vm.LoggedInProvider), new StringElement("Log out") { ShouldDeselectAfterTouch = true } .Bind(bindings, element => element.SelectedCommand, vm => vm.LogOutCommand) }; } Root = new RootElement("Log in") { new BindableSection<CustomStringElement>("Log in using") .Bind(bindings, element => element.SelectedCommand, vm => vm.LoginSelectedIdentityProviderCommand) .Bind(bindings, element => element.ItemsSource, vm => vm.IdentityProviders), }; //Section Visible is not bindable :'( if (ViewModel.IsLoggedIn) if (!Root.Sections.Contains(_loginDetailSection)) Root.Add(_loginDetailSection); ViewModel.WeakSubscribe(() => ViewModel.IsLoggedIn, (s, e) => { if (ViewModel.IsLoggedIn) { if (!Root.Sections.Contains(_loginDetailSection)) Root.Add(_loginDetailSection); } else if (Root.Sections.Contains(_loginDetailSection)) Root.Remove(_loginDetailSection); }); } #region Dunno if this can be made differently, lol! public interface IBindableElement : IMvxBindingContextOwner { object DataContext { get; set; } } public class BindableSection<TElementTemplate> : Section where TElementTemplate : Element, IBindableElement { private IEnumerable _itemsSource; private MvxNotifyCollectionChangedEventSubscription _subscription; public BindableSection() { } public BindableSection(string caption) : base(caption) { } [MvxSetToNullAfterBinding] public IEnumerable ItemsSource { get { return _itemsSource; } set { SetItemsSource(value); } } [MvxSetToNullAfterBinding] public new ICommand SelectedCommand { get; set; } protected virtual void SetItemsSource(IEnumerable value) { if (Equals(_itemsSource, value)) return; if (_subscription != null) { _subscription.Dispose(); _subscription = null; } _itemsSource = value; if (_itemsSource != null && !(_itemsSource is IList)) MvxBindingTrace.Trace(MvxTraceLevel.Warning, "Binding to IEnumerable rather than IList - this can be inefficient, especially for large lists"); var newObservable = _itemsSource as INotifyCollectionChanged; if (newObservable != null) _subscription = newObservable.WeakSubscribe(OnItemsSourceCollectionChanged); NotifyDataSetChanged(); } private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { NotifyDataSetChanged(); } private void NotifyDataSetChanged() { var newElements = new List<Element>(); if (_itemsSource != null) { foreach (var item in _itemsSource) { var element = Activator.CreateInstance<TElementTemplate>(); element.DataContext = item; var item1 = item; element.SelectedCommand = new MvxCommand(() => SelectedCommand.Execute(item1)); newElements.Add(element); } } Elements.Clear(); Elements.AddRange(newElements); var root = Parent as RootElement ?? GetImmediateRootElement(); if (root != null) root.TableView.ReloadData(); } } public class CustomStringElement : StringElement , IBindableElement { public IMvxBindingContext BindingContext { get; set; } public CustomStringElement() { this.CreateBindingContext(); this.DelayBind(() => this.CreateBinding().For(me => me.Caption).To<DefaultIdentityProviderViewModel>(p => p.Name).Apply()); } private static readonly NSString Skey = new NSString("StringElement"); private static readonly NSString SkeyValue = new NSString("StringElementValue"); protected override UITableViewCell GetCellImpl(UITableView tv) { var uiTableViewCell = tv.DequeueReusableCell(Value == null ? Skey : SkeyValue) ?? new UITableViewCell(Value == null ? UITableViewCellStyle.Default : UITableViewCellStyle.Value1, Skey) { SelectionStyle = UITableViewCellSelectionStyle.Blue }; uiTableViewCell.Accessory = UITableViewCellAccessory.DisclosureIndicator; return uiTableViewCell; } protected override void Dispose(bool disposing) { if (disposing) { BindingContext.ClearAllBindings(); } base.Dispose(disposing); } public virtual object DataContext { get { return BindingContext.DataContext; } set { BindingContext.DataContext = value; } } } #endregion } }
38.660465
140
0.567854
[ "Apache-2.0" ]
ghuntley/Cheesebaron.MvxPlugins
AzureAccessControl/Cheesebaron.MvxPlugins.AzureAccessControl.Touch/Views/DefaultLoginIdentityProviderTableViewController.cs
8,314
C#
using N2e.MarkDown.Abstractions; using N2e.MarkDown.Core; namespace N2e.MarkDown.Syntax { public class MarkdownInlineXml : MarkDownInline { public override char TriggerValue => '<'; public override char TriggerEnd => '>'; public override MdType TypeName => MdType.XmlElement; public override bool StopRecursion => true; } }
26.428571
61
0.683784
[ "CC0-1.0" ]
gjkaal/n2e-Markdown
N2e.MarkDown/Syntax/MarkdownInlineXml.cs
372
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license or other governing licenses that can be found in the LICENSE.md file or at * https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE */ #endregion namespace Krypton.Toolkit.Suite.Extended.Buttons { /// <summary> /// Methods that can be used anywhere. /// </summary> public class GlobalMethods { #region Variables private bool _isTargetPlatformSupported = false, _isTargetPlatform64BIT = false, _isAssemblies64BIT = false, _internetConnectionState = false; #endregion #region Properties /// <summary> /// The property to access and alter the variable _isTargetPlatformSupported. /// </summary> private bool IsTargetPlatformSupported { get { return _isTargetPlatformSupported; } set { _isTargetPlatformSupported = value; } } /// <summary> /// The property to access and alter the variable _isTargetPlatform64BIT. /// </summary> private bool IsTargetPlatform64BIT { get { return _isTargetPlatform64BIT; } set { _isTargetPlatform64BIT = value; } } /// <summary> /// The property to access and alter the variable _isAssemblies64BIT. /// </summary> private bool IsAssemblies64BIT { get { return _isAssemblies64BIT; } set { _isAssemblies64BIT = value; } } /// <summary> /// Gets or sets a value indicating whether [internet connection state]. /// </summary> /// <value> /// <c>true</c> if [internet connection state]; otherwise, <c>false</c>. /// </value> private bool InternetConnectionState { get { return _internetConnectionState; } set { _internetConnectionState = value; } } #endregion #region Constructor /// <summary> /// The default constructor. /// </summary> public GlobalMethods() { } #endregion #region Methods /// <summary> /// Checks to see if the client's version of Windows is supported or not. /// </summary> /// <param name="useLegacyVistaSupport">Include Windows Vista in the supported list (the default value is 'false').</param> /// <returns>True if the version of Windows is supported, false if not.</returns> public bool CheckIfTargetPlatformIsSupported(bool useLegacyVistaSupport = false) { try { if (useLegacyVistaSupport) { if (Environment.OSVersion.Version.Major >= 6) { SetIsTargetPlatformSupported(true); } else { SetIsTargetPlatformSupported(false); } } else { if (Environment.Version.Major >= 6 && Environment.Version.Minor >= 1) { SetIsTargetPlatformSupported(true); } else { SetIsTargetPlatformSupported(false); } } } catch (Exception exc) { ExceptionCapture.CaptureException(exc, "Exception Thrown", MessageBoxButtons.OK, MessageBoxIcon.Error, "GlobalMethods", "CheckIfTargetPlatformIsSupported(bool useLegacyVistaSupport = false)"); SetIsTargetPlatformSupported(false); } return GetIsTargetPlatformSupported(); } /// <summary> /// Checks to see whether the client is using a 64-bit version of Windows. /// </summary> /// <returns>True if a 64-bit version of Windows is detected, false if a 32-bit version of Windows is detected.</returns> public bool IsTargetPlatformRunningIn64BITMode() { try { if (Environment.Is64BitOperatingSystem) { SetIsTargetPlatform64BIT(true); } else { SetIsTargetPlatform64BIT(false); } } catch (Exception exc) { KryptonMessageBox.Show("Error: " + exc.Message, "Error Thrown", MessageBoxButtons.OK, MessageBoxIcon.Error); SetIsTargetPlatform64BIT(false); } return GetIsTargetPlatform64BIT(); } /// <summary> /// /// </summary> /// <returns></returns> public bool AreAssemblies64BIT() { try { } catch (Exception exc) { KryptonMessageBox.Show("Error: " + exc.Message, "Error Thrown", MessageBoxButtons.OK, MessageBoxIcon.Error); SetIsAssemblies64BIT(false); } return GetIsAssemblies64BIT(); } /// <summary> /// Elevates the application to use administrative privileges. To be used with <see cref="Button"/> button click. /// </summary> /// <param name="processName">The process name that you wish to elevate.</param> public void ElevateProcessWithAdministrativeRights(string processName) { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = principal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { // Relaunch the application with administrative rights ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.Verb = "runas"; processStartInfo.FileName = processName; try { Process.Start(processStartInfo); } catch (Win32Exception wexc) { MessageBox.Show("Error: " + wexc.Message, "An Error has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error); } return; } } public string GetOSFriendlyName() { string productName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName"), csdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion"); if (productName != string.Empty) { return (productName.StartsWith("Microsoft") ? "" : "Microsoft ") + productName + (csdVersion != "" ? " " + csdVersion : ""); } return string.Empty; } private string HKLM_GetString(string path, string key) { try { RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(path); if (registryKey == null) { return string.Empty; } return (string)registryKey.GetValue(key); } catch (Exception e) { return string.Empty; } } // TODO: Fix this method /* /// <summary> /// This method checks if the client operating system supports the Windows API CodePack set of API's. /// </summary> /// <returns>True, if the client operating system supports the Windows API CodePack set of API's.</returns> public bool IsWindowsAPICodePackSupported() { if (TaskbarManager.IsPlatformSupported) { return true; } else { return false; } } */ #endregion #region Setters and Getters /// <summary> /// Sets the IsTargetPlatformSupported to the value of value. /// </summary> /// <param name="value">The desired value of IsTargetPlatformSupported.</param> public void SetIsTargetPlatformSupported(bool value) { IsTargetPlatformSupported = value; } /// <summary> /// Returns the value of the IsTargetPlatformSupported. /// </summary> /// <returns>The value of the IsTargetPlatformSupported.</returns> public bool GetIsTargetPlatformSupported() { return IsTargetPlatformSupported; } /// <summary> /// Sets the IsTargetPlatform64BIT to the value of value. /// </summary> /// <param name="value">The desired value of IsTargetPlatform64BIT.</param> public void SetIsTargetPlatform64BIT(bool value) { IsTargetPlatform64BIT = value; } /// <summary> /// Returns the value of the IsTargetPlatform64BIT. /// </summary> /// <returns>The value of the IsTargetPlatform64BIT.</returns> public bool GetIsTargetPlatform64BIT() { return IsTargetPlatform64BIT; } /// <summary> /// Sets the IsAssemblies64BIT to the value of value. /// </summary> /// <param name="value">The desired value of IsAssemblies64BIT.</param> public void SetIsAssemblies64BIT(bool value) { IsAssemblies64BIT = value; } /// <summary> /// Returns the value of the IsAssemblies64BIT. /// </summary> /// <returns>The value of the IsAssemblies64BIT.</returns> public bool GetIsAssemblies64BIT() { return IsAssemblies64BIT; } /// <summary> /// Sets the InternetConnectionState to the value of value. /// </summary> /// <param name="value">The desired value of InternetConnectionState.</param> public void SetInternetConnectionState(bool value) { InternetConnectionState = value; } /// <summary> /// Returns the value of the InternetConnectionState. /// </summary> /// <returns>The value of the InternetConnectionState.</returns> public bool GetInternetConnectionState() { return InternetConnectionState; } #endregion #region De-constructor /// <summary> /// Finalizes an instance of the <see cref="GlobalMethods"/> class. /// </summary> ~GlobalMethods() { GC.SuppressFinalize(this); } #endregion } }
31.075419
208
0.525303
[ "BSD-3-Clause" ]
Krypton-Suite/Extended-Toolk
Source/Krypton Toolkit/Main/Krypton.Toolkit.Suite.Extended.Buttons/Classes/Utilities/GlobalMethods.cs
11,127
C#
namespace Newbe.Mahua.Samples.HotUpdate { /// <summary> /// 本插件的基本信息 /// </summary> public class PluginInfo : IPluginInfo { /// <summary> /// 版本号,建议采用 主版本.次版本.修订号 的形式 /// </summary> public string Version { get; set; } = "1.0.0"; /// <summary> /// 插件名称 /// </summary> public string Name { get; set; } = "Newbe.Mahua.Samples.HotUpdate"; /// <summary> /// 作者名称 /// </summary> public string Author { get; set; } = "Newbe"; /// <summary> /// 插件Id,用于唯一标识插件产品的Id,至少包含 AAA.BBB.CCC 三个部分 /// </summary> public string Id { get; set; } = "Newbe.Mahua.Samples.HotUpdate"; /// <summary> /// 插件描述 /// </summary> public string Description { get; set; } = "Newbe.Mahua.Samples.HotUpdate"; } }
24.742857
82
0.496536
[ "MIT" ]
BOBO41/Newbe.Mahua.Framework
src/Newbe.Mahua.Samples.HotUpdate/PluginInfo.cs
994
C#
namespace FPSCamera { using Configuration; using CSkyL.Transform; using CamController = CSkyL.Game.CamController; using Control = CSkyL.Game.Control; using CUtils = CSkyL.Game.Utils; using Log = CSkyL.Log; public class Controller : CSkyL.Game.Behavior { public bool IsActivated => _state == State.Activated; public bool IsIdle => _state == State.Idle; public void StartFreeCam() { Log.Msg("Starting FreeCam mode"); _SetCam(new Cam.FreeCam(_camGame.Positioning)); } public void StartFollow(CSkyL.Game.ID.ObjectID idToFollow) { Log.Msg("Starting Follow mode"); var newCam = Cam.FollowCam.Follow(idToFollow); if (newCam is Cam.FollowCam cam) _SetCam(newCam); else Log.Msg($"Fail to start Follow mode (ID: {idToFollow})"); } public void StartWalkThruMode() { Log.Msg("Starting WalkThru mode"); _SetCam(new Cam.WalkThruCam()); } public void StopFPSCam() { if (!IsActivated) return; _camMod = null; _exitingTimer = Config.G.MaxExitingDuration; _camGame.AllSetting = _originalSetting; if (!Config.G.SetBackCamera) _camGame.Positioning = CamController.I.LocateAt(_camGame.Positioning); _camGame.SetFullScreen(false); _uiHidden = false; _uiCamInfoPanel.enabled = false; _state = State.Exiting; } public bool OnEsc() { if (_uiMainPanel.OnEsc()) return true; if (_camMod is object) { StopFPSCam(); return true; } return false; } private void _SetCam(Cam.Base newCam) { _camMod = newCam; _uiCamInfoPanel.SetAssociatedCam(newCam); if (IsIdle) _EnableFPSCam(); else _uiMainPanel.OnCamActivate(); } private void _EnableFPSCam() { _originalSetting = _camGame.AllSetting; _ResetCamGame(); CamController.I.SetDepthOfField(Config.G.EnableDof); CamController.I.Disable(); _uiMainPanel.OnCamActivate(); _state = State.Activated; } private void _DisableFPSCam() { Log.Msg("FPS camera stopped"); _uiMainPanel.OnCamDeactivate(); Control.ShowUI(); Control.ShowCursor(); CamController.I.Restore(); _state = State.Idle; } private void _ResetCamGame() { _camGame.ResetTarget(); _camGame.FieldOfView = Config.G.CamFieldOfView; _camGame.NearClipPlane = Config.G.CamNearClipPlane; } private Offset _GetInputOffsetAfterHandleInput() { if (Control.KeyTriggered(Config.G.KeyCamToggle)) { if (IsActivated) StopFPSCam(); else StartFreeCam(); } if (!IsActivated || !_camMod.Validate()) return null; if (Control.MouseTriggered(Control.MouseButton.Middle) || Control.KeyTriggered(Config.G.KeyCamReset)) { _camMod.InputReset(); _ResetCamGame(); } if (Control.MouseTriggered(Control.MouseButton.Secondary)) (_camMod as Cam.WalkThruCam)?.SwitchTarget(); if (Control.KeyTriggered(Config.G.KeyAutoMove)) (_camMod as Cam.FreeCam)?.ToggleAutoMove(); if (Control.KeyTriggered(Config.G.KeySaveOffset) && _camMod is Cam.FollowCam followCam) { if (followCam.SaveOffset() is string name) _uiMainPanel.ShowMessage($"Offset saved for <{name}>"); } var movement = LocalMovement.None; { // key movement if (Control.KeyPressed(Config.G.KeyMoveForward)) movement.forward += 1f; if (Control.KeyPressed(Config.G.KeyMoveBackward)) movement.forward -= 1f; if (Control.KeyPressed(Config.G.KeyMoveRight)) movement.right += 1f; if (Control.KeyPressed(Config.G.KeyMoveLeft)) movement.right -= 1f; if (Control.KeyPressed(Config.G.KeyMoveUp)) movement.up += 1f; if (Control.KeyPressed(Config.G.KeyMoveDown)) movement.up -= 1f; movement *= (Control.KeyPressed(Config.G.KeySpeedUp) ? Config.G.SpeedUpFactor : 1f) * Config.G.MovementSpeed * CUtils.TimeSinceLastFrame / CSkyL.Game.Map.ToKilometer(1f); } var cursorVisible = Control.KeyPressed(Config.G.KeyCursorToggle) ^ ( _camMod is Cam.FreeCam ? Config.G.ShowCursor4Free : Config.G.ShowCursor4Follow); Control.ShowCursor(cursorVisible); float yawDegree = 0f, pitchDegree = 0f; { // key rotation if (Control.KeyPressed(Config.G.KeyRotateRight)) yawDegree += 1f; if (Control.KeyPressed(Config.G.KeyRotateLeft)) yawDegree -= 1f; if (Control.KeyPressed(Config.G.KeyRotateUp)) pitchDegree += 1f; if (Control.KeyPressed(Config.G.KeyRotateDown)) pitchDegree -= 1f; if (yawDegree != 0f || pitchDegree != 0f) { var factor = Config.G.RotateKeyFactor * CUtils.TimeSinceLastFrame; yawDegree *= factor; pitchDegree *= factor; } else if (!cursorVisible) { // mouse rotation const float factor = .2f; yawDegree = Control.MouseMoveHori * Config.G.RotateSensitivity * (Config.G.InvertRotateHorizontal ? -1f : 1f) * factor; pitchDegree = Control.MouseMoveVert * Config.G.RotateSensitivity * (Config.G.InvertRotateVertical ? -1f : 1f) * factor; } } { // scroll zooming var scroll = Control.MouseScroll; var targetFoV = _camGame.TargetFoV; if (scroll > 0f && targetFoV > Config.G.CamFieldOfView.Min) _camGame.FieldOfView = targetFoV / Config.G.FoViewScrollfactor; else if (scroll < 0f && targetFoV < Config.G.CamFieldOfView.Max) _camGame.FieldOfView = targetFoV * Config.G.FoViewScrollfactor; } return new Offset(movement, new DeltaAttitude(yawDegree, pitchDegree)); } private void _SetUpUI() { _uiMainPanel = gameObject.AddComponent<UI.MainPanel>(); _uiMainPanel.SetWalkThruCallBack(StartWalkThruMode); _uiCamInfoPanel = gameObject.AddComponent<UI.CamInfoPanel>(); if (CUtils.InGameMode) { _uiFollowButtons = gameObject.AddComponent<UI.FollowButtons>(); _uiFollowButtons.registerFollowCallBack(StartFollow); } } protected override void _Init() { _state = State.Idle; _uiHidden = false; } protected override void _SetUp() { _camGame = new GameCam(); _SetUpUI(); } protected override void _UpdateLate() { try { var controlOffset = _GetInputOffsetAfterHandleInput(); if (IsIdle) return; if (_state == State.Exiting) { _exitingTimer -= CUtils.TimeSinceLastFrame; if (_camGame.AlmostAtTarget() is bool done && done || _exitingTimer <= 0f) { if (!done) _camGame.AdvanceToTarget(); _DisableFPSCam(); return; } } else if (!_camMod.Validate()) { StopFPSCam(); return; } else { _camMod.InputOffset(controlOffset); (_camMod as Cam.ICamUsingTimer)?.ElapseTime(CUtils.TimeSinceLastFrame); _camGame.Positioning = _camMod.GetPositioning(); } var distance = _camGame.Positioning.position .DistanceTo(_camGame.TargetPositioning.position); var factor = Config.G.GetAdvanceRatio(CUtils.TimeSinceLastFrame); if (Config.G.SmoothTransition) { if (distance > Config.G.GiveUpTransDistance) _camGame.AdvanceToTargetSmooth(factor, instantMove: true, instantAngle: true); else if (_camMod is Cam.FollowCam && distance <= Config.G.InstantMoveMax) _camGame.AdvanceToTargetSmooth(factor, instantMove: true); else _camGame.AdvanceToTargetSmooth(factor); } else { _camGame.AdvanceToTarget(); } if (IsActivated) { _uiCamInfoPanel.enabled = Config.G.ShowInfoPanel; if (Config.G.HideGameUI ^ _uiHidden) { _uiHidden = Config.G.HideGameUI; Control.ShowUI(!_uiHidden); _camGame.SetFullScreen(_uiHidden); } } } catch (System.Exception e) { Log.Err("Unrecognized Error: " + e.ToString()); } } // Cameras private Cam.Base _camMod; private GameCam _camGame; private GameCam.Setting _originalSetting; // UI [CSkyL.Game.RequireDestruction] private UI.MainPanel _uiMainPanel; [CSkyL.Game.RequireDestruction] private UI.CamInfoPanel _uiCamInfoPanel; [CSkyL.Game.RequireDestruction] private UI.FollowButtons _uiFollowButtons; private bool _uiHidden; // state private enum State { Idle, Exiting, Activated } private State _state = State.Idle; private float _exitingTimer = 0f; } }
39.358779
99
0.540632
[ "MIT" ]
Asu4ni/CitiesSkylines-FPSCamera
FPSCamera/Controller.cs
10,312
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/codecapi.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="CODECAPI_AVEncVideoCBRMotionTradeoff" /> struct.</summary> public static unsafe partial class CODECAPI_AVEncVideoCBRMotionTradeoffTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncVideoCBRMotionTradeoff" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(CODECAPI_AVEncVideoCBRMotionTradeoff).GUID, Is.EqualTo(IID_CODECAPI_AVEncVideoCBRMotionTradeoff)); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoCBRMotionTradeoff" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CODECAPI_AVEncVideoCBRMotionTradeoff>(), Is.EqualTo(sizeof(CODECAPI_AVEncVideoCBRMotionTradeoff))); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoCBRMotionTradeoff" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CODECAPI_AVEncVideoCBRMotionTradeoff).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoCBRMotionTradeoff" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CODECAPI_AVEncVideoCBRMotionTradeoff), Is.EqualTo(1)); } }
42.545455
145
0.748932
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/codecapi/CODECAPI_AVEncVideoCBRMotionTradeoffTests.cs
1,874
C#
namespace SpaceEngineers.Core.Basics { using System; /// <summary> /// System.Type.MethodInfo extensions /// </summary> public static class MethodExtensions { /// <summary> /// Call method by reflection /// </summary> /// <param name="declaringType">Type that declare the method</param> /// <param name="methodName">Method name</param> /// <returns>MethodExecutionInfo</returns> public static MethodExecutionInfo CallMethod(this Type declaringType, string methodName) { return new MethodExecutionInfo(declaringType, methodName); } /// <summary> /// Call method by reflection /// </summary> /// <param name="target">Target instance of method call</param> /// <param name="methodName">Method name</param> /// <returns>MethodExecutionInfo</returns> public static MethodExecutionInfo CallMethod(this object target, string methodName) { return new MethodExecutionInfo(target.GetType(), methodName).ForInstance(target); } } }
34.90625
96
0.621307
[ "MIT" ]
warning-explosive/Core
Basics/MethodExtensions.cs
1,117
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SampleApp.Controls; using SampleApp.Droid.Renderers; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(WaterDropRefresh), typeof(WaterDropRefreshRenderer))] namespace SampleApp.Droid.Renderers { public class WaterDropRefreshRenderer : ViewRenderer<WaterDropRefresh, Com.Scwang.Smartrefresh.Layout.SmartRefreshLayout> { public WaterDropRefreshRenderer(Context context):base(context) { } private Com.Scwang.Smartrefresh.Layout.SmartRefreshLayout mSmartRefreshLayout; private Com.Scwang.Smartrefresh.Header.WaterDropHeader mWaterDropHeader; protected override void OnElementChanged(ElementChangedEventArgs<WaterDropRefresh> e) { if (mSmartRefreshLayout==null) { mSmartRefreshLayout = new Com.Scwang.Smartrefresh.Layout.SmartRefreshLayout(Context); } if (mWaterDropHeader == null) { mWaterDropHeader = new Com.Scwang.Smartrefresh.Header.WaterDropHeader(Context); } mSmartRefreshLayout.SetRefreshHeader(mWaterDropHeader); SetNativeControl(mSmartRefreshLayout); } } }
32.886364
125
0.710435
[ "MIT" ]
jingliancui/XamarinFormsSmartRefreshLayoutSample
1.1.0/SampleApp/SampleApp/SampleApp.Android/Renderers/WaterDropRefreshRenderer.cs
1,449
C#
//using System; //using System.Collections.Generic; //using System.Configuration; //using System.Linq; //using System.Net; //using System.Net.Http; //using System.Net.Http.Formatting; //using System.Threading.Tasks; //using System.Web.Http; //using System.Web.Http.Description; //using APTCWebb.Common; //using APTCWebb.Library.Models; //using Couchbase; //using Couchbase.Core; //using APTCWebb.OutPutDto; //namespace APTCWebb.Common //{ // public class SendNotification // { // #region PrviavteFields // private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseCRMBucket")); // private readonly IBucket _bucketRef = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseAPTCREFBucket")); // #endregion // string strnotificationDescription = string.Empty; // public string PostNotification(PostNotificationParameters objPostNotificationParameters) // { // strnotificationDescription = @"SELECT NM.notificationText, NM.notificationType, NM.notificationDescription FROM " + _bucketRef.Name + " r use keys 'NotificationTypeMaster' " + // "unnest r.['notificationTypeMaster'] NM where NM.['roleCode'] = '" + objPostNotificationParameters.RoleCode + "' " + // "and NM.['deptCode'] = '" + objPostNotificationParameters.DeptCode + "' and NM.notificationType = " + objPostNotificationParameters.NotificationType + ""; // var notificationDescriptionDocument = _bucket.Query<NotificationMessage>(strnotificationDescription).FirstOrDefault(); // if (notificationDescriptionDocument != null) // { // string notificationText = string.Empty; // switch (notificationDescriptionDocument.NotificationType) // { // case (int) AspectEnums.NotificationType.IndividualCreation: // notificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.Status); // break; // case (int)AspectEnums.NotificationType.VehicleRegistration: // notificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.Value, objPostNotificationParameters.Status); // break; // case (int)AspectEnums.NotificationType.PermitRequest: // notificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.Value, objPostNotificationParameters.Status); // break; // case (int)AspectEnums.NotificationType.CompanyRegistration: // notificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.Value, objPostNotificationParameters.Status); // break; // case (int)AspectEnums.NotificationType.FineRequest: // notificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.Value, objPostNotificationParameters.Status); // break; // } // var NotificationDoc = new Document<Notification>() // { // Id = "notification_" + DateTime.Now.Ticks.ToString(), // Content = new Notification // { // NotificationDescription = notificationDescriptionDocument.NotificationDescription, // NotificationType = objPostNotificationParameters.NotificationType, // RoleCode = objPostNotificationParameters.RoleCode, // DeptCode = objPostNotificationParameters.DeptCode, // UserCode = objPostNotificationParameters.UserCode, // //NotificationText = string.Format(notificationDescriptionDocument.NotificationText, objPostNotificationParameters.KeyID, objPostNotificationParameters.RegistrationNumnber, objPostNotificationParameters.Status), // NotificationText = notificationText, // NotificationCreatedDate = DateTime.Now.ToString(), // ReadReceipt = false, // Validity = 24, // }, // }; // var NotificationResult = _bucket.Insert(NotificationDoc); // } // else // { // return "notification not configured for Dept Code "+ objPostNotificationParameters.DeptCode + " and Role Code "+ objPostNotificationParameters.RoleCode + ""; // } // return "notification has been created"; // } // } //}
60.360465
241
0.636872
[ "MIT" ]
DeePatrick/Ajman
V2.0/APTCWebb/Common/SendNotification.cs
5,193
C#
// <auto-generated /> using System; using CQRSApiTemplate.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CQRSApiTemplate.Infrastructure.persistence.migrations { [DbContext(typeof(CQRSApiTemplateDbContext))] partial class CQRSApiTemplateDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.6") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("CQRSApiTemplate.Domain.Entities.Category", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTimeOffset>("Created") .HasColumnType("datetimeoffset"); b.Property<string>("CreatedBy") .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<DateTimeOffset?>("LastModified") .HasColumnType("datetimeoffset"); b.Property<string>("LastModifiedBy") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.ToTable("Category"); }); modelBuilder.Entity("CQRSApiTemplate.Domain.Entities.Product", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("CategoryId") .HasColumnType("bigint"); b.Property<DateTimeOffset>("Created") .HasColumnType("datetimeoffset"); b.Property<string>("CreatedBy") .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<DateTimeOffset?>("LastModified") .HasColumnType("datetimeoffset"); b.Property<string>("LastModifiedBy") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Product"); }); modelBuilder.Entity("CQRSApiTemplate.Domain.Entities.Product", b => { b.HasOne("CQRSApiTemplate.Domain.Entities.Category", "Category") .WithMany("Products") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.OwnsOne("CQRSApiTemplate.Domain.ValueObjects.Money", "Price", b1 => { b1.Property<long>("ProductId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b1.Property<decimal>("Amount") .HasColumnType("decimal(10,2)") .HasColumnName("Price"); b1.Property<string>("Currency") .IsRequired() .HasMaxLength(10) .HasColumnType("nvarchar(10)") .HasColumnName("Currency"); b1.HasKey("ProductId"); b1.ToTable("Product"); b1.WithOwner() .HasForeignKey("ProductId"); }); b.Navigation("Category"); b.Navigation("Price"); }); modelBuilder.Entity("CQRSApiTemplate.Domain.Entities.Category", b => { b.Navigation("Products"); }); #pragma warning restore 612, 618 } } }
38.690647
133
0.487728
[ "MIT" ]
dekizard/CQRSApiTemplate
src/CQRSApiTemplate.Infrastructure/Persistence/Migrations/CQRSApiTemplateDbContextModelSnapshot.cs
5,380
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 outposts-2019-12-03.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.Outposts.Model { /// <summary> /// Information about a line item. /// </summary> public partial class LineItem { private string _catalogItemId; private string _lineItemId; private int? _quantity; private string _status; /// <summary> /// Gets and sets the property CatalogItemId. /// <para> /// The ID of the catalog item. /// </para> /// </summary> [AWSProperty(Min=1, Max=10)] public string CatalogItemId { get { return this._catalogItemId; } set { this._catalogItemId = value; } } // Check to see if CatalogItemId property is set internal bool IsSetCatalogItemId() { return this._catalogItemId != null; } /// <summary> /// Gets and sets the property LineItemId. /// <para> /// The ID of the line item. /// </para> /// </summary> public string LineItemId { get { return this._lineItemId; } set { this._lineItemId = value; } } // Check to see if LineItemId property is set internal bool IsSetLineItemId() { return this._lineItemId != null; } /// <summary> /// Gets and sets the property Quantity. /// <para> /// The quantity of the line item. /// </para> /// </summary> [AWSProperty(Min=1, Max=20)] public int Quantity { get { return this._quantity.GetValueOrDefault(); } set { this._quantity = value; } } // Check to see if Quantity property is set internal bool IsSetQuantity() { return this._quantity.HasValue; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the line item. /// </para> /// </summary> [AWSProperty(Min=1, Max=1000)] public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
27.495726
106
0.566988
[ "Apache-2.0" ]
MDanialSaleem/aws-sdk-net
sdk/src/Services/Outposts/Generated/Model/LineItem.cs
3,217
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace BLE_UART { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { private TransitionCollection transitions; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
39.156716
126
0.610825
[ "Apache-2.0" ]
resolutedreamer/BLE_UART_8001
BLE_UART/App.xaml.cs
5,249
C#
using Xunit; using FluentAssertions; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using HotelCalifornia.Backend.Database; using HotelCalifornia.Backend.Domain.Entities; using HotelCalifornia.Backend.Core.Generators; using HotelCalifornia.Backend.Core.Services.DateTimeService; using HotelCalifornia.Backend.Cqrs.Handlers.Commands.Booking; namespace HotelCalifornia.UnitTests.Handlers.Booking { public class AddBookingCommandHandlerTest : TestBase { private readonly DateTimeService FDateTimeService; public AddBookingCommandHandlerTest() => FDateTimeService = new DateTimeService(); [Fact] public async Task GivenAllDataProvided_WhenAddBooking_ShouldAddEntity() { // Arrange var LAddBookingCommand = new AddBookingCommand { GuestFullName = StringProvider.GetRandomString(), GuestPhoneNumber = StringProvider.GetRandomString(), BedroomsNumber = 1, DateFrom = FDateTimeService.Now.AddDays(5), DateTo = FDateTimeService.Now.AddDays(15) }; var LDatabaseContext = GetTestDatabaseContext(); await RoomsFactory(10, LDatabaseContext); var LAddBookingCommandHandler = new AddBookingCommandHandler(LDatabaseContext); // Act await LAddBookingCommandHandler.Handle(LAddBookingCommand, CancellationToken.None); // Assert var LBookingEntity = LDatabaseContext.Bookings.ToList(); LBookingEntity.Should().HaveCount(1); LBookingEntity[0].GuestFullName.Should().Be(LAddBookingCommand.GuestFullName); LBookingEntity[0].GuestPhoneNumber.Should().Be(LAddBookingCommand.GuestPhoneNumber); LBookingEntity[0].DateFrom.Should().BeSameDateAs(LAddBookingCommand.DateFrom); LBookingEntity[0].DateTo.Should().BeSameDateAs(LAddBookingCommand.DateTo); } private static async Task RoomsFactory(int ARoomsNumber, DatabaseContext ADatabaseContext) { var LRooms = new List<Rooms>(); for (var LIndex = 0; LIndex < ARoomsNumber; LIndex++) { LRooms.Add(new Rooms { Id = new Guid(), RoomNumber = LIndex, Bedrooms = NumberProvider.GetRandomInteger(1, 3) }); } ADatabaseContext.Rooms.AddRange(LRooms); await ADatabaseContext.SaveChangesAsync(); } } }
39.014706
98
0.64983
[ "MIT" ]
TomaszKandula/HotelCalifornia
HotelCalifornia.UnitTests/Handlers/Booking/AddBookingCommandHandlerTest.cs
2,653
C#
using System; using UltimaOnline; namespace UltimaOnline.Items { public class ElvenStoveSouthAddon : BaseAddon { public override BaseAddonDeed Deed { get { return new ElvenStoveSouthDeed(); } } [Constructable] public ElvenStoveSouthAddon() { AddComponent(new AddonComponent(0x2DDC), 0, 0, 0); } public ElvenStoveSouthAddon(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } public class ElvenStoveSouthDeed : BaseAddonDeed { public override BaseAddon Addon { get { return new ElvenStoveSouthAddon(); } } public override int LabelNumber { get { return 1073394; } } // elven oven (south) [Constructable] public ElvenStoveSouthDeed() { } public ElvenStoveSouthDeed(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } }
25.555556
90
0.567081
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Addons/ElvenStoveSouthAddon.cs
1,610
C#
using System.Collections.Generic; namespace Palaso.Base32 { public partial class Base32Convert { private const string base32hexAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; /// <summary> /// base32hex encoding as defined by RFC4648 /// http://rfc.net/rfc4648.html /// One property with this alphabet, which the base64 and base32 /// alphabets lack, is that encoded data maintains its sort order when /// the encoded data is compared bit-wise. /// </summary> /// <remarks> /// This is suitable for encoding sort keys in xml documents such /// that xslt 1 can produce a proper ordering. /// </remarks> public static string ToBase32HexString(IEnumerable<byte> octets, Base32FormattingOptions options) { return ToBase32String(octets, base32hexAlphabet, options); } /// <summary> /// base32hex decoding as defined by RFC4648 /// http://rfc.net/rfc4648.html /// One property with this alphabet, which the base64 and base32 /// alphabets lack, is that encoded data maintains its sort order when /// the encoded data is compared bit-wise. /// </summary> /// <remarks> /// This is suitable for encoding sort keys in xml documents such /// that xslt 1 can produce a proper ordering. /// </remarks> public static byte[] FromBase32HexString(string base32, Base32FormattingOptions options) { byte[] decodeMap = CreateDecodeMap(base32hexAlphabet, false); return FromBase32String(base32, decodeMap, options); } } }
35.119048
99
0.722034
[ "MIT" ]
JohnThomson/libpalaso
Palaso/Base32/Base32HexConvert.cs
1,475
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("Geometery")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Geometery")] [assembly: AssemblyCopyright("Copyright © 2015")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
39.40678
104
0.748387
[ "MIT" ]
21pages/WPF-Samples
Graphics/Geometery/Properties/AssemblyInfo.cs
2,328
C#
using BoligApp.Bizz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BoligApp.GUI { /// <summary> /// Interaction logic for UiEditTennant.xaml /// </summary> public partial class UiEditTennant : UserControl { private AppBizz CAB; private UserControl ucCenter; public UiEditTennant(AppBizz CAB, UserControl ucCenter) { InitializeComponent(); this.CAB = CAB; this.ucCenter = ucCenter; } } }
24.558824
63
0.700599
[ "Unlicense" ]
gywerd/BoligApp
BoligApp.GUI/UiEditTennant.xaml.cs
837
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.CompensationReview { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Bonus_PlanObjectType : INotifyPropertyChanged { private Bonus_PlanObjectIDType[] idField; private string descriptorField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("ID", Order = 0)] public Bonus_PlanObjectIDType[] ID { get { return this.idField; } set { this.idField = value; this.RaisePropertyChanged("ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string Descriptor { get { return this.descriptorField; } set { this.descriptorField = value; this.RaisePropertyChanged("Descriptor"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.836066
136
0.731982
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.CompensationReview/Bonus_PlanObjectType.cs
1,332
C#
// // DoNotRecurseInEqualityRule: flag recursive operator== and !=. // // Authors: // Jesse Jones <jesjones@mindspring.com> // // Copyright (C) 2008 Jesse Jones // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Cecil; using Mono.Cecil.Cil; using Gendarme.Framework; using Gendarme.Framework.Engines; using Gendarme.Framework.Helpers; using Gendarme.Framework.Rocks; namespace Gendarme.Rules.Correctness { /// <summary> /// An operator== or operator!= method is calling itself recursively. This is /// usually caused by neglecting to cast an argument to System.Object before /// comparing it to null. /// </summary> /// <example> /// Bad example: /// <code> /// public static bool operator== (Customer lhs, Customer rhs) /// { /// if (object.ReferenceEquals (lhs, rhs)) { /// return true; /// } /// if (lhs == null || rhs == null) { /// return false; /// } /// return lhs.name == rhs.name &amp;&amp; lhs.address == rhs.address; /// } /// </code> /// </example> /// <example> /// Good example: /// <code> /// public static bool operator== (Customer lhs, Customer rhs) /// { /// if (object.ReferenceEquals (lhs, rhs)) { /// return true; /// } /// if ((object) lhs == null || (object) rhs == null) { /// return false; /// } /// return lhs.name == rhs.name &amp;&amp; lhs.address == rhs.address; /// } /// </code> /// </example> /// <remarks>This rule is available since Gendarme 2.4</remarks> [Problem ("An operator== or operator!= method is calling itself recursively.")] [Solution ("Fix null argument checks so that they first cast the argument to System.Object.")] [EngineDependency (typeof (OpCodeEngine))] public sealed class DoNotRecurseInEqualityRule : Rule, IMethodRule { public RuleResult CheckMethod (MethodDefinition method) { // rule applies only if the method has a body if (!method.HasBody) return RuleResult.DoesNotApply; // ignore everything but operator== and operator!= string name = method.Name; if (!method.IsSpecialName || (name != "op_Equality" && name != "op_Inequality")) return RuleResult.DoesNotApply; // avoid looping if we're sure there's no Call[virt] in the method if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method))) return RuleResult.DoesNotApply; Log.WriteLine (this); Log.WriteLine (this, "---------------------------------------"); Log.WriteLine (this, method); foreach (Instruction ins in method.Body.Instructions) { switch (ins.OpCode.Code) { case Code.Call: case Code.Callvirt: MethodReference callee = (ins.Operand as MethodReference).Resolve(); // need the resolve for generics if (callee != null) { if (callee.MetadataToken == method.MetadataToken) { // MethodReference.ToString is very costly but, in this case, won't be called often if (callee.ToString () == method.ToString ()) { Log.WriteLine (this, "recursive call at {0:X4}", ins.Offset); Runner.Report (method, ins, Severity.Critical, Confidence.Normal); } } } break; } } return Runner.CurrentRuleResult; } } }
33.895161
106
0.674994
[ "MIT" ]
SteveGilham/Gendarme
gendarme/rules/Gendarme.Rules.Correctness/DoNotRecurseInEqualityRule.cs
4,203
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 apigateway-2015-07-09.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.APIGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.APIGateway.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteDocumentationVersion operation /// </summary> public class DeleteDocumentationVersionResponseUnmarshaller : 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) { DeleteDocumentationVersionResponse response = new DeleteDocumentationVersionResponse(); 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) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return new BadRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return new ConflictException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException")) { return new TooManyRequestsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return new UnauthorizedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonAPIGatewayException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DeleteDocumentationVersionResponseUnmarshaller _instance = new DeleteDocumentationVersionResponseUnmarshaller(); internal static DeleteDocumentationVersionResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteDocumentationVersionResponseUnmarshaller Instance { get { return _instance; } } } }
42.367925
168
0.683812
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/DeleteDocumentationVersionResponseUnmarshaller.cs
4,491
C#
using NUnit.Framework; namespace JetBlack.Sspi.Test { [TestFixture] public class SecurityContextFixture { [TestCase("Negotiate", SspiContextFlags.MutualAuth | SspiContextFlags.InitIdentify | SspiContextFlags.Confidentiality | SspiContextFlags.ReplayDetect | SspiContextFlags.SequenceDetect | SspiContextFlags.Connection | SspiContextFlags.Delegate)] public void Test(string packageName, SspiContextFlags contextFlags) { var clientCredential = new SecurityCredential(packageName, SecurityCredentialUse.Outbound); clientCredential.Acquire(); var serverCredential = new SecurityCredential(packageName, SecurityCredentialUse.Inbound); serverCredential.Acquire(); var clientContext = new SecurityContext(clientCredential, contextFlags); var serverContext = new SecurityContext(serverCredential, contextFlags); byte[] clientToken; clientContext.Initialize(serverCredential.PrincipalName, null, out clientToken); while (true) { byte[] serverToken; serverContext.AcceptToken(clientToken, out serverToken); if (serverContext.IsInitialized && clientContext.IsInitialized) break; clientContext.Initialize(serverCredential.PrincipalName, serverToken, out clientToken); if (clientContext.IsInitialized && serverContext.IsInitialized) break; } clientContext.Dispose(); serverContext.Dispose(); clientCredential.Dispose(); serverCredential.Dispose(); } } }
39.511628
251
0.662154
[ "MIT" ]
rob-blackbourn/JetBlack.Sspi
JetBlack.Sspi.Test/SecurityContextFixture.cs
1,701
C#
namespace NultienShop.DataAccess.Domain.Models { public class Article : BaseEntity { public int ArticleId { get; set; } public string ArticleName { get; set; } public int ArticlePrice { get; set; } } }
26.444444
47
0.630252
[ "MIT" ]
nubara300/shop-nultien
Server/NultienShop.Common.Models/Models/Article.cs
240
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateMember { internal abstract partial class AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax> where TSimpleNameSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode { protected AbstractGenerateMemberService() { } protected static readonly ISet<TypeKind> EnumType = new HashSet<TypeKind> { TypeKind.Enum }; protected static readonly ISet<TypeKind> ClassInterfaceModuleStructTypes = new HashSet<TypeKind> { TypeKind.Class, TypeKind.Module, TypeKind.Struct, TypeKind.Interface }; protected static bool ValidateTypeToGenerateIn( INamedTypeSymbol typeToGenerateIn, bool isStatic, ISet<TypeKind> typeKinds) { if (typeToGenerateIn == null) { return false; } if (typeToGenerateIn.IsAnonymousType) { return false; } if (!typeKinds.Contains(typeToGenerateIn.TypeKind)) { return false; } if (typeToGenerateIn.TypeKind == TypeKind.Interface && isStatic) { return false; } // TODO(cyrusn): Make sure that there is a totally visible part somewhere (i.e. // venus) that we can generate into. var locations = typeToGenerateIn.Locations; return locations.Any(loc => loc.IsInSource); } protected static bool TryDetermineTypeToGenerateIn( SemanticDocument document, INamedTypeSymbol containingType, TExpressionSyntax simpleNameOrMemberAccessExpression, CancellationToken cancellationToken, out INamedTypeSymbol typeToGenerateIn, out bool isStatic) { TryDetermineTypeToGenerateInWorker( document, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out typeToGenerateIn, out isStatic); if (typeToGenerateIn != null) { typeToGenerateIn = typeToGenerateIn.OriginalDefinition; } return typeToGenerateIn != null; } private static void TryDetermineTypeToGenerateInWorker( SemanticDocument semanticDocument, INamedTypeSymbol containingType, TExpressionSyntax expression, CancellationToken cancellationToken, out INamedTypeSymbol typeToGenerateIn, out bool isStatic) { typeToGenerateIn = null; isStatic = false; var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var semanticModel = semanticDocument.SemanticModel; if (syntaxFacts.IsSimpleMemberAccessExpression(expression)) { // Figure out what's before the dot. For VB, that also means finding out // what ".X" might mean, even when there's nothing before the dot itself. var beforeDotExpression = syntaxFacts.GetExpressionOfMemberAccessExpression( expression, allowImplicitTarget: true); if (beforeDotExpression != null) { DetermineTypeToGenerateInWorker( semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken); } return; } if (syntaxFacts.IsConditionalAccessExpression(expression)) { var beforeDotExpression = syntaxFacts.GetExpressionOfConditionalAccessExpression(expression); if (beforeDotExpression != null) { DetermineTypeToGenerateInWorker( semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken); if (typeToGenerateIn.IsNullable(out var underlyingType) && underlyingType is INamedTypeSymbol underlyingNamedType) { typeToGenerateIn = underlyingNamedType; } } return; } if (syntaxFacts.IsPointerMemberAccessExpression(expression)) { var beforeArrowExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression); if (beforeArrowExpression != null) { var typeInfo = semanticModel.GetTypeInfo(beforeArrowExpression, cancellationToken); if (typeInfo.Type.IsPointerType()) { typeToGenerateIn = ((IPointerTypeSymbol)typeInfo.Type).PointedAtType as INamedTypeSymbol; isStatic = false; } } return; } if (syntaxFacts.IsAttributeNamedArgumentIdentifier(expression)) { var attributeNode = expression.GetAncestors().FirstOrDefault(syntaxFacts.IsAttribute); var attributeName = syntaxFacts.GetNameOfAttribute(attributeNode); var attributeType = semanticModel.GetTypeInfo(attributeName, cancellationToken); typeToGenerateIn = attributeType.Type as INamedTypeSymbol; isStatic = false; return; } if (syntaxFacts.IsObjectInitializerNamedAssignmentIdentifier( expression, out var initializedObject)) { typeToGenerateIn = semanticModel.GetTypeInfo(initializedObject, cancellationToken).Type as INamedTypeSymbol; isStatic = false; return; } else if (syntaxFacts.IsNameOfSubpattern(expression)) { var propertyPatternClause = expression.Ancestors().FirstOrDefault(syntaxFacts.IsPropertyPatternClause); if (propertyPatternClause != null) { // something like: { [|X|]: int i } or like: Blah { [|X|]: int i } var inferenceService = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); typeToGenerateIn = inferenceService.InferType(semanticModel, propertyPatternClause, objectAsDefault: true, cancellationToken) as INamedTypeSymbol; isStatic = false; return; } } // Generating into the containing type. typeToGenerateIn = containingType; isStatic = syntaxFacts.IsInStaticContext(expression); } private static void DetermineTypeToGenerateInWorker( SemanticModel semanticModel, SyntaxNode expression, out INamedTypeSymbol typeToGenerateIn, out bool isStatic, CancellationToken cancellationToken) { var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); var semanticInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); typeToGenerateIn = typeInfo.Type is ITypeParameterSymbol typeParameter ? typeParameter.GetNamedTypeSymbolConstraint() : typeInfo.Type as INamedTypeSymbol; isStatic = semanticInfo.Symbol is INamedTypeSymbol; } } }
39.381188
166
0.604777
[ "MIT" ]
BrianFreemanAtlanta/roslyn
src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs
7,957
C#
/* Generated by QSI Date: 2020-08-12 Span: 2830:1 - 2838:24 File: src/postgres/include/nodes/parsenodes.h */ using Qsi.PostgreSql.Internal.Serialization; namespace Qsi.PostgreSql.Internal.PG10.Types { [PgNode("AlterObjectSchemaStmt")] internal class AlterObjectSchemaStmt : IPg10Node { public virtual NodeTag Type => NodeTag.T_AlterObjectSchemaStmt; public ObjectType? objectType { get; set; } public RangeVar[] relation { get; set; } public IPg10Node[] @object { get; set; } public string newschema { get; set; } public bool? missing_ok { get; set; } } }
21.793103
71
0.666139
[ "MIT" ]
ScriptBox99/chequer-qsi
Qsi.PostgreSql/Internal/PG10/Types/AlterObjectSchemaStmt.cs
632
C#
using System; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using TableStorageClient.Interfaces; namespace TableStorageClient.Classes { public class TableOperations<T>:ITableOperations<T> where T: TableEntity { public CloudTable Table { get; set; } public TableOperations(string tableName, string connectionString) { Table = CommonTasks.GetOrCreateTableAsync(tableName, connectionString).Result; } public async Task InsertOrReplaceEntityAsync(T entity) { var insertOrReplaceOperation = TableOperation.InsertOrReplace(entity); await Table.ExecuteAsync(insertOrReplaceOperation); } } }
31.26087
90
0.710709
[ "MIT" ]
akuryan/self-hosted-azure-devops-agents
autoscalingApp/AgentsMonitor/TableStorageClient/Classes/TableOperations.cs
721
C#
using Assets.Tools.Script.Attributes; using System; namespace XQ.ProjectX.Config { public class TaskAddSceneElementToScene { [InspectorStyle("SceneId", "GameSceneIdSelector")] public string SceneId = string.Empty; [InspectorStyle("NPCId", "SceneElementIdSelector")] public string ElementId = string.Empty; } }
21.533333
53
0.767802
[ "MIT" ]
moto2002/kaituo_src
src/XQ.ProjectX.Config/TaskAddSceneElementToScene.cs
323
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AH.Shared.MODEL; namespace AH.DRUGS.MODEL { public class DrugCompany { public string ID { set; get; } public string Name { set; get; } public string NameBeng { set; get; } public string Address { set; get; } public string Web { set; get; } public string Phone { set; get; } public string Fax { set; get; } public string Email { set; get; } public string Remarks { set; get; } public EntryParameter EntryParameter { set; get; } } }
25.92
58
0.62037
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.DRUGS/MODEL/DrugCompany.cs
650
C#
using Newtonsoft.Json; using R6Api.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace R6Api.Models { /// <summary> /// Ranked Data for AS Region for Rainbow6 /// </summary> public class RankedAS : IRegionRanked { /// <inheritdoc/> [JsonProperty("AS_kills")] public int Kills { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_deaths")] public int Deaths { get; internal set; } /// <inheritdoc/> [JsonProperty("_wins")] public int Wins { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_losses")] public int Losses { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_abandons")] public int Abandons { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_maxmmr")] public int MaxMmr { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_champ")] public int Champ { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_mmrchange")] public int MmrChange { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_actualmmr")] public int ActualMmr { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_matches")] public int Matches { get; internal set; } [JsonProperty("AS_wl")] internal string _winLose { get; set; } /// <inheritdoc/> [JsonIgnore] public double WinLose { get { return Convert.ToDouble(_winLose.Remove(_winLose.Length - 1)); } } [JsonProperty("AS_kd")] internal string _kd { get; set; } /// <inheritdoc/> [JsonIgnore] public double KillDeath { get { return Convert.ToDouble(_kd); } } /// <inheritdoc/> [JsonProperty("AS_rank")] public int Rank { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_rankname")] public string RankName { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_maxrank")] public int MaxRank { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_maxrankname")] public string MaxRankName { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_killpermatch")] public double KillPerMatch { get; internal set; } /// <inheritdoc/> [JsonProperty("AS_deathspermatch")] public double DeathPerMatch { get; internal set; } /// <summary> /// Get Rank Banner for the Player's Current Rank /// </summary> /// <returns>Url of the Banner Img</returns> public string GetRankImg () { return $"https://cdn.tab.one/r6/images/ranks/?rank={Rank}&champ={Champ}"; } } }
25.614583
76
0.655144
[ "MIT" ]
Cenngo/R6Tab.NET
R6TabApiWrapper/Models/Ranked/RankedAS.cs
2,461
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type MobileAppContentContainedAppsCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class MobileAppContentContainedAppsCollectionResponse { /// <summary> /// Gets or sets the <see cref="IMobileAppContentContainedAppsCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)] public IMobileAppContentContainedAppsCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
41.558824
153
0.624912
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/MobileAppContentContainedAppsCollectionResponse.cs
1,413
C#
using System; using System.Security.Cryptography; using Newtonsoft.Json; namespace CryptoShredding.Serialization.JsonConverters; public class EncryptionJsonConverter : JsonConverter { private readonly ICryptoTransform _encryptor; private readonly FieldEncryptionDecryption _fieldEncryptionDecryption; public EncryptionJsonConverter( ICryptoTransform encryptor, FieldEncryptionDecryption fieldEncryptionDecryption) { _encryptor = encryptor; _fieldEncryptionDecryption = fieldEncryptionDecryption; } public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { var result = _fieldEncryptionDecryption.GetEncryptedOrDefault(value, _encryptor); writer.WriteValue(result); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return true; } public override bool CanRead => false; public override bool CanWrite => true; }
29.425
136
0.750212
[ "MIT" ]
EventStore/samples
Crypto_Shredding/.NET/src/CryptoShredding/Serialization/JsonConverters/EncryptionJsonConverter.cs
1,177
C#
using EngineeringWork.Core.Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace EngineeringWork.Repository.Configuration { public class DailyRouteEntityTypeConfiguration : IEntityTypeConfiguration<DailyRoute> { public void Configure(EntityTypeBuilder<DailyRoute> builder) { builder.OwnsOne(x => x.MoneyValue); } } }
30.071429
89
0.750594
[ "MIT" ]
piratezxe/Engineering
src/EngineeringWork.Repository/Configuration/DailyRouteEntityTypeConfiguration.cs
421
C#
namespace System.Windows.Controls { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; internal class InputEventRouter : IDisposable { protected TreeViewEx treeView; private List<InputSubscriberBase> inputSubscribers; private bool isLeftMouseButtonDown; private Point mouseDownPoint; public InputEventRouter(TreeViewEx treeView) { inputSubscribers = new List<InputSubscriberBase>(2); this.treeView = treeView; treeView.MouseDown += OnMouseDown; treeView.MouseMove += OnMouseMove; treeView.MouseUp += OnMouseUp; treeView.ScrollViewer.ScrollChanged += OnScrollChanged; } void OnScrollChanged(object sender, ScrollChangedEventArgs e) { Call("OnScrollChanged", e); } internal void Add(InputSubscriberBase inputSubscriber) { inputSubscriber.TreeView = treeView; inputSubscribers.Add(inputSubscriber); inputSubscriber.Initialized(); } private void OnMouseDown(object sender, MouseButtonEventArgs e) { Mouse.Capture(treeView, CaptureMode.SubTree); isLeftMouseButtonDown = true; mouseDownPoint = e.GetPosition(treeView); Call("OnMouseDown", e); } private void Call(string methodName, object e) { foreach (var inputSubscriber in inputSubscribers) { // initialize provider inputSubscriber.IsLeftButtonDown = isLeftMouseButtonDown; // Debug.WriteLine("Calling " + methodName + " on " + inputSubscriber.GetType()); MethodInfo methodInfo = typeof(InputSubscriberBase).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); methodInfo.Invoke(inputSubscriber, new object[] { e }); RoutedEventArgs re = e as RoutedEventArgs; if (re != null && re.Handled) break; } // Debug.WriteLine(DateTime.Now.Millisecond + " -----------------------------"); } private void OnMouseMove(object sender, MouseEventArgs e) { isLeftMouseButtonDown = e.LeftButton == MouseButtonState.Pressed; Call("OnMouseMove", e); } private void OnMouseUp(object sender, MouseButtonEventArgs e) { Call("OnMouseUp", e); isLeftMouseButtonDown = false; Mouse.Capture(null); } public void Dispose() { if (treeView != null) { treeView.MouseDown -= OnMouseDown; treeView.MouseMove -= OnMouseMove; treeView.MouseUp -= OnMouseUp; treeView.ScrollViewer.ScrollChanged -= OnScrollChanged; treeView = null; } if (inputSubscribers != null) { inputSubscribers.Clear(); inputSubscribers = null; } GC.SuppressFinalize(this); } } }
31.228571
138
0.577615
[ "MIT" ]
dotnetprojects/TreeViewEx
TreeViewEx/Controls/InputEventRouter.cs
3,281
C#
using System.Net.Security; using System.Text; using Lib.Socket.Server.Models; namespace DotNetCore.SslSocket.Server.Models { /// <summary> /// Socket state object /// </summary> public class SslStreamState : IStateObject { /// <summary> /// Client Socket /// </summary> public SslStream SslStream = null; private const int FixedBufferSize = 1024; /// <summary> /// Constructor /// </summary> public SslStreamState() { this.Buffer = new byte[this.BufferSize]; this.Content = new StringBuilder(); } /// <summary> /// Size of receive buffer /// </summary> public int BufferSize { get { return FixedBufferSize; } } /// <summary> /// Receive buffer /// </summary> public byte[] Buffer { get; set; } /// <summary> /// Received data string /// </summary> public StringBuilder Content { get; set; } } }
22.595745
52
0.518832
[ "MIT" ]
KarateJB/DotNetCore.Socket.Sample
src/DotNetCore.SslSocket.Server/Models/SslStreamState.cs
1,064
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace io.vertx.core.eventbus.impl { class Handlers<T> { private int pos; public readonly List<T> List = new List<T>(); public T Choose() { while (true) { int size = this.List.Count; if (size == 0) { return (T)(object)null; } int p = Interlocked.Increment(ref this.pos); if (p >= size - 1) { p = 0; } try { return this.List[p]; } catch (ArgumentOutOfRangeException) { this.pos = 0; } } } } }
21.047619
60
0.376697
[ "Apache-2.0" ]
bicorz/vertx-eventbus
src/core/eventbus/impl/Handlers.cs
886
C#
using HADES.Util; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace HADES.Controllers { public class DocumentationController : Controller { [Authorize] public IActionResult Documentation() { if (!ConnexionUtil.CurrentUser(this.User).GetRole().AppConfigAccess) // ACCESS CONTROL { return RedirectToAction("MainView", "Home"); } return View(); } } }
24.45
98
0.615542
[ "MIT" ]
mikeyX101/HADES
HADES/Controllers/DocumentationController.cs
491
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Linq; using Python.Runtime; using QuantConnect.Logging; namespace QuantConnect.Python { /// <summary> /// Helper class for Python initialization /// </summary> public static class PythonInitializer { // Used to allow multiple Python unit and regression tests to be run in the same test run private static bool _isBeginAllowThreadsCalled; /// <summary> /// Initialize the Python.NET library /// </summary> public static void Initialize() { if (!_isBeginAllowThreadsCalled) { Log.Trace("PythonInitializer.Initialize(): start..."); PythonEngine.Initialize(); // required for multi-threading usage PythonEngine.BeginAllowThreads(); _isBeginAllowThreadsCalled = true; Log.Trace("PythonInitializer.Initialize(): ended"); } } /// <summary> /// Adds directories to the python path at runtime /// </summary> public static void AddPythonPaths(IEnumerable<string> paths) { if (_isBeginAllowThreadsCalled) { using (Py.GIL()) { var code = string.Join(";", paths.Select(s => $"sys.path.append('{s}')")); PythonEngine.Exec($"import sys;{code}"); } } } } }
33.257576
97
0.615034
[ "Apache-2.0" ]
FrancisChung/Lean
Common/Python/PythonInitializer.cs
2,197
C#
using System; using System.Runtime.InteropServices; #pragma warning disable 0649 namespace Swifter.Tools { [StructLayout(LayoutKind.Sequential)] internal struct FieldHandleStruct { public readonly IntPtr Handle; public readonly ushort Index; public readonly ushort Flag; public readonly ushort Offset; } }
21
41
0.708683
[ "MIT" ]
BenLampson/Swifter.Json
Swifter.Core/Tools/Type/FieldHandleInfo.cs
359
C#
#region Copyright & License /* Copyright (c) 2022, Integrated Solutions, 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. * Neither the name of the Integrated Solutions, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ISI.Extensions.Extensions; using DTOs = ISI.Extensions.VisualStudio.DataTransferObjects.SolutionApi; using Microsoft.Extensions.Logging; namespace ISI.Extensions.VisualStudio { public partial class SolutionApi { public DTOs.GetSolutionLockResponse GetSolutionLock(DTOs.GetSolutionLockRequest request) { var response = new DTOs.GetSolutionLockResponse(); var logger = new AddToLogLogger(request.AddToLog, Logger); var solutionDirectory = SourceControlClientApi.GetRootDirectory(new ISI.Extensions.Scm.DataTransferObjects.SourceControlClientApi.GetRootDirectoryRequest() { FullName = request.SolutionFullName, }).FullName; if (string.IsNullOrWhiteSpace(solutionDirectory)) { solutionDirectory = System.IO.Path.GetFullPath(request.SolutionFullName); } response.Lock = new ISI.Extensions.Locks.FileLock(solutionDirectory, onWaitingForLock: () => logger.LogInformation("Waiting for Solution Lock"), onCreatingLock: lockFileName => logger.LogInformation("Creating Solution lock: \"{0}\"", lockFileName)); return response; } } }
55
754
0.800727
[ "BSD-3-Clause" ]
ISI-Extensions/ISI.Extensions
src/ISI.Extensions.VisualStudio/SolutionApi/GetSolutionLock.cs
2,750
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 iam-2010-05-08.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.IdentityManagement.Model { ///<summary> /// IdentityManagementService exception /// </summary> public class EntityAlreadyExistsException : AmazonIdentityManagementServiceException { /// <summary> /// Constructs a new EntityAlreadyExistsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public EntityAlreadyExistsException(string message) : base(message) {} public EntityAlreadyExistsException(string message, Exception innerException) : base(message, innerException) {} public EntityAlreadyExistsException(Exception innerException) : base(innerException) {} public EntityAlreadyExistsException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, RequestId, statusCode) {} public EntityAlreadyExistsException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, RequestId, statusCode) {} } }
39.396226
170
0.693008
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.IdentityManagement/Model/EntityAlreadyExistsException.cs
2,088
C#
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.VisualStudio.TestTools.Common; using Microsoft.VisualStudio.TestTools.Vsip; using System.Diagnostics; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace Microsoft.VisualStudio.TestTools.HostAdapters.VsIde { /// <summary> /// UI control for my host adapter configuartion. Hosted inside test run config editor. /// It contains a data grid view where you could define environment variables. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs", Justification = "Public class, cannot rename")] public sealed partial class VsIdeHostAdapterRunConfigControl : UserControl, IRunConfigurationCustomHostEditor { #region Private private VsIdeHostRunConfigData m_data; #endregion #region Constructor public VsIdeHostAdapterRunConfigControl() { InitializeComponent(); } #endregion #region IRunConfigurationEditor /// <summary> /// Initialize the editor to a default state based on given test run. /// </summary> /// <param name="serviceProvider"></param> /// <param name="run">Obselete. Always null.</param> void IRunConfigurationEditor.Initialize(System.IServiceProvider serviceProvider, TestRun run) { // Initialize to something like: 7.0, 7.1, 8.0 foreach (string version in VSRegistry.GetVersions()) { m_hiveCombo.Items.Add(version); } } /// <summary> /// Fire this event when data is modified in this editor. /// </summary> public event EventHandler DataGetDirty; /// <summary> /// Handle the event that core (non-host and not-test-specific) run config data are modified outside this editor. /// </summary> /// <param name="sender"></param> /// <param name="dirtyEventArgs">contains run config object that is changed outside</param> void IRunConfigurationEditor.OnCommonDataDirty(object sender, CommonRunConfigurationDirtyEventArgs dirtyEventArgs) { // Our test config does not depend on other data contained in the run config // but for the case when nobody modifies our config we still want to have our default section in RC, // that's why when the user switches hosts to VS IDE and we did not exist we say we are dirty, and get data will return our data. if (m_data == null) { SetDirty(); // Select 1st item if (m_hiveCombo.SelectedIndex < 0) { m_hiveCombo.SelectedItem = VSRegistry.GetDefaultVersion(); } } } /// <summary> /// Desciption about this editor is displayed in the help panel of main run config editor. /// </summary> string IRunConfigurationEditor.Description { get { return Resources.HostAdapterDescription; } } /// <summary> /// The keyword that is hooked up with the help topic. /// </summary> string IRunConfigurationEditor.HelpKeyword { get { return string.Empty; } } /// <summary> /// Verify the data in the editor. Prompt the user when neccessary. /// </summary> /// <returns>true if the data are correct and don't need correction; otherwise, false.</returns> bool IRunConfigurationEditor.VerifyData() { return true; } #endregion #region IRunConfigurationCustomHostEditor /// <summary> /// The host adapter type that this editor is used for. /// </summary> string IRunConfigurationCustomHostEditor.HostType { get { return VsIdeHostAdapter.Name; } } /// <summary> /// Called by the main editor to load the data into UI. /// </summary> /// <param name="data">host specific data</param> [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")] // TODO: should we care about rightAlign? -- no unless we ship this HA. void IRunConfigurationCustomHostEditor.SetData(IHostSpecificRunConfigurationData data) { string currentVersion = VSRegistry.GetDefaultVersion(); // Throws if VS is not installed. VsIdeHostRunConfigData vsIdeHostData = data as VsIdeHostRunConfigData; if (vsIdeHostData == null) { vsIdeHostData = new VsIdeHostRunConfigData(currentVersion); // TODO: SetDirty() that set run config to dirty is disabled in parent during Initialize/SetData, so this makes no effect. SetDirty(); } else if (!m_hiveCombo.Items.Contains(vsIdeHostData.RegistryHive)) { // If .testrunconfig file has VS version that we do not have in combobox, // show message box and use default version. MessageBox.Show( this, Resources.WrongVSVersionPassedToRunConfigControl(vsIdeHostData.RegistryHive, currentVersion), Resources.MicrosoftVisualStudio); vsIdeHostData.RegistryHive = currentVersion; // TODO: SetDirty() that set run config to dirty is disabled in parent during Initialize/SetData, so this makes no effect. SetDirty(); } // Set the data. m_data = vsIdeHostData; int selectedIndex = m_hiveCombo.Items.IndexOf(vsIdeHostData.RegistryHive); if (selectedIndex < 0) { selectedIndex = m_hiveCombo.Items.IndexOf(currentVersion); Debug.Assert(selectedIndex >= 0); } if (selectedIndex >= 0) { m_hiveCombo.SelectedIndex = selectedIndex; } m_additionalCommandLineArgumentsEdit.Text = vsIdeHostData.AdditionalCommandLineArguments; m_additionalTestDataEdit.Text = vsIdeHostData.AdditionalTestData; } /// <summary> /// Main editor is asking for the current host specific data. /// </summary> /// <returns></returns> IHostSpecificRunConfigurationData IRunConfigurationCustomHostEditor.GetData() { if (m_data == null) { m_data = new VsIdeHostRunConfigData(VSRegistry.GetDefaultVersion()); } m_data.AdditionalCommandLineArguments = m_additionalCommandLineArgumentsEdit.Text; m_data.AdditionalTestData = m_additionalTestDataEdit.Text; return m_data; } #endregion #region Private private void SetDirty() { if (DataGetDirty != null) { DataGetDirty(this, EventArgs.Empty); } } private void HiveCombo_SelectedIndexChanged(object sender, EventArgs e) { Debug.Assert(m_data != null); // Set internal data from combo box. if (m_hiveCombo.SelectedItem != null && m_data != null) { string selectedHive = m_hiveCombo.SelectedItem.ToString(); if (!string.Equals(m_data.RegistryHive, selectedHive, StringComparison.OrdinalIgnoreCase)) { m_data.RegistryHive = selectedHive; SetDirty(); } } } private void AdditionalCommandLineArgumentsEdit_TextChanged(object sender, EventArgs e) { SetDirty(); // Note: we set the data the text when we get data from the control, there's no need to that here. } private void m_additionalTestDataEdit_TextChanged(object sender, EventArgs e) { SetDirty(); // Note: we set the data the text when we get data from the control, there's no need to that here. } #endregion } }
38.165919
159
0.600752
[ "Apache-2.0" ]
Cireson/EntityFramework6
tools/VsIdeHostAdapter/TargetAddIn/HostSide/VsIdeHostAdapterRunConfigControl.cs
8,511
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Abstractions.Models; using BTCPayServer.Models; using BTCPayServer.Models.ServerViewModels; using BTCPayServer.Storage.Models; using BTCPayServer.Storage.Services.Providers.AmazonS3Storage; using BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration; using BTCPayServer.Storage.Services.Providers.AzureBlobStorage; using BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration; using BTCPayServer.Storage.Services.Providers.FileSystemStorage; using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration; using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage; using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration; using BTCPayServer.Storage.Services.Providers.Models; using BTCPayServer.Storage.ViewModels; using BTCPayServer.Views; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Newtonsoft.Json.Linq; namespace BTCPayServer.Controllers { public partial class ServerController { [HttpGet("server/files/{fileId?}")] public async Task<IActionResult> Files(string fileId = null) { var fileUrl = string.IsNullOrEmpty(fileId) ? null : await _FileService.GetFileUrl(Request.GetAbsoluteRootUri(), fileId); var model = new ViewFilesViewModel() { Files = await _StoredFileRepository.GetFiles(), SelectedFileId = string.IsNullOrEmpty(fileUrl) ? null : fileId, DirectFileUrl = fileUrl, StorageConfigured = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) != null }; return View(model); } [HttpGet("server/files/{fileId}/delete")] public async Task<IActionResult> DeleteFile(string fileId) { try { await _FileService.RemoveFile(fileId, null); return RedirectToAction(nameof(Files), new { fileId = "", statusMessage = "File removed" }); } catch (Exception e) { TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = e.Message }); return RedirectToAction(nameof(Files)); } } [HttpGet("server/files/{fileId}/tmp")] public async Task<IActionResult> CreateTemporaryFileUrl(string fileId) { var file = await _StoredFileRepository.GetFile(fileId); if (file == null) { return NotFound(); } return View(new CreateTemporaryFileUrlViewModel()); } [HttpPost("server/files/{fileId}/tmp")] public async Task<IActionResult> CreateTemporaryFileUrl(string fileId, CreateTemporaryFileUrlViewModel viewModel) { if (viewModel.TimeAmount <= 0) { ModelState.AddModelError(nameof(viewModel.TimeAmount), "Time must be at least 1"); } if (!ModelState.IsValid) { return View(viewModel); } var file = await _StoredFileRepository.GetFile(fileId); if (file == null) { return NotFound(); } var expiry = DateTimeOffset.UtcNow; switch (viewModel.TimeType) { case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Seconds: expiry = expiry.AddSeconds(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Minutes: expiry = expiry.AddMinutes(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Hours: expiry = expiry.AddHours(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Days: expiry = expiry.AddDays(viewModel.TimeAmount); break; default: throw new ArgumentOutOfRangeException(); } var url = await _FileService.GetTemporaryFileUrl(Request.GetAbsoluteRootUri(), fileId, expiry, viewModel.IsDownload); TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Success, Html = $"Generated Temporary Url for file {file.FileName} which expires at {expiry.ToBrowserDate()}. <a href='{url}' target='_blank'>{url}</a>" }); return RedirectToAction(nameof(Files), new { fileId }); } public class CreateTemporaryFileUrlViewModel { public enum TmpFileTimeType { Seconds, Minutes, Hours, Days } public int TimeAmount { get; set; } public TmpFileTimeType TimeType { get; set; } public bool IsDownload { get; set; } } [HttpPost("server/files/upload")] public async Task<IActionResult> CreateFile(IFormFile file) { if (!file.FileName.IsValidFileName()) { this.TempData.SetStatusMessageModel(new StatusMessageModel() { Message = "Invalid file name", Severity = StatusMessageModel.StatusSeverity.Error }); return RedirectToAction(nameof(Files)); } var newFile = await _FileService.AddFile(file, GetUserId()); return RedirectToAction(nameof(Files), new { statusMessage = "File added!", fileId = newFile.Id }); } private string GetUserId() { return _UserManager.GetUserId(ControllerContext.HttpContext.User); } [HttpGet("server/storage")] public async Task<IActionResult> Storage(bool forceChoice = false) { var savedSettings = await _SettingsRepository.GetSettingAsync<StorageSettings>(); if (forceChoice || savedSettings == null) { var providersList = _StorageProviderServices.Select(a => new SelectListItem(a.StorageProvider().ToString(), a.StorageProvider().ToString()) ); return View(new ChooseStorageViewModel() { ProvidersList = providersList, ShowChangeWarning = savedSettings != null, Provider = savedSettings?.Provider ?? BTCPayServer.Storage.Models.StorageProvider.FileSystem }); } return RedirectToAction(nameof(StorageProvider), new { provider = savedSettings.Provider }); } [HttpPost("server/storage")] public IActionResult Storage(StorageSettings viewModel) { return RedirectToAction("StorageProvider", "Server", new { provider = viewModel.Provider.ToString() }); } [HttpGet("server/storage/{provider}")] public async Task<IActionResult> StorageProvider(string provider) { if (!Enum.TryParse(typeof(StorageProvider), provider, out var storageProvider)) { TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = $"{provider} provider is not supported" }); return RedirectToAction(nameof(Storage)); } var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings(); var storageProviderService = _StorageProviderServices.SingleOrDefault(service => service.StorageProvider().Equals(storageProvider)); switch (storageProviderService) { case null: TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = $"{storageProvider} is not supported" }); return RedirectToAction(nameof(Storage)); case AzureBlobStorageFileProviderService fileProviderService: return View(nameof(EditAzureBlobStorageStorageProvider), fileProviderService.GetProviderConfiguration(data)); case AmazonS3FileProviderService fileProviderService: return View(nameof(EditAmazonS3StorageProvider), fileProviderService.GetProviderConfiguration(data)); case GoogleCloudStorageFileProviderService fileProviderService: return View(nameof(EditGoogleCloudStorageStorageProvider), fileProviderService.GetProviderConfiguration(data)); case FileSystemFileProviderService fileProviderService: if (data.Provider != BTCPayServer.Storage.Models.StorageProvider.FileSystem) { _ = await SaveStorageProvider(new FileSystemStorageConfiguration(), BTCPayServer.Storage.Models.StorageProvider.FileSystem); } return View(nameof(EditFileSystemStorageProvider), fileProviderService.GetProviderConfiguration(data)); } return NotFound(); } [HttpPost("server/storage/AzureBlobStorage")] public async Task<IActionResult> EditAzureBlobStorageStorageProvider(AzureBlobStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AzureBlobStorage); } [HttpPost("server/storage/AmazonS3")] public async Task<IActionResult> EditAmazonS3StorageProvider(AmazonS3StorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AmazonS3); } [HttpPost("server/storage/GoogleCloudStorage")] public async Task<IActionResult> EditGoogleCloudStorageStorageProvider( GoogleCloudStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.GoogleCloudStorage); } [HttpPost("server/storage/FileSystem")] public async Task<IActionResult> EditFileSystemStorageProvider(FileSystemStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.FileSystem); } private async Task<IActionResult> SaveStorageProvider(IBaseStorageConfiguration viewModel, StorageProvider storageProvider) { if (!ModelState.IsValid) { return View(viewModel); } var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings(); data.Provider = storageProvider; data.Configuration = JObject.FromObject(viewModel); await _SettingsRepository.UpdateSetting(data); TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Success, Message = "Storage settings updated successfully" }); return View(viewModel); } } }
40.078431
159
0.603311
[ "MIT" ]
AlesioKanani/btcpayserver
BTCPayServer/Controllers/ServerController.Storage.cs
12,264
C#
using UnityEngine; namespace KDGame.Base { // 通用单例类 public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T> { private static T _instance = null; public static T Instance { get { if (_instance == null) return null; return _instance; } } private void Awake() { OnAwake(); } protected virtual void OnAwake() { _instance = this as T; } protected virtual void OnDestroy() { } } }
19.470588
77
0.429003
[ "Apache-2.0" ]
Kerydic/AssetDemo
Assets/Scripts/Base/MonoSingleton.cs
674
C#
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using IdSort.Properties; using IdSort.Restructure; namespace IdSort { public partial class MainForm : Form { /// <summary> /// Current workspace. /// </summary> public Workspace Workspace = new(); public bool ShowStaging { get => _showStaging; set { if (value == _showStaging) return; _showStaging = value; previewFileRestructureCheckBox.Checked = _showStaging; ReloadCurrent(); } } private bool _showStaging; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { restructureControl.RequestPreviewRestructure += (o, args) => { Restructurer.Restructure(Workspace, args.Settings, out var results); bool needReload = ShowStaging; // we must reload if show staging is already enabled ShowStaging = true; if (needReload) ReloadCurrent(); }; currentTreeView.ImageList = new ImageList(); currentTreeView.ImageList.Images.Add("default", Resources.blank_treeview_node); currentTreeView.ImageList.Images.Add("file", Resources.file_solid); currentTreeView.ImageList.Images.Add("bad_file", Resources.times_solid); currentTreeView.ImageList.Images.Add("ok_file", Resources.dash_solid); currentTreeView.ImageList.Images.Add("good_file", Resources.check_solid); currentTreeView.ImageList.Images.Add("great_file", Resources.check_double_solid); currentTreeView.ImageList.Images.Add("corrupt_file", Resources.exclamation_triangle_solid); currentTreeView.ImageList.Images.Add("folder", Resources.folder); } public void ReloadCurrent() { if (Workspace == null) throw new Exception("No workspace loaded"); object previousTopNodeVal = null; if (currentTreeView.TopNode is ObjectSelectorEditor.SelectorNode previousTopNode) previousTopNodeVal = previousTopNode.value; object previousSelectedNodeVal = null; if (currentTreeView.SelectedNode is ObjectSelectorEditor.SelectorNode previousSelectedNode) previousSelectedNodeVal = previousSelectedNode.value; // Build treeview Workspace.BuildTreeView(currentTreeView, ShowStaging); TreeNode selectNode = currentTreeView.GetAllNodes().FirstOrDefault(n => n is ObjectSelectorEditor.SelectorNode node && node.value == previousSelectedNodeVal); TreeNode topNode = currentTreeView.GetAllNodes().FirstOrDefault(n => n is ObjectSelectorEditor.SelectorNode node && node.value == previousTopNodeVal); if (selectNode != null) { currentTreeView.SelectedNode = selectNode; currentTreeView.Select(); currentTreeView.AutoScrollOffset = new Point(0, currentTreeView.AutoScrollOffset.Y); } else { fileInfoControl.SetFile(null); } if (topNode != null) { currentTreeView.TopNode = topNode; } else { currentTreeView.Nodes[0].EnsureVisible(); } // Update status bar statusBarFilesLoaded.Text = $"{Workspace.TotalMusicFiles} audio files ({Workspace.TotalCorruptedFiles} corrupted)"; } private void openToolStripMenuItem_Click(object sender, EventArgs e) { new Importer(workspace => { Workspace = workspace; ReloadCurrent(); }).ShowDialog(); } private void currentTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { currentTreeView.SelectedNode = e.Node; if (e.Node is ObjectSelectorEditor.SelectorNode selectorNode) { if (e.Button == MouseButtons.Right) { var context = new ContextMenuStrip(); if (selectorNode.value is IContextMenu contextMenu) { foreach (var item in contextMenu.GetContextMenuItems()) context.Items.Add(item); } if (context.Items.Count == 0) return; // No context menu items context.Show(Cursor.Position); } } } private void previewFileRestructureCheckBox_CheckedChanged_1(object sender, EventArgs e) { ShowStaging = previewFileRestructureCheckBox.Checked; } private void currentTreeView_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node is ObjectSelectorEditor.SelectorNode selectorNode) { if (selectorNode.value is GenericFile file) { fileInfoControl.SetFile(file); } } } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new AboutForm().ShowDialog(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void commitChangesToolStripMenuItem_Click(object sender, EventArgs e) { var plan = Workspace.Plan(); if (plan.Operations.Count == 0) { MessageBox.Show("No changes staged.", "IdSort", MessageBoxButtons.OK, MessageBoxIcon.None); return; } if (MessageBox.Show("Are you sure you want commit your changes to disk?\n\nYou will be able to undo these changes later.", "IdSort", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; var form = new RestructuringForm(plan); form.Success += (o, args) => { Workspace.ApplyStagedChanges(); ReloadCurrent(); }; form.ShowDialog(); } private void revertToolStripMenuItem_Click(object sender, EventArgs e) { string revertFilePath = Workspace.RootPath + Path.DirectorySeparatorChar + "revert.idsort"; if (!File.Exists(revertFilePath)) { MessageBox.Show($"No revert data exists for this folder. Has \"{Plan.RevertFileName}\" been misplaced?", "IdSort", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (MessageBox.Show("Are you sure you want to revert the last sort?", "IdSort", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; var plan = Plan.Load(revertFilePath); new RestructuringForm(plan, true).ShowDialog(); } } }
35.843902
215
0.579205
[ "MIT" ]
mitchfizz05/IdSort
IdSort/MainForm.cs
7,350
C#
namespace Shop.Module.Core.Abstractions.Models { public enum MediaType { Image = 0, Video = 1, File = 2 } }
14.5
47
0.531034
[ "MIT" ]
cn-cam/module-shop
src/server/src/Modules/Shop.Module.Core.Abstractions/Models/MediaType.cs
147
C#
using System; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using PcapDotNet.Packets.Transport; namespace PcapDotNet.Core.Test { internal class WiresharkDatagramComparerUdp : WiresharkDatagramComparer { protected override string PropertyName { get { return "Udp"; } } protected override bool CompareField(XElement field, Datagram parentDatagram, Datagram datagram) { IpV4Datagram ipV4Datagram = (IpV4Datagram)parentDatagram; UdpDatagram udpDatagram = (UdpDatagram)datagram; switch (field.Name()) { case "udp.srcport": field.AssertShowDecimal(udpDatagram.SourcePort); break; case "udp.dstport": field.AssertShowDecimal(udpDatagram.DestinationPort); break; case "udp.port": Assert.IsTrue(ushort.Parse(field.Show()) == udpDatagram.SourcePort || ushort.Parse(field.Show()) == udpDatagram.DestinationPort); break; case "udp.length": field.AssertShowDecimal(udpDatagram.TotalLength); break; case "udp.checksum": field.AssertShowHex(udpDatagram.Checksum); if (udpDatagram.Checksum != 0) { foreach (var checksumField in field.Fields()) { switch (checksumField.Name()) { case "udp.checksum_good": checksumField.AssertShowDecimal(ipV4Datagram.IsTransportChecksumCorrect); break; case "udp.checksum_bad": if (checksumField.Show() == "1") Assert.IsFalse(ipV4Datagram.IsTransportChecksumCorrect); else checksumField.AssertShowDecimal(0); break; } } } break; case "udp.checksum_coverage": field.AssertShowDecimal(udpDatagram.TotalLength); break; default: throw new InvalidOperationException("Invalid udp field " + field.Name()); } return true; } } }
36.306667
109
0.47668
[ "BSD-3-Clause" ]
okaywang/MyPcap
PcapDotNet/src/PcapDotNet.Core.Test/WiresharkDatagramComparerUdp.cs
2,725
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Metadata; namespace Microsoft.Data.Entity.SqlServer.Metadata { public class ReadOnlySqlServerKeyExtensions : ReadOnlyRelationalKeyExtensions, ISqlServerKeyExtensions { protected const string SqlServerNameAnnotation = SqlServerAnnotationNames.Prefix + RelationalAnnotationNames.Name; protected const string SqlServerClusteredAnnotation = SqlServerAnnotationNames.Prefix + SqlServerAnnotationNames.Clustered; public ReadOnlySqlServerKeyExtensions([NotNull] IKey key) : base(key) { } public override string Name { get { return Key[SqlServerNameAnnotation] ?? base.Name; } } public virtual bool? IsClustered { get { // TODO: Issue #777: Non-string annotations // TODO: Issue #700: Annotate associated index object instead var value = Key[SqlServerClusteredAnnotation]; return value == null ? null : (bool?)bool.Parse(value); } } } }
36.459459
131
0.671609
[ "Apache-2.0" ]
matteo-mosca-easydom/EntityFramework
src/EntityFramework.SqlServer/Metadata/ReadOnlySqlServerKeyExtensions.cs
1,351
C#
using System; using System.Collections.Generic; using System.Text; namespace HelloWorldApp.BusinessObjects { [Serializable] public partial class Person { } }
14.583333
40
0.731429
[ "Unlicense" ]
moljac/MonoVersalSharpSerializer
XamarinComponent.SharpSerializer/content/samples/SharpSerializer.Android/HelloWorldApp.MonoForAndroid/BusinessObjects.HolisticWare/Person.Serializable.cs
177
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace AudiotPrism { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var bootstrapper = new Bootstrapper(); bootstrapper.Run(); } } }
20.88
61
0.641762
[ "MIT" ]
kbdnr/Audiot
AudiotPrism/App.xaml.cs
524
C#
using UnityEngine.Rendering.HighDefinition.Attributes; using UnityEngine.Experimental.Rendering; namespace UnityEngine.Rendering.HighDefinition { partial class Lit : RenderPipelineMaterial { // Currently we have only one materialId (Standard GGX), so it is not store in the GBuffer and we don't test for it // If change, be sure it match what is done in Lit.hlsl: MaterialFeatureFlagsFromGBuffer // Material bit mask must match the size define LightDefinitions.s_MaterialFeatureMaskFlags value [GenerateHLSL(PackingRules.Exact)] public enum MaterialFeatureFlags { LitStandard = 1 << 0, // For material classification we need to identify that we are indeed use as standard material, else we are consider as sky/background element LitSpecularColor = 1 << 1, // LitSpecularColor is not use statically but only dynamically LitSubsurfaceScattering = 1 << 2, LitTransmission = 1 << 3, LitAnisotropy = 1 << 4, LitIridescence = 1 << 5, LitClearCoat = 1 << 6 }; //----------------------------------------------------------------------------- // SurfaceData //----------------------------------------------------------------------------- // Main structure that store the user data (i.e user input of master node in material graph) [GenerateHLSL(PackingRules.Exact, false, false, true, 1000)] public struct SurfaceData { [SurfaceDataAttributes("Material Features")] public uint materialFeatures; // Standard [MaterialSharedPropertyMapping(MaterialSharedProperty.Albedo)] [SurfaceDataAttributes("Base Color", false, true, FieldPrecision.Real)] public Vector3 baseColor; [SurfaceDataAttributes("Specular Occlusion", precision = FieldPrecision.Real)] public float specularOcclusion; [MaterialSharedPropertyMapping(MaterialSharedProperty.Normal)] [SurfaceDataAttributes(new string[] {"Normal", "Normal View Space"}, true, checkIsNormalized = true)] public Vector3 normalWS; [MaterialSharedPropertyMapping(MaterialSharedProperty.Smoothness)] [SurfaceDataAttributes("Smoothness", precision = FieldPrecision.Real)] public float perceptualSmoothness; [MaterialSharedPropertyMapping(MaterialSharedProperty.AmbientOcclusion)] [SurfaceDataAttributes("Ambient Occlusion", precision = FieldPrecision.Real)] public float ambientOcclusion; [MaterialSharedPropertyMapping(MaterialSharedProperty.Metal)] [SurfaceDataAttributes("Metallic", precision = FieldPrecision.Real)] public float metallic; [SurfaceDataAttributes("Coat mask", precision = FieldPrecision.Real)] public float coatMask; // MaterialFeature dependent attribute // Specular Color [MaterialSharedPropertyMapping(MaterialSharedProperty.Specular)] [SurfaceDataAttributes("Specular Color", false, true, FieldPrecision.Real)] public Vector3 specularColor; // SSS [SurfaceDataAttributes("Diffusion Profile Hash")] public uint diffusionProfileHash; [SurfaceDataAttributes("Subsurface Mask", precision = FieldPrecision.Real)] public float subsurfaceMask; // Transmission // + Diffusion Profile [SurfaceDataAttributes("Thickness", precision = FieldPrecision.Real)] public float thickness; // Anisotropic [SurfaceDataAttributes("Tangent", true)] public Vector3 tangentWS; [SurfaceDataAttributes("Anisotropy", precision = FieldPrecision.Real)] public float anisotropy; // anisotropic ratio(0->no isotropic; 1->full anisotropy in tangent direction, -1->full anisotropy in bitangent direction) // Iridescence [SurfaceDataAttributes("Iridescence Layer Thickness", precision = FieldPrecision.Real)] public float iridescenceThickness; [SurfaceDataAttributes("Iridescence Mask", precision = FieldPrecision.Real)] public float iridescenceMask; // Forward property only [SurfaceDataAttributes(new string[] { "Geometric Normal", "Geometric Normal View Space" }, true, precision = FieldPrecision.Real, checkIsNormalized = true)] public Vector3 geomNormalWS; // Transparency // Reuse thickness from SSS [SurfaceDataAttributes("Index of refraction", precision = FieldPrecision.Real)] public float ior; [SurfaceDataAttributes("Transmittance Color", precision = FieldPrecision.Real)] public Vector3 transmittanceColor; [SurfaceDataAttributes("Transmittance Absorption Distance", precision = FieldPrecision.Real)] public float atDistance; [SurfaceDataAttributes("Transmittance Mask", precision = FieldPrecision.Real)] public float transmittanceMask; }; //----------------------------------------------------------------------------- // BSDFData //----------------------------------------------------------------------------- [GenerateHLSL(PackingRules.Exact, false, false, true, 1050)] public struct BSDFData { public uint materialFeatures; [SurfaceDataAttributes("", false, true, FieldPrecision.Real)] public Vector3 diffuseColor; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public Vector3 fresnel0; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float ambientOcclusion; // Caution: This is accessible only if light layer is enabled, otherwise it is 1 [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float specularOcclusion; [SurfaceDataAttributes(new string[] { "Normal WS", "Normal View Space" }, true, checkIsNormalized: true)] public Vector3 normalWS; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float perceptualRoughness; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float coatMask; // MaterialFeature dependent attribute // SpecularColor fold into fresnel0 // SSS public uint diffusionProfileIndex; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float subsurfaceMask; // Transmission // + Diffusion Profile [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float thickness; public bool useThickObjectMode; // Read from the diffusion profile [SurfaceDataAttributes(precision = FieldPrecision.Real)] public Vector3 transmittance; // Precomputation of transmittance // Anisotropic [SurfaceDataAttributes("", true)] public Vector3 tangentWS; [SurfaceDataAttributes("", true)] public Vector3 bitangentWS; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float roughnessT; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float roughnessB; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float anisotropy; // Iridescence [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float iridescenceThickness; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float iridescenceMask; // ClearCoat [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float coatRoughness; // Automatically fill // Forward property only [SurfaceDataAttributes(new string[] { "Geometric Normal", "Geometric Normal View Space" }, true, precision = FieldPrecision.Real, checkIsNormalized = true)] public Vector3 geomNormalWS; // Transparency [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float ior; // Reuse thickness from SSS [SurfaceDataAttributes(precision = FieldPrecision.Real)] public Vector3 absorptionCoefficient; [SurfaceDataAttributes(precision = FieldPrecision.Real)] public float transmittanceMask; }; //----------------------------------------------------------------------------- // GBuffer management //----------------------------------------------------------------------------- public override bool IsDefferedMaterial() { return true; } protected void GetGBufferOptions(HDRenderPipelineAsset asset, out int gBufferCount, out bool supportShadowMask, out bool supportLightLayers) { // Caution: This must be in sync with GBUFFERMATERIAL_COUNT definition in supportShadowMask = asset.currentPlatformRenderPipelineSettings.supportShadowMask; supportLightLayers = asset.currentPlatformRenderPipelineSettings.supportLightLayers; gBufferCount = 4 + (supportShadowMask ? 1 : 0) + (supportLightLayers ? 1 : 0); #if ENABLE_VIRTUALTEXTURES gBufferCount++; #endif } // This must return the number of GBuffer to allocate public override int GetMaterialGBufferCount(HDRenderPipelineAsset asset) { int gBufferCount; bool unused0; bool unused1; GetGBufferOptions(asset, out gBufferCount, out unused0, out unused1); return gBufferCount; } public override void GetMaterialGBufferDescription(HDRenderPipelineAsset asset, out GraphicsFormat[] RTFormat, out GBufferUsage[] gBufferUsage, out bool[] enableWrite) { int gBufferCount; bool supportShadowMask; bool supportLightLayers; GetGBufferOptions(asset, out gBufferCount, out supportShadowMask, out supportLightLayers); RTFormat = new GraphicsFormat[gBufferCount]; gBufferUsage = new GBufferUsage[gBufferCount]; enableWrite = new bool[gBufferCount]; RTFormat[0] = GraphicsFormat.R8G8B8A8_SRGB; // Albedo sRGB / SSSBuffer gBufferUsage[0] = GBufferUsage.SubsurfaceScattering; enableWrite[0] = true; RTFormat[1] = GraphicsFormat.R8G8B8A8_UNorm; // Normal Buffer gBufferUsage[1] = GBufferUsage.Normal; enableWrite[1] = true; // normal buffer is used as RWTexture to composite decals in forward RTFormat[2] = GraphicsFormat.R8G8B8A8_UNorm; // Data gBufferUsage[2] = GBufferUsage.None; enableWrite[2] = true; RTFormat[3] = Builtin.GetLightingBufferFormat(); gBufferUsage[3] = GBufferUsage.None; enableWrite[3] = true; #if ENABLE_VIRTUALTEXTURES int index = 4; RTFormat[index] = VTBufferManager.GetFeedbackBufferFormat(); gBufferUsage[index] = GBufferUsage.VTFeedback; enableWrite[index] = false; index++; #else int index = 4; #endif if (supportLightLayers) { RTFormat[index] = GraphicsFormat.R8G8B8A8_UNorm; gBufferUsage[index] = GBufferUsage.LightLayers; index++; } // All buffer above are fixed. However shadow mask buffer can be setup or not depends on light in view. // Thus it need to be the last one, so all indexes stay the same if (supportShadowMask) { RTFormat[index] = Builtin.GetShadowMaskBufferFormat(); gBufferUsage[index] = GBufferUsage.ShadowMask; index++; } } //----------------------------------------------------------------------------- // Init precomputed texture //----------------------------------------------------------------------------- public Lit() {} public override void Build(HDRenderPipelineAsset hdAsset, RenderPipelineResources defaultResources) { PreIntegratedFGD.instance.Build(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse); LTCAreaLight.instance.Build(); } public override void Cleanup() { PreIntegratedFGD.instance.Cleanup(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse); LTCAreaLight.instance.Cleanup(); } public override void RenderInit(CommandBuffer cmd) { PreIntegratedFGD.instance.RenderInit(PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse, cmd); } public override void Bind(CommandBuffer cmd) { PreIntegratedFGD.instance.Bind(cmd, PreIntegratedFGD.FGDIndex.FGD_GGXAndDisneyDiffuse); LTCAreaLight.instance.Bind(cmd); } } }
45.036913
190
0.605395
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/com.unity.render-pipelines.high-definition@10.5.0/Runtime/Material/Lit/Lit.cs
13,421
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MainThread : MonoBehaviour { public static MainThread mainThread; public GameObject Drop; public GameObject StartButton; public GameObject ScoreRankPanel; public int totalDropsAmount = 2; public bool GameStarted = false; // To prevent from vanishing when generating drops public int score = 0; public GameObject scoreText; public GameObject targetScoreText; public int dropsCount; // for multiple levels private float[] initialDropsRadiusList = new float[11]; public int currentLevel = 0; public int targetScore = 0; // For Data Saving private const string PLAY_PREF_KEY_HS = "High Score"; private const string FILE_SCORE_RANK = "/score_rank.txt"; private void Awake() { if(mainThread == null){ mainThread = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } // Start is called before the first frame update void Start() { // Screen.SetResolution(1920, 1080, true, 60); ScoreRankPanel.SetActive(false); dropsCount = 0; scoreText.GetComponent<Text>().text = "Score: "+score.ToString(); initTarget(); loadData(true); targetScoreText.GetComponent<Text>().text = "Target Score: "+targetScore.ToString(); StartButton.GetComponent<Button>().onClick.AddListener(StartButtonCliked); } // Update is called once per frame void Update() { scoreText.GetComponent<Text>().text = "Score: "+score.ToString(); if (dropsCount<=1 && GameStarted){ GameStarted = false; StartButton.transform.GetChild(0).GetComponent<Text>().text = "Start"; if(score<targetScore){ gameEnded(); }else{ currentLevel ++; initTarget(); targetScoreText.GetComponent<Text>().text = "Target Score: "+targetScore.ToString(); SceneManager.LoadScene("LevelScene"); } } } // Initialization public void initTarget(){ for (; dropsCount < totalDropsAmount; dropsCount++) { Drop.GetComponent<DropsProperty>().id = dropsCount; Drop.GetComponent<DropsProperty>().r = UnityEngine.Random.Range(50.0f, 150.0f); initialDropsRadiusList[dropsCount] = System.Convert.ToInt16(Drop.GetComponent<DropsProperty>().r); Drop.transform.localScale = new Vector2(Drop.GetComponent<DropsProperty>().r, Drop.GetComponent<DropsProperty>().r); // keep score label original size // Drop.transform.GetChild(0).gameObject.transform.localScale = new Vector2(1/Drop.GetComponent<DropsProperty>().r, 1/Drop.GetComponent<DropsProperty>().r); Instantiate(Drop, new Vector3(UnityEngine.Random.Range(200.0f, 1600.0f), UnityEngine.Random.Range(100.0f, 800.0f), 0.0f), Quaternion.identity); } targetScore = getTargetScore(currentLevel); } // start/pause game public void gamestart() { GameStarted = !GameStarted; if (GameStarted){ StartButton.transform.GetChild(0).GetComponent<Text>().text = "Pause"; }else{ StartButton.transform.GetChild(0).GetComponent<Text>().text = "Start"; } } // Calculate target score for different levels private int getTargetScore(int level){ float difFactorDeno = 5; // larger -> easier float difFactorBase = 2; // larger -> harder float difficulty = 1 - Mathf.Pow(difFactorBase, ((float)level)*(-1)/difFactorDeno); // compute difficulty factor, larger -> easier float maxPossibleScore = 0; for (int i = 0; i < initialDropsRadiusList.Length; i++) { Array.Sort(initialDropsRadiusList); if (initialDropsRadiusList[0]<int.MaxValue){ maxPossibleScore += initialDropsRadiusList[0]/4; initialDropsRadiusList[1] += initialDropsRadiusList[0]/2; initialDropsRadiusList[0] = int.MaxValue; }else break; } return System.Convert.ToUInt16(maxPossibleScore*difficulty)+score; } // load rank data private void loadData(bool isInit){ string hsString; if (File.Exists(Application.dataPath+FILE_SCORE_RANK)){ hsString = File.ReadAllText(Application.dataPath + FILE_SCORE_RANK); }else { hsString = "0,0,0,0,0,0,0,0,0,"; } string[] splitString = hsString.TrimEnd(',').Split(','); int[] scoreRank = Array.ConvertAll(splitString, int.Parse); string scoretext = ""; bool highScoreInterted = false; string allScoreString = ""; for (int i = 0; i < scoreRank.Length; i++){ if (score>scoreRank[i] && !highScoreInterted && !isInit){ for (int j = scoreRank.Length-1; j > i; j--){ scoreRank[j] = scoreRank[j-1]; } scoreRank[i] = score; highScoreInterted = true; scoretext += "* "; } scoretext += ("("+(i+1)+")"+". "+'\t'+scoreRank[i]+'\n'); allScoreString = allScoreString + scoreRank[i] + ","; } ScoreRankPanel.transform.GetChild(1).GetComponent<Text>().text = scoretext; File.WriteAllText(Application.dataPath + FILE_SCORE_RANK, allScoreString); } // Game Ends, read and saving data private void gameEnded(){ scoreText.GetComponent<Text>().text = "Game Over!, Your score is: "+score.ToString(); loadData(false); ScoreRankPanel.SetActive(true); } private void StartButtonCliked(){ gamestart(); ScoreRankPanel.SetActive(GameStarted ? false:true); } }
39.75974
169
0.599543
[ "Unlicense" ]
Jonysand/CodeLab1-yl7113-HW3
Week3-CodeLab1-DataSave/Assets/Scripts/MainThread.cs
6,125
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; namespace Aliyun.Acs.Smartag.Model.V20180313 { public class GetCloudConnectNetworkUseLimitResponse : AcsResponse { private string requestId; private int? totalAmount; private int? usedAmount; public string RequestId { get { return requestId; } set { requestId = value; } } public int? TotalAmount { get { return totalAmount; } set { totalAmount = value; } } public int? UsedAmount { get { return usedAmount; } set { usedAmount = value; } } } }
20.71831
67
0.670972
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-smartag/Smartag/Model/V20180313/GetCloudConnectNetworkUseLimitResponse.cs
1,471
C#
using System; using System.Collections.Generic; namespace LobotJR.Shared.Authentication { /// <summary> /// The response object from the authorization code flow and refresh call. /// </summary> public class TokenResponse { /// <summary> /// The oauth token to use when authenticating calls. /// </summary> public string AccessToken { get; set; } /// <summary> /// The refresh token used to refresh the access token when it expires. /// </summary> public string RefreshToken { get; set; } /// <summary> /// The number of seconds from the time of issuance until the token expires. /// </summary> public int ExpiresIn { get; set; } /// <summary> /// Calculated upon receipt using ExpiresIn /// </summary> public DateTime ExpirationDate { get; set; } /// <summary> /// The list of scopes the token has access to. /// </summary> public IEnumerable<string> Scope { get; set; } /// <summary> /// The type of token. This should always be "bearer" /// </summary> public string TokenType { get; set; } } }
32.810811
84
0.574135
[ "MIT" ]
EmpyrealHell/lobotjr
LobotJR.Shared/Authentication/TokenResponse.cs
1,216
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Execution; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Algorithm.Framework.Selection; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using System; using System.Collections.Generic; using System.Linq; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Basic template framework algorithm uses framework components to define the algorithm. /// Shows EqualWeightingPortfolioConstructionModel.LongOnly() application /// </summary> /// <meta name="tag" content="alpha streams" /> /// <meta name="tag" content="using quantconnect" /> /// <meta name="tag" content="algorithm framework" /> public class LongOnlyAlphaStreamAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { public override void Initialize() { // 1. Required: SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 11); // 2. Required: Alpha Streams Models: SetBrokerageModel(BrokerageName.AlphaStreams); // 3. Required: Significant AUM Capacity SetCash(1000000); // Only SPY will be traded SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(Resolution.Daily, PortfolioBias.Long)); SetExecution(new ImmediateExecutionModel()); // set algorithm framework models SetUniverseSelection( new ManualUniverseSelectionModel( new[] {"SPY", "IBM"} .Select(x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA)) ) ); } public override void OnData(Slice slice) { if (Portfolio.Invested) return; EmitInsights( Insight.Price("SPY", TimeSpan.FromDays(1), InsightDirection.Up), Insight.Price("IBM", TimeSpan.FromDays(1), InsightDirection.Down) ); } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status.IsFill()) { if (Securities[orderEvent.Symbol].Holdings.IsShort) { throw new Exception("Invalid position, should not be short"); } Debug($"Purchased Stock: {orderEvent}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "9"}, {"Average Win", "1.00%"}, {"Average Loss", "-0.59%"}, {"Compounding Annual Return", "220.252%"}, {"Drawdown", "2.300%"}, {"Expectancy", "0.343"}, {"Net Profit", "1.499%"}, {"Sharpe Ratio", "7.318"}, {"Probabilistic Sharpe Ratio", "64.891%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "1.69"}, {"Alpha", "-0.274"}, {"Beta", "1.001"}, {"Annual Standard Deviation", "0.22"}, {"Annual Variance", "0.049"}, {"Information Ratio", "-77.454"}, {"Tracking Error", "0.004"}, {"Treynor Ratio", "1.61"}, {"Total Fees", "$293.12"}, {"Fitness Score", "0.999"}, {"Kelly Criterion Estimate", "-7.18"}, {"Kelly Criterion Probability Value", "0.596"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "74.148"}, {"Portfolio Turnover", "1.741"}, {"Total Insights Generated", "10"}, {"Total Insights Closed", "8"}, {"Total Insights Analysis Completed", "8"}, {"Long Insight Count", "5"}, {"Short Insight Count", "5"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$65693.4230"}, {"Total Accumulated Estimated Alpha Value", "$10583.9404"}, {"Mean Population Estimated Insight Value", "$1322.9925"}, {"Mean Population Direction", "62.5%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "73.0394%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "-1723530785"} }; } }
40.743056
146
0.589398
[ "Apache-2.0" ]
Zingasoft/Lean
Algorithm.CSharp/LongOnlyAlphaStreamAlgorithm.cs
5,867
C#
using Never; using Never.CommandStreams; using Never.DataAnnotations; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace B2C.Admin.Web.Permissions.Commands { [Serializable, CommandDomain(Domain = "admin")] [Validator(typeof(CommandValidator))] public class ChangeDepartmentInfoCommand : Never.Domains.ChangeAggregateCommand<string> { #region ctor private ChangeDepartmentInfoCommand() : this(string.Empty) { } public ChangeDepartmentInfoCommand(string aggregateId) : base(aggregateId) { } #endregion ctor #region prop /// <summary> /// 部门名称 /// </summary> public string Name { get; set; } /// <summary> /// 描述 /// </summary> public string Descn { get; set; } #endregion prop #region validator private class CommandValidator : Validator<ChangeDepartmentInfoCommand> { public override IEnumerable<KeyValuePair<Expression<Func<ChangeDepartmentInfoCommand, object>>, string>> RuleFor(ChangeDepartmentInfoCommand target) { if (target.Name.IsNullOrWhiteSpace()) yield return new KeyValuePair<Expression<Func<ChangeDepartmentInfoCommand, object>>, string>(model => model.Name, "名称为空"); if (target.Descn.IsNullOrWhiteSpace()) yield return new KeyValuePair<Expression<Func<ChangeDepartmentInfoCommand, object>>, string>(model => model.Descn, "描述为空"); if (target.AggregateId.IsNullOrWhiteSpace()) yield return new KeyValuePair<Expression<Func<ChangeDepartmentInfoCommand, object>>, string>(m => m.AggregateId, "聚合Id为空"); } } #endregion validator } }
30.758065
160
0.640273
[ "MIT" ]
shelldudu/never_application
src/admin/B2C.Admin.Web/Permissions/Commands/ChangeDepartmentInfoCommand.cs
1,945
C#
using System; using System.Web.Mvc; namespace NoMoreSusi.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }
16.769231
44
0.591743
[ "MIT" ]
Ico093/NoMoreSusi
NoMoreSusi.Web/Controllers/HomeController.cs
220
C#
using System; using System.Globalization; using ClearHl7.Extensions; using ClearHl7.Helpers; using ClearHl7.Serialization; using ClearHl7.V260.Types; namespace ClearHl7.V260.Segments { /// <summary> /// HL7 Version 2 Segment VND - Purchasing Vendor. /// </summary> public class VndSegment : ISegment { /// <inheritdoc/> public string Id { get; } = "VND"; /// <inheritdoc/> public int Ordinal { get; set; } /// <summary> /// VND.1 - Set Id - VND. /// </summary> public uint? SetIdVnd { get; set; } /// <summary> /// VND.2 - Vendor Identifier. /// </summary> public EntityIdentifier VendorIdentifier { get; set; } /// <summary> /// VND.3 - Vendor Name. /// </summary> public string VendorName { get; set; } /// <summary> /// VND.4 - Vendor Catalog Number. /// </summary> public EntityIdentifier VendorCatalogNumber { get; set; } /// <summary> /// VND.5 - Primary Vendor Indicator. /// <para>Suggested: 0532 Expanded Yes/No Indicator -&gt; ClearHl7.Codes.V260.CodeExpandedYesNoIndicator</para> /// </summary> public CodedWithNoExceptions PrimaryVendorIndicator { get; set; } /// <inheritdoc/> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <inheritdoc/> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } SetIdVnd = segments.Length > 1 && segments[1].Length > 0 ? segments[1].ToNullableUInt() : null; VendorIdentifier = segments.Length > 2 && segments[2].Length > 0 ? TypeSerializer.Deserialize<EntityIdentifier>(segments[2], false, seps) : null; VendorName = segments.Length > 3 && segments[3].Length > 0 ? segments[3] : null; VendorCatalogNumber = segments.Length > 4 && segments[4].Length > 0 ? TypeSerializer.Deserialize<EntityIdentifier>(segments[4], false, seps) : null; PrimaryVendorIndicator = segments.Length > 5 && segments[5].Length > 0 ? TypeSerializer.Deserialize<CodedWithNoExceptions>(segments[5], false, seps) : null; } /// <inheritdoc/> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 6, Configuration.FieldSeparator), Id, SetIdVnd.HasValue ? SetIdVnd.Value.ToString(culture) : null, VendorIdentifier?.ToDelimitedString(), VendorName, VendorCatalogNumber?.ToDelimitedString(), PrimaryVendorIndicator?.ToDelimitedString() ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
40
181
0.567819
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7/V260/Segments/VndSegment.cs
3,762
C#
/* Copyright 2014-2021 SourceGear, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 © Microsoft Open Technologies, Inc. // All Rights Reserved // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache 2 License for the specific language governing permissions and limitations under the License. namespace SQLitePCL { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Reflection; using System.Text; [Preserve(AllMembers = true)] public sealed class SQLite3Provider_winsqlite3 : ISQLite3Provider { const CallingConvention CALLING_CONVENTION = CallingConvention.StdCall; string ISQLite3Provider.GetNativeLibraryName() { return "winsqlite3"; } bool my_streq(IntPtr p, IntPtr q, int len) { return 0 == NativeMethods.sqlite3_strnicmp(p, q, len); } hook_handles get_hooks(sqlite3 db) { return db.GetOrCreateExtra<hook_handles>(() => new hook_handles(my_streq)); } unsafe int ISQLite3Provider.sqlite3_win32_set_directory(int typ, utf8z path) { fixed (byte* p = path) { return NativeMethods.sqlite3_win32_set_directory8((uint) typ, p); } } unsafe int ISQLite3Provider.sqlite3_open(utf8z filename, out IntPtr db) { fixed (byte* p = filename) { return NativeMethods.sqlite3_open(p, out db); } } unsafe int ISQLite3Provider.sqlite3_open_v2(utf8z filename, out IntPtr db, int flags, utf8z vfs) { fixed (byte* p_filename = filename, p_vfs = vfs) { return NativeMethods.sqlite3_open_v2(p_filename, out db, flags, p_vfs); } } #pragma warning disable 649 private struct sqlite3_vfs { public int iVersion; public int szOsFile; public int mxPathname; public IntPtr pNext; public IntPtr zName; public IntPtr pAppData; public IntPtr xOpen; public SQLiteDeleteDelegate xDelete; public IntPtr xAccess; public IntPtr xFullPathname; public IntPtr xDlOpen; public IntPtr xDlError; public IntPtr xDlSym; public IntPtr xDlClose; public IntPtr xRandomness; public IntPtr xSleep; public IntPtr xCurrentTime; public IntPtr xGetLastError; [UnmanagedFunctionPointer(CALLING_CONVENTION)] public unsafe delegate int SQLiteDeleteDelegate(IntPtr pVfs, byte* zName, int syncDir); } #pragma warning restore 649 unsafe int ISQLite3Provider.sqlite3__vfs__delete(utf8z vfs, utf8z filename, int syncDir) { fixed (byte* p_vfs = vfs, p_filename = filename) { IntPtr ptrVfs = NativeMethods.sqlite3_vfs_find(p_vfs); // this code and the struct it uses was taken from aspnet/DataCommon.SQLite, Apache License 2.0 sqlite3_vfs vstruct = (sqlite3_vfs) Marshal.PtrToStructure(ptrVfs, typeof(sqlite3_vfs)); return vstruct.xDelete(ptrVfs, p_filename, 1); } } int ISQLite3Provider.sqlite3_close_v2(IntPtr db) { var rc = NativeMethods.sqlite3_close_v2(db); return rc; } int ISQLite3Provider.sqlite3_close(IntPtr db) { var rc = NativeMethods.sqlite3_close(db); return rc; } void ISQLite3Provider.sqlite3_free(IntPtr p) { NativeMethods.sqlite3_free(p); } int ISQLite3Provider.sqlite3_stricmp(IntPtr p, IntPtr q) { return NativeMethods.sqlite3_stricmp(p, q); } int ISQLite3Provider.sqlite3_strnicmp(IntPtr p, IntPtr q, int n) { return NativeMethods.sqlite3_strnicmp(p, q, n); } int ISQLite3Provider.sqlite3_enable_shared_cache(int enable) { return NativeMethods.sqlite3_enable_shared_cache(enable); } void ISQLite3Provider.sqlite3_interrupt(sqlite3 db) { NativeMethods.sqlite3_interrupt(db); } [MonoPInvokeCallback (typeof(NativeMethods.callback_exec))] static int exec_hook_bridge_impl(IntPtr p, int n, IntPtr values_ptr, IntPtr names_ptr) { exec_hook_info hi = exec_hook_info.from_ptr(p); return hi.call(n, values_ptr, names_ptr); } // shouldn't there be a impl/bridge thing here? no, because this callback is not stored so it doesn't need further GC protection int ISQLite3Provider.sqlite3_exec(sqlite3 db, utf8z sql, delegate_exec func, object user_data, out IntPtr errMsg) { int rc; NativeMethods.callback_exec cb; exec_hook_info hi; if (func != null) { cb = exec_hook_bridge_impl; hi = new exec_hook_info(func, user_data); } else { cb = null; hi = null; } var h = new hook_handle(hi); unsafe { fixed (byte* p_sql = sql) { rc = NativeMethods.sqlite3_exec(db, p_sql, cb, h, out errMsg); } } h.Dispose(); return rc; } unsafe int ISQLite3Provider.sqlite3_complete(utf8z sql) { fixed (byte* p = sql) { return NativeMethods.sqlite3_complete(p); } } unsafe utf8z ISQLite3Provider.sqlite3_compileoption_get(int n) { return utf8z.FromPtr(NativeMethods.sqlite3_compileoption_get(n)); } unsafe int ISQLite3Provider.sqlite3_compileoption_used(utf8z s) { fixed (byte* p = s) { return NativeMethods.sqlite3_compileoption_used(p); } } unsafe int ISQLite3Provider.sqlite3_table_column_metadata(sqlite3 db, utf8z dbName, utf8z tblName, utf8z colName, out utf8z dataType, out utf8z collSeq, out int notNull, out int primaryKey, out int autoInc) { fixed (byte* p_dbName = dbName, p_tblName = tblName, p_colName = colName) { var rc = NativeMethods.sqlite3_table_column_metadata( db, p_dbName, p_tblName, p_colName, out var p_dataType, out var p_collSeq, out notNull, out primaryKey, out autoInc); dataType = utf8z.FromPtr(p_dataType); collSeq = utf8z.FromPtr(p_collSeq); return rc; } } unsafe int ISQLite3Provider.sqlite3_key(sqlite3 db, ReadOnlySpan<byte> k) { return raw.SQLITE_ERROR; } unsafe int ISQLite3Provider.sqlite3_key_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return raw.SQLITE_ERROR; } unsafe int ISQLite3Provider.sqlite3_rekey(sqlite3 db, ReadOnlySpan<byte> k) { return raw.SQLITE_ERROR; } unsafe int ISQLite3Provider.sqlite3_rekey_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return raw.SQLITE_ERROR; } unsafe int ISQLite3Provider.sqlite3_prepare_v2(sqlite3 db, ReadOnlySpan<byte> sql, out IntPtr stm, out ReadOnlySpan<byte> tail) { fixed (byte* p_sql = sql) { var rc = NativeMethods.sqlite3_prepare_v2(db, p_sql, sql.Length, out stm, out var p_tail); var len_consumed = (int) (p_tail - p_sql); int len_remain = sql.Length - len_consumed; if (len_remain > 0) { tail = sql.Slice(len_consumed, len_remain); } else { tail = ReadOnlySpan<byte>.Empty; } return rc; } } unsafe int ISQLite3Provider.sqlite3_prepare_v2(sqlite3 db, utf8z sql, out IntPtr stm, out utf8z tail) { fixed (byte* p_sql = sql) { var rc = NativeMethods.sqlite3_prepare_v2(db, p_sql, -1, out stm, out var p_tail); // TODO we could skip the strlen by using the length we were given tail = utf8z.FromPtr(p_tail); return rc; } } unsafe int ISQLite3Provider.sqlite3_prepare_v3(sqlite3 db, ReadOnlySpan<byte> sql, uint flags, out IntPtr stm, out ReadOnlySpan<byte> tail) { fixed (byte* p_sql = sql) { var rc = NativeMethods.sqlite3_prepare_v3(db, p_sql, sql.Length, flags, out stm, out var p_tail); var len_consumed = (int) (p_tail - p_sql); int len_remain = sql.Length - len_consumed; if (len_remain > 0) { tail = sql.Slice(len_consumed, len_remain); } else { tail = ReadOnlySpan<byte>.Empty; } return rc; } } unsafe int ISQLite3Provider.sqlite3_prepare_v3(sqlite3 db, utf8z sql, uint flags, out IntPtr stm, out utf8z tail) { fixed (byte* p_sql = sql) { var rc = NativeMethods.sqlite3_prepare_v3(db, p_sql, -1, flags, out stm, out var p_tail); // TODO we could skip the strlen by using the length we were given tail = utf8z.FromPtr(p_tail); return rc; } } int ISQLite3Provider.sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg) { return NativeMethods.sqlite3_db_status(db, op, out current, out highest, resetFlg); } unsafe utf8z ISQLite3Provider.sqlite3_sql(sqlite3_stmt stmt) { return utf8z.FromPtr(NativeMethods.sqlite3_sql(stmt)); } IntPtr ISQLite3Provider.sqlite3_db_handle(IntPtr stmt) { return NativeMethods.sqlite3_db_handle(stmt); } unsafe int ISQLite3Provider.sqlite3_blob_open(sqlite3 db, utf8z db_utf8, utf8z table_utf8, utf8z col_utf8, long rowid, int flags, out IntPtr blob) { fixed (byte* p_db = db_utf8, p_table = table_utf8, p_col = col_utf8) { return NativeMethods.sqlite3_blob_open(db, p_db, p_table, p_col, rowid, flags, out blob); } } int ISQLite3Provider.sqlite3_blob_bytes(sqlite3_blob blob) { return NativeMethods.sqlite3_blob_bytes(blob); } int ISQLite3Provider.sqlite3_blob_reopen(sqlite3_blob blob, long rowid) { return NativeMethods.sqlite3_blob_reopen(blob, rowid); } unsafe int ISQLite3Provider.sqlite3_blob_read(sqlite3_blob blob, Span<byte> b, int offset) { fixed (byte* p = b) { return NativeMethods.sqlite3_blob_read(blob, p, b.Length, offset); } } unsafe int ISQLite3Provider.sqlite3_blob_write(sqlite3_blob blob, ReadOnlySpan<byte> b, int offset) { fixed (byte* p = b) { return NativeMethods.sqlite3_blob_write(blob, p, b.Length, offset); } } int ISQLite3Provider.sqlite3_blob_close(IntPtr blob) { return NativeMethods.sqlite3_blob_close(blob); } unsafe int ISQLite3Provider.sqlite3_snapshot_get(sqlite3 db, utf8z schema, out IntPtr snap) { fixed (byte* p_schema = schema) { return NativeMethods.sqlite3_snapshot_get(db, p_schema, out snap); } } int ISQLite3Provider.sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2) { return NativeMethods.sqlite3_snapshot_cmp(p1, p2); } unsafe int ISQLite3Provider.sqlite3_snapshot_open(sqlite3 db, utf8z schema, sqlite3_snapshot snap) { fixed (byte* p_schema = schema) { return NativeMethods.sqlite3_snapshot_open(db, p_schema, snap); } } unsafe int ISQLite3Provider.sqlite3_snapshot_recover(sqlite3 db, utf8z name) { fixed (byte* p_name = name) { return NativeMethods.sqlite3_snapshot_recover(db, p_name); } } void ISQLite3Provider.sqlite3_snapshot_free(IntPtr snap) { NativeMethods.sqlite3_snapshot_free(snap); } unsafe sqlite3_backup ISQLite3Provider.sqlite3_backup_init(sqlite3 destDb, utf8z destName, sqlite3 sourceDb, utf8z sourceName) { fixed (byte* p_destName = destName, p_sourceName = sourceName) { return NativeMethods.sqlite3_backup_init(destDb, p_destName, sourceDb, p_sourceName); } } int ISQLite3Provider.sqlite3_backup_step(sqlite3_backup backup, int nPage) { return NativeMethods.sqlite3_backup_step(backup, nPage); } int ISQLite3Provider.sqlite3_backup_remaining(sqlite3_backup backup) { return NativeMethods.sqlite3_backup_remaining(backup); } int ISQLite3Provider.sqlite3_backup_pagecount(sqlite3_backup backup) { return NativeMethods.sqlite3_backup_pagecount(backup); } int ISQLite3Provider.sqlite3_backup_finish(IntPtr backup) { return NativeMethods.sqlite3_backup_finish(backup); } IntPtr ISQLite3Provider.sqlite3_next_stmt(sqlite3 db, IntPtr stmt) { return NativeMethods.sqlite3_next_stmt(db, stmt); } long ISQLite3Provider.sqlite3_last_insert_rowid(sqlite3 db) { return NativeMethods.sqlite3_last_insert_rowid(db); } int ISQLite3Provider.sqlite3_changes(sqlite3 db) { return NativeMethods.sqlite3_changes(db); } int ISQLite3Provider.sqlite3_total_changes(sqlite3 db) { return NativeMethods.sqlite3_total_changes(db); } int ISQLite3Provider.sqlite3_extended_result_codes(sqlite3 db, int onoff) { return NativeMethods.sqlite3_extended_result_codes(db, onoff); } unsafe utf8z ISQLite3Provider.sqlite3_errstr(int rc) { return utf8z.FromPtr(NativeMethods.sqlite3_errstr(rc)); } int ISQLite3Provider.sqlite3_errcode(sqlite3 db) { return NativeMethods.sqlite3_errcode(db); } int ISQLite3Provider.sqlite3_extended_errcode(sqlite3 db) { return NativeMethods.sqlite3_extended_errcode(db); } int ISQLite3Provider.sqlite3_busy_timeout(sqlite3 db, int ms) { return NativeMethods.sqlite3_busy_timeout(db, ms); } int ISQLite3Provider.sqlite3_get_autocommit(sqlite3 db) { return NativeMethods.sqlite3_get_autocommit(db); } unsafe int ISQLite3Provider.sqlite3_db_readonly(sqlite3 db, utf8z dbName) { fixed (byte* p_dbName = dbName) { return NativeMethods.sqlite3_db_readonly(db, p_dbName); } } unsafe utf8z ISQLite3Provider.sqlite3_db_filename(sqlite3 db, utf8z att) { fixed (byte* p_att = att) { return utf8z.FromPtr(NativeMethods.sqlite3_db_filename(db, p_att)); } } unsafe utf8z ISQLite3Provider.sqlite3_errmsg(sqlite3 db) { return utf8z.FromPtr(NativeMethods.sqlite3_errmsg(db)); } unsafe utf8z ISQLite3Provider.sqlite3_libversion() { return utf8z.FromPtr(NativeMethods.sqlite3_libversion()); } int ISQLite3Provider.sqlite3_libversion_number() { return NativeMethods.sqlite3_libversion_number(); } int ISQLite3Provider.sqlite3_threadsafe() { return NativeMethods.sqlite3_threadsafe(); } int ISQLite3Provider.sqlite3_config(int op) { return NativeMethods.sqlite3_config_none(op); } int ISQLite3Provider.sqlite3_config(int op, int val) { return NativeMethods.sqlite3_config_int(op, val); } int ISQLite3Provider.sqlite3_initialize() { return NativeMethods.sqlite3_initialize(); } int ISQLite3Provider.sqlite3_shutdown() { return NativeMethods.sqlite3_shutdown(); } int ISQLite3Provider.sqlite3_enable_load_extension(sqlite3 db, int onoff) { return NativeMethods.sqlite3_enable_load_extension(db, onoff); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. The implementation details // can vary depending on the .NET implementation, so we hide these // in platform-specific code underneath the ISQLite3Provider boundary. // // The caller gives us a delegate and an object they want passed to that // delegate. We do not actually pass that stuff down to SQLite as // the callback. Instead, we store the information and pass down a bridge // function, with an IntPtr that can be used to retrieve the info later. // // When SQLite calls the bridge function, we lookup the info we previously // stored and call the delegate provided by the upper layer. // // The class we use to remember the original info (delegate and user object) // is shared but not portable. It is in the util.cs file which is compiled // into each platform assembly. [MonoPInvokeCallback (typeof(NativeMethods.callback_commit))] static int commit_hook_bridge_impl(IntPtr p) { commit_hook_info hi = commit_hook_info.from_ptr(p); return hi.call(); } readonly NativeMethods.callback_commit commit_hook_bridge = new NativeMethods.callback_commit(commit_hook_bridge_impl); void ISQLite3Provider.sqlite3_commit_hook(sqlite3 db, delegate_commit func, object v) { var info = get_hooks(db); if (info.commit != null) { // TODO maybe turn off the hook here, for now info.commit.Dispose(); info.commit = null; } NativeMethods.callback_commit cb; commit_hook_info hi; if (func != null) { cb = commit_hook_bridge; hi = new commit_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); NativeMethods.sqlite3_commit_hook(db, cb, h); info.commit = h.ForDispose(); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_scalar_function))] static void scalar_function_hook_bridge_impl(IntPtr context, int num_args, IntPtr argsptr) { IntPtr p = NativeMethods.sqlite3_user_data(context); function_hook_info hi = function_hook_info.from_ptr(p); hi.call_scalar(context, num_args, argsptr); } readonly NativeMethods.callback_scalar_function scalar_function_hook_bridge = new NativeMethods.callback_scalar_function(scalar_function_hook_bridge_impl); int ISQLite3Provider.sqlite3_create_function(sqlite3 db, byte[] name, int nargs, int flags, object v, delegate_function_scalar func) { var info = get_hooks(db); if (info.RemoveScalarFunction(name, nargs)) { // TODO maybe turn off the hook here, for now } // 1 is SQLITE_UTF8 int arg4 = 1 | flags; NativeMethods.callback_scalar_function cb; function_hook_info hi; if (func != null) { cb = scalar_function_hook_bridge; hi = new function_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); int rc = NativeMethods.sqlite3_create_function_v2(db, name, nargs, arg4, h, cb, null, null, null); if ((rc == 0) && (cb != null)) { info.AddScalarFunction(name, nargs, h.ForDispose()); } return rc; } // ---------------------------------------------------------------- static IDisposable disp_log_hook_handle; [MonoPInvokeCallback (typeof(NativeMethods.callback_log))] static void log_hook_bridge_impl(IntPtr p, int rc, IntPtr s) { log_hook_info hi = log_hook_info.from_ptr(p); hi.call(rc, utf8z.FromIntPtr(s)); } readonly NativeMethods.callback_log log_hook_bridge = new NativeMethods.callback_log(log_hook_bridge_impl); int ISQLite3Provider.sqlite3_config_log(delegate_log func, object v) { if (disp_log_hook_handle != null) { // TODO maybe turn off the hook here, for now disp_log_hook_handle.Dispose(); disp_log_hook_handle = null; } NativeMethods.callback_log cb; log_hook_info hi; if (func != null) { cb = log_hook_bridge; hi = new log_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); disp_log_hook_handle = h; // TODO if valid var rc = NativeMethods.sqlite3_config_log(raw.SQLITE_CONFIG_LOG, cb, h); return rc; } unsafe void ISQLite3Provider.sqlite3_log(int errcode, utf8z s) { fixed (byte* p = s) { NativeMethods.sqlite3_log(errcode, p); } } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_agg_function_step))] static void agg_function_step_hook_bridge_impl(IntPtr context, int num_args, IntPtr argsptr) { IntPtr agg = NativeMethods.sqlite3_aggregate_context(context, 8); // TODO error check agg nomem IntPtr p = NativeMethods.sqlite3_user_data(context); function_hook_info hi = function_hook_info.from_ptr(p); hi.call_step(context, agg, num_args, argsptr); } [MonoPInvokeCallback (typeof(NativeMethods.callback_agg_function_final))] static void agg_function_final_hook_bridge_impl(IntPtr context) { IntPtr agg = NativeMethods.sqlite3_aggregate_context(context, 8); // TODO error check agg nomem IntPtr p = NativeMethods.sqlite3_user_data(context); function_hook_info hi = function_hook_info.from_ptr(p); hi.call_final(context, agg); } readonly NativeMethods.callback_agg_function_step agg_function_step_hook_bridge = new NativeMethods.callback_agg_function_step(agg_function_step_hook_bridge_impl); readonly NativeMethods.callback_agg_function_final agg_function_final_hook_bridge = new NativeMethods.callback_agg_function_final(agg_function_final_hook_bridge_impl); int ISQLite3Provider.sqlite3_create_function(sqlite3 db, byte[] name, int nargs, int flags, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final) { var info = get_hooks(db); if (info.RemoveAggFunction(name, nargs)) { // TODO maybe turn off the hook here, for now } // 1 is SQLITE_UTF8 int arg4 = 1 | flags; NativeMethods.callback_agg_function_step cb_step; NativeMethods.callback_agg_function_final cb_final; function_hook_info hi; if (func_step != null) { // TODO both func_step and func_final must be non-null cb_step = agg_function_step_hook_bridge; cb_final = agg_function_final_hook_bridge; hi = new function_hook_info(func_step, func_final, v); } else { cb_step = null; cb_final = null; hi = null; } var h = new hook_handle(hi); int rc = NativeMethods.sqlite3_create_function_v2(db, name, nargs, arg4, h, null, cb_step, cb_final, null); if ((rc == 0) && (cb_step != null)) { info.AddAggFunction(name, nargs, h.ForDispose()); } return rc; } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_collation))] static int collation_hook_bridge_impl(IntPtr p, int len1, IntPtr pv1, int len2, IntPtr pv2) { collation_hook_info hi = collation_hook_info.from_ptr(p); ReadOnlySpan<byte> s1; ReadOnlySpan<byte> s2; unsafe { s1 = new ReadOnlySpan<byte>(pv1.ToPointer(), len1); s2 = new ReadOnlySpan<byte>(pv2.ToPointer(), len2); } return hi.call(s1, s2); } readonly NativeMethods.callback_collation collation_hook_bridge = new NativeMethods.callback_collation(collation_hook_bridge_impl); int ISQLite3Provider.sqlite3_create_collation(sqlite3 db, byte[] name, object v, delegate_collation func) { var info = get_hooks(db); if (info.RemoveCollation(name)) { // TODO maybe turn off the hook here, for now } NativeMethods.callback_collation cb; collation_hook_info hi; if (func != null) { cb = collation_hook_bridge; hi = new collation_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); // 1 is SQLITE_UTF8 int rc = NativeMethods.sqlite3_create_collation(db, name, 1, h, cb); if ((rc == 0) && (cb != null)) { info.AddCollation(name, h.ForDispose()); } return rc; } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_update))] static void update_hook_bridge_impl(IntPtr p, int typ, IntPtr db, IntPtr tbl, Int64 rowid) { update_hook_info hi = update_hook_info.from_ptr(p); hi.call(typ, utf8z.FromIntPtr(db), utf8z.FromIntPtr(tbl), rowid); } readonly NativeMethods.callback_update update_hook_bridge = new NativeMethods.callback_update(update_hook_bridge_impl); void ISQLite3Provider.sqlite3_update_hook(sqlite3 db, delegate_update func, object v) { var info = get_hooks(db); if (info.update != null) { // TODO maybe turn off the hook here, for now info.update.Dispose(); info.update = null; } NativeMethods.callback_update cb; update_hook_info hi; if (func != null) { cb = update_hook_bridge; hi = new update_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.update = h.ForDispose(); NativeMethods.sqlite3_update_hook(db, cb, h); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_rollback))] static void rollback_hook_bridge_impl(IntPtr p) { rollback_hook_info hi = rollback_hook_info.from_ptr(p); hi.call(); } readonly NativeMethods.callback_rollback rollback_hook_bridge = new NativeMethods.callback_rollback(rollback_hook_bridge_impl); void ISQLite3Provider.sqlite3_rollback_hook(sqlite3 db, delegate_rollback func, object v) { var info = get_hooks(db); if (info.rollback != null) { // TODO maybe turn off the hook here, for now info.rollback.Dispose(); info.rollback = null; } NativeMethods.callback_rollback cb; rollback_hook_info hi; if (func != null) { cb = rollback_hook_bridge; hi = new rollback_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.rollback = h.ForDispose(); NativeMethods.sqlite3_rollback_hook(db, cb, h); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_trace))] static void trace_hook_bridge_impl(IntPtr p, IntPtr s) { trace_hook_info hi = trace_hook_info.from_ptr(p); hi.call(utf8z.FromIntPtr(s)); } readonly NativeMethods.callback_trace trace_hook_bridge = new NativeMethods.callback_trace(trace_hook_bridge_impl); void ISQLite3Provider.sqlite3_trace(sqlite3 db, delegate_trace func, object v) { var info = get_hooks(db); if (info.trace != null) { // TODO maybe turn off the hook here, for now info.trace.Dispose(); info.trace = null; } NativeMethods.callback_trace cb; trace_hook_info hi; if (func != null) { cb = trace_hook_bridge; hi = new trace_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.trace = h.ForDispose(); NativeMethods.sqlite3_trace(db, cb, h); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_profile))] static void profile_hook_bridge_impl(IntPtr p, IntPtr s, long elapsed) { profile_hook_info hi = profile_hook_info.from_ptr(p); hi.call(utf8z.FromIntPtr(s), elapsed); } readonly NativeMethods.callback_profile profile_hook_bridge = new NativeMethods.callback_profile(profile_hook_bridge_impl); void ISQLite3Provider.sqlite3_profile(sqlite3 db, delegate_profile func, object v) { var info = get_hooks(db); if (info.profile != null) { // TODO maybe turn off the hook here, for now info.profile.Dispose(); info.profile = null; } NativeMethods.callback_profile cb; profile_hook_info hi; if (func != null) { cb = profile_hook_bridge; hi = new profile_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.profile = h.ForDispose(); NativeMethods.sqlite3_profile(db, cb, h); } // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_progress_handler))] static int progress_handler_hook_bridge_impl(IntPtr p) { progress_hook_info hi = progress_hook_info.from_ptr(p); return hi.call(); } readonly NativeMethods.callback_progress_handler progress_handler_hook_bridge = new NativeMethods.callback_progress_handler(progress_handler_hook_bridge_impl); void ISQLite3Provider.sqlite3_progress_handler(sqlite3 db, int instructions, delegate_progress func, object v) { var info = get_hooks(db); if (info.progress != null) { // TODO maybe turn off the hook here, for now info.progress.Dispose(); info.progress = null; } NativeMethods.callback_progress_handler cb; progress_hook_info hi; if (func != null) { cb = progress_handler_hook_bridge; hi = new progress_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.progress = h.ForDispose(); NativeMethods.sqlite3_progress_handler(db, instructions, cb, h); } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // Passing a callback into SQLite is tricky. See comments near commit_hook // implementation in pinvoke/SQLite3Provider.cs [MonoPInvokeCallback (typeof(NativeMethods.callback_authorizer))] static int authorizer_hook_bridge_impl(IntPtr p, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view) { authorizer_hook_info hi = authorizer_hook_info.from_ptr(p); return hi.call(action_code, utf8z.FromIntPtr(param0), utf8z.FromIntPtr(param1), utf8z.FromIntPtr(dbName), utf8z.FromIntPtr(inner_most_trigger_or_view)); } readonly NativeMethods.callback_authorizer authorizer_hook_bridge = new NativeMethods.callback_authorizer(authorizer_hook_bridge_impl); int ISQLite3Provider.sqlite3_set_authorizer(sqlite3 db, delegate_authorizer func, object v) { var info = get_hooks(db); if (info.authorizer != null) { // TODO maybe turn off the hook here, for now info.authorizer.Dispose(); info.authorizer = null; } NativeMethods.callback_authorizer cb; authorizer_hook_info hi; if (func != null) { cb = authorizer_hook_bridge; hi = new authorizer_hook_info(func, v); } else { cb = null; hi = null; } var h = new hook_handle(hi); info.authorizer = h.ForDispose(); return NativeMethods.sqlite3_set_authorizer(db, cb, h); } // ---------------------------------------------------------------- long ISQLite3Provider.sqlite3_memory_used() { return NativeMethods.sqlite3_memory_used(); } long ISQLite3Provider.sqlite3_memory_highwater(int resetFlag) { return NativeMethods.sqlite3_memory_highwater(resetFlag); } int ISQLite3Provider.sqlite3_status(int op, out int current, out int highwater, int resetFlag) { return NativeMethods.sqlite3_status(op, out current, out highwater, resetFlag); } unsafe utf8z ISQLite3Provider.sqlite3_sourceid() { return utf8z.FromPtr(NativeMethods.sqlite3_sourceid()); } void ISQLite3Provider.sqlite3_result_int64(IntPtr ctx, long val) { NativeMethods.sqlite3_result_int64(ctx, val); } void ISQLite3Provider.sqlite3_result_int(IntPtr ctx, int val) { NativeMethods.sqlite3_result_int(ctx, val); } void ISQLite3Provider.sqlite3_result_double(IntPtr ctx, double val) { NativeMethods.sqlite3_result_double(ctx, val); } void ISQLite3Provider.sqlite3_result_null(IntPtr stm) { NativeMethods.sqlite3_result_null(stm); } unsafe void ISQLite3Provider.sqlite3_result_error(IntPtr ctx, ReadOnlySpan<byte> val) { fixed (byte* p = val) { NativeMethods.sqlite3_result_error(ctx, p, val.Length); } } unsafe void ISQLite3Provider.sqlite3_result_error(IntPtr ctx, utf8z val) { fixed (byte* p = val) { NativeMethods.sqlite3_result_error(ctx, p, -1); } } unsafe void ISQLite3Provider.sqlite3_result_text(IntPtr ctx, ReadOnlySpan<byte> val) { fixed (byte* p = val) { NativeMethods.sqlite3_result_text(ctx, p, val.Length, new IntPtr(-1)); } } unsafe void ISQLite3Provider.sqlite3_result_text(IntPtr ctx, utf8z val) { fixed (byte* p = val) { NativeMethods.sqlite3_result_text(ctx, p, -1, new IntPtr(-1)); } } unsafe void ISQLite3Provider.sqlite3_result_blob(IntPtr ctx, ReadOnlySpan<byte> blob) { fixed (byte* p = blob) { NativeMethods.sqlite3_result_blob(ctx, (IntPtr) p, blob.Length, new IntPtr(-1)); } } void ISQLite3Provider.sqlite3_result_zeroblob(IntPtr ctx, int n) { NativeMethods.sqlite3_result_zeroblob(ctx, n); } // TODO sqlite3_result_value void ISQLite3Provider.sqlite3_result_error_toobig(IntPtr ctx) { NativeMethods.sqlite3_result_error_toobig(ctx); } void ISQLite3Provider.sqlite3_result_error_nomem(IntPtr ctx) { NativeMethods.sqlite3_result_error_nomem(ctx); } void ISQLite3Provider.sqlite3_result_error_code(IntPtr ctx, int code) { NativeMethods.sqlite3_result_error_code(ctx, code); } ReadOnlySpan<byte> ISQLite3Provider.sqlite3_value_blob(IntPtr p) { IntPtr blobPointer = NativeMethods.sqlite3_value_blob(p); if (blobPointer == IntPtr.Zero) { return null; } var length = NativeMethods.sqlite3_value_bytes(p); unsafe { return new ReadOnlySpan<byte>(blobPointer.ToPointer(), length); } } int ISQLite3Provider.sqlite3_value_bytes(IntPtr p) { return NativeMethods.sqlite3_value_bytes(p); } double ISQLite3Provider.sqlite3_value_double(IntPtr p) { return NativeMethods.sqlite3_value_double(p); } int ISQLite3Provider.sqlite3_value_int(IntPtr p) { return NativeMethods.sqlite3_value_int(p); } long ISQLite3Provider.sqlite3_value_int64(IntPtr p) { return NativeMethods.sqlite3_value_int64(p); } int ISQLite3Provider.sqlite3_value_type(IntPtr p) { return NativeMethods.sqlite3_value_type(p); } unsafe utf8z ISQLite3Provider.sqlite3_value_text(IntPtr p) { return utf8z.FromPtr(NativeMethods.sqlite3_value_text(p)); } int ISQLite3Provider.sqlite3_bind_int(sqlite3_stmt stm, int paramIndex, int val) { return NativeMethods.sqlite3_bind_int(stm, paramIndex, val); } int ISQLite3Provider.sqlite3_bind_int64(sqlite3_stmt stm, int paramIndex, long val) { return NativeMethods.sqlite3_bind_int64(stm, paramIndex, val); } unsafe int ISQLite3Provider.sqlite3_bind_text(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<byte> t) { fixed (byte* p_t = t) { return NativeMethods.sqlite3_bind_text(stm, paramIndex, p_t, t.Length, new IntPtr(-1)); } } unsafe int ISQLite3Provider.sqlite3_bind_text16(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<char> t) { fixed (char* p_t = t) { // mul span length times 2 to get num bytes, which is what sqlite wants return NativeMethods.sqlite3_bind_text16(stm, paramIndex, p_t, t.Length * 2, new IntPtr(-1)); } } unsafe int ISQLite3Provider.sqlite3_bind_text(sqlite3_stmt stm, int paramIndex, utf8z t) { fixed (byte* p_t = t) { return NativeMethods.sqlite3_bind_text(stm, paramIndex, p_t, -1, new IntPtr(-1)); } } int ISQLite3Provider.sqlite3_bind_double(sqlite3_stmt stm, int paramIndex, double val) { return NativeMethods.sqlite3_bind_double(stm, paramIndex, val); } unsafe int ISQLite3Provider.sqlite3_bind_blob(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<byte> blob) { if (blob.Length == 0) { // passing a zero-length blob to sqlite3_bind_blob() requires // a non-null pointer, even though conceptually, that pointer // point to zero things, ie nothing. var ba_fake = new byte[] { 42 }; ReadOnlySpan<byte> span_fake = ba_fake; fixed (byte* p_fake = span_fake) { return NativeMethods.sqlite3_bind_blob(stm, paramIndex, p_fake, 0, new IntPtr(-1)); } } else { fixed (byte* p = blob) { return NativeMethods.sqlite3_bind_blob(stm, paramIndex, p, blob.Length, new IntPtr(-1)); } } } int ISQLite3Provider.sqlite3_bind_zeroblob(sqlite3_stmt stm, int paramIndex, int size) { return NativeMethods.sqlite3_bind_zeroblob(stm, paramIndex, size); } int ISQLite3Provider.sqlite3_bind_null(sqlite3_stmt stm, int paramIndex) { return NativeMethods.sqlite3_bind_null(stm, paramIndex); } int ISQLite3Provider.sqlite3_bind_parameter_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_bind_parameter_count(stm); } unsafe utf8z ISQLite3Provider.sqlite3_bind_parameter_name(sqlite3_stmt stm, int paramIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_bind_parameter_name(stm, paramIndex)); } unsafe int ISQLite3Provider.sqlite3_bind_parameter_index(sqlite3_stmt stm, utf8z paramName) { fixed (byte* p_paramName = paramName) { return NativeMethods.sqlite3_bind_parameter_index(stm, p_paramName); } } int ISQLite3Provider.sqlite3_step(sqlite3_stmt stm) { return NativeMethods.sqlite3_step(stm); } int ISQLite3Provider.sqlite3_stmt_isexplain(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_isexplain(stm); } int ISQLite3Provider.sqlite3_stmt_busy(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_busy(stm); } int ISQLite3Provider.sqlite3_stmt_readonly(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_readonly(stm); } int ISQLite3Provider.sqlite3_column_int(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_int(stm, columnIndex); } long ISQLite3Provider.sqlite3_column_int64(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_int64(stm, columnIndex); } unsafe utf8z ISQLite3Provider.sqlite3_column_text(sqlite3_stmt stm, int columnIndex) { byte* p = NativeMethods.sqlite3_column_text(stm, columnIndex); var length = NativeMethods.sqlite3_column_bytes(stm, columnIndex); return utf8z.FromPtrLen(p, length); } unsafe utf8z ISQLite3Provider.sqlite3_column_decltype(sqlite3_stmt stm, int columnIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_column_decltype(stm, columnIndex)); } double ISQLite3Provider.sqlite3_column_double(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_double(stm, columnIndex); } ReadOnlySpan<byte> ISQLite3Provider.sqlite3_column_blob(sqlite3_stmt stm, int columnIndex) { IntPtr blobPointer = NativeMethods.sqlite3_column_blob(stm, columnIndex); if (blobPointer == IntPtr.Zero) { return null; } var length = NativeMethods.sqlite3_column_bytes(stm, columnIndex); unsafe { return new ReadOnlySpan<byte>(blobPointer.ToPointer(), length); } } int ISQLite3Provider.sqlite3_column_type(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_type(stm, columnIndex); } int ISQLite3Provider.sqlite3_column_bytes(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_bytes(stm, columnIndex); } int ISQLite3Provider.sqlite3_column_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_column_count(stm); } int ISQLite3Provider.sqlite3_data_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_data_count(stm); } unsafe utf8z ISQLite3Provider.sqlite3_column_name(sqlite3_stmt stm, int columnIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_column_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_origin_name(sqlite3_stmt stm, int columnIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_column_origin_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_table_name(sqlite3_stmt stm, int columnIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_column_table_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_database_name(sqlite3_stmt stm, int columnIndex) { return utf8z.FromPtr(NativeMethods.sqlite3_column_database_name(stm, columnIndex)); } int ISQLite3Provider.sqlite3_reset(sqlite3_stmt stm) { return NativeMethods.sqlite3_reset(stm); } int ISQLite3Provider.sqlite3_clear_bindings(sqlite3_stmt stm) { return NativeMethods.sqlite3_clear_bindings(stm); } int ISQLite3Provider.sqlite3_stmt_status(sqlite3_stmt stm, int op, int resetFlg) { return NativeMethods.sqlite3_stmt_status(stm, op, resetFlg); } int ISQLite3Provider.sqlite3_finalize(IntPtr stm) { return NativeMethods.sqlite3_finalize(stm); } int ISQLite3Provider.sqlite3_wal_autocheckpoint(sqlite3 db, int n) { return NativeMethods.sqlite3_wal_autocheckpoint(db, n); } unsafe int ISQLite3Provider.sqlite3_wal_checkpoint(sqlite3 db, utf8z dbName) { fixed (byte* p_dbName = dbName) { return NativeMethods.sqlite3_wal_checkpoint(db, p_dbName); } } unsafe int ISQLite3Provider.sqlite3_wal_checkpoint_v2(sqlite3 db, utf8z dbName, int eMode, out int logSize, out int framesCheckPointed) { fixed (byte* p_dbName = dbName) { return NativeMethods.sqlite3_wal_checkpoint_v2(db, p_dbName, eMode, out logSize, out framesCheckPointed); } } int ISQLite3Provider.sqlite3_keyword_count() { return NativeMethods.sqlite3_keyword_count(); } unsafe int ISQLite3Provider.sqlite3_keyword_name(int i, out string name) { var rc = NativeMethods.sqlite3_keyword_name(i, out var p_name, out var length); // p_name is NOT null-terminated name = Encoding.UTF8.GetString(p_name, length); return rc; } static class NativeMethods { private const string SQLITE_DLL = "winsqlite3"; [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_close(IntPtr db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_close_v2(IntPtr db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_enable_shared_cache(int enable); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_interrupt(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_finalize(IntPtr stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_reset(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_clear_bindings(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_stmt_status(sqlite3_stmt stm, int op, int resetFlg); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_bind_parameter_name(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_database_name(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_decltype(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_name(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_origin_name(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_table_name(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_column_text(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_errmsg(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_db_readonly(sqlite3 db, byte* dbName); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_db_filename(sqlite3 db, byte* att); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_prepare_v2(sqlite3 db, byte* pSql, int nBytes, out IntPtr stmt, out byte* ptrRemain); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_prepare_v3(sqlite3 db, byte* pSql, int nBytes, uint flags, out IntPtr stmt, out byte* ptrRemain); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_complete(byte* pSql); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_compileoption_used(byte* pSql); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_compileoption_get(int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_table_column_metadata(sqlite3 db, byte* dbName, byte* tblName, byte* colName, out byte* ptrDataType, out byte* ptrCollSeq, out int notNull, out int primaryKey, out int autoInc); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_value_text(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_enable_load_extension(sqlite3 db, int enable); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_initialize(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_shutdown(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_libversion(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_libversion_number(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_threadsafe(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_sourceid(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_malloc(int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_realloc(IntPtr p, int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_free(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_stricmp(IntPtr p, IntPtr q); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_strnicmp(IntPtr p, IntPtr q, int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_open(byte* filename, out IntPtr db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_open_v2(byte* filename, out IntPtr db, int flags, byte* vfs); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_vfs_find(byte* vfs); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe long sqlite3_last_insert_rowid(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_changes(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_total_changes(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe long sqlite3_memory_used(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe long sqlite3_memory_highwater(int resetFlag); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_status(int op, out int current, out int highwater, int resetFlag); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_busy_timeout(sqlite3 db, int ms); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_blob(sqlite3_stmt stmt, int index, byte* val, int nSize, IntPtr nTransient); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_zeroblob(sqlite3_stmt stmt, int index, int size); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_double(sqlite3_stmt stmt, int index, double val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_int(sqlite3_stmt stmt, int index, int val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_int64(sqlite3_stmt stmt, int index, long val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_null(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_text(sqlite3_stmt stmt, int index, byte* val, int nlen, IntPtr pvReserved); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_text16(sqlite3_stmt stmt, int index, char* val, int nlen, IntPtr pvReserved); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_parameter_count(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_bind_parameter_index(sqlite3_stmt stmt, byte* strName); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_column_count(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_data_count(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_step(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_sql(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe double sqlite3_column_double(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_column_int(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe long sqlite3_column_int64(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_column_blob(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_column_bytes(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_column_type(sqlite3_stmt stmt, int index); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_aggregate_count(IntPtr context); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_value_blob(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_value_bytes(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe double sqlite3_value_double(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_value_int(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe long sqlite3_value_int64(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_value_type(IntPtr p); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_user_data(IntPtr context); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_blob(IntPtr context, IntPtr val, int nSize, IntPtr pvReserved); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_double(IntPtr context, double val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_error(IntPtr context, byte* strErr, int nLen); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_int(IntPtr context, int val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_int64(IntPtr context, long val); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_null(IntPtr context); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_text(IntPtr context, byte* val, int nLen, IntPtr pvReserved); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_zeroblob(IntPtr context, int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_error_toobig(IntPtr context); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_error_nomem(IntPtr context); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_result_error_code(IntPtr context, int code); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes); [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_config_none(int op); [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_config_int(int op, int val); [DllImport(SQLITE_DLL, ExactSpelling=true, EntryPoint = "sqlite3_config", CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_config_log(int op, NativeMethods.callback_log func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_create_collation(sqlite3 db, byte[] strName, int nType, hook_handle pvUser, NativeMethods.callback_collation func); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_update_hook(sqlite3 db, NativeMethods.callback_update func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_commit_hook(sqlite3 db, NativeMethods.callback_commit func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_profile(sqlite3 db, NativeMethods.callback_profile func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_progress_handler(sqlite3 db, int instructions, NativeMethods.callback_progress_handler func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_trace(sqlite3 db, NativeMethods.callback_trace func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_rollback_hook(sqlite3 db, NativeMethods.callback_rollback func, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_db_handle(IntPtr stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe IntPtr sqlite3_next_stmt(sqlite3 db, IntPtr stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_stmt_isexplain(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_stmt_busy(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_stmt_readonly(sqlite3_stmt stmt); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_exec(sqlite3 db, byte* strSql, NativeMethods.callback_exec cb, hook_handle pvParam, out IntPtr errMsg); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_get_autocommit(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_extended_result_codes(sqlite3 db, int onoff); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_errcode(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_extended_errcode(sqlite3 db); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe byte* sqlite3_errstr(int rc); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_log(int iErrCode, byte* zFormat); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_file_control(sqlite3 db, byte[] zDbName, int op, IntPtr pArg); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe sqlite3_backup sqlite3_backup_init(sqlite3 destDb, byte* zDestName, sqlite3 sourceDb, byte* zSourceName); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_backup_step(sqlite3_backup backup, int nPage); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_backup_remaining(sqlite3_backup backup); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_backup_pagecount(sqlite3_backup backup); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_backup_finish(IntPtr backup); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_snapshot_get(sqlite3 db, byte* schema, out IntPtr snap); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_snapshot_open(sqlite3 db, byte* schema, sqlite3_snapshot snap); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_snapshot_recover(sqlite3 db, byte* name); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe void sqlite3_snapshot_free(IntPtr snap); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_open(sqlite3 db, byte* sdb, byte* table, byte* col, long rowid, int flags, out IntPtr blob); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_write(sqlite3_blob blob, byte* b, int n, int offset); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_read(sqlite3_blob blob, byte* b, int n, int offset); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_bytes(sqlite3_blob blob); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_reopen(sqlite3_blob blob, long rowid); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_blob_close(IntPtr blob); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_wal_autocheckpoint(sqlite3 db, int n); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_wal_checkpoint(sqlite3 db, byte* dbName); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_wal_checkpoint_v2(sqlite3 db, byte* dbName, int eMode, out int logSize, out int framesCheckPointed); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_set_authorizer(sqlite3 db, NativeMethods.callback_authorizer cb, hook_handle pvUser); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_win32_set_directory8(uint directoryType, byte* directoryPath); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_create_function_v2(sqlite3 db, byte[] strName, int nArgs, int nType, hook_handle pvUser, NativeMethods.callback_scalar_function func, NativeMethods.callback_agg_function_step fstep, NativeMethods.callback_agg_function_final ffinal, NativeMethods.callback_destroy fdestroy); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_keyword_count(); [DllImport(SQLITE_DLL, ExactSpelling=true, CallingConvention = CALLING_CONVENTION)] public static extern unsafe int sqlite3_keyword_name(int i, out byte* name, out int length); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_log(IntPtr pUserData, int errorCode, IntPtr pMessage); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_scalar_function(IntPtr context, int nArgs, IntPtr argsptr); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_agg_function_step(IntPtr context, int nArgs, IntPtr argsptr); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_agg_function_final(IntPtr context); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_destroy(IntPtr p); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate int callback_collation(IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_update(IntPtr p, int typ, IntPtr db, IntPtr tbl, long rowid); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate int callback_commit(IntPtr puser); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_profile(IntPtr puser, IntPtr statement, long elapsed); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate int callback_progress_handler(IntPtr puser); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate int callback_authorizer(IntPtr puser, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_trace(IntPtr puser, IntPtr statement); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate void callback_rollback(IntPtr puser); [UnmanagedFunctionPointer(CALLING_CONVENTION)] public delegate int callback_exec(IntPtr db, int n, IntPtr values, IntPtr names); } } }
40.062533
315
0.673417
[ "Apache-2.0" ]
Chatina73/SQLitePCL.raw
src/SQLitePCLRaw.provider.winsqlite3/Generated/provider_winsqlite3.cs
75,599
C#
// MIT License // // Copyright (c) 2017 Kyle Kingsbury // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace Sitecore.Feature.Blog.Resolvers { using System; using System.Collections.Generic; using Tokens; public class MappedResolver { /// <summary> /// Gets the Mapped Tokens /// </summary> public IList<MappedToken> Tokens { get; private set; } /// <summary> /// Gets the Resolver taht resolved the tokens /// </summary> public IResolver ResolvedBy { get; private set; } public MappedResolver(IResolver resolvedBy, IList<MappedToken> tokens) { if (resolvedBy == null) { throw new ArgumentNullException(nameof(resolvedBy)); } this.ResolvedBy = resolvedBy; this.Tokens = tokens; } } }
37.470588
81
0.680272
[ "MIT" ]
KKings/Sitecore.Feature.Blog
src/Feature/Blog/code/Resolvers/MappedResolver.cs
1,913
C#
using System.ComponentModel.DataAnnotations; namespace LookupBusiness.Models { public class Shop { public int ShopId { get; set; } [Required] [StringLength(50)] public string Name { get; set; } [Required] [StringLength(200)] public string Offerings { get; set; } [Required] public string NearestIntersection { get; set; } [Required] [Range(1, 5, ErrorMessage = "1 being affordable, 5 being super expensive")] public int Pricing { get; set; } } }
25
79
0.658
[ "MIT" ]
taylulz/LookupBusiness
APILookupBusiness/Models/Shop.cs
500
C#
using System.Globalization; namespace Microsoft.Recognizers.Text.NumberWithUnit.French { public class LengthParserConfiguration : FrenchNumberWithUnitParserConfiguration { public LengthParserConfiguration() : this(new CultureInfo(Culture.French)) { } public LengthParserConfiguration(CultureInfo ci) : base(ci) { this.BindDictionary(LengthExtractorConfiguration.LengthSuffixList); } } }
29.733333
86
0.730942
[ "MIT" ]
Cicero96/Recognizers-Text
.NET/Microsoft.Recognizers.Text.NumberWithUnit/French/Parsers/LengthParserConfiguration.cs
448
C#
namespace WindowsIcon { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); } } }
17.214286
45
0.539419
[ "MIT" ]
ChrisDiky/MaterialDesignInXaml.Examples
MahApps/WindowIcon/WindowsIcon/MainWindow.xaml.cs
243
C#
// ***************************************************************************** // // © Component Factory Pty Ltd 2012 - 2019 - 2019. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 4.5.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Text; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; using ComponentFactory.Krypton.Navigator; using ComponentFactory.Krypton.Docking; namespace NavigatorAndFloatingWindows { public partial class ContentDocument : UserControl { public ContentDocument() { InitializeComponent(); } } }
31.5625
81
0.625743
[ "BSD-3-Clause" ]
anuprakash/Krypton-NET-5.472
Source/Krypton Docking Examples/Navigator + FloatingWindows/ContentDocument.cs
1,013
C#
using System; using System.IO; using GroupDocs.Conversion.Options.Convert; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert XML file into TXT format. /// For more details about Extended Markup Language (.xml) to Plain Text File Format (.txt) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-xml-to-txt /// </summary> internal static class ConvertXmlToTxt { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "xml-converted-to.txt"); // Load the source XML file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_XML)) { WordProcessingConvertOptions options = new WordProcessingConvertOptions { Format = GroupDocs.Conversion.FileTypes.WordProcessingFileType.Txt }; // Save converted TXT file converter.Convert(outputFile, options); } Console.WriteLine("\nConversion to txt completed successfully. \nCheck output in {0}", outputFolder); } } }
41.16129
159
0.664577
[ "MIT" ]
groupdocs-conversion/GroupDocs.Conversion-for-.NET
Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToWordProcessing/ConvertToTxt/ConvertXmlToTxt.cs
1,276
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; using Object = UnityEngine.Object; namespace UnityEditor.Timeline { static class SequencerContextMenu { static readonly TimelineAction[] MarkerHeaderCommonOperations = { new PasteAction() }; public static readonly TimelineAction[] MarkerHeaderMenuItems = TimelineAction.AllActions.OfType<MarkerHeaderAction>(). Where(a => a.showInMenu). Union(MarkerHeaderCommonOperations). ToArray(); static class Styles { public static readonly string addItemFromAssetTemplate = L10n.Tr("Add {0} From {1}"); public static readonly string addSingleItemFromAssetTemplate = L10n.Tr("Add From {1}"); public static readonly string addItemTemplate = L10n.Tr("Add {0}"); public static readonly string typeSelectorTemplate = L10n.Tr("Select {0}"); public static readonly string trackGroup = L10n.Tr("Track Group"); public static readonly string trackSubGroup = L10n.Tr("Track Sub-Group"); public static readonly string addTrackLayer = L10n.Tr("Add Layer"); public static readonly string layerName = L10n.Tr("Layer {0}"); } public static void ShowMarkerHeaderContextMenu(Vector2? mousePosition, WindowState state) { var menu = new GenericMenu(); List<MenuActionItem> items = new List<MenuActionItem>(100); BuildMarkerHeaderContextMenu(items, mousePosition, state); MenuItemActionBase.BuildMenu(menu, items); menu.ShowAsContext(); } public static void ShowNewTracksContextMenu(ICollection<TrackAsset> tracks, WindowState state) { var menu = new GenericMenu(); List<MenuActionItem> items = new List<MenuActionItem>(100); BuildNewTracksContextMenu(items, tracks, state); MenuItemActionBase.BuildMenu(menu, items); menu.ShowAsContext(); } public static void ShowNewTracksContextMenu(ICollection<TrackAsset> tracks, WindowState state, Rect rect) { var menu = new GenericMenu(); List<MenuActionItem> items = new List<MenuActionItem>(100); BuildNewTracksContextMenu(items, tracks, state); MenuItemActionBase.BuildMenu(menu, items); menu.DropDown(rect); } public static void ShowTrackContextMenu(TrackAsset[] tracks, Vector2? mousePosition) { if (tracks == null || tracks.Length == 0) return; var items = new List<MenuActionItem>(); var menu = new GenericMenu(); BuildTrackContextMenu(items, tracks, mousePosition); MenuItemActionBase.BuildMenu(menu, items); menu.ShowAsContext(); } public static void ShowItemContextMenu(Vector2 mousePosition, TimelineClip[] clips, IMarker[] markers) { var menu = new GenericMenu(); var items = new List<MenuActionItem>(); BuildItemContextMenu(items, mousePosition, clips, markers); MenuItemActionBase.BuildMenu(menu, items); menu.ShowAsContext(); } internal static void BuildItemContextMenu(List<MenuActionItem> items, Vector2 mousePosition, TimelineClip[] clips, IMarker[] markers) { var state = TimelineWindow.instance.state; TimelineAction.GetMenuEntries(TimelineAction.MenuActions, mousePosition, items); ItemAction<TimelineClip>.GetMenuEntries(clips, items); ItemAction<IMarker>.GetMenuEntries(markers, items); if (clips.Length > 0) AddMarkerMenuCommands(items, clips.Select(c => c.parentTrack).Distinct().ToList(), TimelineHelpers.GetCandidateTime(state, mousePosition)); } internal static void BuildNewTracksContextMenu(List<MenuActionItem> menuItems, ICollection<TrackAsset> parentTracks, WindowState state, string format = null) { if (parentTracks == null) parentTracks = new TrackAsset[0]; if (string.IsNullOrEmpty(format)) format = "{0}"; // Add Group or SubGroup var title = string.Format(format, parentTracks.Any(t => t != null) ? Styles.trackSubGroup : Styles.trackGroup); var menuState = MenuActionDisplayState.Visible; if (state.editSequence.isReadOnly) menuState = MenuActionDisplayState.Disabled; if (parentTracks.Any() && parentTracks.Any(t => t != null && t.lockedInHierarchy)) menuState = MenuActionDisplayState.Disabled; GenericMenu.MenuFunction command = () => { SelectionManager.Clear(); if (parentTracks.Count == 0) Selection.Add(TimelineHelpers.CreateTrack<GroupTrack>(null, title)); foreach (var parentTrack in parentTracks) Selection.Add(TimelineHelpers.CreateTrack<GroupTrack>(parentTrack, title)); TimelineEditor.Refresh(RefreshReason.ContentsAddedOrRemoved); }; menuItems.Add( new MenuActionItem() { category = string.Empty, entryName = title, shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = MenuOrder.AddGroupItemStart, state = menuState, callback = command } ); var allTypes = TypeUtility.AllTrackTypes().Where(x => x != typeof(GroupTrack) && !TypeUtility.IsHiddenInMenu(x)).ToList(); int builtInPriority = MenuOrder.AddTrackItemStart; int customPriority = MenuOrder.AddCustomTrackItemStart; foreach (var trackType in allTypes) { var trackItemType = trackType; command = () => { SelectionManager.Clear(); if (parentTracks.Count == 0) SelectionManager.Add(TimelineHelpers.CreateTrack((Type)trackItemType, null)); foreach (var parentTrack in parentTracks) SelectionManager.Add(TimelineHelpers.CreateTrack((Type)trackItemType, parentTrack)); }; menuItems.Add( new MenuActionItem() { category = TimelineHelpers.GetTrackCategoryName(trackType), entryName = string.Format(format, TimelineHelpers.GetTrackMenuName(trackItemType)), shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = TypeUtility.IsBuiltIn(trackType) ? builtInPriority++ : customPriority++, state = menuState, callback = command } ); } } internal static void BuildMarkerHeaderContextMenu(List<MenuActionItem> menu, Vector2? mousePosition, WindowState state) { TimelineAction.GetMenuEntries(MarkerHeaderMenuItems, null, menu); var timeline = state.editSequence.asset; var time = TimelineHelpers.GetCandidateTime(state, mousePosition); var enabled = timeline.markerTrack == null || !timeline.markerTrack.lockedInHierarchy; var addMarkerCommand = new Action<Type, Object> ( (type, obj) => AddSingleMarkerCallback(type, time, timeline, state.editSequence.director, obj) ); AddMarkerMenuCommands(menu, new TrackAsset[] {timeline.markerTrack}, addMarkerCommand, enabled); } internal static void BuildTrackContextMenu(List<MenuActionItem> items, TrackAsset[] tracks, Vector2? mousePosition) { if (tracks == null || tracks.Length == 0) return; TimelineAction.GetMenuEntries(TimelineAction.MenuActions, mousePosition, items); TrackAction.GetMenuEntries(TimelineWindow.instance.state, mousePosition, tracks, items); AddLayeredTrackCommands(items, tracks); var first = tracks.First().GetType(); var allTheSame = tracks.All(t => t.GetType() == first); if (allTheSame) { if (first != typeof(GroupTrack)) { var candidateTime = TimelineHelpers.GetCandidateTime(TimelineWindow.instance.state, mousePosition, tracks); AddClipMenuCommands(items, tracks, candidateTime); AddMarkerMenuCommands(items, tracks, candidateTime); } else { BuildNewTracksContextMenu(items, tracks, TimelineWindow.instance.state, Styles.addItemTemplate); } } } static void AddLayeredTrackCommands(List<MenuActionItem> menuItems, ICollection<TrackAsset> tracks) { if (tracks.Count == 0) return; var layeredType = tracks.First().GetType(); // animation tracks have a special menu. if (layeredType == typeof(AnimationTrack)) return; // must implement ILayerable if (!typeof(UnityEngine.Timeline.ILayerable).IsAssignableFrom(layeredType)) return; if (tracks.Any(t => t.GetType() != layeredType)) return; // only supported on the master track no nesting. if (tracks.Any(t => t.isSubTrack)) return; var enabled = tracks.All(t => t != null && !t.lockedInHierarchy) && !TimelineWindow.instance.state.editSequence.isReadOnly; int priority = MenuOrder.TrackAddMenu.AddLayerTrack; GenericMenu.MenuFunction menuCallback = () => { foreach (var track in tracks) TimelineHelpers.CreateTrack(layeredType, track, string.Format(Styles.layerName, track.GetChildTracks().Count() + 1)); }; var entryName = Styles.addTrackLayer; menuItems.Add( new MenuActionItem() { category = string.Empty, entryName = entryName, shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = priority++, state = enabled ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled, callback = menuCallback } ); } static void AddClipMenuCommands(List<MenuActionItem> menuItems, ICollection<TrackAsset> tracks, double candidateTime) { if (!tracks.Any()) return; var trackAsset = tracks.First(); var trackType = trackAsset.GetType(); if (tracks.Any(t => t.GetType() != trackType)) return; var enabled = tracks.All(t => t != null && !t.lockedInHierarchy) && !TimelineWindow.instance.state.editSequence.isReadOnly; var assetTypes = TypeUtility.GetPlayableAssetsHandledByTrack(trackType); var visibleAssetTypes = TypeUtility.GetVisiblePlayableAssetsHandledByTrack(trackType); // skips the name if there is only a single type var commandNameTemplate = assetTypes.Count() == 1 ? Styles.addSingleItemFromAssetTemplate : Styles.addItemFromAssetTemplate; int builtInPriority = MenuOrder.AddClipItemStart; int customPriority = MenuOrder.AddCustomClipItemStart; foreach (var assetType in assetTypes) { var assetItemType = assetType; var category = TimelineHelpers.GetItemCategoryName(assetType); Action<Object> onObjectChanged = obj => { if (obj != null) { foreach (var t in tracks) { TimelineHelpers.CreateClipOnTrack(assetItemType, obj, t, candidateTime); } } }; foreach (var objectReference in TypeUtility.ObjectReferencesForType(assetType)) { var isSceneReference = objectReference.isSceneReference; var dataType = objectReference.type; GenericMenu.MenuFunction menuCallback = () => { ObjectSelector.get.Show(null, dataType, null, isSceneReference, null, (obj) => onObjectChanged(obj), null); ObjectSelector.get.titleContent = EditorGUIUtility.TrTextContent(string.Format(Styles.typeSelectorTemplate, TypeUtility.GetDisplayName(dataType))); }; menuItems.Add( new MenuActionItem() { category = category, entryName = string.Format(commandNameTemplate, TypeUtility.GetDisplayName(assetType), TypeUtility.GetDisplayName(objectReference.type)), shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = TypeUtility.IsBuiltIn(assetType) ? builtInPriority++ : customPriority++, state = enabled ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled, callback = menuCallback } ); } } foreach (var assetType in visibleAssetTypes) { var assetItemType = assetType; var category = TimelineHelpers.GetItemCategoryName(assetType); var commandName = string.Format(Styles.addItemTemplate, TypeUtility.GetDisplayName(assetType)); GenericMenu.MenuFunction command = () => { foreach (var t in tracks) { TimelineHelpers.CreateClipOnTrack(assetItemType, t, candidateTime); } }; menuItems.Add( new MenuActionItem() { category = category, entryName = commandName, shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = TypeUtility.IsBuiltIn(assetItemType) ? builtInPriority++ : customPriority++, state = enabled ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled, callback = command } ); } } static void AddMarkerMenuCommands(List<MenuActionItem> menu, IEnumerable<Type> markerTypes, Action<Type, Object> addMarkerCommand, bool enabled) { int builtInPriority = MenuOrder.AddMarkerItemStart; int customPriority = MenuOrder.AddCustomMarkerItemStart; foreach (var markerType in markerTypes) { var markerItemType = markerType; string category = TimelineHelpers.GetItemCategoryName(markerItemType); menu.Add( new MenuActionItem() { category = category, entryName = string.Format(Styles.addItemTemplate, TypeUtility.GetDisplayName(markerType)), shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = TypeUtility.IsBuiltIn(markerType) ? builtInPriority++ : customPriority++, state = enabled ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled, callback = () => addMarkerCommand(markerItemType, null) } ); foreach (var objectReference in TypeUtility.ObjectReferencesForType(markerType)) { var isSceneReference = objectReference.isSceneReference; GenericMenu.MenuFunction menuCallback = () => { var dataType = markerItemType; ObjectSelector.get.Show(null, dataType, null, isSceneReference, null, (obj) => addMarkerCommand(markerItemType, obj), null); ObjectSelector.get.titleContent = EditorGUIUtility.TrTextContent(string.Format(Styles.typeSelectorTemplate, TypeUtility.GetDisplayName(dataType))); }; menu.Add( new MenuActionItem() { category = TimelineHelpers.GetItemCategoryName(markerItemType), entryName = string.Format(Styles.addItemFromAssetTemplate, TypeUtility.GetDisplayName(markerType), TypeUtility.GetDisplayName(objectReference.type)), shortCut = string.Empty, isActiveInMode = true, isChecked = false, priority = TypeUtility.IsBuiltIn(markerType) ? builtInPriority++ : customPriority++, state = enabled ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled, callback = menuCallback } ); } } } static void AddMarkerMenuCommands(List<MenuActionItem> menuItems, ICollection<TrackAsset> tracks, double candidateTime) { if (tracks.Count == 0) return; var enabled = tracks.All(t => !t.lockedInHierarchy) && !TimelineWindow.instance.state.editSequence.isReadOnly; var addMarkerCommand = new Action<Type, Object>((type, obj) => AddMarkersCallback(tracks, type, candidateTime, obj)); AddMarkerMenuCommands(menuItems, tracks, addMarkerCommand, enabled); } static void AddMarkerMenuCommands(List<MenuActionItem> menuItems, ICollection<TrackAsset> tracks, Action<Type, Object> command, bool enabled) { var markerTypes = TypeUtility.GetBuiltInMarkerTypes().Union(TypeUtility.GetUserMarkerTypes()); if (tracks != null) markerTypes = markerTypes.Where(x => tracks.All(track => (track == null) || TypeUtility.DoesTrackSupportMarkerType(track, x))); // null track indicates marker track to be created AddMarkerMenuCommands(menuItems, markerTypes, command, enabled); } static void AddMarkersCallback(ICollection<TrackAsset> targets, Type markerType, double time, Object obj) { SelectionManager.Clear(); foreach (var target in targets) { var marker = TimelineHelpers.CreateMarkerOnTrack(markerType, obj, target, time); SelectionManager.Add(marker); } TimelineEditor.Refresh(RefreshReason.ContentsAddedOrRemoved); } static void AddSingleMarkerCallback(Type markerType, double time, TimelineAsset timeline, PlayableDirector director, Object assignableObject) { timeline.CreateMarkerTrack(); var markerTrack = timeline.markerTrack; SelectionManager.Clear(); var marker = TimelineHelpers.CreateMarkerOnTrack(markerType, assignableObject, markerTrack, time); SelectionManager.Add(marker); if (typeof(INotification).IsAssignableFrom(markerType) && director != null) { if (director != null && director.GetGenericBinding(markerTrack) == null) director.SetGenericBinding(markerTrack, director.gameObject); } TimelineEditor.Refresh(RefreshReason.ContentsAddedOrRemoved); } } }
46.109131
194
0.569338
[ "MIT" ]
16pxdesign/genetic-algorithm-unity
Library/PackageCache/com.unity.timeline@1.2.10/Editor/Actions/Menus/TimelineContextMenu.cs
20,703
C#
using UnityEngine; public class TrailComponent : MonoBehaviour { [SerializeField] protected SpriteRenderer _renderer; protected float _fadeStartTime; protected float _fadeEndTime; private void Awake() { _fadeStartTime = Time.time + 1.0f; _fadeEndTime = _fadeStartTime + 1.0f; } private void Update() { if(Time.time < _fadeStartTime) { return; } _renderer.color = new Color( _renderer.color.r, _renderer.color.g, _renderer.color.b, 0.7f * (_fadeEndTime - Time.time) ); if(Time.time >= _fadeEndTime) { Destroy(gameObject); } } }
20.078947
46
0.524246
[ "MIT" ]
Red-Plus-Blue/Ludum-Dare-48
Assets/Scripts/Components/TrailComponent.cs
763
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.UI.WebControls { using System; using System.Web.UI; using System.Web.UI.WebControls; public class DnnImageButton : ImageButton { public string IconKey { get; set; } public string IconSize { get; set; } public string IconStyle { get; set; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (string.IsNullOrEmpty(this.ImageUrl)) { this.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); } } } }
30.392857
116
0.625147
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs
853
C#
using System.ComponentModel.DataAnnotations; namespace Web.Models.Books { public class BooksCreateViewModel { [Required] [MaxLength(80, ErrorMessage = "Author name cannot be longer than 80 characters")] public string Author { get; set; } [Required] [MaxLength(80, ErrorMessage = "Title length cannot be more than 80 characters")] public string Title { get; set; } [Required] [Range(0, double.MaxValue, ErrorMessage = "Negative values are not accepted")] public decimal Price { get; set; } [Required] [RegularExpression(@"^\d{10}$|^\d{13}$", ErrorMessage = "ISBN should be either 10 or 13 characters long")] public string ISBN { get; set; } [Required] [Range(1, int.MaxValue, ErrorMessage = "Negative values or 0 are not accepted")] public int Pages { get; set; } } }
32.321429
114
0.624309
[ "MIT" ]
viksuper555/Csharp-Programming
MyLibrary/Web/Models/Books/BooksCreateViewModel.cs
907
C#
using System; using System.Collections; using System.Collections.Specialized; using System.Linq; using System.Web; using System.Web.SessionState; namespace Aranasoft.Cobweb.Mvc.Validation.Fakes { public class FakeHttpSessionState : HttpSessionStateBase { private SessionStateItemCollection _objects; public FakeHttpSessionState() { _objects = new SessionStateItemCollection(); } public override HttpSessionStateBase Contents { get { return this; } } public override int Count { get { return _objects.Count; } } public override object this[string name] { get { return _objects[name]; } set { _objects[name] = value; } } public override object this[int index] { get { return _objects[index]; } set { _objects[index] = value; } } public override NameObjectCollectionBase.KeysCollection Keys { get { return _objects.Keys; } } public override void Abandon() { _objects = new SessionStateItemCollection(); } public override void Add(string name, object value) { _objects[name] = value; } public override void Clear() { _objects.Clear(); } public override void CopyTo(Array array, int index) { var entities = new object[_objects.Count]; for (var entityIndex = 0; entityIndex < _objects.Count; entityIndex++) { entities[entityIndex] = _objects[entityIndex]; } entities.CopyTo(array, index); } public override IEnumerator GetEnumerator() { return _objects.GetEnumerator(); } public override void Remove(string name) { _objects.Remove(name); } public override void RemoveAll() { _objects.Clear(); } public override void RemoveAt(int index) { _objects.RemoveAt(index); } } }
27.157895
84
0.582849
[ "BSD-3-Clause" ]
aranasoft/cobweb
src/aspnet/src/mvc4.validation/Fakes/FakeHttpSessionState.cs
2,064
C#
using System; using System.Windows.Forms; namespace PPDFramework { /// <summary> /// フォーム拡張です。 /// </summary> public static class FormExtention { /// <summary> /// インボークします。 /// </summary> /// <param name="control"></param> /// <param name="action"></param> public static void Invoke(this Control control, Action action) { if (control.InvokeRequired && !control.IsDisposed) { try { control.Invoke(action); } catch { } } else { action(); } } } }
21.114286
70
0.404601
[ "Apache-2.0" ]
KHCmaster/PPD
Win/PPDFramework/FormExtention.cs
777
C#
namespace MassTransitBenchmark.Latency { using System; using System.Threading.Tasks; using MassTransit; using MassTransit.AmazonSqsTransport; public class AmazonSqsMessageLatencyTransport : IMessageLatencyTransport { readonly AmazonSqsHostSettings _hostSettings; readonly IMessageLatencySettings _settings; IBusControl _busControl; Uri _targetAddress; Task<ISendEndpoint> _targetEndpoint; public AmazonSqsMessageLatencyTransport(AmazonSqsHostSettings hostSettings, IMessageLatencySettings settings) { _hostSettings = hostSettings; _settings = settings; } public Task<ISendEndpoint> TargetEndpoint => _targetEndpoint; public async Task Start(Action<IReceiveEndpointConfigurator> callback) { _busControl = Bus.Factory.CreateUsingAmazonSqs(x => { x.Host(_hostSettings); x.ReceiveEndpoint("latency_consumer" + (_settings.Durable ? "" : "_express"), e => { e.Durable = _settings.Durable; e.PrefetchCount = _settings.PrefetchCount; if (_settings.ConcurrencyLimit > 0) e.ConcurrentMessageLimit = _settings.ConcurrencyLimit; callback(e); _targetAddress = e.InputAddress; }); }); await _busControl.StartAsync(); _targetEndpoint = _busControl.GetSendEndpoint(_targetAddress); } public async ValueTask DisposeAsync() { await _busControl.StopAsync(); } } }
30.285714
117
0.605542
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
tests/MassTransit.Benchmark/Latency/AmazonSqsMessageLatencyTransport.cs
1,696
C#
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; namespace MoreLinq.Test { /// <summary> /// Enumerable sequence which throws InvalidOperationException as soon as its /// enumerator is requested. Used to check lazy evaluation. /// </summary> internal sealed class BreakingSequence<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { throw new InvalidOperationException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
32.317073
82
0.676981
[ "Apache-2.0" ]
AndreyBogach/morelinq
MoreLinq.Test/BreakingSequence.cs
1,325
C#
using System; using LiteDB; using Newtonsoft.Json.Linq; namespace pony.Storage { public class PonyWriteEntity { private readonly BsonDocument _bsonDocument; private PonyWriteEntity(BsonDocument bsonDocument) { _bsonDocument = bsonDocument; } public BsonValue this[string key] => _bsonDocument[key]; public static PonyWriteEntity Parse(string text) { var bsonDocument = new BsonDocument {["_id"] = ObjectId.NewObjectId()}; var json = JObject.Parse(text); foreach (var (key, value) in json) { if (key.Equals("_id", StringComparison.InvariantCultureIgnoreCase)) { bsonDocument["_id"] = new ObjectId(value.Value<string>()); continue; } bsonDocument.Set(key, value); } return new PonyWriteEntity(bsonDocument); } public BsonDocument Save(ILiteCollection<BsonDocument> collection) { var id = collection.Insert(_bsonDocument); _bsonDocument["_id"] = id; return _bsonDocument; } public bool Delete(ILiteCollection<BsonDocument> collection) { return collection.Delete(_bsonDocument["_id"]); } public bool Update(ILiteCollection<BsonDocument> collection) { return collection.Update(_bsonDocument); } } }
27.777778
83
0.574
[ "MIT" ]
a-severin/pony
pony/Storage/PonyWriteEntity.cs
1,502
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace CastleTests.SpecializedResolvers { using System; using System.Linq; using Castle.MicroKernel.Handlers; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers.SpecializedResolvers; using CastleTests; using CastleTests.Components; using NUnit.Framework; [TestFixture] public class ArrayResolverTestCase : AbstractContainerTestCase { [Test(Description = "IOC-239")] public void ArrayResolution_UnresolvableDependencyCausesResolutionFailure() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel, true)); Container.Register( Component.For<IDependency>().ImplementedBy<ResolvableDependency>(), Component.For<IDependency>().ImplementedBy<UnresolvalbeDependencyWithPrimitiveConstructor>(), Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>() ); var exception = Assert.Throws<HandlerException>(() => Container.Resolve<IDependOnArray>()); var message = string.Format( "Can't create component '{1}' as it has dependencies to be satisfied.{0}{0}'{1}' is waiting for the following dependencies:{0}- Service '{2}' which was not registered.{0}- Parameter 'str' which was not provided. Did you forget to set the dependency?{0}", Environment.NewLine, typeof(UnresolvalbeDependencyWithPrimitiveConstructor).FullName, typeof(A).FullName); Assert.AreEqual(message, exception.Message); } [Test(Description = "IOC-239")] public void ArrayResolution_UnresolvableDependencyCausesResolutionFailure_ServiceConstructor() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel, true)); Container.Register( Component.For<IDependency>().ImplementedBy<ResolvableDependency>(), Component.For<IDependency>().ImplementedBy<UnresolvalbeDependencyWithAdditionalServiceConstructor>(), Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>() ); var exception = Assert.Throws<HandlerException>(() => Container.Resolve<IDependOnArray>()); var message = string.Format( "Can't create component '{1}' as it has dependencies to be satisfied.{0}{0}'{1}' is waiting for the following dependencies:{0}- Service '{2}' which was not registered.{0}- Service '{3}' which was not registered.{0}", Environment.NewLine, typeof(UnresolvalbeDependencyWithAdditionalServiceConstructor).FullName, typeof(A).FullName, typeof(IEmptyService).FullName); Assert.AreEqual(message, exception.Message); } [Test(Description = "IOC-239")] public void ArrayResolution_UnresolvableDependencyIsNotIncluded() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register( Component.For<IDependency>().ImplementedBy<ResolvableDependency>(), Component.For<IDependency>().ImplementedBy<UnresolvalbeDependency>(), Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>() ); var exception = Assert.Throws<HandlerException>(() => Container.Resolve<IDependOnArray>()); var message = string.Format( "Can't create component '{1}' as it has dependencies to be satisfied.{0}{0}'{1}' is waiting for the following dependencies:{0}- Service '{2}' which was not registered.{0}", Environment.NewLine, typeof(UnresolvalbeDependency).FullName, typeof(A).FullName); Assert.AreEqual(message, exception.Message); } [Test] public void Composite_service_can_be_resolved_without_triggering_circular_dependency_detection_fuse() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register(Classes.FromThisAssembly() .BasedOn<IEmptyService>() .WithService.Base() .ConfigureFor<EmptyServiceComposite>(r => r.Forward<EmptyServiceComposite>())); var composite = Container.Resolve<EmptyServiceComposite>(); Assert.AreEqual(5, composite.Inner.Length); } [Test(Description = "IOC-238")] public void Composite_service_can_be_resolved_without_triggering_circular_dependency_detection_fuse_composite_registered_first() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register( Component.For<IEmptyService, EmptyServiceComposite>().ImplementedBy<EmptyServiceComposite>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceB>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceDecorator>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceDecoratorViaProperty>() ); var composite = Container.Resolve<EmptyServiceComposite>(); Assert.AreEqual(4, composite.Inner.Length); } [Test] public void DependencyOnArrayOfServices_OnConstructor() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceB>(), Component.For<ArrayDepAsConstructor>()); var comp = Container.Resolve<ArrayDepAsConstructor>(); Assert.IsNotNull(comp); Assert.IsNotNull(comp.Services); Assert.AreEqual(2, comp.Services.Length); foreach (var service in comp.Services) { Assert.IsNotNull(service); } } [Test] public void DependencyOnArrayOfServices_OnProperty() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceB>(), Component.For<ArrayDepAsProperty>()); var comp = Container.Resolve<ArrayDepAsProperty>(); Assert.IsNotNull(comp); Assert.IsNotNull(comp.Services); Assert.AreEqual(2, comp.Services.Length); foreach (var service in comp.Services) { Assert.IsNotNull(service); } } [Test] public void DependencyOnArrayWhenEmpty() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel, true)); Container.Register(Component.For<ArrayDepAsConstructor>(), Component.For<ArrayDepAsProperty>()); var proxy = Container.Resolve<ArrayDepAsConstructor>(); Assert.IsNotNull(proxy.Services); var proxy2 = Container.Resolve<ArrayDepAsProperty>(); Assert.IsNotNull(proxy2.Services); } [Test] public void DependencyOn_ref_ArrayOfServices_OnConstructor() { Kernel.Resolver.AddSubResolver(new ArrayResolver(Kernel)); Container.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>(), Component.For<IEmptyService>().ImplementedBy<EmptyServiceB>(), Component.For<ArrayRefDepAsConstructor>()); var comp = Container.Resolve<ArrayRefDepAsConstructor>(); Assert.IsNotNull(comp); Assert.IsNotNull(comp.Services); Assert.AreEqual(2, comp.Services.Length); foreach (var service in comp.Services) { Assert.IsNotNull(service); } } [Test(Description = "IOC-240")] public void InjectAll() { Container.Kernel.Resolver.AddSubResolver(new ArrayResolver(Container.Kernel, true)); Container.Install(new CollectionServiceOverridesInstaller()); var fooItemTest = Container.Resolve<ArrayDepAsConstructor>("InjectAll"); var dependencies = fooItemTest.Services.Select(d => d.GetType()).ToList(); Assert.That(dependencies, Has.Count.EqualTo(3)); Assert.That(dependencies, Has.Member(typeof(EmptyServiceA))); Assert.That(dependencies, Has.Member(typeof(EmptyServiceB))); Assert.That(dependencies, Has.Member(typeof(EmptyServiceDecoratorViaProperty))); } [Test(Description = "IOC-240")] public void InjectFooAndBarOnly_WithArrayResolver() { Container.Kernel.Resolver.AddSubResolver(new ArrayResolver(Container.Kernel, true)); Container.Install(new CollectionServiceOverridesInstaller()); var fooItemTest = Container.Resolve<ArrayDepAsConstructor>("InjectFooAndBarOnly"); var dependencies = fooItemTest.Services.Select(d => d.GetType()).ToList(); Assert.That(dependencies, Has.Count.EqualTo(2)); Assert.That(dependencies, Has.Member(typeof(EmptyServiceA))); Assert.That(dependencies, Has.Member(typeof(EmptyServiceB))); } [Test(Description = "IOC-240")] public void InjectFooAndBarOnly_WithoutArrayResolver() { Container.Install(new CollectionServiceOverridesInstaller()); var fooItemTest = Container.Resolve<ArrayDepAsConstructor>("InjectFooAndBarOnly"); var dependencies = fooItemTest.Services.Select(d => d.GetType()).ToList(); Assert.That(dependencies, Has.Count.EqualTo(2)); Assert.That(dependencies, Has.Member(typeof(EmptyServiceA))); Assert.That(dependencies, Has.Member(typeof(EmptyServiceB))); } [Test(Description = "IOC-240")] public void InjectFooOnly_WithArrayResolver() { Container.Kernel.Resolver.AddSubResolver(new ArrayResolver(Container.Kernel, true)); Container.Install(new CollectionServiceOverridesInstaller()); var fooItemTest = Container.Resolve<ArrayDepAsConstructor>("InjectFooOnly"); var dependencies = fooItemTest.Services.Select(d => d.GetType()).ToList(); Assert.That(dependencies, Has.Count.EqualTo(1)); Assert.That(dependencies, Has.Member(typeof(EmptyServiceA))); } [Test(Description = "IOC-240")] public void InjectFooOnly_WithoutArrayResolver() { Container.Install(new CollectionServiceOverridesInstaller()); var fooItemTest = Container.Resolve<ArrayDepAsConstructor>("InjectFooOnly"); var dependencies = fooItemTest.Services.Select(d => d.GetType()).ToList(); Assert.That(dependencies, Has.Count.EqualTo(1)); Assert.That(dependencies, Has.Member(typeof(EmptyServiceA))); } } }
40.152091
260
0.721496
[ "Apache-2.0" ]
flcdrg/Windsor
src/Castle.Windsor.Tests/SpecializedResolvers/ArrayResolverTestCase.cs
10,562
C#
using UnityEngine; using UnityEditor; using System.Collections; namespace PrefabInPrefabAsset { [CustomEditor(typeof(PrefabInPrefab))] public class PrefabInPrefabEditor : Editor { private SerializedProperty prefab; private SerializedProperty moveComponents; private SerializedProperty previewInEditor; void OnEnable() { prefab = serializedObject.FindProperty("prefab"); moveComponents = serializedObject.FindProperty("moveComponents"); previewInEditor = serializedObject.FindProperty("previewInEditor"); } public override void OnInspectorGUI() { serializedObject.Update(); prefab.objectReferenceValue = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab.objectReferenceValue, typeof(GameObject), false); moveComponents.boolValue = EditorGUILayout.Toggle("Move Components", moveComponents.boolValue); previewInEditor.boolValue = EditorGUILayout.Toggle("Preview In Editor", previewInEditor.boolValue); if(GUI.changed) { serializedObject.ApplyModifiedProperties(); var targetComponent = target as PrefabInPrefab; targetComponent.ForceDrawDontEditablePrefab(); } } } }
30.944444
138
0.802513
[ "MIT" ]
anchan828/prefab_in_prefab
Assets/PrefabInPrefab/Editor/PrefabInPrefabEditor.cs
1,116
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MoneyTaker { public partial class AddTradeForm : Form { private FormExchangeManager formManager; public AddTradeForm() { InitializeComponent(); } internal void SetFormManager(FormExchangeManager formManager) { this.formManager = formManager; } private async void btnCancle_Click(object sender, EventArgs e) { await Task.Delay(150); formManager.ShowTabBasicForm(); } private async void AddTradeForm_Load(object sender, EventArgs e) { // Tab Form Add AddTradeFirstForm tradeFirstForm = new AddTradeFirstForm(); tradeFirstForm.TopLevel = false; tradeFirstForm.SetFormManager(formManager); tradeFirstForm.SetTradePanel(panelTrade); tradeFirstForm.Show(); panelTrade.Controls.Add(tradeFirstForm); for (Width = 0; Width < 700; Width += 50) await Task.Delay(1); } } }
24.461538
72
0.623428
[ "Apache-2.0" ]
foryou8033j/MoneyTaker
MoneyTaker/Forms/SubForm/AddSubject/AddTradeForm.cs
1,274
C#
namespace MultiMiner.Remoting.Server { public class Config { private const int UserPortMin = 49152; public const int BroadcastPort = UserPortMin + 1475; public const int RemotingPort = UserPortMin + 1473; } }
22.454545
60
0.663968
[ "MIT" ]
mindfox/MultiMiner
MultiMiner.Remoting.Server/Config.cs
249
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.LabServices.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Extensions; using System; /// <summary> /// Action to redeploy a lab virtual machine to a different compute node. For troubleshooting connectivity. /// </summary> /// <remarks> /// [OpenAPI] Redeploy=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labs/{labName}/virtualMachines/{virtualMachineName}/redeploy" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsLifecycle.Start, @"AzLabServicesVMRedeployment_Redeploy", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(bool))] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Description(@"Action to redeploy a lab virtual machine to a different compute node. For troubleshooting connectivity.")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Generated] public partial class StartAzLabServicesVMRedeployment_Redeploy : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.LabServices.LabServices Client => Microsoft.Azure.PowerShell.Cmdlets.LabServices.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary>Backing field for <see cref="LabName" /> property.</summary> private string _labName; /// <summary> /// The name of the lab that uniquely identifies it within containing lab account. Used in resource URIs. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the lab that uniquely identifies it within containing lab account. Used in resource URIs.")] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the lab that uniquely identifies it within containing lab account. Used in resource URIs.", SerializedName = @"labName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Path)] public string LabName { get => this._labName; set => this._labName = value; } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary> /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter PassThru { get; set; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary> private string _resourceGroupName; /// <summary>The name of the resource group. The name is case insensitive.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the resource group. The name is case insensitive.", SerializedName = @"resourceGroupName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Path)] public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Path)] public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary>Backing field for <see cref="VirtualMachineName" /> property.</summary> private string _virtualMachineName; /// <summary> /// The ID of the virtual machine that uniquely identifies it within the containing lab. Used in resource URIs. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the virtual machine that uniquely identifies it within the containing lab. Used in resource URIs.")] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the virtual machine that uniquely identifies it within the containing lab. Used in resource URIs.", SerializedName = @"virtualMachineName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.LabServices.ParameterCategory.Path)] public string VirtualMachineName { get => this._virtualMachineName; set => this._virtualMachineName = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.IErrorResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of StartAzLabServicesVMRedeployment_Redeploy</returns> public Microsoft.Azure.PowerShell.Cmdlets.LabServices.Cmdlets.StartAzLabServicesVMRedeployment_Redeploy Clone() { var clone = new StartAzLabServicesVMRedeployment_Redeploy(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.SubscriptionId = this.SubscriptionId; clone.ResourceGroupName = this.ResourceGroupName; clone.LabName = this.LabName; clone.VirtualMachineName = this.VirtualMachineName; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.LabServices.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'VirtualMachinesRedeploy' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.LabServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.VirtualMachinesRedeploy(SubscriptionId, ResourceGroupName, LabName, VirtualMachineName, onOk, onDefault, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,LabName=LabName,VirtualMachineName=VirtualMachineName}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary> /// Intializes a new instance of the <see cref="StartAzLabServicesVMRedeployment_Redeploy" /> cmdlet class. /// </summary> public StartAzLabServicesVMRedeployment_Redeploy() { } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.IErrorResponse> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.IErrorResponse>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, LabName=LabName, VirtualMachineName=VirtualMachineName }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, LabName=LabName, VirtualMachineName=VirtualMachineName }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) { WriteObject(true); } } } } }
71.918534
475
0.663486
[ "MIT" ]
Agazoth/azure-powershell
src/LabServices/generated/cmdlets/StartAzLabServicesVMRedeployment_Redeploy.cs
34,822
C#
#region usings using System; using AppSoftware.LicenceEngine.Common; using AppSoftware.LicenceEngine.KeyGenerator; using AppSoftware.LicenceEngine.KeyVerification; using NUnit.Framework; #endregion namespace AppSoftware.LicenceEngine.Tests { [TestFixture] public class PkvLicenceKeyTests { [Test] public void Test_pkv_licence_key_generation_and_verification() { var pkvLicenceKey = new PkvLicenceKeyGenerator(); var pkvKeyCheck = new PkvKeyCheck(); string key = string.Empty; KeyByteSet[] keyByteSets = new[] { new KeyByteSet(1, 58, 6, 97), new KeyByteSet(2, 96, 254, 23), new KeyByteSet(3, 11, 185, 69), new KeyByteSet(4, 2, 93, 41), new KeyByteSet(5, 62, 4, 234), new KeyByteSet(6, 200, 56, 49), new KeyByteSet(7, 89, 45, 142), new KeyByteSet(8, 6, 88, 32) }; // Change these to a random key byte set from the above array to test key verification with KeyByteSet kbs1 = keyByteSets[3]; KeyByteSet kbs2 = keyByteSets[7]; KeyByteSet kbs3 = keyByteSets[4]; // The check project also uses a class called KeyByteSet, but with // separate name spacing to achieve single self contained dll KeyByteSet keyByteSet1 = new KeyByteSet(kbs1.KeyByteNo, kbs1.KeyByteA, kbs1.KeyByteB, kbs1.KeyByteC); // Change no to test others KeyByteSet keyByteSet2 = new KeyByteSet(kbs2.KeyByteNo, kbs2.KeyByteA, kbs2.KeyByteB, kbs2.KeyByteC); KeyByteSet keyByteSet3 = new KeyByteSet(kbs3.KeyByteNo, kbs3.KeyByteA, kbs3.KeyByteB, kbs3.KeyByteC); Random rand = new Random(); for (int i = 0; i < 10000; i++) { int seed = rand.Next(0, int.MaxValue); key = pkvLicenceKey.MakeKey(seed, keyByteSets); // Check that check sum validation passes Assert.True(pkvKeyCheck.CheckKeyChecksum(key, keyByteSets.Length)); // Check using full check method Assert.True(pkvKeyCheck.CheckKey(key, new[] {keyByteSet1, keyByteSet2, keyByteSet3}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood, "Failed on iteration " + i); // Check that erroneous check sum validation fails Assert.False(pkvKeyCheck.CheckKeyChecksum(key.Remove(23, 1) + "A", keyByteSets.Length)); // Change key by replacing 17th char } // Check a few random inputs Assert.False(pkvKeyCheck.CheckKey("adcsadrewf", new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood); Assert.False(pkvKeyCheck.CheckKey("", new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood); Assert.False(pkvKeyCheck.CheckKey("123", new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood); Assert.False(pkvKeyCheck.CheckKey("*()", new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood); Assert.False(pkvKeyCheck.CheckKey("dasdasdasgdjwqidqiwd21887127eqwdaishxckjsabcxjkabskdcbq2e81y12e8712", new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood); } [Test] public void Test_PKV_licence_key_generation_and_verification_with_random_key_bytes_key_byte_qty_and_verification_key_byte_selection() { var pkvLicenceKey = new PkvLicenceKeyGenerator(); var pkvKeyCheck = new PkvKeyCheck(); for (int i = 0; i < 10000; i++) { int randomKeyByteSetsLength = new Random().Next(2, 400); KeyByteSet[] keyByteSets = new KeyByteSet[randomKeyByteSetsLength]; for (int j = 0; j < randomKeyByteSetsLength; j++) { var random = new Random(); var kbs = new KeyByteSet(j + 1, (byte) random.Next(0, 256), (byte) random.Next(0, 256), (byte) random.Next(0, 256)); keyByteSets[j] = kbs; } // Select a random key byte set to test key verification with KeyByteSet kbs1 = keyByteSets[new Random().Next(0, randomKeyByteSetsLength)]; KeyByteSet kbs2 = keyByteSets[new Random().Next(0, randomKeyByteSetsLength)]; // The check project also uses a class called KeyByteSet, but with // separate name spacing to achieve single self contained dll KeyByteSet keyByteSet1 = new KeyByteSet(kbs1.KeyByteNo, kbs1.KeyByteA, kbs1.KeyByteB, kbs1.KeyByteC); // Change no to test others KeyByteSet keyByteSet2 = new KeyByteSet(kbs2.KeyByteNo, kbs2.KeyByteA, kbs2.KeyByteB, kbs2.KeyByteC); int seed = new Random().Next(0, int.MaxValue); string key = pkvLicenceKey.MakeKey(seed, keyByteSets); // Check that check sum validation passes Assert.True(pkvKeyCheck.CheckKeyChecksum(key, keyByteSets.Length)); // Check using full check method Assert.True(pkvKeyCheck.CheckKey(key, new[] {keyByteSet1, keyByteSet2}, keyByteSets.Length, null) == PkvLicenceKeyResult.KeyGood, "Failed on iteration " + i); } } } }
42.503704
159
0.598118
[ "MIT" ]
VarChar42/dotnet-licence-key-generator
AppSoftware.LicenceEngine.Tests/PkvLicenceKeyTests.cs
5,740
C#
namespace Lucene.Net.Facet.Taxonomy.WriterCache { /* * 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> /// Abstract class for storing Label->Ordinal mappings in a taxonomy. /// /// @lucene.experimental /// </summary> public abstract class LabelToOrdinal { /// <summary> /// How many ordinals we've seen. </summary> protected internal int counter; /// <summary> /// Returned by <seealso cref="#getOrdinal"/> when the label isn't /// recognized. /// </summary> public const int INVALID_ORDINAL = -2; /// <summary> /// Default constructor. </summary> public LabelToOrdinal() { } /// <summary> /// return the maximal Ordinal assigned so far /// </summary> public virtual int MaxOrdinal { get { return this.counter; } } /// <summary> /// Returns the next unassigned ordinal. The default behavior of this method /// is to simply increment a counter. /// </summary> public virtual int NextOrdinal { get { return this.counter++; } } /// <summary> /// Adds a new label if its not yet in the table. /// Throws an <seealso cref="IllegalArgumentException"/> if the same label with /// a different ordinal was previoulsy added to this table. /// </summary> public abstract void AddLabel(FacetLabel label, int ordinal); /// <summary> /// Returns the ordinal assigned to the given label, /// or <seealso cref="#INVALID_ORDINAL"/> if the label cannot be found in this table. /// </summary> public abstract int GetOrdinal(FacetLabel label); } }
28.578313
88
0.672007
[ "Apache-2.0" ]
CerebralMischief/lucenenet
src/Lucene.Net.Facet/Taxonomy/WriterCache/LabelToOrdinal.cs
2,374
C#