content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Python.Runtime; using System; using System.Collections.Generic; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using WinIO.WPF.Command; using WinIO.WPF.Control; namespace WinIO.WPF { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow { private Thread thread; private List<Window> windows = new List<Window>(); private List<TabControl> tabs = new List<TabControl>(); public IOMenuItem VersionMenu; public IOMenuItem CreatePanelMenuItem(object header, IOTabItem tabItem) { IOMenuItem item = new IOMenuItem(); item.Header = header; item.Command = new RelayCommand(()=>showItem(item, tabItem)); PanelMenu.Items.Add(item); return item; } private void showItem(IOMenuItem item, IOTabItem tabItem) { tabItem.Visibility = Visibility.Visible; var content = tabItem.Content as UIElement; content.Visibility = Visibility.Visible; var control = tabItem.Parent as IOTabControl; control.SelectedItem = tabItem; PanelMenu.Items.Remove(item); } public IOMenuItem CreateTopMenuItem(string header, bool autoAdd=true) { IOMenuItem item = new IOMenuItem(); item.Header = header; if(autoAdd) { MainMenu.Items.Add(item); } item.Click += MenuItem_Click; return item; } private void MenuItem_Click(object sender, RoutedEventArgs e) { var menuitem = (IOMenuItem)sender; if (menuitem.PyOnClick != null) { using (Py.GIL()) { menuitem.PyOnClick.Invoke(); } } } public IOMenuItem CreateMenuItem(string header) { IOMenuItem item = new IOMenuItem(); item.Header = header; item.Click += MenuItem_Click; return item; } private IOTabItem CreateOuputTextBox(string name) { return new IOTabItem(name, "OutputTextBox"); } private IOTabItem CreateInputTextBox(string name) { return new IOTabItem(name, "InputTextBox", false); } public ExportPython.TabItem CreateOutputTab(uint tabPanel, string name) { if (tabs.Count > tabPanel) { var panel = tabs[(int)tabPanel]; var item = CreateOuputTextBox(name); item.TabPanelID = (int)tabPanel; panel.Items.Add(item); if (panel.Items.Count == 1) { panel.SelectedIndex = 0; } return item; } return null; } public ExportPython.TabItem CreateInputTab(uint tabPanel, string name) { if (tabs.Count > tabPanel) { var panel = tabs[(int)tabPanel]; var item = CreateInputTextBox(name); item.TabPanelID = (int)tabPanel; panel.Items.Add(item); if (panel.Items.Count == 1) { panel.SelectedIndex = 0; } return item; } return null; } public void CloseTab(IOTabItem item) { var tab = tabs[item.TabPanelID]; item.AfterClose(); tab.Items.Remove(item); } public void CloseTabPanel(uint tabPanel) { if (tabs.Count > tabPanel) { tabs[(int)tabPanel].Items.Clear(); } } public MainWindow(Thread thread) { this.thread = thread; Init(); } public MainWindow(MainWindow mainWindow) { mainWindow.windows.Add(this); Init(); } //private UnityPage unityPage; private void Init() { InitializeComponent(); System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical; tabs.Add(TabControl0); tabs.Add(TabControl1); tabs.Add(TabControl2); tabs.Add(TabControl3); tabs.Add(TabControl4); tabs.Add(TabControl5); //unityPage = new UnityPage(this); //WindowsFormsHost } public void SetWindowsSize(double height, double width) { this.Height = height; this.Width = width; } public Tuple<double, double> GetWindowSize() { return new Tuple<double, double>(this.Height, this.Width); } public int GetTabIndex(IOTabControl control) { return tabs.IndexOf(control); } } }
27.540541
130
0.523258
[ "Apache-2.0" ]
sak9188/WinIO
WinIO/WinIOMain/WPF/MainWindow.xaml.cs
5,105
C#
namespace ShuHai { public static class MathEx { public static bool IsPowerOfTwo(int value) { return value != 0 && (value & (value - 1)) == 0; } } }
24
103
0.583333
[ "MIT" ]
xenosl/DebugInspector
Assets/ShuHai/Scripts/Core/MathEx.cs
170
C#
using Microsoft.AspNetCore.Http; namespace AspNetCoreRateLimit { public class IpConnectionResolveContributor : IIpResolveContributor { public IpConnectionResolveContributor() { } public string ResolveIp(HttpContext httpContext) { return httpContext.Connection.RemoteIpAddress?.ToString(); } } }
23.0625
71
0.669377
[ "MIT" ]
XzaR90/AspNetCoreRateLim
src/AspNetCoreRateLimit/Resolvers/IpConnectionResolveContributor.cs
371
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. using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.InteropServices.RuntimeInformationTests { public class CheckArchitectureTests { [Fact] public void VerifyArchitecture() { Architecture osArch = RuntimeInformation.OSArchitecture; Architecture processArch = RuntimeInformation.ProcessArchitecture; switch (osArch) { case Architecture.X64: Assert.NotEqual(Architecture.Arm, processArch); break; case Architecture.X86: Assert.Equal(Architecture.X86, processArch); break; case Architecture.Arm: Assert.Equal(Architecture.Arm, processArch); break; case Architecture.Arm64: Assert.Equal(IntPtr.Size == 4 ? Architecture.Arm : Architecture.Arm64, processArch); break; default: Assert.False(true, "Unexpected Architecture."); break; } Assert.Equal(osArch, RuntimeInformation.OSArchitecture); Assert.Equal(processArch, RuntimeInformation.ProcessArchitecture); } } }
32.608696
104
0.586667
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Runtime.InteropServices.RuntimeInformation/tests/CheckArchitectureTests.cs
1,500
C#
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDevPack.Identity; using NetDevPack.Identity.Jwt; namespace AspNetCore.Jwt.Sample.Config { public static class CustomIdentityAndKeyConfig { public static void AddCustomIdentityAndKeyConfiguration(this IServiceCollection services, IConfiguration configuration) { // Your own EF Identity configuration - Use when you have another database like postgres services.AddDbContext<MyIntIdentityContext>(options => options.UseSqlServer(configuration.GetConnectionString("CustomKeyConnection"))); // Your own Identity configuration services.AddCustomIdentity<MyIntIdentityUser, int>(options => { options.SignIn.RequireConfirmedEmail = false; options.Lockout.MaxFailedAccessAttempts = 5; }) .AddCustomRoles<MyIntIdentityRoles, int>() .AddCustomEntityFrameworkStores<MyIntIdentityContext>() .AddDefaultTokenProviders(); // Ours JWT configuration services.AddJwtConfiguration(configuration, "AppSettings"); } } public class MyIntIdentityUser : IdentityUser<int> { } public class MyIntIdentityRoles : IdentityRole<int> { } public class MyIntIdentityContext : IdentityDbContext<MyIntIdentityUser, MyIntIdentityRoles, int> { public MyIntIdentityContext(DbContextOptions<MyIntIdentityContext> options) : base(options) { } } }
36.145833
128
0.69683
[ "MIT" ]
dougstefe/Security.Identity
src/Samples/AspNetCore.Jwt.Sample/Config/CustomIdentityAndKeyConfig.cs
1,737
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace SeedWorld { class SceneCuller { class MeshDistanceSort : IComparer<MeshInstance> { public int Compare(MeshInstance instance1, MeshInstance instance2) { return instance1.distance.CompareTo(instance2.distance); } } /// <summary> /// Culls all possible objects in a scene /// </summary> public class SceneCuller { /// Cached list of instances from last model culling. private List<MeshInstance> visibleInstances = new List<MeshInstance>(); /// Minimum distance to limit full mesh rendering. public float maxLODdistance = 25000f; /// Number of meshes culled so far public int culledMeshes { private set; get; } /// <summary> /// Cull an InstancedModel and its mesh groups. /// </summary> public void CullModelInstances(Camera camera, Model instancedModel) { int meshIndex = 0; foreach (MeshInstanceGroup instanceGroup in instancedModel.MeshInstanceGroups.Values) { // Pre-cull mesh parts instanceGroup.totalVisible = 0; foreach (MeshInstance meshInstance in instanceGroup.instances) { // Add mesh and instances to visible list if they're contained in the frustum if (camera.frustum.Contains(meshInstance.boundingSphere) != ContainmentType.Disjoint) instanceGroup.visibleInstances[instanceGroup.totalVisible++] = meshInstance; } int fullMeshInstances = 0; // Out of the visible instances, sort those by distance for (int i = 0; i < instanceGroup.totalVisible; i++) { MeshInstance meshInstance = instanceGroup.visibleInstances[i]; meshInstance.distance = Vector3.Distance(camera.position, meshInstance.position); // Use a second loop-through to separate the full meshes from the imposters. // Meshes closer than the limit distance will be moved to the front of the list, // and those beyond will be put into a separate bucket for imposter rendering. if (meshInstance.distance < maxLODdistance) instanceGroup.visibleInstances[fullMeshInstances++] = meshInstance; } // Update the new, filtered amount of full meshes to draw instanceGroup.totalVisible = fullMeshInstances; //instanceGroup.instances.Sort((a, b) => a.distance.CompareTo(b.distance)); meshIndex++; } // Finished culling this model } /// <summary> /// Check all meshes in a scene that are outside the view frustum. /// </summary> public void CullModelMeshes(Scene scene, Camera camera) { culledMeshes = 0; CullFromList(camera, scene.sceneModels); } /// <summary> /// Wrapper to cull meshes from a specified list. /// </summary> public void CullFromList(Camera camera, Dictionary<String, Model> modelList) { visibleInstances.Clear(); foreach (Model instancedModel in modelList.Values) CullModelInstances(camera, instancedModel); // Finished culling all models int total = visibleInstances.Count; } /// <summary> /// Remove any lights outside of the viewable frustum. /// </summary> public void CullLights(Scene scene, Camera camera) { Vector3 lightPosition = Vector3.Zero; Vector3 radiusVector = Vector3.Zero; // Refresh the list of visible point lights scene.visiblePointLights.Clear(); BoundingSphere bounds = new BoundingSphere(); // Pre-cull point lights foreach (PointLight light in scene.pointLights) { lightPosition.X = light.instance.transform.M41; lightPosition.Y = light.instance.transform.M42; lightPosition.Z = light.instance.transform.M43; radiusVector.X = light.instance.transform.M11; radiusVector.Y = light.instance.transform.M12; radiusVector.Z = light.instance.transform.M13; float radius = radiusVector.Length(); // Create bounding sphere to check which lights are in view bounds.Center = lightPosition; bounds.Radius = radius; if (camera.frustum.Contains(bounds) != ContainmentType.Disjoint) { scene.visiblePointLights.Add(light); } } // Finished culling lights } } } }
38.20979
109
0.53825
[ "MIT" ]
ccajas/SeedWorld
SeedWorld/Engine/Graphics/SceneCuller.cs
5,466
C#
namespace WorldDomination.SimpleRavenDb { internal static class StringExtensions { internal static string ToFirstNewLineOrDefault(this string value) { return value.Contains('\n') ? value[..value.IndexOf('\n')] : value; } } }
24.384615
74
0.545741
[ "MIT" ]
PureKrome/simpleravendb
src/WorldDomination.SimpleRavenDb/StringExtensions.cs
317
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementByteMatchStatementTextTransformation { /// <summary> /// Relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> public readonly int Priority; /// <summary> /// Transformation to apply, please refer to the Text Transformation [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> public readonly string Type; [OutputConstructor] private WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementByteMatchStatementTextTransformation( int priority, string type) { Priority = priority; Type = type; } } }
40.055556
220
0.724688
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementOrStatementStatementByteMatchStatementTextTransformation.cs
1,442
C#
using System.Web; using System.Web.Optimization; namespace DrinksInventory.API { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.551724
112
0.580501
[ "MIT" ]
dikili/CheckOut
DrinksInventory.WEBAPI/DrinksInventory.API/App_Start/BundleConfig.cs
1,120
C#
#nullable disable // // System.Reflection.Emit/MethodOnTypeBuilderInst.cs // // Author: // Zoltan Varga (vargaz@gmail.com) // // // Copyright (C) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if MONO_FEATURE_SRE using System; using System.Globalization; using System.Reflection; using System.Text; using System.Runtime.InteropServices; namespace System.Reflection.Emit { /* * This class represents a method of an instantiation of a generic type builder. */ [StructLayout (LayoutKind.Sequential)] internal class MethodOnTypeBuilderInst : MethodInfo { #region Keep in sync with object-internals.h Type instantiation; MethodInfo base_method; /*This is the base method definition, it must be non-inflated and belong to a non-inflated type.*/ Type[] method_arguments; #endregion MethodInfo generic_method_definition; public MethodOnTypeBuilderInst (TypeBuilderInstantiation instantiation, MethodInfo base_method) { this.instantiation = instantiation; this.base_method = base_method; } internal MethodOnTypeBuilderInst (MethodOnTypeBuilderInst gmd, Type[] typeArguments) { this.instantiation = gmd.instantiation; this.base_method = gmd.base_method; this.method_arguments = new Type [typeArguments.Length]; typeArguments.CopyTo (this.method_arguments, 0); this.generic_method_definition = gmd; } internal MethodOnTypeBuilderInst (MethodInfo method, Type[] typeArguments) { this.instantiation = method.DeclaringType; this.base_method = ExtractBaseMethod (method); this.method_arguments = new Type [typeArguments.Length]; typeArguments.CopyTo (this.method_arguments, 0); if (base_method != method) this.generic_method_definition = method; } static MethodInfo ExtractBaseMethod (MethodInfo info) { if (info is MethodBuilder) return info; if (info is MethodOnTypeBuilderInst) return ((MethodOnTypeBuilderInst)info).base_method; if (info.IsGenericMethod) info = info.GetGenericMethodDefinition (); Type t = info.DeclaringType; if (!t.IsGenericType || t.IsGenericTypeDefinition) return info; return (MethodInfo)t.Module.ResolveMethod (info.MetadataToken); } internal Type[] GetTypeArgs () { if (!instantiation.IsGenericType || instantiation.IsGenericParameter) return null; return instantiation.GetGenericArguments (); } // Called from the runtime to return the corresponding finished MethodInfo object internal MethodInfo RuntimeResolve () { var type = instantiation.InternalResolve (); var m = type.GetMethod (base_method); if (method_arguments != null) { var args = new Type [method_arguments.Length]; for (int i = 0; i < method_arguments.Length; ++i) args [i] = method_arguments [i].InternalResolve (); m = m.MakeGenericMethod (args); } return m; } // // MemberInfo members // public override Type DeclaringType { get { return instantiation; } } public override string Name { get { return base_method.Name; } } public override Type ReflectedType { get { return instantiation; } } public override Type ReturnType { get { return base_method.ReturnType; } } public override Module Module { get { return base_method.Module; } } public override bool IsDefined (Type attributeType, bool inherit) { throw new NotSupportedException (); } public override object [] GetCustomAttributes (bool inherit) { throw new NotSupportedException (); } public override object [] GetCustomAttributes (Type attributeType, bool inherit) { throw new NotSupportedException (); } public override string ToString () { //IEnumerable`1 get_Item(TKey) StringBuilder sb = new StringBuilder (ReturnType.ToString ()); sb.Append (" "); sb.Append (base_method.Name); sb.Append ("("); sb.Append (")"); return sb.ToString (); } // // MethodBase members // public override MethodImplAttributes GetMethodImplementationFlags () { return base_method.GetMethodImplementationFlags (); } public override ParameterInfo [] GetParameters () { return GetParametersInternal (); } internal override ParameterInfo [] GetParametersInternal () { throw new NotSupportedException (); } public override int MetadataToken { get { return base.MetadataToken; } } internal override int GetParametersCount () { return base_method.GetParametersCount (); } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException (); } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException (); } } public override MethodAttributes Attributes { get { return base_method.Attributes; } } public override CallingConventions CallingConvention { get { return base_method.CallingConvention; } } public override MethodInfo MakeGenericMethod (params Type [] methodInstantiation) { if (!base_method.IsGenericMethodDefinition || (method_arguments != null)) throw new InvalidOperationException ("Method is not a generic method definition"); if (methodInstantiation == null) throw new ArgumentNullException ("methodInstantiation"); if (base_method.GetGenericArguments ().Length != methodInstantiation.Length) throw new ArgumentException ("Incorrect length", "methodInstantiation"); foreach (Type type in methodInstantiation) { if (type == null) throw new ArgumentNullException ("methodInstantiation"); } return new MethodOnTypeBuilderInst (this, methodInstantiation); } public override Type [] GetGenericArguments () { if (!base_method.IsGenericMethodDefinition) return null; Type[] source = method_arguments ?? base_method.GetGenericArguments (); Type[] result = new Type [source.Length]; source.CopyTo (result, 0); return result; } public override MethodInfo GetGenericMethodDefinition () { return generic_method_definition ?? base_method; } public override bool ContainsGenericParameters { get { if (base_method.ContainsGenericParameters) return true; if (!base_method.IsGenericMethodDefinition) throw new NotSupportedException (); if (method_arguments == null) return true; foreach (Type t in method_arguments) { if (t.ContainsGenericParameters) return true; } return false; } } public override bool IsGenericMethodDefinition { get { return base_method.IsGenericMethodDefinition && method_arguments == null; } } public override bool IsGenericMethod { get { return base_method.IsGenericMethodDefinition; } } // // MethodInfo members // public override MethodInfo GetBaseDefinition () { throw new NotSupportedException (); } public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException (); } } } } #endif
26.091772
125
0.720437
[ "MIT" ]
ARhj/runtime
src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs
8,245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BasicLogin.Dtos { public class UserForLoginDto { public string Username { get; set; } public string Password { get; set; } } }
18.857143
44
0.685606
[ "MIT" ]
andersonsalles/BasicLogin
Dtos/UserForLoginDto.cs
266
C#
using System; using System.Collections.Generic; using System.Data.Common; // using System.Data.Entity.Core.EntityClient; // using System.Data.Entity.Core.Mapping; // using System.Data.Entity.Core.Metadata.Edm; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Transactions; using System.Xml; using System.Xml.Linq; using AutoMapper; using Npgsql; using QP8.Infrastructure; using Quantumart.QP8.BLL.Facades; using Quantumart.QP8.Configuration; using Quantumart.QP8.Constants; using Quantumart.QP8.DAL; namespace Quantumart.QP8.BLL { [SuppressMessage("ReSharper", "InconsistentNaming")] public sealed class QPConnectionScope : IDisposable { private DbConnection _efConnection; private int _scopeCount; public static QPConnectionScope Current { get => QPContext.CurrentConnectionScope; private set => QPContext.CurrentConnectionScope = value; } public string ConnectionString { get; } public DatabaseType DbType { get; set; } public DatabaseType CurrentDbType => Current.DbType; static QPConnectionScope() { if (!IsMapperInitialized()) { Mapper.Initialize(MapperFacade.CreateAllMappings); } } public static bool IsMapperInitialized() { try { Mapper.Configuration.AssertConfigurationIsValid(); } catch (InvalidOperationException) { return false; } catch (AutoMapperConfigurationException) { return true; } return true; } public QPConnectionScope() : this(QPContext.CurrentDbConnectionInfo) { } public QPConnectionScope(string connectionString, DatabaseType dbType = default(DatabaseType)) : this(new QpConnectionInfo(connectionString, dbType)) { } public QPConnectionScope(QpConnectionInfo info) { if (Current == null) { Ensure.NotNull(info, "Connection info should not be null"); Ensure.NotNullOrWhiteSpace(info.ConnectionString, "Connection string should not be null or empty"); Current = this; ConnectionString = info.ConnectionString; DbType = info.DbType; } else if (info != null && !string.IsNullOrWhiteSpace(info.ConnectionString) && !info.ConnectionString.Equals(Current.ConnectionString, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Attempt to create connection in the existing scope with different connection string."); } Current._scopeCount++; } public QPConnectionScope(QpConnectionInfo info, HashSet<string> identityInsertOptions) : this(info) { IdentityInsertOptions = identityInsertOptions; } public void Dispose() { if (Current != null) { // уменьшаем счетчик вложенных scope // если это последний, то все очищаем Current._scopeCount--; if (Current._scopeCount == 0) { ForcedDispose(); } } } public void ForcedDispose() { if (Current._efConnection != null) { Current._efConnection.Close(); Current._efConnection.Dispose(); Current._efConnection = null; Current._scopeCount = 0; } Current = null; } public DbConnection DbConnection => EfConnection; public DbConnection EfConnection { get { Current.CreateEfConnection(); return Current._efConnection; } } public HashSet<string> IdentityInsertOptions { get; } = new HashSet<string>(); [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] [SuppressMessage("Microsoft.Reliability", "CA2000", Justification = "Object will dispose in QPConnectionScope.Dispose")] private void CreateEfConnection() { if (Current._efConnection == null) { var usePostgres = DbType == DatabaseType.Postgres; var dbConnection = usePostgres ? (DbConnection)new NpgsqlConnection(ConnectionString) : new SqlConnection(ConnectionString); dbConnection.Open(); Current._efConnection = dbConnection; if (Transaction.Current == null && !usePostgres) { using (var cmd = DbCommandFactory.Create("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED", dbConnection as SqlConnection)) { cmd.ExecuteNonQuery(); } } } } } }
30.964072
182
0.576678
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
QuantumArt/QP
bll/QPConnectionScope.cs
5,226
C#
namespace INStock { using INStock.Contracts; using System; using System.Collections; using System.Collections.Generic; using System.Linq; public class ProductStock : IProductStock, IEnumerable<IProduct> { //--------- Fields ---------- private List<IProduct> productStock; //------ Constructors ------- public ProductStock() { this.productStock = new List<IProduct>(); } //------- Properties -------- public IProduct this[int index] { get { if (index >= 0 && index < this.productStock.Count) { return this.productStock[index] as IProduct; } throw new IndexOutOfRangeException("Index was out of range!"); } set { if (index < 0 && index >= this.productStock.Count) { throw new IndexOutOfRangeException("Index was out of range!"); } this.productStock.Insert(index, value); } } public int Count => this.productStock.Count; //-------- Methods ---------- public void Add(IProduct product) { foreach (IProduct prod in this.productStock) { if (prod.CompareTo(product) == 0) { throw new ArgumentException("Product already existing!"); } } this.productStock.Add(product); } public bool Contains(IProduct product) { foreach (IProduct prod in this.productStock) { if (prod.CompareTo(product) == 0) { return true; } } return false; } public IProduct Find(int index) { if (index >= 0 && index < this.productStock.Count) { return this.productStock[index]; } throw new IndexOutOfRangeException("Index was out of range!"); } public IEnumerable<IProduct> FindAllByPrice(double price) { return productStock.Where(p => decimal.ToDouble(p.Price) == price); } public IEnumerable<IProduct> FindAllByQuantity(int quantity) { return productStock.Where(p => p.Quantity == quantity).ToList(); } public IEnumerable<IProduct> FindAllInRange(double lo, double hi) { return productStock.Where(p => decimal.ToDouble(p.Price) >= lo && decimal.ToDouble(p.Price) <= hi) .OrderByDescending(p => p.Price).ToList(); } public IProduct FindByLabel(string label) { if (!this.productStock.Any(p => p.Label == label)) { throw new ArgumentException("No such product in stock!"); } return this.productStock.First(p => p.Label == label); } public IProduct FindMostExpensiveProduct() { return this.productStock.OrderByDescending(p => p.Price) .ToList() .FirstOrDefault(); } public bool Remove(IProduct product) { return this.productStock.Remove(product); } //------------------------------------------ public IEnumerator<IProduct> GetEnumerator() { for (int i = 0; i < this.productStock.Count; i++) { yield return this.productStock[i]; } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } }
28.533835
110
0.481423
[ "MIT" ]
radrex/SoftuniCourses
C# Web Developer/C# Advanced/C# OOP/10.Test-Driven Development/Lab/INStock/ProductStock.cs
3,797
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client.OrganizationPatchRequestPartialBuilder { public static class OrganizationPatchRequestPartialExtensions { public static Partial<OrganizationPatchRequest> WithOrgData(this Partial<OrganizationPatchRequest> it) => it.AddFieldName("orgData"); public static Partial<OrganizationPatchRequest> WithOrgData(this Partial<OrganizationPatchRequest> it, Func<Partial<OrganizationForUpdate>, Partial<OrganizationForUpdate>> partialBuilder) => it.AddFieldName("orgData", partialBuilder(new Partial<OrganizationForUpdate>(it))); } }
36.72093
195
0.696643
[ "Apache-2.0" ]
PatrickRatzow/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Partials/OrganizationPatchRequestPartialBuilder.generated.cs
1,579
C#
#region Copyright and License // Copyright 2010..2016 Alexander Reinert // // This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ARSoft.Tools.Net.Dns { /// <summary> /// Extension methods for DNSSEC resolvers /// </summary> public static class DnsSecResolverExtensions { /// <summary> /// Queries a dns resolver for specified records. /// </summary> /// <typeparam name="T"> Type of records, that should be returned </typeparam> /// <param name="resolver"> The resolver instance, that should be used for queries </param> /// <param name="name"> Domain, that should be queried </param> /// <param name="recordType"> Type the should be queried </param> /// <param name="recordClass"> Class the should be queried </param> /// <returns> The validating result and a list of matching <see cref="DnsRecordBase">records</see> </returns> public static DnsSecResult<T> ResolveSecure<T>(this IDnsSecResolver resolver, string name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet) where T : DnsRecordBase { return resolver.ResolveSecure<T>(DomainName.Parse(name), recordType, recordClass); } /// <summary> /// Queries a dns resolver for specified records as an asynchronous operation. /// </summary> /// <typeparam name="T"> Type of records, that should be returned </typeparam> /// <param name="resolver"> The resolver instance, that should be used for queries </param> /// <param name="name"> Domain, that should be queried </param> /// <param name="recordType"> Type the should be queried </param> /// <param name="recordClass"> Class the should be queried </param> /// <param name="token"> The token to monitor cancellation requests </param> /// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns> public static Task<DnsSecResult<T>> ResolveSecureAsync<T>(this IDnsSecResolver resolver, string name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet, CancellationToken token = default(CancellationToken)) where T : DnsRecordBase { return resolver.ResolveSecureAsync<T>(DomainName.Parse(name), recordType, recordClass, token); } } }
46.59375
239
0.729712
[ "Apache-2.0" ]
TomWeps/ARSoft.Tools.Net-Modified
ARSoft.Tools.Net/Dns/Resolver/DnsSecResolverExtensions.cs
2,984
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 datasync-2018-11-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DataSync.Model { /// <summary> /// DescribeLocationSmbResponse /// </summary> public partial class DescribeLocationSmbResponse : AmazonWebServiceResponse { private List<string> _agentArns = new List<string>(); private DateTime? _creationTime; private string _domain; private string _locationArn; private string _locationUri; private SmbMountOptions _mountOptions; private string _user; /// <summary> /// Gets and sets the property AgentArns. /// <para> /// The Amazon Resource Name (ARN) of the source SMB file system location that is created. /// </para> /// </summary> [AWSProperty(Min=1, Max=4)] public List<string> AgentArns { get { return this._agentArns; } set { this._agentArns = value; } } // Check to see if AgentArns property is set internal bool IsSetAgentArns() { return this._agentArns != null && this._agentArns.Count > 0; } /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The time that the SMB location was created. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property Domain. /// <para> /// The name of the Windows domain that the SMB server belongs to. /// </para> /// </summary> [AWSProperty(Max=253)] public string Domain { get { return this._domain; } set { this._domain = value; } } // Check to see if Domain property is set internal bool IsSetDomain() { return this._domain != null; } /// <summary> /// Gets and sets the property LocationArn. /// <para> /// The Amazon Resource Name (ARN) of the SMB location that was described. /// </para> /// </summary> [AWSProperty(Max=128)] public string LocationArn { get { return this._locationArn; } set { this._locationArn = value; } } // Check to see if LocationArn property is set internal bool IsSetLocationArn() { return this._locationArn != null; } /// <summary> /// Gets and sets the property LocationUri. /// <para> /// The URL of the source SBM location that was described. /// </para> /// </summary> [AWSProperty(Max=4356)] public string LocationUri { get { return this._locationUri; } set { this._locationUri = value; } } // Check to see if LocationUri property is set internal bool IsSetLocationUri() { return this._locationUri != null; } /// <summary> /// Gets and sets the property MountOptions. /// <para> /// The mount options that are available for DataSync to use to access an SMB location. /// </para> /// </summary> public SmbMountOptions MountOptions { get { return this._mountOptions; } set { this._mountOptions = value; } } // Check to see if MountOptions property is set internal bool IsSetMountOptions() { return this._mountOptions != null; } /// <summary> /// Gets and sets the property User. /// <para> /// The user who can mount the share, has the permissions to access files and folders /// in the SMB share. /// </para> /// </summary> [AWSProperty(Max=104)] public string User { get { return this._user; } set { this._user = value; } } // Check to see if User property is set internal bool IsSetUser() { return this._user != null; } } }
29.666667
106
0.564845
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/DataSync/Generated/Model/DescribeLocationSmbResponse.cs
5,251
C#
namespace GeekShopping.CartAPI.Model { public class Product { public Guid Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string? Description { get; set; } public string? CategoryName { get; set; } public string? ImageURL { get; set; } } }
19.444444
49
0.571429
[ "Apache-2.0" ]
edulima2412/erudio-microservices-dotnet6
GeekShopping/GeekShopping.CartAPI/Model/Product.cs
352
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dingtalkesign_1_0.Models { public class CorpInfoResponse : TeaModel { [NameInMap("headers")] [Validation(Required=true)] public Dictionary<string, string> Headers { get; set; } [NameInMap("body")] [Validation(Required=true)] public CorpInfoResponseBody Body { get; set; } } }
21.565217
63
0.669355
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/esign_1_0/Models/CorpInfoResponse.cs
496
C#
using System; using System.Collections.Generic; using System.Text; namespace Tensorflow { public class embedding_ops : Python { /// <summary> /// Helper function for embedding_lookup and _compute_sampled_logits. /// </summary> /// <param name="params"></param> /// <param name="ids"></param> /// <param name="partition_strategy"></param> /// <param name="name"></param> /// <returns></returns> public static Tensor _embedding_lookup_and_transform(RefVariable @params, Tensor ids, string partition_strategy = "mod", string name = null, string max_norm = null) { return with(ops.name_scope(name, "embedding_lookup", new { @params, ids }), scope => { name = scope; int np = 1; ids = ops.convert_to_tensor(ids, name: "ids"); if(np == 1) { var gather = array_ops.gather(@params, ids, name: name); var result = _clip(gather, ids, max_norm); return array_ops.identity(result); } throw new NotImplementedException("_embedding_lookup_and_transform"); }); } public static Tensor _clip(Tensor @params, Tensor ids, string max_norm = null) { if (max_norm == null) return @params; throw new NotImplementedException("_clip"); } } }
31.816327
96
0.520847
[ "Apache-2.0" ]
SciEvan/TensorFlow.NET
src/TensorFlowNET.Core/Operations/embedding_ops.cs
1,561
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; using System.Collections.Generic; using UIAutomationClient; using Axe.Windows.Core.Attributes; using Axe.Windows.Desktop.Utility; using Axe.Windows.Telemetry; using System.Drawing; using System.Runtime.InteropServices; namespace Axe.Windows.Desktop.UIAutomation.Patterns { /// <summary> /// Wrapper for IUIAutomationTextRange /// https://msdn.microsoft.com/en-us/library/windows/desktop/ee671377(v=vs.85).aspx /// </summary> public class TextRange : IDisposable { /// <summary> /// UIAInterface of TextRange /// </summary> public IUIAutomationTextRange UIATextRange { get; private set; } /// <summary> /// TextPattern which this Range was from /// </summary> public TextPattern TextPattern { get; private set; } public TextRange(IUIAutomationTextRange tr, TextPattern tp) { UIATextRange = tr; this.TextPattern = tp; } [PatternMethod] public void Select() { this.UIATextRange.Select(); } [PatternMethod] public void AddToSelection() { this.UIATextRange.AddToSelection(); } [PatternMethod] public void RemoveFromSelection() { this.UIATextRange.RemoveFromSelection(); } [PatternMethod] public void ScrollIntoView(bool alignToTop) { this.UIATextRange.ScrollIntoView(alignToTop ? 1 : 0); } [PatternMethod] public List<DesktopElement> GetChildren() { return this.UIATextRange.GetChildren()?.ToListOfDesktopElements(); } [PatternMethod] public DesktopElement GetEnclosingElement() { return new DesktopElement(this.UIATextRange.GetEnclosingElement()); } [PatternMethod] public int Move(TextUnit unit, int count) { return this.UIATextRange.Move(unit, count); } [PatternMethod] public void MoveEndpointByRange(TextPatternRangeEndpoint srcEndPoint, TextRange tr, TextPatternRangeEndpoint targetEndPoint) { if (tr == null) throw new ArgumentNullException(nameof(tr)); this.UIATextRange.MoveEndpointByRange(srcEndPoint, tr.UIATextRange, targetEndPoint); } [PatternMethod] public int MoveEndpointByUnit(TextPatternRangeEndpoint endpoint, TextUnit unit, int count) { return this.UIATextRange.MoveEndpointByUnit(endpoint, unit, count); } [PatternMethod] public void ExpandToEnclosingUnit(TextUnit tu) { this.UIATextRange.ExpandToEnclosingUnit(tu); } [PatternMethod] public TextRange Clone() { return new TextRange(this.UIATextRange.Clone(), this.TextPattern); } [PatternMethod] public bool Compare(TextRange tr) { if (tr == null) throw new ArgumentNullException(nameof(tr)); return Convert.ToBoolean(this.UIATextRange.Compare(tr.UIATextRange)); } [PatternMethod] public int CompareEndpoints(TextPatternRangeEndpoint srcEndPoint, TextRange tr, TextPatternRangeEndpoint targetEndPoint) { if (tr == null) throw new ArgumentNullException(nameof(tr)); return this.UIATextRange.CompareEndpoints(srcEndPoint, tr.UIATextRange, targetEndPoint); } [PatternMethod] public TextRange FindAttribute(int attr, object val, bool backward) { var uiatr = this.UIATextRange.FindAttribute(attr, val, backward ? 1 : 0); return uiatr != null ? new TextRange(uiatr, this.TextPattern) : null; } [PatternMethod] public TextRange FindText(string text, bool backward, bool ignoreCase) { var uiatr = this.UIATextRange.FindText(text, backward ? 1 : 0, ignoreCase ? 1 : 0); return uiatr != null ? new TextRange(uiatr, this.TextPattern) : null; } /// <summary> /// it is not still clear on how we will handle GetAttributeValue(). /// ToDo Item. /// </summary> /// <param name="attr"></param> /// <returns></returns> [PatternMethod] public dynamic GetAttributeValue(int attr) { try { return this.UIATextRange.GetAttributeValue(attr); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) { e.ReportException(); } #pragma warning restore CA1031 // Do not catch general exception types return null; } [PatternMethod] public List<Rectangle> GetBoundingRectangles() { List<Rectangle> list = new List<Rectangle>(); var arr = this.UIATextRange.GetBoundingRectangles(); for (int i = 0; i < arr.Length; i += 4) { list.Add(new Rectangle(Convert.ToInt32((double)arr.GetValue(i)), Convert.ToInt32((double)arr.GetValue(i + 1)), Convert.ToInt32((double)arr.GetValue(i + 2)), Convert.ToInt32((double)arr.GetValue(i + 3)))); } return list; } [PatternMethod] public string GetText(int max) { return this.UIATextRange.GetText(max); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if(this.UIATextRange != null) { Marshal.ReleaseComObject(UIATextRange); UIATextRange = null; } disposedValue = true; } } ~TextRange() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } }
32.144231
221
0.570595
[ "MIT" ]
Bhaskers-Blu-Org2/axe-windows
src/Desktop/UIAutomation/Patterns/TextRange.cs
6,479
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26.Maps { using V26; /// <summary> /// PV2 (SegmentMap) - Patient Visit - Additional Information /// </summary> public class PV2Map : HL7V26SegmentMap<PV2> { public PV2Map() { Id = "PV2"; Name = "Patient Visit - Additional Information"; Entity(x => x.PriorPendingLocation, 1); Entity(x => x.AccommodationCode, 2); Entity(x => x.AdmitReason, 3); Entity(x => x.TransferReason, 4); Value(x => x.PatientValuables, 5); Value(x => x.PatientValuablesLocation, 6); Value(x => x.VisitUserCode, 7); Value(x => x.ExpectedAdmitDateTime, 8, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ExpectedDischargeDateTime, 9, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.EstimatedLengthOfInpatientStay, 10); Value(x => x.ActualLengthOfInpatientStay, 11); Value(x => x.VisitDescription, 12); Entity(x => x.ReferralSourceCode, 13); Value(x => x.PreviouServiceDate, 14, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.EmploymentIllnessRelatedIndicator, 15); Value(x => x.PurgeStatusCode, 16); Value(x => x.PurgeStatusDate, 17, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.SpecialProgramCode, 18); Value(x => x.RetentionIndicator, 19); Value(x => x.ExpectedNumberOfInsurancePlans, 20); Value(x => x.VisitPublicityCode, 21); Value(x => x.VisitProtectionIndicator, 22); Entity(x => x.ClinicOrganizationName, 23); Value(x => x.PatientStatusCode, 24); Value(x => x.VisitPriorityCode, 25); Value(x => x.PreviouTreatmentDate, 26, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ExpectedDischargeDisposition, 27); Value(x => x.SignatureOnFileDate, 28, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.FirstSimilarIllnessDate, 29, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Entity(x => x.PatientChargeAdjustmentCode, 30); Value(x => x.RecurringServiceCode, 31); Value(x => x.BillingMediaCode, 32); Value(x => x.ExpectedSurgeryDateAndTime, 33, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.MilitaryPartnershipCode, 34); Value(x => x.MilitaryNonAvailabilityCode, 35); Value(x => x.NewbornBabyIndicator, 36); Value(x => x.BabyDetainedIndicator, 37); Entity(x => x.ModeOfArrivalCode, 38); Entity(x => x.RecreationalDrugUseCode, 39); Entity(x => x.AdmissionLevelOfCareCode, 40); Entity(x => x.PrecautionCode, 41); Entity(x => x.PatientConditionCode, 42); Value(x => x.LivingWillCode, 43); Value(x => x.OrganDonorCode, 44); Entity(x => x.AdvanceDirectiveCode, 45); Value(x => x.PatientStatusEffectiveDate, 46, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ExpectedLOAReturnDateTime, 47, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ExpectedPreAdmissionTestingDateTime, 48, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.NotifyClergyCode, 49); Value(x => x.AdvanceDirectiveLastVerifiedDate, 50, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); } } }
55.708333
133
0.615308
[ "Apache-2.0" ]
amccool/Machete
src/Machete.HL7Schema/Generated/V26/Segments/Maps/PV2Map.cs
4,011
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("TriangleOf55StarsWithTwoFors")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("TriangleOf55StarsWithTwoFors")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [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("1a997b1c-608a-414b-947c-15de71ee3113")] // 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.108108
84
0.753974
[ "MIT" ]
AlexanderPetrovv/Programming-Basics-December-2016
FirstStepsInCoding/TriangleOf55StarsWithTwoFors/Properties/AssemblyInfo.cs
1,450
C#
using System.Collections.Generic; using Upgrade; namespace Ship { namespace SecondEdition.ST70AssaultShip { public class OuterRimEnforcer : ST70AssaultShip { public OuterRimEnforcer() : base() { PilotInfo = new PilotCardInfo ( "Outer Rim Enforcer", 2, 48 ); ImageUrl = "https://infinitearenas.com/xw2/images/pilots/outerrimenforcer.png"; } } } }
23.652174
95
0.490809
[ "MIT" ]
sampson-matt/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/ST70AssaultShip/OuterRimEnforcer.cs
546
C#
using System; using Microsoft.Maui.Controls.CustomAttributes; #if UITEST using Xamarin.UITest; using NUnit.Framework; using Microsoft.Maui.Controls.UITests; #endif namespace Microsoft.Maui.Controls.ControlGallery.Issues { [Issue(IssueTracker.Github, 7856, "[Bug] Shell BackButtonBehaviour TextOverride breaks back", PlatformAffected.iOS)] #if UITEST [NUnit.Framework.Category(UITestCategories.Shell)] #endif public class Issue7856 : TestShell { const string ContentPageTitle = "Item1"; const string ButtonId = "ButtonId"; protected override void Init() { CreateContentPage(ContentPageTitle).Content = new StackLayout { Children = { new Button { AutomationId = ButtonId, Text = "Tap to Navigate To the Page With BackButtonBehavior", Command = new Command(NavToBackButtonBehaviorPage) } } }; } private void NavToBackButtonBehaviorPage() { _ = Shell.Current.Navigation.PushAsync(new Issue7856_1()); } #if UITEST && __IOS__ [Test] public void BackButtonBehaviorTest() { RunningApp.Tap(x => x.Text("Tap to Navigate To the Page With BackButtonBehavior")); RunningApp.WaitForElement(x => x.Text("Navigate again")); RunningApp.Tap(x => x.Text("Navigate again")); RunningApp.WaitForElement(x => x.Text("Test")); RunningApp.Tap(x => x.Text("Test")); } #endif } }
21.65625
86
0.698413
[ "MIT" ]
jongalloway/maui
src/ControlGallery/src/Xamarin.Forms.Controls.Issues.Shared/Issue7856.cs
1,388
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections; using System.Diagnostics; namespace HelperEditor { public class TabFileData { private const int TABLE_ROW_MAX = 100; // 可能的 ID 最大值 private string[] tTabHeader; // 文件表头 private string[,] tTabContent; // 文件内容, 矩阵数组 private string szMainKeyName; // 主键名字 // 构造函数 public TabFileData(string szFileName, string szKey) { Debug.Assert(File.Exists(szFileName), "文件 '" + szFileName + "' 没有找到。"); // 查找文件是否存在 StreamReader stFile = new StreamReader(szFileName, Encoding.Default); string[] tFileLines = stFile.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); stFile.Close(); szMainKeyName = szKey; // 记录主键名 tTabHeader = tFileLines[0].Split('\t'); // 获取表头 tTabContent = new string[TABLE_ROW_MAX, tTabHeader.Length]; // 初始化文件内容 for (int nRow = 0; nRow < TABLE_ROW_MAX; nRow++) for (int nCol = 0; nCol < tTabHeader.Length; nCol++) { tTabContent[nRow, nCol] = ""; } for (int nRow = 1; nRow < tFileLines.Length; nRow++) { string[] tLine = tFileLines[nRow].Split('\t'); int nID = Convert.ToInt32(tLine[GetColIndexByFieldName(szKey)]); //Debug.Assert(nID >= 0 && nID <= TABLE_ROW_MAX, "TAB文件数据访问,ID越界。"); for (int nCol = 0; nCol < tTabHeader.Length; nCol++) { tTabContent[nID, nCol] = tLine[nCol]; } } } // *************** 属性 *************** /// <summary> /// 数据表格的有效记录总数。 /// </summary> public int RecordLength { get { int nCount = 0; for (int i = 0; i < TABLE_ROW_MAX; i++) { if (tTabContent[i, GetColIndexByFieldName(szMainKeyName)] != "") nCount++; } return nCount; } } /// <summary> /// 数据表格记录的最大长度。 /// </summary> public int RecordLengthMax { get { return TABLE_ROW_MAX; } } /// <summary> /// 数据表格的有效字段数(列数)。 /// </summary> public int FieldLength { get { return tTabHeader.Length; } } /// <summary> /// 取得表的主键名。 /// </summary> public string MainKeyName { get { return szMainKeyName; } } // *************** 方法 *************** /// <summary> /// 通过字段名获取其相应的列序号。 /// </summary> /// <param name="szFieldName">字段名。</param> /// <returns>返回与字段名相应的列序号。</returns> public int GetColIndexByFieldName(string szFieldName) { for (int nCol = 0; nCol < tTabHeader.Length; nCol++) { if (tTabHeader[nCol] == szFieldName) { return nCol; } } return -1; } /// <summary> /// 通过 MainKeyID 和 FieldName 获取数据表格中一个单元的值。 /// </summary> /// <param name="nID">主键 ID,需要一个不小于 0 的整数。</param> /// <param name="szFieldName">字段名,用来定位一条记录的某个字段。</param> /// <returns>返回一个字符串数据。</returns> public string GetTabCell(int nID, string szFieldName) { int nColIndex = GetColIndexByFieldName(szFieldName); //Debug.Assert(nID >= 0 && nID <= TABLE_ROW_MAX, "TAB文件数据访问,ID越界。"); //Debug.Assert(nColIndex >= 0 && nColIndex < tTabHeader.Length, "TAB文件数据访问,ID越界。"); return tTabContent[nID, nColIndex]; } /// <summary> /// 通过 MainKeyID 和 FieldName 获取数据表格中一个单元的值。 /// </summary> /// <param name="szID">主键 ID,需要一个不小于 0 的整数形式的字符串。</param> /// <param name="szFieldName">字段名,用来定位一条记录的某个字段。</param> /// <returns>返回一个字符串数据。</returns> public string GetTabCell(string szID, string szFieldName) { int nID = Convert.ToInt32(szID); return GetTabCell(nID, szFieldName); } /// <summary> /// 通过 MainKeyID 和 FieldName 设置数据表格中一个单元的值。 /// </summary> /// <param name="nID">主键 ID,需要一个不小于 0 的整数。</param> /// <param name="szFieldName">字段名,用来定位一条记录的某个字段。</param> /// <param name="szValue">新的单元格值。</param> public void SetTabCell(int nID, string szFieldName, string szValue) { int nColIndex = GetColIndexByFieldName(szFieldName); tTabContent[nID, nColIndex] = szValue; } /// <summary> /// 通过 MainKeyID 和 FieldName 设置数据表格中一个单元的值。 /// </summary> /// <param name="szID">主键 ID,需要一个不小于 0 的整数形式的字符串。</param> /// <param name="szFieldName">字段名,用来定位一条记录的某个字段。</param> /// <param name="szValue">新的单元格值。</param> public void SetTabCell(string szID, string szFieldName, string szValue) { int nID = Convert.ToInt32(szID); SetTabCell(nID, szFieldName, szValue); } public void ExportSettingsFile(string szFileName) { StreamWriter stFile = new StreamWriter(szFileName, false, Encoding.Default); // 写表头 string szFileHeader = ""; foreach (string szTitleName in tTabHeader) szFileHeader += szTitleName + "\t"; stFile.WriteLine(szFileHeader); for (int i = 0; i < TABLE_ROW_MAX; i++) { int nKeyIndex = GetColIndexByFieldName(MainKeyName); if (tTabContent[i, nKeyIndex] != "") { string szFileLine = ""; for (int j = 0; j < tTabHeader.Length; j++) { szFileLine += tTabContent[i, j] + "\t"; } stFile.WriteLine(szFileLine); } } stFile.Close(); } /// <summary> /// 取得当前数据表格的表头数组。 /// </summary> /// <returns>表头数组。</returns> public string[] GetTabHeader() { return tTabHeader; } /// <summary> /// 取得当前数据表格的内容数据数组。 /// </summary> /// <returns>内容数据数组</returns> public string[,] GetTabContent() { return tTabContent; } } public class TabFile { public static TabFileData EventData; // 声明事件表 public static TabFileData ConditionData; // 声明条件表 public static TabFileData ActionData; // 声明行为表 } }
34.123288
126
0.458718
[ "MIT" ]
RivenZoo/FullSource
Jx3Full/Source/Source/Tools/GameDesignerEditor/Controls/HelperEditor/HelperEditor/TabFile.cs
8,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace LinqToDB { using Async; using Linq; public static partial class LinqExtensions { /// <summary> /// Inserts single record into target table and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <returns>Inserted record.</returns> public static TTarget InsertWithOutput<TTarget>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, setter), query.Expression, Expression.Quote(setter))); return items.AsEnumerable().First(); } /// <summary> /// Inserts single record into target table asynchronously and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task<TTarget> InsertWithOutputAsync<TTarget>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, CancellationToken token = default) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, setter), query.Expression, Expression.Quote(setter))); return items.AsAsyncEnumerable().FirstAsync(token); } /// <summary> /// Inserts single record into target table and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="obj">Object with data to insert.</param> /// <returns>Inserted record.</returns> public static TTarget InsertWithOutput<TTarget>( this ITable<TTarget> target, [InstantHandle] TTarget obj) { if (target == null) throw new ArgumentNullException(nameof(target)); if (obj == null) throw new ArgumentNullException(nameof(obj)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, obj), query.Expression, Expression.Constant(obj))); return items.AsEnumerable().First(); } /// <summary> /// Inserts single record into target table asynchronously and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="obj">Object with data to insert.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task<TTarget> InsertWithOutputAsync<TTarget>( this ITable<TTarget> target, [InstantHandle] TTarget obj, CancellationToken token = default) { if (target == null) throw new ArgumentNullException(nameof(target)); if (obj == null) throw new ArgumentNullException(nameof(obj)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, obj), query.Expression, Expression.Constant(obj))); return items.AsAsyncEnumerable().FirstOrDefaultAsync(token); } /// <summary> /// Inserts single record into target table and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <returns>Inserted record.</returns> public static TOutput InsertWithOutput<TTarget,TOutput>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, Expression<Func<TTarget,TOutput>> outputExpression) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TOutput>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, setter, outputExpression), query.Expression, Expression.Quote(setter), Expression.Quote(outputExpression))); return items.AsEnumerable().First(); } /// <summary> /// Inserts single record into target table asynchronously and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task<TOutput> InsertWithOutputAsync<TTarget,TOutput>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, Expression<Func<TTarget,TOutput>> outputExpression, CancellationToken token = default) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); IQueryable<TTarget> query = target; var items = query.Provider.CreateQuery<TOutput>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, setter, outputExpression), query.Expression, Expression.Quote(setter), Expression.Quote(outputExpression))); return items.AsAsyncEnumerable().FirstAsync(token); } /// <summary> /// Inserts single record into target table and outputs that record into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <returns>Number of affected records.</returns> public static int InsertWithOutputInto<TTarget>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, ITable<TTarget> outputTable) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); IQueryable<TTarget> query = target; return query.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, target, setter, outputTable), query.Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression)); } /// <summary> /// Inserts single record into target table asynchronously and outputs that record into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Number of affected records.</returns> public static Task<int> InsertWithOutputIntoAsync<TTarget>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, ITable<TTarget> outputTable, CancellationToken token = default) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); IQueryable<TTarget> query = target; var expr = Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, target, setter, outputTable), query.Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression); if (query is IQueryProviderAsync queryAsync) return queryAsync.ExecuteAsync<int>(expr, token); return TaskEx.Run(() => query.Provider.Execute<int>(expr), token); } /// <summary> /// Inserts single record into target table and outputs that record into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <returns>Number of affected records.</returns> public static int InsertWithOutputInto<TTarget,TOutput>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, ITable<TOutput> outputTable, Expression<Func<TTarget,TOutput>> outputExpression) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); IQueryable<TTarget> query = target; return query.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, target, setter, outputTable, outputExpression), query.Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression, Expression.Quote(outputExpression))); } /// <summary> /// Inserts single record into target table asynchronously and outputs that record into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Number of affected records.</returns> public static Task<int> InsertWithOutputIntoAsync<TTarget,TOutput>( this ITable<TTarget> target, [InstantHandle] Expression<Func<TTarget>> setter, ITable<TOutput> outputTable, Expression<Func<TTarget,TOutput>> outputExpression, CancellationToken token = default) { if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); IQueryable<TTarget> query = target; var expr = Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, target, setter, outputTable, outputExpression), query.Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression, Expression.Quote(outputExpression)); if (query is IQueryProviderAsync queryAsync) return queryAsync.ExecuteAsync<int>(expr, token); return TaskEx.Run(() => query.Provider.Execute<int>(expr), token); } #region Many records /// <summary> /// Inserts records from source query into target table and returns newly created records. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <returns>Enumeration of records.</returns> public static IEnumerable<TTarget> InsertWithOutput<TSource,TTarget>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source, target, setter), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter))) .AsEnumerable(); } /// <summary> /// Inserts records from source query into target table asynchronously and returns newly created records. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Array of records.</returns> public static Task<TTarget[]> InsertWithOutputAsync<TSource, TTarget>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource, TTarget>> setter, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source, target, setter), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter))) .ToArrayAsync(token); } /// <summary> /// Inserts records from source query into target table and returns newly created records. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <returns>Enumeration of records.</returns> [Pure] public static IEnumerable<TOutput> InsertWithOutput<TSource,TTarget,TOutput>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, Expression<Func<TTarget,TOutput>> outputExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.CreateQuery<TOutput>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source, target, setter, outputExpression), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter), Expression.Quote(outputExpression))) .AsEnumerable(); } /// <summary> /// Inserts records from source query into target table asynchronously and returns newly created records. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Array of records.</returns> public static Task<TOutput[]> InsertWithOutputAsync<TSource,TTarget,TOutput>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, Expression<Func<TTarget,TOutput>> outputExpression, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.CreateQuery<TOutput>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source, target, setter, outputExpression), currentSource.Expression, ((IQueryable<TTarget>) target).Expression, Expression.Quote(setter), Expression.Quote(outputExpression))) .ToArrayAsync(token); } /// <summary> /// Inserts records from source query into target table and outputs newly created records into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <returns>Number of affected records.</returns> public static int InsertWithOutputInto<TSource,TTarget>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, ITable<TTarget> outputTable ) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, target, setter, outputTable), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression)); } /// <summary> /// Inserts records from source query into target table asynchronously and outputs inserted records into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Number of affected records.</returns> public static Task<int> InsertWithOutputIntoAsync<TSource,TTarget>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, ITable<TTarget> outputTable, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; var expr = Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, target, setter, outputTable), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression); if (source is IQueryProviderAsync queryAsync) return queryAsync.ExecuteAsync<int>(expr, token); return TaskEx.Run(() => source.Provider.Execute<int>(expr), token); } /// <summary> /// Inserts records from source query into target table and outputs inserted records into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <returns>Number of affected records.</returns> public static int InsertWithOutputInto<TSource,TTarget,TOutput>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, ITable<TOutput> outputTable, Expression<Func<TTarget,TOutput>> outputExpression) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return source.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, target, setter, outputTable, outputExpression), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression, Expression.Quote(outputExpression))); } /// <summary> /// Inserts records from source query into target table asynchronously and outputs inserted records into <paramref name="outputTable"/>. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="source">Source query, that returns data for insert operation.</param> /// <param name="target">Target table.</param> /// <param name="setter">Inserted record constructor expression. /// Expression supports only target table record new expression with field initializers.</param> /// <param name="outputTable">Output table.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Number of affected records.</returns> public static Task<int> InsertWithOutputIntoAsync<TSource,TTarget,TOutput>( this IQueryable<TSource> source, ITable<TTarget> target, [InstantHandle] Expression<Func<TSource,TTarget>> setter, ITable<TOutput> outputTable, Expression<Func<TTarget,TOutput>> outputExpression, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (target == null) throw new ArgumentNullException(nameof(target)); if (setter == null) throw new ArgumentNullException(nameof(setter)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); if (outputExpression == null) throw new ArgumentNullException(nameof(outputExpression)); var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; var expr = Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, target, setter, outputTable, outputExpression), currentSource.Expression, ((IQueryable<TTarget>)target).Expression, Expression.Quote(setter), ((IQueryable<TTarget>)outputTable).Expression, Expression.Quote(outputExpression)); if (currentSource is IQueryProviderAsync queryAsync) return queryAsync.ExecuteAsync<int>(expr, token); return TaskEx.Run(() => currentSource.Provider.Execute<int>(expr), token); } /// <summary> /// Executes configured insert query and returns inserted record. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Insert query.</param> /// <returns>Inserted record.</returns> public static TTarget InsertWithOutput<TSource,TTarget>(this ISelectInsertable<TSource,TTarget> source) { if (source == null) throw new ArgumentNullException(nameof(source)); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source), query.Expression)); return items.AsEnumerable().First(); } /// <summary> /// Executes configured insert query asynchronously and returns inserted record. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Insert query.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task<TTarget> InsertWithOutputAsync<TSource,TTarget>( this ISelectInsertable<TSource,TTarget> source, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var items = query.Provider.CreateQuery<TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, source), query.Expression)); return items.AsAsyncEnumerable().FirstAsync(token); } /// <summary> /// Executes configured insert query and returns inserted record. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Insert query.</param> /// <param name="outputTable">Output table.</param> /// <returns>Number of affected records.</returns> public static int InsertWithOutputInto<TSource,TTarget>( this ISelectInsertable<TSource,TTarget> source, ITable<TTarget> outputTable) { if (source == null) throw new ArgumentNullException(nameof(source)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); var query = ((SelectInsertable<TSource,TTarget>)source).Query; return query.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, outputTable), query.Expression, ((IQueryable<TTarget>)outputTable).Expression)); } /// <summary> /// Executes configured insert query asynchronously and returns inserted record. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TTarget">Target table record type.</typeparam> /// <param name="source">Insert query.</param> /// <param name="outputTable">Output table.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Number of affected records.</returns> public static Task<int> InsertWithOutputIntoAsync<TSource,TTarget>( this ISelectInsertable<TSource,TTarget> source, ITable<TTarget> outputTable, CancellationToken token = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (outputTable == null) throw new ArgumentNullException(nameof(outputTable)); var query = ((SelectInsertable<TSource,TTarget>)source).Query; var expr = Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutputInto, source, outputTable), query.Expression, ((IQueryable<TTarget>)outputTable).Expression); if (query is IQueryProviderAsync queryAsync) return queryAsync.ExecuteAsync<int>(expr, token); return TaskEx.Run(() => query.Provider.Execute<int>(expr), token); } #endregion } }
49.197461
148
0.681718
[ "MIT" ]
Corey-M/linq2db
Source/LinqToDB/LinqExtensions.Insert.cs
34,175
C#
namespace Yumiko.SelfProtection.Infrastructure { public enum WmiSubject { _1394Controller, _1394ControllerDevice, AccountSID, ActionCheck, ActiveRoute, AllocatedResource, ApplicationCommandLine, ApplicationService, AssociatedBattery, AssociatedProcessorMemory, AutochkSetting, BaseBoard, Battery, Binary, BindImageAction, BIOS, BootConfiguration, Bus, CacheMemory, CDROMDrive, CheckCheck, CIMLogicalDeviceCIMDataFile, ClassicCOMApplicationClasses, ClassicCOMClass, ClassicCOMClassSetting, ClassicCOMClassSettings, ClassInforAction, ClientApplicationSetting, CodecFile, COMApplicationSettings, COMClassAutoEmulator, ComClassEmulator, CommandLineAccess, ComponentCategory, ComputerSystem, ComputerSystemProcessor, ComputerSystemProduct, ComputerSystemWindowsProductActivationSetting, Condition, ConnectionShare, ControllerHastHub, CreateFolderAction, CurrentProbe, DCOMApplication, DCOMApplicationAccessAllowedSetting, DCOMApplicationLaunchAllowedSetting, DCOMApplicationSetting, DependentService, Desktop, DesktopMonitor, DeviceBus, DeviceMemoryAddress, Directory, DirectorySpecification, DiskDrive, DiskDrivePhysicalMedia, DiskDriveToDiskPartition, DiskPartition, DiskQuota, DisplayConfiguration, DisplayControllerConfiguration, DMAChanner, DriverForDevice, DriverVXD, DuplicateFileAction, Environment, EnvironmentSpecification, ExtensionInfoAction, Fan, FileSpecification, FloppyController, FloppyDrive, FontInfoAction, Group, GroupDomain, GroupUser, HeatPipe, IDEController, IDEControllerDevice, ImplementedCategory, InfraredDevice, IniFileSpecification, InstalledSoftwareElement, IP4PersistedRouteTable, IP4RouteTable, IRQResource, Keyboard, LaunchCondition, LoadOrderGroup, LoadOrderGroupServiceDependencies, LoadOrderGroupServiceMembers, LocalTime, LoggedOnUser, LogicalDisk, LogicalDiskRootDirectory, LogicalDiskToPartition, LogicalFileAccess, LogicalFileAuditing, LogicalFileGroup, LogicalFileOwner, LogicalFileSecuritySetting, LogicalMemoryConfiguration, LogicalProgramGroup, LogicalProgramGroupDirectory, LogicalProgramGroupItem, LogicalProgramGroupItemDataFile, LogicalShareAccess, LogicalShareAuditing, LogicalShareSecuritySetting, LogonSession, LogonSessionMappedDisk, MappedLogicalDisk, MemoryArray, MemoryArrayLocation, MemoryDevice, MemoryDeviceArray, MemoryDeviceLocation, MIMEInfoAction, MotherboardDevice, MoveFileAction, NamedJobObject, NamedJobObjectActgInfo, NamedJobObjectLimit, NamedJobObjectLimitSetting, NamedJobObjectProcess, NamedJobObjectSecLimit, NamedJobObjectSecLimitSetting, NamedJobObjectStatistics, NetworkAdapter, NetworkAdapterConfiguration, NetworkAdapterSetting, NetworkClient, NetworkConnection, NetworkLoginProfile, NetworkProtocol, NTDomain, NTEventlogFile, NTLogEvent, NTLogEventComputer, NTLogEvnetLog, NTLogEventUser, ODBCAttribute, ODBCDataSourceAttribute, ODBCDataSourceSpecification, ODBCDriverAttribute, ODBCDriverSoftwareElement, ODBCDriverSpecification, ODBCSourceAttribute, ODBCTranslatorSpecification, OnBoardDevice, OperatingSystem, OperatingSystemAutochkSetting, OperatingSystemQFE, OSRecoveryConfiguración, PageFile, PageFileElementSetting, PageFileSetting, PageFileUsage, ParallelPort, Patch, PatchFile, PatchPackage, PCMCIAControler, PerfFormattedData_ASP_ActiveServerPages, PerfFormattedData_ASPNET_114322_ASPNETAppsv114322, PerfFormattedData_ASPNET_114322_ASPNETv114322, PerfFormattedData_ASPNET_2040607_ASPNETAppsv2040607, PerfFormattedData_ASPNET_2040607_ASPNETv2040607, PerfFormattedData_ASPNET_ASPNET, PerfFormattedData_ASPNET_ASPNETApplications, PerfFormattedData_aspnet_state_ASPNETStateService, PerfFormattedData_ContentFilter_IndexingServiceFilter, PerfFormattedData_ContentIndex_IndexingService, PerfFormattedData_DTSPipeline_SQLServerDTSPipeline, PerfFormattedData_Fax_FaxServices, PerfFormattedData_InetInfo_InternetInformationServicesGlobal, PerfFormattedData_ISAPISearch_HttpIndexingService, PerfFormattedData_MSDTC_DistributedTransactionCoordinator, PerfFormattedData_NETCLRData_NETCLRData, PerfFormattedData_NETCLRNetworking_NETCLRNetworking, PerfFormattedData_NETDataProviderforOracle_NETCLRData, PerfFormattedData_NETDataProviderforSqlServer_NETDataProviderforSqlServer, PerfFormattedData_NETFramework_NETCLRExceptions, PerfFormattedData_NETFramework_NETCLRInterop, PerfFormattedData_NETFramework_NETCLRJit, PerfFormattedData_NETFramework_NETCLRLoading, PerfFormattedData_NETFramework_NETCLRLocksAndThreads, PerfFormattedData_NETFramework_NETCLRMemory, PerfFormattedData_NETFramework_NETCLRRemoting, PerfFormattedData_NETFramework_NETCLRSecurity, PerfFormattedData_NTFSDRV_ControladordealmacenamientoNTFSdeSMTP, PerfFormattedData_Outlook_Outlook, PerfFormattedData_PerfDisk_LogicalDisk, PerfFormattedData_PerfDisk_PhysicalDisk, PerfFormattedData_PerfNet_Browser, PerfFormattedData_PerfNet_Redirector, PerfFormattedData_PerfNet_Server, PerfFormattedData_PerfNet_ServerWorkQueues, PerfFormattedData_PerfOS_Cache, PerfFormattedData_PerfOS_Memory, PerfFormattedData_PerfOS_Objects, PerfFormattedData_PerfOS_PagingFile, PerfFormattedData_PerfOS_Processor, PerfFormattedData_PerfOS_System, PerfFormattedData_PerfProc_FullImage_Costly, PerfFormattedData_PerfProc_Image_Costly, PerfFormattedData_PerfProc_JobObject, PerfFormattedData_PerfProc_JobObjectDetails, PerfFormattedData_PerfProc_Process, PerfFormattedData_PerfProc_ProcessAddressSpace_Costly, PerfFormattedData_PerfProc_Thread, PerfFormattedData_PerfProc_ThreadDetails_Costly, PerfFormattedData_RemoteAccess_RASPort, PerfFormattedData_RemoteAccess_RASTotal, PerfFormattedData_RSVP_RSVPInterfaces, PerfFormattedData_RSVP_RSVPService, PerfFormattedData_Spooler_PrintQueue, PerfFormattedData_TapiSrv_Telephony, PerfFormattedData_Tcpip_ICMP, PerfFormattedData_Tcpip_IP, PerfFormattedData_Tcpip_NBTConnection, PerfFormattedData_Tcpip_NetworkInterface, PerfFormattedData_Tcpip_TCP, PerfFormattedData_Tcpip_UDP, PerfFormattedData_TermService_TerminalServices, PerfFormattedData_TermService_TerminalServicesSession, PerfFormattedData_W3SVC_WebService, PerfRawData_ASP_ActiveServerPages, PerfRawData_ASPNET_114322_ASPNETAppsv114322, PerfRawData_ASPNET_114322_ASPNETv114322, PerfRawData_ASPNET_2040607_ASPNETAppsv2040607, PerfRawData_ASPNET_2040607_ASPNETv2040607, PerfRawData_ASPNET_ASPNET, PerfRawData_ASPNET_ASPNETApplications, PerfRawData_aspnet_state_ASPNETStateService, PerfRawData_ContentFilter_IndexingServiceFilter, PerfRawData_ContentIndex_IndexingService, PerfRawData_DTSPipeline_SQLServerDTSPipeline, PerfRawData_Fax_FaxServices, PerfRawData_InetInfo_InternetInformationServicesGlobal, PerfRawData_ISAPISearch_HttpIndexingService, PerfRawData_MSDTC_DistributedTransactionCoordinator, PerfRawData_NETCLRData_NETCLRData, PerfRawData_NETCLRNetworking_NETCLRNetworking, PerfRawData_NETDataProviderforOracle_NETCLRData, PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer, PerfRawData_NETFramework_NETCLRExceptions, PerfRawData_NETFramework_NETCLRInterop, PerfRawData_NETFramework_NETCLRJit, PerfRawData_NETFramework_NETCLRLoading, PerfRawData_NETFramework_NETCLRLocksAndThreads, PerfRawData_NETFramework_NETCLRMemory, PerfRawData_NETFramework_NETCLRRemoting, PerfRawData_NETFramework_NETCLRSecurity, PerfRawData_NTFSDRV_ControladordealmacenamientoNTFSdeSMTP, PerfRawData_Outlook_Outlook, PerfRawData_PerfDisk_LogicalDisk, PerfRawData_PerfDisk_PhysicalDisk, PerfRawData_PerfNet_Browser, PerfRawData_PerfNet_Redirector, PerfRawData_PerfNet_Server, PerfRawData_PerfNet_ServerWorkQueues, PerfRawData_PerfOS_Cache, PerfRawData_PerfOS_Memory, PerfRawData_PerfOS_Objects, PerfRawData_PerfOS_PagingFile, PerfRawData_PerfOS_Processor, PerfRawData_PerfOS_System, PerfRawData_PerfProc_FullImage_Costly, PerfRawData_PerfProc_Image_Costly, PerfRawData_PerfProc_JobObject, PerfRawData_PerfProc_JobObjectDetails, PerfRawData_PerfProc_Process, PerfRawData_PerfProc_ProcessAddressSpace_Costly, PerfRawData_PerfProc_Thread, PerfRawData_PerfProc_ThreadDetails_Costly, PerfRawData_RemoteAccess_RASPort, PerfRawData_RemoteAccess_RASTotal, PerfRawData_RSVP_RSVPInterfaces, PerfRawData_RSVP_RSVPService, PerfRawData_Spooler_PrintQueue, PerfRawData_TapiSrv_Telephony, PerfRawData_Tcpip_ICMP, PerfRawData_Tcpip_IP, PerfRawData_Tcpip_NBTConnection, PerfRawData_Tcpip_NetworkInterface, PerfRawData_Tcpip_TCP, PerfRawData_Tcpip_UDP, PerfRawData_TermService_TerminalServices, PerfRawData_TermService_TerminalServicesSession, PerfRawData_W3SVC_WebService, PhysicalMedia, PhysicalMemory, PhysicalMemoryArray, PhysicalMemoryLocation, PingStatus, PNPAllocatedResource, PnPDevice, PnPEntity, PnPSignedDriver, PnPSignedDriverCIMDataFile, PointingDevice, PortableBattery, PortConnector, PortResource, POTSModem, POTSModemToSerialPort, Printer, PrinterConfiguration, PrinterController, PrinterDriver, PrinterDriverDll, PrinterSetting, PrinterShare, PrintJob, Process, Processor, Product, ProductCheck, ProductResource, ProductSoftwareFeatures, ProgIDSpecification, ProgramGroup, ProgramGroupContents, Property, ProtocolBinding, Proxy, PublishComponentAction, QuickFixEngineering, QuotaSetting, Refrigeration, Registry, RegistryAction, RemoveFileAction, RemoveIniAction, ReserveCost, ScheduledJob, SCSIController, SCSIControllerDevice, SecuritySettingOfLogicalFile, SecuritySettingOfLogicalShare, SelfRegModuleAction, SerialPort, SerialPortConfiguration, SerialPortSetting, ServerConnection, ServerSession, Service, ServiceControl, ServiceSpecification, ServiceSpecificationService, SessionConnection, SessionProcess, Share, ShareToDirectory, ShortcutAction, ShortcutFile, ShortcutSAP, SID, SoftwareElement, SoftwareElementAction, SoftwareElementCheck, SoftwareElementCondition, SoftwareElementResource, SoftwareFeature, SoftwareFeatureAction, SoftwareFeatureCheck, SoftwareFeatureParent, SoftwareFeatureSoftwareElements, SoundDevice, StartupCommand, SubDirectory, SystemAccount, SystemBIOS, SystemBootConfiguration, SystemDesktop, SystemDevices, SystemDriver, SystemDriverPNPEntity, SystemEnclosure, SystemLoadOrderGroups, SystemLogicalMemoryConfiguration, SystemNetworkConnections, SystemOperatingSystem, SystemPartitions, SystemProcesses, SystemProgramGroups, SystemResources, SystemServices, SystemSlot, SystemSystemDriver, SystemTimeZone, SystemUsers, TapeDrive, TCPIPPrinterPort, TemperatureProbe, Terminal, TerminalService, TerminalServiceSetting, TerminalServiceToSetting, TerminalTerminalSetting, Thread, TimeZone, TSAccount, TSClientSetting, TSEnvironmentSetting, TSGeneralSetting, TSLogonSetting, TSNetworkAdapterListSetting, TSNetworkAdapterSetting, TSPermissionsSetting, TSRemoteControlSetting, TSSessionDirectory, TSSessionDirectorySetting, TSSessionSetting, TypeLibraryAction, UninterruptiblePowerSupply, USBController, USBControllerDevice, USBHub, UserAccount, UserDesktop, UserInDomain, UTCTime, VideoController, VideoSettings, VoltageProbe, VolumeQuotaSetting, WindowsProductActivation, WMIElementSetting, WMISetting } }
32.583144
82
0.696728
[ "MIT" ]
0x0001F36D/Yumiko.SelfProtection
Yumiko.SelfProtection/Infrastructure/WmiSubject.cs
14,307
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Elastic.Apm.Api; using Elastic.Apm.Helpers; using Elastic.Apm.Model; using Elastic.Apm.Tests.Extensions; using Elastic.Apm.Tests.Mocks; using Elastic.Apm.Tests.TestHelpers; using FluentAssertions; using Microsoft.EntityFrameworkCore; using MySql.Data.MySqlClient; using Xunit; using Xunit.Abstractions; namespace Elastic.Apm.EntityFrameworkCore.Tests { /// <summary> /// Tests using external DB servers. /// Tests will not run (even though they will show as passed) if any of the following environment variables is not set: /// - ELASTIC_APM_TESTS_XYZ_HOST /// Note: The value should contain only the host name i.e., without DB instance name - the test uses default DB instance /// - ELASTIC_APM_TESTS_XYZ_USERNAME /// - ELASTIC_APM_TESTS_XYZ_PASSWORD /// where XYZ is database type. /// For MySQL the expected environment variables are: /// - ELASTIC_APM_TESTS_MYSQL_HOST /// - ELASTIC_APM_TESTS_MYSQL_USERNAME /// - ELASTIC_APM_TESTS_MYSQL_PASSWORD /// For Microsoft SQL Server the expected environment variables are: /// - ELASTIC_APM_TESTS_MS_SQL_HOST /// - ELASTIC_APM_TESTS_MS_SQL_USERNAME /// - ELASTIC_APM_TESTS_MS_SQL_PASSWORD /// </summary> public class ExternalDbTests : LoggingTestBase { private static readonly IDictionary<string, Action<ConnectionDetails, string>> EnvVarSuffixToConnectionProperty = new Dictionary<string, Action<ConnectionDetails, string>> { { "HOST", (connectionDetails, envVarValue) => { connectionDetails.Host = envVarValue; } }, { "USERNAME", (connectionDetails, envVarValue) => { connectionDetails.Username = envVarValue; } }, { "PASSWORD", (connectionDetails, envVarValue) => { connectionDetails.Password = envVarValue; } } }; private static readonly IReadOnlyList<ExternalDbType> PotentialExternalDbTypes = new List<ExternalDbType> { new ExternalDbType { Description = "Microsoft SQL Server", EnvVarNameMiddlePart = "MS_SQL", DbContextBuilder = connectionDetails => new MsSqlDbContext(connectionDetails), DefaultPort = DbSpanCommon.DefaultPorts.MsSql, SpanSubtype = ApiConstants.SubtypeMssql }, new ExternalDbType { Description = "MySQL", EnvVarNameMiddlePart = "MYSQL", DbContextBuilder = connectionDetails => new MySqlDbContext(connectionDetails), DefaultPort = DbSpanCommon.DefaultPorts.MySql, SpanSubtype = ApiConstants.SubtypeMySql }, }; public ExternalDbTests(ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { } private static IEnumerable<ValueTuple<ExternalDbType, ConnectionDetails>> FindConfiguredExternalDbs() { var isAtLeastOneExternalDbConfigured = false; foreach (var externalDbType in PotentialExternalDbTypes) { var connectionDetails = GetConnectionDetails(externalDbType); if (connectionDetails == null) continue; isAtLeastOneExternalDbConfigured = true; yield return (externalDbType, connectionDetails); } if (!isAtLeastOneExternalDbConfigured) yield return (new ExternalDbType { Description = "None of the potential external DB types is configured " }, null); } public static IEnumerable<object[]> ConfiguredExternalDbVariants => FindConfiguredExternalDbs().Select(tuple => new object[] { tuple.Item1, tuple.Item2 }); [Theory] [MemberData(nameof(ConfiguredExternalDbVariants))] public void Context_Destination_from_Db(ExternalDbType externalDbType, ConnectionDetails connectionDetails) { if (connectionDetails == null) return; var mockPayloadSender = new MockPayloadSender(); using (var agent = new ApmAgent(new AgentComponents(payloadSender: mockPayloadSender))) { agent.Subscribe(new EfCoreDiagnosticsSubscriber()); agent.Tracer.CaptureTransaction("test TX name", "test TX type" , () => { ExecuteTestCrudSequence(() => externalDbType.DbContextBuilder(connectionDetails)); }); } mockPayloadSender.Transactions.Should().HaveCount(1); mockPayloadSender.Spans.ForEach(span => { span.Type.Should().Be(ApiConstants.TypeDb); span.Subtype.Should().Be(externalDbType.SpanSubtype); span.Action.Should().Be(ApiConstants.ActionQuery); span.Context.Db.Type.Should().Be(Database.TypeSql); span.Context.Destination.Address.Should().Be(connectionDetails.Host); span.Context.Destination.Port.Should().Be(externalDbType.DefaultPort); }); } private static ConnectionDetails GetConnectionDetails(ExternalDbType externalDbType) { var connectionDetails = new ConnectionDetails(); foreach (var envVarSuffixToConnectionProperty in EnvVarSuffixToConnectionProperty) { var envVarName = "ELASTIC_APM_TESTS_" + externalDbType.EnvVarNameMiddlePart + "_" + envVarSuffixToConnectionProperty.Key; var envVarValue = Environment.GetEnvironmentVariable(envVarName); if (envVarValue == null) return null; envVarSuffixToConnectionProperty.Value(connectionDetails, envVarValue); } return connectionDetails; } private static void ExecuteTestCrudSequence(Func<DbContextImplBase> dbContextFactory) { using(var dbContext = dbContextFactory()) { dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); } // // Create data // Publisher publisher; Book book1; using(var dbContext = dbContextFactory()) { publisher = new Publisher { Name = "Mariner Books" }; dbContext.Publishers.Add(publisher); book1 = new Book { ISBN = "978-0544003415", Title = "The Lord of the Rings", Publisher = publisher }; dbContext.Books.Add(book1); dbContext.SaveChanges(); } // // Read data and verify // using(var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; publishers.Should().HaveCount(1); books.Should().HaveCount(1); var actualPublisher = publishers.First(); actualPublisher.Name.Should().Be(publisher.Name); actualPublisher.Books.Should().HaveCount(1); actualPublisher.Books.First().ISBN.Should().Be(book1.ISBN); } // // Update some data // Book book2; using(var dbContext = dbContextFactory()) { book2 = new Book { ISBN = "978-0547247762", Title = "The Sealed Letter", Publisher = dbContext.Publishers.First() }; dbContext.Books.Add(book2); dbContext.SaveChanges(); } // // Read data and verify // using(var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; publishers.Should().HaveCount(1); books.Should().HaveCount(2); var actualPublisher = publishers.First(); actualPublisher.Name.Should().Be(publisher.Name); actualPublisher.Books.Should().HaveCount(2); actualPublisher.Books.Select(b => b.ISBN).Should().Equal(book1.ISBN, book2.ISBN); } // // Delete some data // using(var dbContext = dbContextFactory()) { dbContext.Books.Remove(book1); dbContext.SaveChanges(); } // // Read data and verify // using(var dbContext = dbContextFactory()) { var publishers = dbContext.Publishers; var books = dbContext.Books; publishers.Should().HaveCount(1); books.Should().HaveCount(1); var actualPublisher = publishers.First(); actualPublisher.Name.Should().Be(publisher.Name); actualPublisher.Books.Should().HaveCount(1); actualPublisher.Books.First().ISBN.Should().Be(book2.ISBN); } } public class ConnectionDetails { internal string Host { get; set; } internal string Password { get; set; } internal string Username { get; set; } public override string ToString() => new ToStringBuilder { { nameof(Host), Host.ToLog() }, { nameof(Username), Username.ToLog() }, { nameof(Password), Password.ToLog() } }.ToString(); } public class ExternalDbType { internal Func<ConnectionDetails, DbContextImplBase> DbContextBuilder { get; set; } internal string Description { get; set; } internal string EnvVarNameMiddlePart { get; set; } internal int DefaultPort { get; set; } internal string SpanSubtype { get; set; } public override string ToString() => Description; } public class DbContextImplBase : DbContext { protected const string DbInstance = "ElasticApmExternalDbTests"; internal readonly ConnectionDetails ConnectionDetails; protected DbContextImplBase(ConnectionDetails connectionDetails) => ConnectionDetails = connectionDetails; protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Publisher>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Name).IsRequired(); }); modelBuilder.Entity<Book>(entity => { entity.HasKey(e => e.ISBN); entity.Property(e => e.Title).IsRequired(); entity.HasOne(d => d.Publisher) .WithMany(p => p.Books); }); } // ReSharper disable UnusedAutoPropertyAccessor.Local public DbSet<Book> Books { get; set; } public DbSet<Publisher> Publishers { get; set; } // ReSharper restore UnusedAutoPropertyAccessor.Local } private class MsSqlDbContext : DbContextImplBase { internal MsSqlDbContext(ConnectionDetails connectionDetails) : base(connectionDetails) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // "Data Source=<Host>;Initial Catalog=<SubDatabase>;User ID=<Username>;Password=<Password>" var connectionStringBuilder = new SqlConnectionStringBuilder { DataSource = ConnectionDetails.Host, UserID = ConnectionDetails.Username, Password = ConnectionDetails.Password, InitialCatalog = DbInstance }; optionsBuilder.UseSqlServer(connectionStringBuilder.ConnectionString); } } private class MySqlDbContext : DbContextImplBase { internal MySqlDbContext(ConnectionDetails connectionDetails) : base(connectionDetails) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // "server=<Host>;database=<SubDatabase>;user=<Username>;password=<Password>" var connectionStringBuilder = new MySqlConnectionStringBuilder { Server = ConnectionDetails.Host, UserID = ConnectionDetails.Username, Password = ConnectionDetails.Password, Database = DbInstance }; optionsBuilder.UseMySQL(connectionStringBuilder.ConnectionString); } } public class Book { // ReSharper disable once InconsistentNaming public string ISBN { get; set; } public virtual Publisher Publisher { get; set; } public string Title { get; set; } public override string ToString() => new ToStringBuilder(nameof(Book)) { { nameof(ISBN), ISBN }, { nameof(Title), Title }, { nameof(Publisher), Publisher } }.ToString(); } public class Publisher { public virtual ICollection<Book> Books { get; set; } public int Id { get; set; } public string Name { get; set; } public override string ToString() => new ToStringBuilder(nameof(Publisher)) { { nameof(Id), Id }, { nameof(Name), Name }, { "Books.Count", Books.Count } }.ToString(); } } }
32.316092
125
0.717677
[ "Apache-2.0" ]
ElWPenn/apm-agent-dotnet
test/Elastic.Apm.EntityFrameworkCore.Tests/ExternalDbTests.cs
11,246
C#
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace EdnaMonitoring.Infra.Identity.TokenProviders { public class EmailConfirmationTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class { public EmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider, IOptions<EmailConfirmationTokenProviderOptions> options, ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options, logger) { } } public class EmailConfirmationTokenProviderOptions : DataProtectionTokenProviderOptions { } }
32.521739
110
0.764706
[ "MIT" ]
nagasudhirpulla/edna_monitoring
src/EdnaMonitoring.Infra/Identity/TokenProviders/EmailConfirmationTokenProvider.cs
750
C#
using System; namespace IxMilia.LinearAlgebra { public class SubMatrix : Matrix { public Matrix Parent { get; } public int RowOffset { get; } public override int Rows { get; } public int ColumnOffset { get; } public override int Columns { get; } public override double this[int row, int column] { get { CheckIndexAccess(row, column); var r = RowOffset + row; var c = ColumnOffset + column; CheckParentIndexAccess(r, c); return Parent[r, c]; } set { CheckIndexAccess(row, column); var r = RowOffset + row; var c = ColumnOffset + column; CheckParentIndexAccess(r, c); Parent[r, c] = value; } } public SubMatrix(Matrix parent, int rowOffset, int rows, int columnOffset, int columns) { if (parent == null) { throw new ArgumentNullException(nameof(parent)); } if (rowOffset < 0) { throw new ArgumentOutOfRangeException(nameof(rowOffset)); } if (rowOffset + rows >= parent.Rows) { throw new ArgumentOutOfRangeException(nameof(rows)); } if (columnOffset < 0) { throw new ArgumentOutOfRangeException(nameof(columnOffset)); } if (columnOffset + columns >= parent.Columns) { throw new ArgumentOutOfRangeException(nameof(columns)); } Parent = parent; RowOffset = rowOffset; Rows = rows; ColumnOffset = columnOffset; Columns = columns; } private void CheckParentIndexAccess(int row, int column) { if (row < 0 || row >= Parent.Rows) { throw new ArgumentOutOfRangeException(nameof(row)); } if (column < 0 || column >= Parent.Columns) { throw new ArgumentOutOfRangeException(nameof(column)); } } } }
27.130952
95
0.481351
[ "MIT" ]
IxMilia/LinearAlgebra
src/IxMilia.LinearAlgebra/SubMatrix.cs
2,281
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using RegionFlags = OpenMetaverse.RegionFlags; namespace OpenSim.Region.CoreModules.World.Land { /// <summary> /// Keeps track of a specific piece of land's information /// </summary> public class LandObject : ILandObject { #region Member Variables private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[LAND OBJECT]"; protected const int GROUPMEMBERCACHETIMEOUT = 30000; // cache invalidation after 30s private readonly int landUnit = 4; private int m_lastSeqId = 0; private int m_expiryCounter = 0; protected Scene m_scene; protected readonly List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>(); private readonly Dictionary<uint, UUID> m_listTransactions = new Dictionary<uint, UUID>(); private readonly object m_listTransactionsLock = new object(); protected readonly ExpiringCacheOS<UUID, bool> m_groupMemberCache = new ExpiringCacheOS<UUID, bool>(); IDwellModule m_dwellModule; private bool[,] m_landBitmap; public bool[,] LandBitmap { get { return m_landBitmap; } set { m_landBitmap = value; } } #endregion public int GetPrimsFree() { m_scene.EventManager.TriggerParcelPrimCountUpdate(); int free = GetSimulatorMaxPrimCount() - LandData.SimwidePrims; return free; } protected LandData m_landData; public LandData LandData { get { return m_landData; } set { m_landData = value; } } public UUID GlobalID { get { return m_landData == null ? UUID.Zero : m_landData.GlobalID; } } public UUID FakeID { get { return m_landData == null ? UUID.Zero : m_landData.FakeID; } } public UUID OwnerID { get { return m_landData == null ? UUID.Zero : m_landData.OwnerID; } } public UUID GroupID { get { return m_landData == null ? UUID.Zero : m_landData.GroupID; } } public int LocalID { get { return m_landData == null ? -1 : m_landData.LocalID; } } public IPrimCounts PrimCounts { get; set; } public UUID RegionUUID { get { return m_scene.RegionInfo.RegionID; } } private Vector2 m_startPoint = Vector2.Zero; private Vector2 m_endPoint = Vector2.Zero; private Vector2 m_centerPoint = Vector2.Zero; private Vector2 m_AABBmin = Vector2.Zero; private Vector2 m_AABBmax = Vector2.Zero; public Vector2 StartPoint { get { return m_startPoint; } } public Vector2 EndPoint { get { return m_endPoint; } } //estimate a center point of a parcel public Vector2 CenterPoint { get { return m_centerPoint; } } public ISceneObject[] GetSceneObjectGroups() { return primsOverMe.ToArray(); } public Vector2? GetNearestPoint(Vector3 pos) { Vector3 direction = new Vector3(m_centerPoint.X - pos.X, m_centerPoint.Y - pos.Y, 0f ); return GetNearestPointAlongDirection(pos, direction); } public Vector2? GetNearestPointAlongDirection(Vector3 pos, Vector3 pdirection) { Vector2 testpos; Vector2 direction; testpos.X = pos.X / landUnit; testpos.Y = pos.Y / landUnit; if(LandBitmap[(int)testpos.X, (int)testpos.Y]) return new Vector2(pos.X, pos.Y); // we are already here direction.X = pdirection.X; direction.Y = pdirection.Y; if(direction.X == 0f && direction.Y == 0f) return null; // we can't look anywhere direction.Normalize(); int minx = (int)(m_AABBmin.X / landUnit); int maxx = (int)(m_AABBmax.X / landUnit); // check against AABB if(direction.X > 0f) { if(testpos.X >= maxx) return null; // will never get there if(testpos.X < minx) testpos.X = minx; } else if(direction.X < 0f) { if(testpos.X < minx) return null; // will never get there if(testpos.X >= maxx) testpos.X = maxx - 1; } else { if(testpos.X < minx) return null; // will never get there else if(testpos.X >= maxx) return null; // will never get there } int miny = (int)(m_AABBmin.Y / landUnit); int maxy = (int)(m_AABBmax.Y / landUnit); if(direction.Y > 0f) { if(testpos.Y >= maxy) return null; // will never get there if(testpos.Y < miny) testpos.Y = miny; } else if(direction.Y < 0f) { if(testpos.Y < miny) return null; // will never get there if(testpos.Y >= maxy) testpos.Y = maxy - 1; } else { if(testpos.Y < miny) return null; // will never get there else if(testpos.Y >= maxy) return null; // will never get there } while(!LandBitmap[(int)testpos.X, (int)testpos.Y]) { testpos += direction; if(testpos.X < minx) return null; if (testpos.X >= maxx) return null; if(testpos.Y < miny) return null; if (testpos.Y >= maxy) return null; } testpos *= landUnit; float ftmp; if(Math.Abs(direction.X) > Math.Abs(direction.Y)) { if(direction.X < 0) testpos.X += landUnit - 0.5f; else testpos.X += 0.5f; ftmp = testpos.X - pos.X; ftmp /= direction.X; ftmp = Math.Abs(ftmp); ftmp *= direction.Y; ftmp += pos.Y; if(ftmp < testpos.Y + .5f) ftmp = testpos.Y + .5f; else { testpos.Y += landUnit - 0.5f; if(ftmp > testpos.Y) ftmp = testpos.Y; } testpos.Y = ftmp; } else { if(direction.Y < 0) testpos.Y += landUnit - 0.5f; else testpos.Y += 0.5f; ftmp = testpos.Y - pos.Y; ftmp /= direction.Y; ftmp = Math.Abs(ftmp); ftmp *= direction.X; ftmp += pos.X; if(ftmp < testpos.X + .5f) ftmp = testpos.X + .5f; else { testpos.X += landUnit - 0.5f; if(ftmp > testpos.X) ftmp = testpos.X; } testpos.X = ftmp; } return testpos; } #region Constructors public LandObject(LandData landData, Scene scene) { LandData = landData.Copy(); m_scene = scene; m_scene.EventManager.OnFrame += OnFrame; m_dwellModule = m_scene.RequestModuleInterface<IDwellModule>(); } public LandObject(UUID owner_id, bool is_group_owned, Scene scene, LandData data = null) { m_scene = scene; if (m_scene == null) LandBitmap = new bool[Constants.RegionSize / landUnit, Constants.RegionSize / landUnit]; else { LandBitmap = new bool[m_scene.RegionInfo.RegionSizeX / landUnit, m_scene.RegionInfo.RegionSizeY / landUnit]; m_dwellModule = m_scene.RequestModuleInterface<IDwellModule>(); } if(data == null) LandData = new LandData(); else LandData = data; LandData.OwnerID = owner_id; if (is_group_owned) LandData.GroupID = owner_id; LandData.IsGroupOwned = is_group_owned; if(m_dwellModule == null) LandData.Dwell = 0; m_scene.EventManager.OnFrame += OnFrame; } public void Clear() { if(m_scene != null) m_scene.EventManager.OnFrame -= OnFrame; LandData = null; } #endregion #region Member Functions #region General Functions /// <summary> /// Checks to see if this land object contains a point /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Returns true if the piece of land contains the specified point</returns> public bool ContainsPoint(int x, int y) { if (x >= 0 && y >= 0 && x < m_scene.RegionInfo.RegionSizeX && y < m_scene.RegionInfo.RegionSizeY) { return LandBitmap[x / landUnit, y / landUnit]; } else { return false; } } public ILandObject Copy() { ILandObject newLand = new LandObject(LandData, m_scene); newLand.LandBitmap = (bool[,]) (LandBitmap.Clone()); return newLand; } static overrideParcelMaxPrimCountDelegate overrideParcelMaxPrimCount; static overrideSimulatorMaxPrimCountDelegate overrideSimulatorMaxPrimCount; public void SetParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { overrideParcelMaxPrimCount = overrideDel; } public void SetSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { overrideSimulatorMaxPrimCount = overrideDel; } public int GetParcelMaxPrimCount() { if (overrideParcelMaxPrimCount != null) { return overrideParcelMaxPrimCount(this); } else { // Normal Calculations int parcelMax = (int)( (double)LandData.Area * (double)m_scene.RegionInfo.ObjectCapacity * (double)m_scene.RegionInfo.RegionSettings.ObjectBonus / (double)(m_scene.RegionInfo.RegionSizeX * m_scene.RegionInfo.RegionSizeY) + 0.5 ); if(parcelMax > m_scene.RegionInfo.ObjectCapacity) parcelMax = m_scene.RegionInfo.ObjectCapacity; //m_log.DebugFormat("Area: {0}, Capacity {1}, Bonus {2}, Parcel {3}", LandData.Area, m_scene.RegionInfo.ObjectCapacity, m_scene.RegionInfo.RegionSettings.ObjectBonus, parcelMax); return parcelMax; } } // the total prims a parcel owner can have on a region public int GetSimulatorMaxPrimCount() { if (overrideSimulatorMaxPrimCount != null) { return overrideSimulatorMaxPrimCount(this); } else { //Normal Calculations int simMax = (int)( (double)LandData.SimwideArea * (double)m_scene.RegionInfo.ObjectCapacity * (double)m_scene.RegionInfo.RegionSettings.ObjectBonus / (long)(m_scene.RegionInfo.RegionSizeX * m_scene.RegionInfo.RegionSizeY) +0.5 ); // sanity check if(simMax > m_scene.RegionInfo.ObjectCapacity) simMax = m_scene.RegionInfo.ObjectCapacity; //m_log.DebugFormat("Simwide Area: {0}, Capacity {1}, SimMax {2}, SimWidePrims {3}", // LandData.SimwideArea, m_scene.RegionInfo.ObjectCapacity, simMax, LandData.SimwidePrims); return simMax; } } #endregion #region Packet Request Handling public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client) { if(m_scene.RegionInfo.RegionSettings.AllowDamage) remote_client.SceneAgent.Invulnerable = false; else remote_client.SceneAgent.Invulnerable = (m_landData.Flags & (uint)ParcelFlags.AllowDamage) == 0; if (remote_client.SceneAgent.PresenceType == PresenceType.Npc) return; IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>(); // uint regionFlags = 336723974 & ~((uint)(RegionFlags.AllowLandmark | RegionFlags.AllowSetHome)); uint regionFlags = (uint)(RegionFlags.PublicAllowed | RegionFlags.AllowDirectTeleport | RegionFlags.AllowParcelChanges | RegionFlags.AllowVoice ); if (estateModule != null) regionFlags = estateModule.GetRegionFlags(); int seq_id; if (snap_selection && (sequence_id == 0)) { seq_id = m_lastSeqId; } else { seq_id = sequence_id; m_lastSeqId = seq_id; } remote_client.SendLandProperties(seq_id, snap_selection, request_result, this, (float)m_scene.RegionInfo.RegionSettings.ObjectBonus, GetParcelMaxPrimCount(), GetSimulatorMaxPrimCount(), regionFlags); } public bool UpdateLandProperties(LandUpdateArgs args, IClientAPI remote_client, out bool snap_selection, out bool needOverlay) { //Needs later group support snap_selection = false; needOverlay = false; LandData newData = LandData.Copy(); uint allowedDelta = 0; // These two are always blocked as no client can set them anyway // ParcelFlags.ForSaleObjects // ParcelFlags.LindenHome if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions, false)) { allowedDelta |= (uint)(ParcelFlags.AllowLandmark | ParcelFlags.AllowTerraform | ParcelFlags.AllowDamage | ParcelFlags.CreateObjects | ParcelFlags.RestrictPushObject | ParcelFlags.AllowOtherScripts | ParcelFlags.AllowGroupScripts | ParcelFlags.CreateGroupObjects | ParcelFlags.AllowAPrimitiveEntry | ParcelFlags.AllowGroupObjectEntry | ParcelFlags.AllowFly); newData.SeeAVs = args.SeeAVs; newData.AnyAVSounds = args.AnyAVSounds; newData.GroupAVSounds = args.GroupAVSounds; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandSetSale, true)) { if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice) { snap_selection = true; } newData.AuthBuyerID = args.AuthBuyerID; newData.SalePrice = args.SalePrice; if (!LandData.IsGroupOwned) { newData.GroupID = args.GroupID; if(newData.GroupID != LandData.GroupID) m_groupMemberCache.Clear(); allowedDelta |= (uint)(ParcelFlags.AllowDeedToGroup | ParcelFlags.ContributeWithDeed | ParcelFlags.SellParcelObjects); } allowedDelta |= (uint)ParcelFlags.ForSale; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.FindPlaces, false)) { newData.Category = args.Category; allowedDelta |= (uint)(ParcelFlags.ShowDirectory | ParcelFlags.AllowPublish | ParcelFlags.MaturePublish) | (uint)(1 << 23); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandChangeIdentity, false)) { newData.Description = args.Desc; newData.Name = args.Name; newData.SnapshotID = args.SnapshotID; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.SetLandingPoint, false)) { newData.LandingType = args.LandingType; newData.UserLocation = args.UserLocation; newData.UserLookAt = args.UserLookAt; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.ChangeMedia, false)) { newData.MediaAutoScale = args.MediaAutoScale; newData.MediaID = args.MediaID; newData.MediaURL = args.MediaURL; newData.MusicURL = args.MusicURL; newData.MediaType = args.MediaType; newData.MediaDescription = args.MediaDescription; newData.MediaWidth = args.MediaWidth; newData.MediaHeight = args.MediaHeight; newData.MediaLoop = args.MediaLoop; newData.ObscureMusic = args.ObscureMusic; newData.ObscureMedia = args.ObscureMedia; allowedDelta |= (uint)(ParcelFlags.SoundLocal | ParcelFlags.UrlWebPage | ParcelFlags.UrlRawHtml | ParcelFlags.AllowVoiceChat | ParcelFlags.UseEstateVoiceChan); } if(!m_scene.RegionInfo.EstateSettings.TaxFree) { // don't allow passes on group owned until we can give money to groups if (!newData.IsGroupOwned && m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandManagePasses, false)) { newData.PassHours = args.PassHours; newData.PassPrice = args.PassPrice; allowedDelta |= (uint)ParcelFlags.UsePassList; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandManageAllowed, false)) { allowedDelta |= (uint)(ParcelFlags.UseAccessGroup | ParcelFlags.UseAccessList); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandManageBanned, false)) { allowedDelta |= (uint)(ParcelFlags.UseBanList | ParcelFlags.DenyAnonymous | ParcelFlags.DenyAgeUnverified); } } // enforce estate age and payinfo limitations if (m_scene.RegionInfo.EstateSettings.DenyMinors) { args.ParcelFlags |= (uint)ParcelFlags.DenyAgeUnverified; allowedDelta |= (uint)ParcelFlags.DenyAgeUnverified; } if (m_scene.RegionInfo.EstateSettings.DenyAnonymous) { args.ParcelFlags |= (uint)ParcelFlags.DenyAnonymous; allowedDelta |= (uint)ParcelFlags.DenyAnonymous; } if (allowedDelta != (uint)ParcelFlags.None) { uint preserve = LandData.Flags & ~allowedDelta; newData.Flags = preserve | (args.ParcelFlags & allowedDelta); uint curdelta = LandData.Flags ^ newData.Flags; curdelta &= (uint)(ParcelFlags.SoundLocal); if(curdelta != 0 || newData.SeeAVs != LandData.SeeAVs) needOverlay = true; m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); return true; } return false; } public void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area) { LandData newData = LandData.Copy(); newData.OwnerID = avatarID; newData.GroupID = groupID; newData.IsGroupOwned = groupOwned; //newData.auctionID = AuctionID; newData.ClaimDate = Util.UnixTimeSinceEpoch(); newData.ClaimPrice = claimprice; newData.SalePrice = 0; newData.AuthBuyerID = UUID.Zero; newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); bool sellObjects = (LandData.Flags & (uint)(ParcelFlags.SellParcelObjects)) != 0 && !LandData.IsGroupOwned && !groupOwned; UUID previousOwner = LandData.OwnerID; m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); if (sellObjects) SellLandObjects(previousOwner); m_scene.EventManager.TriggerParcelPrimCountUpdate(); } public void DeedToGroup(UUID groupID) { LandData newData = LandData.Copy(); newData.OwnerID = groupID; newData.GroupID = groupID; newData.IsGroupOwned = true; // Reset show in directory flag on deed newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); m_scene.EventManager.TriggerParcelPrimCountUpdate(); } public bool IsEitherBannedOrRestricted(UUID avatar) { if (m_scene.RegionInfo.EstateSettings.TaxFree) // region access control only return false; if (IsBannedFromLand(avatar)) { return true; } else if (IsRestrictedFromLand(avatar)) { return true; } return false; } public bool CanBeOnThisLand(UUID avatar, float posHeight) { if (m_scene.RegionInfo.EstateSettings.TaxFree) // region access control only return true; if (posHeight < m_scene.LandChannel.BanLineSafeHeight && IsBannedFromLand(avatar)) { return false; } else if (IsRestrictedFromLand(avatar)) { return false; } return true; } public bool HasGroupAccess(UUID avatar) { if (LandData.GroupID != UUID.Zero && (LandData.Flags & (uint)ParcelFlags.UseAccessGroup) == (uint)ParcelFlags.UseAccessGroup) { if (m_groupMemberCache.TryGetValue(avatar, out bool isMember)) { m_groupMemberCache.Add(avatar, isMember, GROUPMEMBERCACHETIMEOUT); return isMember; } if (!m_scene.TryGetScenePresence(avatar, out ScenePresence sp)) { IGroupsModule groupsModule = m_scene.RequestModuleInterface<IGroupsModule>(); if (groupsModule == null) return false; GroupMembershipData[] membership = groupsModule.GetMembershipData(avatar); if (membership == null || membership.Length == 0) { m_groupMemberCache.Add(avatar, false, GROUPMEMBERCACHETIMEOUT); return false; } foreach (GroupMembershipData d in membership) { if (d.GroupID == LandData.GroupID) { m_groupMemberCache.Add(avatar, true, GROUPMEMBERCACHETIMEOUT); return true; } } m_groupMemberCache.Add(avatar, false, GROUPMEMBERCACHETIMEOUT); return false; } else { isMember = sp.ControllingClient.IsGroupMember(LandData.GroupID); m_groupMemberCache.Add(avatar, isMember, GROUPMEMBERCACHETIMEOUT); return isMember; } } return false; } public bool IsBannedFromLand(UUID avatar) { ExpireAccessList(); if (m_scene.RegionInfo.EstateSettings.TaxFree) // region access control only return false; if (m_scene.Permissions.IsAdministrator(avatar)) return false; if (m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(avatar)) return false; if (avatar == LandData.OwnerID) return false; if ((LandData.Flags & (uint) ParcelFlags.UseBanList) > 0) { if (LandData.ParcelAccessList.FindIndex( delegate(LandAccessEntry e) { if (e.AgentID == avatar && e.Flags == AccessList.Ban) return true; return false; }) != -1) { return true; } } return false; } public bool IsRestrictedFromLand(UUID avatar) { if (m_scene.RegionInfo.EstateSettings.TaxFree) // estate access only return false; if ((LandData.Flags & (uint) ParcelFlags.UseAccessList) == 0) { bool adults = m_scene.RegionInfo.EstateSettings.DoDenyMinors && (m_scene.RegionInfo.EstateSettings.DenyMinors || ((LandData.Flags & (uint)ParcelFlags.DenyAgeUnverified) != 0)); bool anonymous = m_scene.RegionInfo.EstateSettings.DoDenyAnonymous && (m_scene.RegionInfo.EstateSettings.DenyAnonymous || ((LandData.Flags & (uint)ParcelFlags.DenyAnonymous) != 0)); if(adults || anonymous) { int userflags; if(m_scene.TryGetScenePresence(avatar, out ScenePresence snp)) { if(snp.IsNPC) return false; userflags = snp.UserFlags; } else userflags = m_scene.GetUserFlags(avatar); if(adults && ((userflags & 32) == 0)) return true; if(anonymous && ((userflags & 4) == 0)) return true; } return false; } if (m_scene.Permissions.IsAdministrator(avatar)) return false; if (m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(avatar)) return false; if (avatar == LandData.OwnerID) return false; if (HasGroupAccess(avatar)) return false; if(IsInLandAccessList(avatar)) return false; // check for a NPC ScenePresence sp; if (!m_scene.TryGetScenePresence(avatar, out sp)) return true; if(sp==null || !sp.IsNPC) return true; INPC npccli = (INPC)sp.ControllingClient; if(npccli== null) return true; UUID owner = npccli.Owner; if(owner == UUID.Zero) return true; if (owner == LandData.OwnerID) return false; return !IsInLandAccessList(owner); } public bool IsInLandAccessList(UUID avatar) { ExpireAccessList(); if (LandData.ParcelAccessList.FindIndex( delegate(LandAccessEntry e) { if (e.AgentID == avatar && e.Flags == AccessList.Access) return true; return false; }) == -1) { return false; } return true; } public void SendLandUpdateToClient(IClientAPI remote_client) { SendLandProperties(0, false, 0, remote_client); } public void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client) { m_scene.EventManager.TriggerParcelPrimCountUpdate(); SendLandProperties(0, snap_selection, 0, remote_client); } public void SendLandUpdateToAvatarsOverMe() { SendLandUpdateToAvatarsOverMe(false); } public void SendLandUpdateToAvatarsOverMe(bool snap_selection) { m_scene.EventManager.TriggerParcelPrimCountUpdate(); m_scene.ForEachRootScenePresence(delegate(ScenePresence avatar) { if (avatar.IsNPC) return; ILandObject over = null; try { over = m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.X), 0, ((int)m_scene.RegionInfo.RegionSizeX - 1)), Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.Y), 0, ((int)m_scene.RegionInfo.RegionSizeY - 1))); } catch (Exception) { m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatar.AbsolutePosition.X) + " y: " + Math.Round(avatar.AbsolutePosition.Y)); } if (over != null) { if (over.LandData.LocalID == LandData.LocalID) { if(m_scene.RegionInfo.RegionSettings.AllowDamage) avatar.Invulnerable = false; else avatar.Invulnerable = (over.LandData.Flags & (uint)ParcelFlags.AllowDamage) == 0; SendLandUpdateToClient(snap_selection, avatar.ControllingClient); avatar.currentParcelUUID = LandData.GlobalID; } } }); } public void SendLandUpdateToAvatars() { m_scene.ForEachScenePresence(delegate (ScenePresence avatar) { if (avatar.IsNPC) return; if(avatar.IsChildAgent) { SendLandProperties(-10000, false, LandChannel.LAND_RESULT_SINGLE, avatar.ControllingClient); return; } ILandObject over = null; try { over = m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.X), 0, ((int)m_scene.RegionInfo.RegionSizeX - 1)), Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.Y), 0, ((int)m_scene.RegionInfo.RegionSizeY - 1))); } catch (Exception) { m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatar.AbsolutePosition.X) + " y: " + Math.Round(avatar.AbsolutePosition.Y)); } if (over != null) { if (over.LandData.LocalID == LandData.LocalID) { if (m_scene.RegionInfo.RegionSettings.AllowDamage) avatar.Invulnerable = false; else avatar.Invulnerable = (over.LandData.Flags & (uint)ParcelFlags.AllowDamage) == 0; avatar.currentParcelUUID = LandData.GlobalID; SendLandProperties(0, true, LandChannel.LAND_RESULT_SINGLE, avatar.ControllingClient); return; } } SendLandProperties(-10000, false, LandChannel.LAND_RESULT_SINGLE, avatar.ControllingClient); }); } #endregion #region AccessList Functions public List<LandAccessEntry> CreateAccessListArrayByFlag(AccessList flag) { ExpireAccessList(); List<LandAccessEntry> list = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in LandData.ParcelAccessList) { if (entry.Flags == flag) list.Add(entry); } if (list.Count == 0) { LandAccessEntry e = new LandAccessEntry(); e.AgentID = UUID.Zero; e.Flags = 0; e.Expires = 0; list.Add(e); } return list; } public void SendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID, IClientAPI remote_client) { if ((flags & (uint) AccessList.Access) != 0) { List<LandAccessEntry> accessEntries = CreateAccessListArrayByFlag(AccessList.Access); remote_client.SendLandAccessListData(accessEntries,(uint) AccessList.Access,LandData.LocalID); } if ((flags & (uint) AccessList.Ban) != 0) { List<LandAccessEntry> accessEntries = CreateAccessListArrayByFlag(AccessList.Ban); remote_client.SendLandAccessListData(accessEntries, (uint)AccessList.Ban, LandData.LocalID); } } public void UpdateAccessList(uint flags, UUID transactionID, List<LandAccessEntry> entries) { if((flags & 0x03) == 0) return; // we only have access and ban flags &=0x03 ; // get a work copy of lists List<LandAccessEntry> parcelAccessList = new List<LandAccessEntry>(LandData.ParcelAccessList); // first packet on a transaction clears before adding // we need to this way because viewer protocol does not seem reliable lock (m_listTransactionsLock) { if ((!m_listTransactions.ContainsKey(flags)) || m_listTransactions[flags] != transactionID) { m_listTransactions[flags] = transactionID; List<LandAccessEntry> toRemove = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in parcelAccessList) { if (((uint)entry.Flags & flags) != 0) toRemove.Add(entry); } foreach (LandAccessEntry entry in toRemove) parcelAccessList.Remove(entry); // a delete all command ? if (entries.Count == 1 && entries[0].AgentID == UUID.Zero) { LandData.ParcelAccessList = parcelAccessList; if ((flags & (uint)AccessList.Access) != 0) LandData.Flags &= ~(uint)ParcelFlags.UseAccessList; if ((flags & (uint)AccessList.Ban) != 0) LandData.Flags &= ~(uint)ParcelFlags.UseBanList; m_listTransactions.Remove(flags); return; } } } foreach (LandAccessEntry entry in entries) { LandAccessEntry temp = new LandAccessEntry(); temp.AgentID = entry.AgentID; temp.Expires = entry.Expires; temp.Flags = (AccessList)flags; parcelAccessList.Add(temp); } LandData.ParcelAccessList = parcelAccessList; if ((flags & (uint)AccessList.Access) != 0) LandData.Flags |= (uint)ParcelFlags.UseAccessList; if ((flags & (uint)AccessList.Ban) != 0) LandData.Flags |= (uint)ParcelFlags.UseBanList; } #endregion #region Update Functions public void UpdateLandBitmapByteArray() { LandData.Bitmap = ConvertLandBitmapToBytes(); } /// <summary> /// Update all settings in land such as area, bitmap byte array, etc /// </summary> public void ForceUpdateLandInfo() { UpdateGeometryValues(); UpdateLandBitmapByteArray(); } public void SetLandBitmapFromByteArray() { LandBitmap = ConvertBytesToLandBitmap(); } /// <summary> /// Updates geomtric values after area/shape modification of the land object /// </summary> private void UpdateGeometryValues() { int min_x = Int32.MaxValue; int min_y = Int32.MaxValue; int max_x = Int32.MinValue; int max_y = Int32.MinValue; int tempArea = 0; int x, y; int lastX = 0; int lastY = 0; float avgx = 0f; float avgy = 0f; bool needFirst = true; for (x = 0; x < LandBitmap.GetLength(0); x++) { for (y = 0; y < LandBitmap.GetLength(1); y++) { if (LandBitmap[x, y]) { if (min_x > x) min_x = x; if (min_y > y) min_y = y; if (max_x < x) max_x = x; if (max_y < y) max_y = y; if(needFirst) { avgx = x; avgy = y; m_startPoint.X = x * landUnit; m_startPoint.Y = y * landUnit; needFirst = false; } else { // keeping previous odd average avgx = (avgx * tempArea + x) / (tempArea + 1); avgy = (avgy * tempArea + y) / (tempArea + 1); } tempArea++; lastX = x; lastY = y; } } } int halfunit = landUnit/2; m_centerPoint.X = avgx * landUnit + halfunit; m_centerPoint.Y = avgy * landUnit + halfunit; m_endPoint.X = lastX * landUnit + landUnit; m_endPoint.Y = lastY * landUnit + landUnit; // next tests should not be needed // if they fail, something is wrong int regionSizeX = (int)Constants.RegionSize; int regionSizeY = (int)Constants.RegionSize; ulong regionHandle; if(m_scene != null) { RegionInfo ri = m_scene.RegionInfo; regionSizeX = (int)ri.RegionSizeX; regionSizeY = (int)ri.RegionSizeY; regionHandle = ri.RegionHandle; //create a fake ID LandData.FakeID = Util.BuildFakeParcelID(regionHandle, (uint)(lastX * landUnit), (uint)(lastY * landUnit)); } int tx = min_x * landUnit; if (tx >= regionSizeX) tx = regionSizeX - 1; int ty = min_y * landUnit; if (ty >= regionSizeY) ty = regionSizeY - 1; m_AABBmin.X = tx; m_AABBmin.Y = ty; if(m_scene == null || m_scene.Heightmap == null) LandData.AABBMin = new Vector3(tx, ty, 0f); else LandData.AABBMin = new Vector3(tx, ty, (float)m_scene.Heightmap[tx, ty]); max_x++; tx = max_x * landUnit; if (tx > regionSizeX) tx = regionSizeX; max_y++; ty = max_y * landUnit; if (ty > regionSizeY) ty = regionSizeY; m_AABBmax.X = tx; m_AABBmax.Y = ty; if(m_scene == null || m_scene.Heightmap == null) LandData.AABBMax = new Vector3(tx, ty, 0f); else LandData.AABBMax = new Vector3(tx, ty, (float)m_scene.Heightmap[tx - 1, ty - 1]); tempArea *= landUnit * landUnit; LandData.Area = tempArea; } #endregion #region Land Bitmap Functions /// <summary> /// Sets the land's bitmap manually /// </summary> /// <param name="bitmap">block representing where this land is on a map mapped in a 4x4 meter grid</param> public void SetLandBitmap(bool[,] bitmap) { LandBitmap = bitmap; ForceUpdateLandInfo(); } /// <summary> /// Gets the land's bitmap manually /// </summary> /// <returns></returns> public bool[,] GetLandBitmap() { return LandBitmap; } public bool[,] BasicFullRegionLandBitmap() { return GetSquareLandBitmap(0, 0, (int)m_scene.RegionInfo.RegionSizeX, (int) m_scene.RegionInfo.RegionSizeY, true); } public bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y, bool set_value = true) { bool[,] tempBitmap = ModifyLandBitmapSquare(null, start_x, start_y, end_x, end_y, set_value); return tempBitmap; } /// <summary> /// Change a land bitmap at within a square and set those points to a specific value /// </summary> /// <param name="land_bitmap"></param> /// <param name="start_x"></param> /// <param name="start_y"></param> /// <param name="end_x"></param> /// <param name="end_y"></param> /// <param name="set_value"></param> /// <returns></returns> public bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value) { if(land_bitmap == null) { land_bitmap = new bool[m_scene.RegionInfo.RegionSizeX / landUnit, m_scene.RegionInfo.RegionSizeY / landUnit]; if(!set_value) return land_bitmap; } start_x /= landUnit; end_x /= landUnit; start_y /= landUnit; end_y /= landUnit; for (int x = start_x; x < end_x; ++x) { for (int y = start_y; y < end_y; ++y) { land_bitmap[x, y] = set_value; } } // m_log.DebugFormat("{0} ModifyLandBitmapSquare. startXY=<{1},{2}>, endXY=<{3},{4}>, val={5}, landBitmapSize=<{6},{7}>", // LogHeader, start_x, start_y, end_x, end_y, set_value, land_bitmap.GetLength(0), land_bitmap.GetLength(1)); return land_bitmap; } /// <summary> /// Join the true values of 2 bitmaps together /// </summary> /// <param name="bitmap_base"></param> /// <param name="bitmap_add"></param> /// <returns></returns> public bool[,] MergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add) { if (bitmap_base.GetLength(0) != bitmap_add.GetLength(0) || bitmap_base.GetLength(1) != bitmap_add.GetLength(1)) { throw new Exception( String.Format("{0} MergeLandBitmaps. merging maps not same size. baseSizeXY=<{1},{2}>, addSizeXY=<{3},{4}>", LogHeader, bitmap_base.GetLength(0), bitmap_base.GetLength(1), bitmap_add.GetLength(0), bitmap_add.GetLength(1)) ); } for (int x = 0; x < bitmap_add.GetLength(0); x++) { for (int y = 0; y < bitmap_base.GetLength(1); y++) { bitmap_base[x, y] |= bitmap_add[x, y]; } } return bitmap_base; } /// <summary> /// Remap a land bitmap. Takes the supplied land bitmap and rotates it, crops it and finally offsets it into /// a final land bitmap of the target region size. /// </summary> /// <param name="bitmap_base">The original parcel bitmap</param> /// <param name="rotationDegrees"></param> /// <param name="displacement">&lt;x,y,?&gt;</param> /// <param name="boundingOrigin">&lt;x,y,?&gt;</param> /// <param name="boundingSize">&lt;x,y,?&gt;</param> /// <param name="regionSize">&lt;x,y,?&gt;</param> /// <param name="isEmptyNow">out: This is set if the resultant bitmap is now empty</param> /// <param name="AABBMin">out: parcel.AABBMin &lt;x,y,0&gt</param> /// <param name="AABBMax">out: parcel.AABBMax &lt;x,y,0&gt</param> /// <returns>New parcel bitmap</returns> public bool[,] RemapLandBitmap(bool[,] bitmap_base, Vector2 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize, Vector2 regionSize, out bool isEmptyNow) { // get the size of the incoming bitmap int baseX = bitmap_base.GetLength(0); int baseY = bitmap_base.GetLength(1); // create an intermediate bitmap that is 25% bigger on each side that we can work with to handle rotations int offsetX = baseX / 4; // the original origin will now be at these coordinates so now we can have imaginary negative coordinates ;) int offsetY = baseY / 4; int tmpX = baseX + baseX / 2; int tmpY = baseY + baseY / 2; int centreX = tmpX / 2; int centreY = tmpY / 2; bool[,] bitmap_tmp = new bool[tmpX, tmpY]; double radianRotation = Math.PI * rotationDegrees / 180f; double cosR = Math.Cos(radianRotation); double sinR = Math.Sin(radianRotation); if (rotationDegrees < 0f) rotationDegrees += 360f; //-90=270 -180=180 -270=90 // So first we apply the rotation to the incoming bitmap, storing the result in bitmap_tmp // We special case orthogonal rotations for accuracy because even using double precision math, Math.Cos(90 degrees) is never fully 0 // and we can never rotate around a centre pixel because the bitmap size is always even int x, y, sx, sy; for (y = 0; y <= tmpY; y++) { for (x = 0; x <= tmpX; x++) { if (rotationDegrees == 0f) { sx = x - offsetX; sy = y - offsetY; } else if (rotationDegrees == 90f) { sx = y - offsetX; sy = tmpY - 1 - x - offsetY; } else if (rotationDegrees == 180f) { sx = tmpX - 1 - x - offsetX; sy = tmpY - 1 - y - offsetY; } else if (rotationDegrees == 270f) { sx = tmpX - 1 - y - offsetX; sy = x - offsetY; } else { // arbitary rotation: hmmm should I be using (centreX - 0.5) and (centreY - 0.5) and round cosR and sinR to say only 5 decimal places? sx = centreX + (int)Math.Round((((double)x - centreX) * cosR) + (((double)y - centreY) * sinR)) - offsetX; sy = centreY + (int)Math.Round((((double)y - centreY) * cosR) - (((double)x - centreX) * sinR)) - offsetY; } if (sx >= 0 && sx < baseX && sy >= 0 && sy < baseY) { try { if (bitmap_base[sx, sy]) bitmap_tmp[x, y] = true; } catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;) { m_log.DebugFormat("{0} RemapLandBitmap Rotate: Out of Bounds sx={1} sy={2} dx={3} dy={4}", LogHeader, sx, sy, x, y); } } } } // We could also incorporate the next steps, bounding-rectangle and displacement in the loop above, but it's simpler to visualise if done separately // and will also make it much easier when later I want the option for maybe a circular or oval bounding shape too ;). // So... our output land bitmap must be the size of the current region but rememeber, parcel landbitmaps are landUnit metres (4x4 metres) per point, // and region sizes, boundaries and displacements are in metres so we need to scale down int newX = (int)(regionSize.X / landUnit); int newY = (int)(regionSize.Y / landUnit); bool[,] bitmap_new = new bool[newX, newY]; // displacement is relative to <0,0> in the destination region and defines where the origin of the data selected by the bounding-rectangle is placed int dispX = (int)Math.Floor(displacement.X / landUnit); int dispY = (int)Math.Floor(displacement.Y / landUnit); // startX/Y and endX/Y are coordinates in bitmap_tmp int startX = (int)Math.Floor(boundingOrigin.X / landUnit) + offsetX; if (startX > tmpX) startX = tmpX; if (startX < 0) startX = 0; int startY = (int)Math.Floor(boundingOrigin.Y / landUnit) + offsetY; if (startY > tmpY) startY = tmpY; if (startY < 0) startY = 0; int endX = (int)Math.Floor((boundingOrigin.X + boundingSize.X) / landUnit) + offsetX; if (endX > tmpX) endX = tmpX; if (endX < 0) endX = 0; int endY = (int)Math.Floor((boundingOrigin.Y + boundingSize.Y) / landUnit) + offsetY; if (endY > tmpY) endY = tmpY; if (endY < 0) endY = 0; //m_log.DebugFormat("{0} RemapLandBitmap: inSize=<{1},{2}>, disp=<{3},{4}> rot={5}, offset=<{6},{7}>, boundingStart=<{8},{9}>, boundingEnd=<{10},{11}>, cosR={12}, sinR={13}, outSize=<{14},{15}>", LogHeader, // baseX, baseY, dispX, dispY, radianRotation, offsetX, offsetY, startX, startY, endX, endY, cosR, sinR, newX, newY); isEmptyNow = true; int dx, dy; for (y = startY; y < endY; y++) { for (x = startX; x < endX; x++) { dx = x - startX + dispX; dy = y - startY + dispY; if (dx >= 0 && dx < newX && dy >= 0 && dy < newY) { try { if (bitmap_tmp[x, y]) { bitmap_new[dx, dy] = true; isEmptyNow = false; } } catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;) { m_log.DebugFormat("{0} RemapLandBitmap - Bound & Displace: Out of Bounds sx={1} sy={2} dx={3} dy={4}", LogHeader, x, y, dx, dy); } } } } return bitmap_new; } /// <summary> /// Clears any parcel data in bitmap_base where there exists parcel data in bitmap_new. In other words the parcel data /// in bitmap_new takes over the space of the parcel data in bitmap_base. /// </summary> /// <param name="bitmap_base"></param> /// <param name="bitmap_new"></param> /// <param name="isEmptyNow">out: This is set if the resultant bitmap is now empty</param> /// <param name="AABBMin">out: parcel.AABBMin &lt;x,y,0&gt</param> /// <param name="AABBMax">out: parcel.AABBMax &lt;x,y,0&gt</param> /// <returns>New parcel bitmap</returns> public bool[,] RemoveFromLandBitmap(bool[,] bitmap_base, bool[,] bitmap_new, out bool isEmptyNow) { // get the size of the incoming bitmaps int baseX = bitmap_base.GetLength(0); int baseY = bitmap_base.GetLength(1); int newX = bitmap_new.GetLength(0); int newY = bitmap_new.GetLength(1); if (baseX != newX || baseY != newY) { throw new Exception( String.Format("{0} RemoveFromLandBitmap: Land bitmaps are not the same size! baseX={1} baseY={2} newX={3} newY={4}", LogHeader, baseX, baseY, newX, newY)); } isEmptyNow = true; for (int x = 0; x < baseX; x++) { for (int y = 0; y < baseY; y++) { if (bitmap_new[x, y]) bitmap_base[x, y] = false; if (bitmap_base[x, y]) { isEmptyNow = false; } } } return bitmap_base; } /// <summary> /// Converts the land bitmap to a packet friendly byte array /// </summary> /// <returns></returns> public byte[] ConvertLandBitmapToBytes() { byte[] tempConvertArr = new byte[LandBitmap.GetLength(0) * LandBitmap.GetLength(1) / 8]; int tempByte = 0; int byteNum = 0; int mask = 1; for (int y = 0; y < LandBitmap.GetLength(1); y++) { for (int x = 0; x < LandBitmap.GetLength(0); x++) { if (LandBitmap[x, y]) tempByte |= mask; mask = mask << 1; if (mask == 0x100) { mask = 1; tempConvertArr[byteNum++] = (byte)tempByte; tempByte = 0; } } } if(tempByte != 0 && byteNum < 512) tempConvertArr[byteNum] = (byte)tempByte; return tempConvertArr; } public bool[,] ConvertBytesToLandBitmap(bool overrideRegionSize = false) { int bitmapLen; int xLen; bool[,] tempConvertMap; if (overrideRegionSize) { // Importing land parcel data from an OAR where the source region is a different size to the dest region requires us // to make a LandBitmap that's not derived from the current region's size. We use the LandData.Bitmap size in bytes // to figure out what the OAR's region dimensions are. (Is there a better way to get the src region x and y from the OAR?) // This method assumes we always will have square regions bitmapLen = LandData.Bitmap.Length; xLen = (int)Math.Abs(Math.Sqrt(bitmapLen * 8)); tempConvertMap = new bool[xLen, xLen]; tempConvertMap.Initialize(); } else { tempConvertMap = new bool[m_scene.RegionInfo.RegionSizeX / landUnit, m_scene.RegionInfo.RegionSizeY / landUnit]; tempConvertMap.Initialize(); // Math.Min overcomes an old bug that might have made it into the database. Only use the bytes that fit into convertMap. bitmapLen = Math.Min(LandData.Bitmap.Length, tempConvertMap.GetLength(0) * tempConvertMap.GetLength(1) / 8); xLen = (int)(m_scene.RegionInfo.RegionSizeX / landUnit); if (bitmapLen == 512) { // Legacy bitmap being passed in. Use the legacy region size // and only set the lower area of the larger region. xLen = (int)(Constants.RegionSize / landUnit); } } // m_log.DebugFormat("{0} ConvertBytesToLandBitmap: bitmapLen={1}, xLen={2}", LogHeader, bitmapLen, xLen); byte tempByte; int x = 0, y = 0; for (int i = 0; i < bitmapLen; i++) { tempByte = LandData.Bitmap[i]; for (int bitmask = 0x01; bitmask < 0x100; bitmask = bitmask << 1) { bool bit = (tempByte & bitmask) == bitmask; try { tempConvertMap[x, y] = bit; } catch (Exception) { m_log.DebugFormat("{0} ConvertBytestoLandBitmap: i={1}, x={2}, y={3}", LogHeader, i, x, y); } x++; if (x >= xLen) { x = 0; y++; } } } return tempConvertMap; } public bool IsLandBitmapEmpty(bool[,] landBitmap) { for (int y = 0; y < landBitmap.GetLength(1); y++) { for (int x = 0; x < landBitmap.GetLength(0); x++) { if (landBitmap[x, y]) return false; } } return true; } public void DebugLandBitmap(bool[,] landBitmap) { m_log.InfoFormat("{0}: Map Key: #=claimed land .=unclaimed land.", LogHeader); for (int y = landBitmap.GetLength(1) - 1; y >= 0; y--) { string row = ""; for (int x = 0; x < landBitmap.GetLength(0); x++) { row += landBitmap[x, y] ? "#" : "."; } m_log.InfoFormat("{0}: {1}", LogHeader, row); } } #endregion #region Object Select and Object Owner Listing public void SendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client) { if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions, true)) { List<uint> resultLocalIDs = new List<uint>(); try { lock (primsOverMe) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.LocalId > 0) { if (request_type == LandChannel.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == LandData.OwnerID) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == LandChannel.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == LandData.GroupID && LandData.GroupID != UUID.Zero) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == LandChannel.LAND_SELECT_OBJECTS_OTHER && obj.OwnerID != remote_client.AgentId) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == (int)ObjectReturnType.List && returnIDs.Contains(obj.OwnerID)) { resultLocalIDs.Add(obj.LocalId); } } } } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to force select the parcel objects. Arr."); } remote_client.SendForceClientSelectObjects(resultLocalIDs); } } /// <summary> /// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes /// aggreagete details such as the number of prims. /// /// </summary> /// <param name="remote_client"> /// A <see cref="IClientAPI"/> /// </param> public void SendLandObjectOwners(IClientAPI remote_client) { if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions, true)) { Dictionary<UUID, int> primCount = new Dictionary<UUID, int>(); List<UUID> groups = new List<UUID>(); lock (primsOverMe) { // m_log.DebugFormat( // "[LAND OBJECT]: Request for SendLandObjectOwners() from {0} with {1} known prims on region", // remote_client.Name, primsOverMe.Count); try { foreach (SceneObjectGroup obj in primsOverMe) { try { if (!primCount.ContainsKey(obj.OwnerID)) { primCount.Add(obj.OwnerID, 0); } } catch (NullReferenceException) { m_log.Error("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel"); } try { primCount[obj.OwnerID] += obj.PrimCount; } catch (KeyNotFoundException) { m_log.Error("[LAND]: Unable to match a prim with it's owner."); } if (obj.OwnerID == obj.GroupID && (!groups.Contains(obj.OwnerID))) groups.Add(obj.OwnerID); } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to Enumerate Land object arr."); } } remote_client.SendLandObjectOwners(LandData, groups, primCount); } } public Dictionary<UUID, int> GetLandObjectOwners() { Dictionary<UUID, int> ownersAndCount = new Dictionary<UUID, int>(); lock (primsOverMe) { try { foreach (SceneObjectGroup obj in primsOverMe) { if (!ownersAndCount.ContainsKey(obj.OwnerID)) { ownersAndCount.Add(obj.OwnerID, 0); } ownersAndCount[obj.OwnerID] += obj.PrimCount; } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to enumerate land owners. arr."); } } return ownersAndCount; } #endregion #region Object Sales public void SellLandObjects(UUID previousOwner) { // m_log.DebugFormat( // "[LAND OBJECT]: Request to sell objects in {0} from {1}", LandData.Name, previousOwner); if (LandData.IsGroupOwned) return; IBuySellModule m_BuySellModule = m_scene.RequestModuleInterface<IBuySellModule>(); if (m_BuySellModule == null) { m_log.Error("[LAND OBJECT]: BuySellModule not found"); return; } ScenePresence sp; if (!m_scene.TryGetScenePresence(LandData.OwnerID, out sp)) { m_log.Error("[LAND OBJECT]: New owner is not present in scene"); return; } lock (primsOverMe) { foreach (SceneObjectGroup obj in primsOverMe) { if(m_scene.Permissions.CanSellObject(previousOwner,obj, (byte)SaleType.Original)) m_BuySellModule.BuyObject(sp.ControllingClient, UUID.Zero, obj.LocalId, (byte)SaleType.Original, 0); } } } #endregion #region Object Returning public void ReturnObject(SceneObjectGroup obj) { SceneObjectGroup[] objs = new SceneObjectGroup[1]; objs[0] = obj; m_scene.returnObjects(objs, null); } public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client) { // m_log.DebugFormat( // "[LAND OBJECT]: Request to return objects in {0} from {1}", LandData.Name, remote_client.Name); Dictionary<UUID,List<SceneObjectGroup>> returns = new Dictionary<UUID,List<SceneObjectGroup>>(); lock (primsOverMe) { if (type == (uint)ObjectReturnType.Owner) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.OwnerID == LandData.OwnerID) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.Group && LandData.GroupID != UUID.Zero) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.GroupID == LandData.GroupID) { if (obj.OwnerID == LandData.OwnerID) continue; if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.Other) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.OwnerID != LandData.OwnerID && (obj.GroupID != LandData.GroupID || LandData.GroupID == UUID.Zero)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.List) { List<UUID> ownerlist = new List<UUID>(owners); foreach (SceneObjectGroup obj in primsOverMe) { if (ownerlist.Contains(obj.OwnerID)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } } foreach (List<SceneObjectGroup> ol in returns.Values) { if (m_scene.Permissions.CanReturnObjects(this, remote_client, ol)) m_scene.returnObjects(ol.ToArray(), remote_client); } } #endregion #region Object Adding/Removing from Parcel public void ResetOverMeRecord() { lock (primsOverMe) primsOverMe.Clear(); } public void AddPrimOverMe(SceneObjectGroup obj) { // m_log.DebugFormat("[LAND OBJECT]: Adding scene object {0} {1} over {2}", obj.Name, obj.LocalId, LandData.Name); lock (primsOverMe) primsOverMe.Add(obj); } public void RemovePrimFromOverMe(SceneObjectGroup obj) { // m_log.DebugFormat("[LAND OBJECT]: Removing scene object {0} {1} from over {2}", obj.Name, obj.LocalId, LandData.Name); lock (primsOverMe) primsOverMe.Remove(obj); } #endregion /// <summary> /// Set the media url for this land parcel /// </summary> /// <param name="url"></param> public void SetMediaUrl(string url) { if (String.IsNullOrWhiteSpace(url)) LandData.MediaURL = String.Empty; else { try { Uri dummmy = new Uri(url, UriKind.Absolute); LandData.MediaURL = url; } catch (Exception e) { m_log.ErrorFormat("[LAND OBJECT]: SetMediaUrl error: {0}", e.Message); return; } } m_scene.LandChannel.UpdateLandObject(LandData.LocalID, LandData); SendLandUpdateToAvatarsOverMe(); } /// <summary> /// Set the music url for this land parcel /// </summary> /// <param name="url"></param> public void SetMusicUrl(string url) { if (String.IsNullOrWhiteSpace(url)) LandData.MusicURL = String.Empty; else { try { Uri dummmy = new Uri(url, UriKind.Absolute); LandData.MusicURL = url; } catch (Exception e) { m_log.ErrorFormat("[LAND OBJECT]: SetMusicUrl error: {0}", e.Message); return; } } m_scene.LandChannel.UpdateLandObject(LandData.LocalID, LandData); SendLandUpdateToAvatarsOverMe(); } /// <summary> /// Get the music url for this land parcel /// </summary> /// <returns>The music url.</returns> public string GetMusicUrl() { return LandData.MusicURL; } #endregion private void OnFrame() { m_expiryCounter++; if (m_expiryCounter >= 50) { ExpireAccessList(); m_expiryCounter = 0; } // need to update dwell here bc landdata has no parent info if(LandData != null && m_dwellModule != null) { double now = Util.GetTimeStampMS(); double elapsed = now - LandData.LastDwellTimeMS; if(elapsed > 150000) //2.5 minutes resolution / throttle { float dwell = LandData.Dwell; double cur = dwell * 60000.0; double decay = 1.5e-8 * cur * elapsed; cur -= decay; if(cur < 0) cur = 0; UUID lgid = LandData.GlobalID; m_scene.ForEachRootScenePresence(delegate(ScenePresence sp) { if(sp.IsNPC || sp.IsDeleted || sp.currentParcelUUID != lgid) return; cur += (now - sp.ParcelDwellTickMS); sp.ParcelDwellTickMS = now; }); float newdwell = (float)(cur * 1.666666666667e-5); LandData.Dwell = newdwell; if(Math.Abs(newdwell - dwell) >= 0.9) m_scene.EventManager.TriggerLandObjectAdded(this); } } } private void ExpireAccessList() { List<LandAccessEntry> delete = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in LandData.ParcelAccessList) { if (entry.Expires != 0 && entry.Expires < Util.UnixTimeSinceEpoch()) delete.Add(entry); } foreach (LandAccessEntry entry in delete) { LandData.ParcelAccessList.Remove(entry); ScenePresence presence; if (m_scene.TryGetScenePresence(entry.AgentID, out presence) && (!presence.IsChildAgent)) { ILandObject land = m_scene.LandChannel.GetLandObject(presence.AbsolutePosition.X, presence.AbsolutePosition.Y); if (land.LandData.LocalID == LandData.LocalID) { Vector3 pos = m_scene.GetNearestAllowedPosition(presence, land); presence.TeleportOnEject(pos); presence.ControllingClient.SendAlertMessage("You have been ejected from this land"); } } m_log.DebugFormat("[LAND]: Removing entry {0} because it has expired", entry.AgentID); } if (delete.Count > 0) m_scene.EventManager.TriggerLandObjectUpdated((uint)LandData.LocalID, this); } public void StoreEnvironment(ViewerEnvironment VEnv) { int lastVersion = LandData.EnvironmentVersion; LandData.Environment = VEnv; if (VEnv == null) LandData.EnvironmentVersion = -1; else { ++LandData.EnvironmentVersion; VEnv.version = LandData.EnvironmentVersion; } if(lastVersion != LandData.EnvironmentVersion) { m_scene.LandChannel.UpdateLandObject(LandData.LocalID, LandData); SendLandUpdateToAvatarsOverMe(); } } } }
38.402237
218
0.492116
[ "BSD-3-Clause" ]
CloudFiveDev/metagrid
OpenSim/Region/CoreModules/World/Land/LandObject.cs
78,955
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Mandater.Models; using Mandater.Repository; using Microsoft.AspNetCore.Cors; namespace Mandater.Controllers { //[EnableCors("CorsPolicy")] //[Produces("application/json")] //[Route("api/v0.1.0/no/2017/")] //public class VDModelsController : Controller //{ // private readonly VDContext _context; // public VDModelsController(VDContext context) // { // _context = context; // } // // GET: api/v0.1.0/no/2017/ // [HttpGet] // public IEnumerable<VDModel> GetVDModels() // { // return _context.VDModels; // } // // GET: api/v0.1.0/no/2017/fylkenavn // [HttpGet("fylkenavn")] // public IEnumerable<string> GetVDFylkenavn() // { // List<VDModel> all = _context.VDModels.ToList(); // List<string> fylkenavn = new List<string>(); // foreach (var element in all) // { // fylkenavn.Add(element.Fylkenavn); // } // System.Diagnostics.Debug.WriteLine(fylkenavn.Distinct().FirstOrDefault()); // return fylkenavn.Distinct(); // } //} }
29.085106
88
0.595465
[ "Apache-2.0" ]
Log234/Mandater
Mandater/Controllers/VDModelsController.cs
1,369
C#
using mc_Bonalds.Models; using mc_Bonalds.Repositorios; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace mc_Bonalds.Controllers { public class PedidoController : Controller { private PedidoRepositorio Repositorio = new PedidoRepositorio(); [HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult RegistrarPedido(IFormCollection form){ System.Console.WriteLine(form["nome"]); System.Console.WriteLine(form["endereco"]); System.Console.WriteLine(form["telefone"]); System.Console.WriteLine(form["email"]); System.Console.WriteLine(form["hambúrguer"]); System.Console.WriteLine(form["shake"]); Pedido pedido = new Pedido(); Cliente cliente = new Cliente(); cliente.Nome = form["nome"]; cliente.Endereco = form["endereco"]; cliente.Telefone = form["telefone"]; cliente.Email = form["email"]; pedido.Cliente = cliente; Hamburguer hamburguer = new Hamburguer( Nome: form["hamburguer"] ); pedido.Hamburguer = hamburguer; Shake shake = new Shake(){ Nome = form["shake"] }; pedido.Shake = shake; Repositorio.Inserir(pedido); return RedirectToAction("Index", "Home"); } } }
28.942308
72
0.572093
[ "MIT" ]
regiamariana/cshtml
mc Bonalds/Controllers/PedidoController.cs
1,506
C#
using System; namespace Chester.Models; public record SavedMove(Move Move, SquareState ToSquare) { }; [Flags] public enum MoveType : ushort { Normal = 0b0000000000, Capture = 0b0000000001, EnPassant = 0b0000000010, PromotionQueen = 0b0000000100, PromotionRook = 0b0000001000, PromotionBishop = 0b0000010000, PromotionKnight = 0b0000100000, PromotionMask = 0b0000111100, CastleQueenSide = 0b0001000000, CastleKingSide = 0b0010000000, CastleMask = 0b0011000000, Check = 0b0100000000, CheckMate = 0b1000000000, } public record Move { public SquareState FromSquare { get; init; } public Position From { get; init; } public Position To { get; init; } public MoveType MoveType { get; init; } public Move(SquareState fromSquare, Position from, Position to, MoveType type = MoveType.Normal) { if (fromSquare.IsInvalid()) throw new ArgumentException("Cannot make move from invalid square", nameof(fromSquare)); if (!from.Valid) throw new ArgumentException("Cannot make move from invalid position", nameof(from)); if (!to.Valid) throw new ArgumentException("Cannot make move to invalid position", nameof(to)); if (type.HasFlag(MoveType.CastleKingSide) && !((to.Rank == 0 || to.Rank == 7) && to.File == 6)) throw new ArgumentException("Invalid castling move", nameof(to)); if (type.HasFlag(MoveType.CastleQueenSide) && !((to.Rank == 0 || to.Rank == 7) && (to.File == 2))) throw new ArgumentException("Invalid castling move", nameof(to)); FromSquare = fromSquare; From = from; To = to; MoveType = type; } public void Deconstruct(out SquareState fromSquare, out Position from, out Position to, out MoveType moveType) => (fromSquare, from, to, moveType) = (FromSquare, From, To, MoveType); public override string ToString() { if ((MoveType & MoveType.CastleMask) != 0) { return (MoveType & MoveType.CastleMask) switch { MoveType.CastleKingSide => "O-O", MoveType.CastleQueenSide => "O-O-O", _ => throw new InvalidOperationException($"Invalid castling move type {MoveType}"), }; } if (FromSquare.IsPawn() && MoveType.HasFlag(MoveType.Capture)) return $"{From.FileString}x{To}"; if (FromSquare.IsPawn()) return $"{To}"; return $"{FromSquare.AsString()}{From}{(MoveType.HasFlag(MoveType.Capture) ? 'x' : string.Empty)}{To}"; } public string ToStringLong() => $"{From}{To}"; }
35.626667
124
0.625749
[ "MIT" ]
stefer/Chester
Chester/Models/Move.cs
2,674
C#
using System; namespace ShellLoginSample.Models { public class Item { public string Id { get; set; } public string Text { get; set; } public string Description { get; set; } } }
19.545455
47
0.595349
[ "MIT" ]
davidortinau/ShellLoginSample
ShellLoginSample/Models/Item.cs
217
C#
using Celerik.NetCore.Services; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Celerik.NetCore.Web.Test { [TestClass] public class CorsExtensionsTest : WebBaseTest { [TestMethod] public void CorsExtensions_GetCorsConfig_Disabled() { var config = GetService<IConfiguration>(); var corsConfig = config.GetCorsConfig(); Assert.AreEqual(CorsPolicy.Disabled, corsConfig.Policy); CollectionAssert.AreEqual(new string[0], corsConfig.Origins); } [TestMethod] [ExpectedException(typeof(ConfigException))] public void CorsExtensions_GetCorsConfig_InvalidPolicy() { var config = GetService<IConfiguration>(); config["Cors:PolicyName"] = "QueBuenoUnasSalchipapas"; config.GetCorsConfig(); } [TestMethod] public void CorsExtensions_GetCorsConfig_AllowAnyOrigin() { var config = GetService<IConfiguration>(); config["Cors:PolicyName"] = "AllowAnyOrigin"; var corsConfig = config.GetCorsConfig(); Assert.AreEqual(CorsPolicy.AllowAnyOrigin, corsConfig.Policy); CollectionAssert.AreEqual(new string[0], corsConfig.Origins); } [TestMethod] [ExpectedException(typeof(ConfigException))] public void CorsExtensions_GetCorsConfig_AllowSpecificOrigins_NoOrigins() { var config = GetService<IConfiguration>(); config["Cors:PolicyName"] = "AllowSpecificOrigins"; config.GetCorsConfig(); } [TestMethod] [ExpectedException(typeof(ConfigException))] public void CorsExtensions_GetCorsConfig_AllowSpecificOrigins_InvalidOrigin() { var config = GetService<IConfiguration>(); config["Cors:PolicyName"] = "AllowSpecificOrigins"; config["Cors:Origins"] = "QueBuenoUnTamalConChocolate"; config.GetCorsConfig(); } [TestMethod] public void CorsExtensions_GetCorsConfig_AllowSpecificOrigins_VaidOrigins() { var config = GetService<IConfiguration>(); config["Cors:PolicyName"] = "AllowSpecificOrigins"; config["Cors:Origins"] = "http://salchipapas.com,http://tamales.com"; var corsConfig = config.GetCorsConfig(); Assert.AreEqual(CorsPolicy.AllowSpecificOrigins, corsConfig.Policy); CollectionAssert.AreEqual( new string[] { "http://salchipapas.com", "http://tamales.com" }, corsConfig.Origins ); } } }
36.106667
85
0.633309
[ "MIT" ]
celerik/celerik-netcore-web
source/Celerik.NetCore.Web.Test/Cors/CorsExtensionsTest.cs
2,710
C#
using AdventOfCode.Common; using AdventOfCode.Common.Day; namespace AdventOfCode.Day7 { public class Solution : AdventOfCodeDay<Part1, Part2> { protected override int Day => 7; } public class Part1 : ParSolution<CrabSubmarinesV1> { protected override CrabSubmarinesV1 BuildCrabSubmarines(int[] sumbarineHorizontalPositions) => new(sumbarineHorizontalPositions); } public class Part2 : ParSolution<CrabSubmarinesV2> { protected override CrabSubmarinesV2 BuildCrabSubmarines(int[] sumbarineHorizontalPositions) => new(sumbarineHorizontalPositions); } public abstract class ParSolution<TCrabSumbarines> : IPartSolution where TCrabSumbarines : ICrabSubmarines { public long Solve(string input) { var submarinesHorizontalPositions = input .Split(',') .Select(n => int.Parse(n)) .ToArray(); var crabSubmarines = BuildCrabSubmarines(submarinesHorizontalPositions); var optimalAlignment = crabSubmarines.GetOptimalAlignment(); var fuelCost = crabSubmarines.CalculateFuelCostTo(optimalAlignment); return fuelCost; } protected abstract TCrabSumbarines BuildCrabSubmarines(int[] sumbarineHorizontalPositions); } }
31.511628
99
0.673801
[ "MIT" ]
Almantask/AdventOfCode2021
AdventOfCode/Day7/Solution.cs
1,357
C#
using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using SFA.DAS.Api.Common.Infrastructure; using SFA.DAS.SharedOuterApi.Configuration; using SFA.DAS.SharedOuterApi.InnerApi.Requests; using SFA.DAS.SharedOuterApi.Interfaces; namespace SFA.DAS.SharedOuterApi.Infrastructure.HealthCheck { public class AssessorsApiHealthCheck : IHealthCheck { private const string HealthCheckResultDescription = "Assessors Api check"; private readonly IAssessorsApiClient<AssessorsApiConfiguration> _apiClient; private readonly ILogger<AssessorsApiHealthCheck> _logger; public AssessorsApiHealthCheck( IAssessorsApiClient<AssessorsApiConfiguration> apiClient, ILogger<AssessorsApiHealthCheck> logger) { _apiClient = apiClient; _logger = logger; } public async Task<HealthCheckResult> CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { _logger.LogInformation("Pinging Assessors API"); var timer = Stopwatch.StartNew(); var response = await _apiClient.GetResponseCode(new GetPingRequest()); timer.Stop(); if ((int)response == 200) { var durationString = timer.Elapsed.ToHumanReadableString(); _logger.LogInformation($"Assessors API ping successful and took {durationString}"); return HealthCheckResult.Healthy(HealthCheckResultDescription, new Dictionary<string, object> { { "Duration", durationString } }); } _logger.LogWarning($"Assessors API ping failed : [Code: {response}]"); return HealthCheckResult.Unhealthy(HealthCheckResultDescription); } } }
37.471698
99
0.687311
[ "MIT" ]
SkillsFundingAgency/das-apim-endpoints
src/SFA.DAS.SharedOuterApi/Infrastructure/HealthCheck/AssessorsApiHealthCheck.cs
1,988
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Dns.Fluent { using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; /// <summary> /// Base interface for all record sets. /// </summary> /// <typeparam name="RecordSetT">The record set type.</typeparam> public interface IDnsRecordSets<RecordSetT> : Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListing<RecordSetT>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsGettingByName<RecordSetT>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Dns.Fluent.IDnsZone> { /// <summary> /// Lists all the record sets with the given suffix. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <return>List of record sets.</return> System.Collections.Generic.IEnumerable<RecordSetT> List(string recordSetNameSuffix); /// <summary> /// Lists all the record sets, with number of entries in each page limited to given size. /// </summary> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>List of record sets.</return> System.Collections.Generic.IEnumerable<RecordSetT> List(int pageSize); /// <summary> /// Lists all the record sets with the given suffix, also limits the number of entries /// per page to the given page size. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>The record sets.</return> System.Collections.Generic.IEnumerable<RecordSetT> List(string recordSetNameSuffix, int pageSize); /// <summary> /// Lists all the record sets with the given suffix. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <return>An observable that emits record sets.</return> Task<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IPagedCollection<RecordSetT>> ListAsync(string recordSetNameSuffix, bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the record sets, with number of entries in each page limited to given size. /// </summary> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>An observable that emits record sets.</return> Task<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IPagedCollection<RecordSetT>> ListAsync(int pageSize, bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the record sets with the given suffix, also limits the number of entries /// per page to the given page size. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>An observable that emits record sets.</return> Task<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IPagedCollection<RecordSetT>> ListAsync(string recordSetNameSuffix, int pageSize, bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken)); } }
58.044776
242
0.697609
[ "MIT" ]
graemefoster/azure-libraries-for-net
src/ResourceManagement/Dns/Domain/IDnsRecordSets.cs
3,889
C#
using System.Collections.Specialized; using System.ComponentModel.Composition; using DevExpress.Xpf.Docking; using Prism.Regions; namespace WpfEQDValidationApp.Infrastructure.Adapters { public class DocumentGroupAdapter : RegionAdapterBase<DocumentGroup> { [ImportingConstructor] public DocumentGroupAdapter(IRegionBehaviorFactory behaviorFactory) : base(behaviorFactory) { } protected override IRegion CreateRegion() { return new AllActiveRegion(); } protected override void Adapt(IRegion region, DocumentGroup regionTarget) { region.Views.CollectionChanged += (s, e) => { OnViewsCollectionChanged(region, regionTarget, s, e); }; } private void OnViewsCollectionChanged(IRegion region, DocumentGroup regionTarget, object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (var view in e.NewItems) { var manager = regionTarget.GetDockLayoutManager(); var panel = manager.DockController.AddDocumentPanel(regionTarget); panel.Content = view; if (view is IPanelInfo) { panel.Caption = ((IPanelInfo)view).GetPanelCaption(); panel.ShowCloseButton = ((IPanelInfo)view).ShowCloseButton; } else panel.Caption = "new Page"; manager.DockController.Activate(panel); } } } } }
35.765957
114
0.586556
[ "MIT" ]
isachpaz/EQDValidation
WpfEQDValidationApp/WpfEQDValidationApp.Infrastructure/Adapters/DocumentGroupAdapter.cs
1,683
C#
using System; using System.Collections.Generic; using System.Text; using VB = Dlrsoft.VBScript.Parser; using Microsoft.Scripting.Runtime; using System.Dynamic; #if USE35 using Microsoft.Scripting.Ast; #else using System.Linq.Expressions; #endif using Microsoft.Scripting.Utils; using System.Reflection; using System.IO; using Dlrsoft.VBScript.Binders; using Dlrsoft.VBScript.Compiler; using Dlrsoft.VBScript.Runtime; using Debug = System.Diagnostics.Debug; using Dlrsoft.VBScript.Parser; namespace Dlrsoft.VBScript.Compiler { /// <summary> /// The analysis phase. We don't do much except for generating the global functions, constants and variables table /// </summary> internal class VBScriptAnalyzer { public static void AnalyzeFile(Dlrsoft.VBScript.Parser.ScriptBlock block, AnalysisScope scope) { Debug.Assert(scope.IsModule); if (block.Statements != null) { foreach (VB.Statement s in block.Statements) { AnalyzeStatement(s, scope); } } } private static void AnalyzeStatement(VB.Statement s, AnalysisScope scope) { if (s is VB.MethodDeclaration) { string methodName = ((VB.MethodDeclaration)s).Name.Name.ToLower(); scope.FunctionTable.Add(methodName); ParameterExpression method = System.Linq.Expressions.Expression.Parameter(typeof(object)); scope.Names[methodName] = method; } else if (s is VB.LocalDeclarationStatement) { AnalyzeDeclarationExpr((VB.LocalDeclarationStatement)s, scope); } else if (s is VB.IfBlockStatement) { AnalyzeIfBlockStatement((VB.IfBlockStatement)s, scope); } else if (s is VB.SelectBlockStatement) { AnalyzeSelectBlockStatement((VB.SelectBlockStatement)s, scope); } else if (s is VB.BlockStatement) { AnalyzeBlockStatement((VB.BlockStatement)s, scope); } } private static void AnalyzeDeclarationExpr(VB.LocalDeclarationStatement stmt, AnalysisScope scope) { bool isConst = false; if (stmt.Modifiers != null) { if (stmt.Modifiers.ModifierTypes == VB.ModifierTypes.Const) { isConst = true; } } foreach (VB.VariableDeclarator d in stmt.VariableDeclarators) { foreach (VB.VariableName v in d.VariableNames) { string name = v.Name.Name.ToLower(); ParameterExpression p = System.Linq.Expressions.Expression.Parameter(typeof(object), name); scope.Names.Add(name, p); } } } private static void AnalyzeIfBlockStatement(VB.IfBlockStatement block, AnalysisScope scope) { AnalyzeBlockStatement(block, scope); if (block.ElseIfBlockStatements != null && block.ElseIfBlockStatements.Count > 0) { foreach (VB.ElseIfBlockStatement elseif in block.ElseIfBlockStatements) { AnalyzeBlockStatement(elseif, scope); } } if (block.ElseBlockStatement != null) { AnalyzeBlockStatement(block.ElseBlockStatement, scope); } } private static void AnalyzeSelectBlockStatement(VB.SelectBlockStatement block, AnalysisScope scope) { AnalyzeBlockStatement(block, scope); if (block.CaseBlockStatements != null && block.CaseBlockStatements.Count > 0) { foreach (VB.CaseBlockStatement caseStmt in block.CaseBlockStatements) { AnalyzeBlockStatement(caseStmt, scope); } } if (block.CaseElseBlockStatement != null) { AnalyzeBlockStatement(block.CaseElseBlockStatement, scope); } } public static void AnalyzeBlockStatement(VB.BlockStatement block, AnalysisScope scope) { if (block.Statements != null) { foreach (VB.Statement stmt in block.Statements) { AnalyzeStatement(stmt, scope); } } } } }
33.253623
118
0.568098
[ "Apache-2.0" ]
boldbrush/ASPClassicCompiler
aspclassiccompiler/VBScript/Compiler/VBScriptAnalyzer.cs
4,591
C#
//------------------------------------------------------------------------------ // <copyright file="SmiMetaData.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">Microsoft</owner> // <owner current="true" primary="false">Microsoft</owner> //------------------------------------------------------------------------------ namespace Microsoft.SqlServer.Server { using System; using System.Collections.Generic; using System.Diagnostics; using System.Data; using System.Data.Sql; using System.Data.SqlTypes; using System.Globalization; // DESIGN NOTES // // The following classes are a tight inheritance heirarchy, and are not designed for // being inherited outside of this file. Instances are guaranteed to be immutable, and // outside classes rely on this fact. // // The various levels may not all be used outside of this file, but for clarity of purpose // they are all usefull distinctions to make. // // In general, moving lower in the type heirarchy exposes less portable values. Thus, // the root metadata can be readily shared across different (MSSQL) servers and clients, // while QueryMetaData has attributes tied to a specific query, running against specific // data storage on a specific server. // // The SmiMetaData heirarchy does not do data validation on retail builds! It will assert // that the values passed to it have been validated externally, however. // // SmiMetaData // // Root of the heirarchy. // Represents the minimal amount of metadata required to represent any Sql Server datum // without any references to any particular server or schema (thus, no server-specific multi-part names). // It could be used to communicate solely between two disconnected clients, for instance. // // NOTE: It currently does not contain sufficient information to describe typed XML, since we // don't have a good server-independent mechanism for such. // // This class is also used as implementation for the public SqlMetaData class. internal class SmiMetaData { private SqlDbType _databaseType; // Main enum that determines what is valid for other attributes. private long _maxLength; // Varies for variable-length types, others are fixed value per type private byte _precision; // Varies for SqlDbType.Decimal, others are fixed value per type private byte _scale; // Varies for SqlDbType.Decimal, others are fixed value per type private long _localeId; // Valid only for character types, others are 0 private SqlCompareOptions _compareOptions; // Valid only for character types, others are SqlCompareOptions.Default private Type _clrType; // Varies for SqlDbType.Udt, others are fixed value per type. private string _udtAssemblyQualifiedName; // Valid only for UDT types when _clrType is not available private bool _isMultiValued; // Multiple instances per value? (I.e. tables, arrays) private IList<SmiExtendedMetaData> _fieldMetaData; // Metadata of fields for structured types private SmiMetaDataPropertyCollection _extendedProperties; // Extended properties, Key columns, sort order, etc. // DevNote: For now, since the list of extended property types is small, we can handle them in a simple list. // In the future, we may need to create a more performant storage & lookup mechanism, such as a hash table // of lists indexed by type of property or an array of lists with a well-known index for each type. // Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor) internal const long UnlimitedMaxLengthIndicator = -1; // unlimited (except by implementation) max-length. internal const long MaxUnicodeCharacters = 4000; // Maximum for limited type internal const long MaxANSICharacters = 8000; // Maximum for limited type internal const long MaxBinaryLength = 8000; // Maximum for limited type internal const int MinPrecision = 1; // SqlDecimal defines max precision internal const int MinScale = 0; // SqlDecimal defines max scale internal const int MaxTimeScale = 7; // Max scale for time, datetime2, and datetimeoffset internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998); internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999); internal static readonly SqlMoney MaxSmallMoney = new SqlMoney( ( (Decimal)Int32.MaxValue ) / 10000 ); internal static readonly SqlMoney MinSmallMoney = new SqlMoney( ( (Decimal)Int32.MinValue ) / 10000 ); internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; internal const long MaxNameLength = 128; // maximum length in the server is 128. private static readonly IList<SmiExtendedMetaData> __emptyFieldList = new List<SmiExtendedMetaData>().AsReadOnly(); // Precision to max length lookup table private static byte[] __maxLenFromPrecision = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9, 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17}; // Scale offset to max length lookup table private static byte[] __maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 }; // Defaults // SmiMetaData(SqlDbType, MaxLen, Prec, Scale, CompareOptions) internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None); // SqlDbType.BigInt internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None); // SqlDbType.Binary internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None); // SqlDbType.Bit internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.Char internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None); // SqlDbType.DateTime internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None); // SqlDbType.Decimal internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None); // SqlDbType.Float internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator,0, 0, SqlCompareOptions.None); // SqlDbType.Image internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None); // SqlDbType.Int internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None); // SqlDbType.Money internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.NChar internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator,0, 0, DefaultStringCompareOptions);// SqlDbType.NText internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.NVarChar internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None); // SqlDbType.Real internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None); // SqlDbType.UniqueIdentifier internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None); // SqlDbType.SmallDateTime internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None); // SqlDbType.SmallInt internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None); // SqlDbType.SmallMoney internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator,0, 0, DefaultStringCompareOptions);// SqlDbType.Text internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None); // SqlDbType.Timestamp internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None); // SqlDbType.TinyInt internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None); // SqlDbType.VarBinary internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.VarChar internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None); // SqlDbType.Variant internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator,0, 0, DefaultStringCompareOptions);// SqlDbType.Xml internal static readonly SmiMetaData DefaultUdt_NoType = new SmiMetaData(SqlDbType.Udt, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Udt internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Structured internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None); // SqlDbType.Date internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None); // SqlDbType.Time internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTime2 internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTimeOffset // No default for generic UDT // character defaults hook thread-local culture to get collation internal static SmiMetaData DefaultChar { get { return new SmiMetaData( DefaultChar_NoCollation.SqlDbType, DefaultChar_NoCollation.MaxLength, DefaultChar_NoCollation.Precision, DefaultChar_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } internal static SmiMetaData DefaultNChar { get { return new SmiMetaData( DefaultNChar_NoCollation.SqlDbType, DefaultNChar_NoCollation.MaxLength, DefaultNChar_NoCollation.Precision, DefaultNChar_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } internal static SmiMetaData DefaultNText { get { return new SmiMetaData( DefaultNText_NoCollation.SqlDbType, DefaultNText_NoCollation.MaxLength, DefaultNText_NoCollation.Precision, DefaultNText_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } internal static SmiMetaData DefaultNVarChar { get { return new SmiMetaData( DefaultNVarChar_NoCollation.SqlDbType, DefaultNVarChar_NoCollation.MaxLength, DefaultNVarChar_NoCollation.Precision, DefaultNVarChar_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } internal static SmiMetaData DefaultText { get { return new SmiMetaData( DefaultText_NoCollation.SqlDbType, DefaultText_NoCollation.MaxLength, DefaultText_NoCollation.Precision, DefaultText_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } internal static SmiMetaData DefaultVarChar { get { return new SmiMetaData( DefaultVarChar_NoCollation.SqlDbType, DefaultVarChar_NoCollation.MaxLength, DefaultVarChar_NoCollation.Precision, DefaultVarChar_NoCollation.Scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth, null ); } } // The one and only constructor for use by outside code. // // Parameters that matter for given values of dbType (other parameters are ignored in favor of internal defaults). // Thus, if dbType parameter value is SqlDbType.Decimal, the values of precision and scale passed in are used, but // maxLength, localeId, compareOptions, etc are set to defaults for the Decimal type: // SqlDbType.BigInt: dbType // SqlDbType.Binary: dbType, maxLength // SqlDbType.Bit: dbType // SqlDbType.Char: dbType, maxLength, localeId, compareOptions // SqlDbType.DateTime: dbType // SqlDbType.Decimal: dbType, precision, scale // SqlDbType.Float: dbType // SqlDbType.Image: dbType // SqlDbType.Int: dbType // SqlDbType.Money: dbType // SqlDbType.NChar: dbType, maxLength, localeId, compareOptions // SqlDbType.NText: dbType, localeId, compareOptions // SqlDbType.NVarChar: dbType, maxLength, localeId, compareOptions // SqlDbType.Real: dbType // SqlDbType.UniqueIdentifier: dbType // SqlDbType.SmallDateTime: dbType // SqlDbType.SmallInt: dbType // SqlDbType.SmallMoney: dbType // SqlDbType.Text: dbType, localeId, compareOptions // SqlDbType.Timestamp: dbType // SqlDbType.TinyInt: dbType // SqlDbType.VarBinary: dbType, maxLength // SqlDbType.VarChar: dbType, maxLength, localeId, compareOptions // SqlDbType.Variant: dbType // PlaceHolder for value 24 // SqlDbType.Xml: dbType // Placeholder for value 26 // Placeholder for value 27 // Placeholder for value 28 // SqlDbType.Udt: dbType, userDefinedType // [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use ctor without columns param." )] internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, SmiMetaData[] columns) : // Implement as calling the new ctor this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType ) { Debug.Assert( null == columns, "Row types not supported" ); } // SMI V100 (aka V3) constructor. Superceded in V200. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, false, null, null ) { } // SMI V200 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) : this(dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, null, isMultiValued, fieldTypes, extendedProperties) { } // SMI V220 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) { Debug.Assert( IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType ); SetDefaultsForType( dbType ); // switch ( dbType ) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.Real: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.UniqueIdentifier: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: break; case SqlDbType.Binary: case SqlDbType.VarBinary: _maxLength = maxLength; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NVarChar: case SqlDbType.VarChar: // locale and compare options are not validated until they get to the server _maxLength = maxLength; _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.NText: case SqlDbType.Text: _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.Decimal: Debug.Assert( MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision ); Debug.Assert( MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale ); Debug.Assert( scale <= precision, "Precision: " + precision + " greater than scale: " + scale ); _precision = precision; _scale = scale; _maxLength = __maxLenFromPrecision[precision - 1]; break; case SqlDbType.Udt: // Assert modified for VSFTDEVDIV479492 - for SqlParameter both userDefinedType and udtAssemblyQualifiedName // can be NULL, we are checking only maxLength if it will be used (i.e. userDefinedType is NULL) Debug.Assert((null != userDefinedType) || (0 <= maxLength || UnlimitedMaxLengthIndicator == maxLength), String.Format((IFormatProvider)null, "SmiMetaData.ctor: Udt name={0}, maxLength={1}", udtAssemblyQualifiedName, maxLength)); // Type not validated until matched to a server. Could be null if extended metadata supplies three-part name! _clrType = userDefinedType; if (null != userDefinedType) { _maxLength = SerializationHelperSql9.GetUdtMaxLength(userDefinedType); } else { _maxLength = maxLength; } _udtAssemblyQualifiedName = udtAssemblyQualifiedName; break; case SqlDbType.Structured: if (null != fieldTypes) { _fieldMetaData = (new List<SmiExtendedMetaData>(fieldTypes)).AsReadOnly(); } _isMultiValued = isMultiValued; _maxLength = _fieldMetaData.Count; break; case SqlDbType.Time: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 5 - __maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTime2: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 8 - __maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTimeOffset: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 10 - __maxVarTimeLenOffsetFromScale[scale]; break; default: Debug.Assert( false, "How in the world did we get here? :" + dbType ); break; } if (null != extendedProperties) { extendedProperties.SetReadOnly(); _extendedProperties = extendedProperties; } // properties and fields must meet the following conditions at this point: // 1) not null // 2) read only // 3) same number of columns in each list (0 count acceptable for properties that are "unused") Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null!=_extendedProperties?"writeable":"null")); Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null!=_fieldMetaData?"writeable":"null")); #if DEBUG ((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count); ((SmiOrderProperty)_extendedProperties[SmiPropertySelector.SortOrder]).CheckCount(_fieldMetaData.Count); ((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count); #endif } internal bool IsValidMaxLengthForCtorGivenType( SqlDbType dbType, long maxLength ) { bool result = true; switch( dbType ) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.Real: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.UniqueIdentifier: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.NText: case SqlDbType.Text: case SqlDbType.Decimal: case SqlDbType.Udt: case SqlDbType.Structured: // case SqlDbType.Date: case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: break; case SqlDbType.Binary: result = 0 < maxLength && MaxBinaryLength >= maxLength; break; case SqlDbType.VarBinary: result = UnlimitedMaxLengthIndicator == maxLength || ( 0 < maxLength && MaxBinaryLength >= maxLength ); break; case SqlDbType.Char: result = 0 < maxLength && MaxANSICharacters >= maxLength; break; case SqlDbType.NChar: result = 0 < maxLength && MaxUnicodeCharacters >= maxLength; break; case SqlDbType.NVarChar: result = UnlimitedMaxLengthIndicator == maxLength || ( 0 < maxLength && MaxUnicodeCharacters >= maxLength ); break; case SqlDbType.VarChar: result = UnlimitedMaxLengthIndicator == maxLength || ( 0 < maxLength && MaxANSICharacters >= maxLength ); break; default: Debug.Assert( false, "How in the world did we get here? :" + dbType ); break; } return result; } // Sql-style compare options for character types. internal SqlCompareOptions CompareOptions { get { return _compareOptions; } } // LCID for type. 0 for non-character types. internal long LocaleId { get{ return _localeId; } } // Units of length depend on type. // NVarChar, NChar, NText: # of unicode characters // Everything else: # of bytes internal long MaxLength { get { return _maxLength; } } internal byte Precision { get { return _precision; } } internal byte Scale { get { return _scale; } } internal SqlDbType SqlDbType { get { return _databaseType; } } // Clr Type instance for user-defined types internal Type Type { get { // Fault-in UDT clr types on access if have assembly-qualified name if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) { _clrType = Type.GetType(_udtAssemblyQualifiedName, true); } return _clrType; } } // Clr Type instance for user-defined types in cases where we don't want to throw if the assembly isn't available internal Type TypeWithoutThrowing { get { // Fault-in UDT clr types on access if have assembly-qualified name if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) { _clrType = Type.GetType(_udtAssemblyQualifiedName, false); } return _clrType; } } internal string TypeName { get { string result = null; if (SqlDbType.Udt == _databaseType) { Debug.Assert(String.Empty == __typeNameByDatabaseType[(int)_databaseType], "unexpected udt?"); result = Type.FullName; } else { result = __typeNameByDatabaseType[(int)_databaseType]; Debug.Assert(null != result, "unknown type name?"); } return result; } } internal string AssemblyQualifiedName { get { string result = null; if (SqlDbType.Udt == _databaseType) { // Fault-in assembly-qualified name if type is available if (_udtAssemblyQualifiedName == null && _clrType != null) { _udtAssemblyQualifiedName = _clrType.AssemblyQualifiedName; } result = _udtAssemblyQualifiedName; } return result; } } internal bool IsMultiValued { get { return _isMultiValued; } } // Returns read-only list of field metadata internal IList<SmiExtendedMetaData> FieldMetaData { get { return _fieldMetaData; } } // Returns read-only list of extended properties internal SmiMetaDataPropertyCollection ExtendedProperties { get { return _extendedProperties; } } internal static bool IsSupportedDbType(SqlDbType dbType) { // Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios. return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) || (SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType); } // Only correct access point for defaults per SqlDbType. internal static SmiMetaData GetDefaultForType( SqlDbType dbType ) { Debug.Assert( IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType); return __defaultValues[(int)dbType]; } // Private constructor used only to initialize default instance array elements. // DO NOT EXPOSE OUTSIDE THIS CLASS! private SmiMetaData ( SqlDbType sqlDbType, long maxLength, byte precision, byte scale, SqlCompareOptions compareOptions) { _databaseType = sqlDbType; _maxLength = maxLength; _precision = precision; _scale = scale; _compareOptions = compareOptions; // defaults are the same for all types for the following attributes. _localeId = 0; _clrType = null; _isMultiValued = false; _fieldMetaData = __emptyFieldList; _extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance; } // static array of default-valued metadata ordered by corresponding SqlDbType. // NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType! // ONLY ACCESS THIS GLOBAL FROM GetDefaultForType! private static SmiMetaData[] __defaultValues = { DefaultBigInt, // SqlDbType.BigInt DefaultBinary, // SqlDbType.Binary DefaultBit, // SqlDbType.Bit DefaultChar_NoCollation, // SqlDbType.Char DefaultDateTime, // SqlDbType.DateTime DefaultDecimal, // SqlDbType.Decimal DefaultFloat, // SqlDbType.Float DefaultImage, // SqlDbType.Image DefaultInt, // SqlDbType.Int DefaultMoney, // SqlDbType.Money DefaultNChar_NoCollation, // SqlDbType.NChar DefaultNText_NoCollation, // SqlDbType.NText DefaultNVarChar_NoCollation, // SqlDbType.NVarChar DefaultReal, // SqlDbType.Real DefaultUniqueIdentifier, // SqlDbType.UniqueIdentifier DefaultSmallDateTime, // SqlDbType.SmallDateTime DefaultSmallInt, // SqlDbType.SmallInt DefaultSmallMoney, // SqlDbType.SmallMoney DefaultText_NoCollation, // SqlDbType.Text DefaultTimestamp, // SqlDbType.Timestamp DefaultTinyInt, // SqlDbType.TinyInt DefaultVarBinary, // SqlDbType.VarBinary DefaultVarChar_NoCollation, // SqlDbType.VarChar DefaultVariant, // SqlDbType.Variant DefaultNVarChar_NoCollation, // Placeholder for value 24 DefaultXml, // SqlDbType.Xml DefaultNVarChar_NoCollation, // Placeholder for value 26 DefaultNVarChar_NoCollation, // Placeholder for value 27 DefaultNVarChar_NoCollation, // Placeholder for value 28 DefaultUdt_NoType, // Generic Udt DefaultStructured, // Generic structured type DefaultDate, // SqlDbType.Date DefaultTime, // SqlDbType.Time DefaultDateTime2, // SqlDbType.DateTime2 DefaultDateTimeOffset, // SqlDbType.DateTimeOffset }; // static array of type names ordered by corresponding SqlDbType. // NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType! // ONLY ACCESS THIS GLOBAL FROM get_TypeName! private static string[] __typeNameByDatabaseType = { "bigint", // SqlDbType.BigInt "binary", // SqlDbType.Binary "bit", // SqlDbType.Bit "char", // SqlDbType.Char "datetime", // SqlDbType.DateTime "decimal", // SqlDbType.Decimal "float", // SqlDbType.Float "image", // SqlDbType.Image "int", // SqlDbType.Int "money", // SqlDbType.Money "nchar", // SqlDbType.NChar "ntext", // SqlDbType.NText "nvarchar", // SqlDbType.NVarChar "real", // SqlDbType.Real "uniqueidentifier", // SqlDbType.UniqueIdentifier "smalldatetime", // SqlDbType.SmallDateTime "smallint", // SqlDbType.SmallInt "smallmoney", // SqlDbType.SmallMoney "text", // SqlDbType.Text "timestamp", // SqlDbType.Timestamp "tinyint", // SqlDbType.TinyInt "varbinary", // SqlDbType.VarBinary "varchar", // SqlDbType.VarChar "sql_variant", // SqlDbType.Variant null, // placeholder for 24 "xml", // SqlDbType.Xml null, // placeholder for 26 null, // placeholder for 27 null, // placeholder for 28 String.Empty, // SqlDbType.Udt -- get type name from Type.FullName instead. String.Empty, // Structured types have user-defined type names. "date", // SqlDbType.Date "time", // SqlDbType.Time "datetime2", // SqlDbType.DateTime2 "datetimeoffset", // SqlDbType.DateTimeOffset }; // Internal setter to be used by constructors only! Modifies state! private void SetDefaultsForType( SqlDbType dbType ) { SmiMetaData smdDflt = GetDefaultForType( dbType ); _databaseType = dbType; _maxLength = smdDflt.MaxLength; _precision = smdDflt.Precision; _scale = smdDflt.Scale; _localeId = smdDflt.LocaleId; _compareOptions = smdDflt.CompareOptions; _clrType = null; _isMultiValued = smdDflt._isMultiValued; _fieldMetaData = smdDflt._fieldMetaData; // This is ok due to immutability _extendedProperties = smdDflt._extendedProperties; // This is ok due to immutability } internal string TraceString() { return TraceString(0); } virtual internal string TraceString(int indent) { string indentStr = new String(' ', indent); string fields = String.Empty; if (null != _fieldMetaData) { foreach(SmiMetaData fieldMd in _fieldMetaData) { fields = String.Format(CultureInfo.InvariantCulture, "{0}{1}\n\t", fields, fieldMd.TraceString(indent+5)); } } string properties = String.Empty; if (null != _extendedProperties) { foreach(SmiMetaDataProperty property in _extendedProperties.Values) { properties = String.Format(CultureInfo.InvariantCulture, "{0}{1} {2}\n\t", properties, indentStr, property.TraceString()); } } return String.Format(CultureInfo.InvariantCulture, "\n\t" +"{0} SqlDbType={1:g}\n\t" +"{0} MaxLength={2:d}\n\t" +"{0} Precision={3:d}\n\t" +"{0} Scale={4:d}\n\t" +"{0} LocaleId={5:x}\n\t" +"{0} CompareOptions={6:g}\n\t" +"{0} Type={7}\n\t" +"{0} MultiValued={8}\n\t" +"{0} fields=\n\t{9}" +"{0} properties=\n\t{10}", indentStr, SqlDbType, MaxLength, Precision, Scale, LocaleId, CompareOptions, (null!=Type) ? Type.ToString():"<null>", IsMultiValued, fields, properties); } } // SmiExtendedMetaData // // Adds server-specific type extension information to base metadata, but still portable across a specific server. // internal class SmiExtendedMetaData : SmiMetaData { private string _name; // context-dependant identifier, ie. parameter name for parameters, column name for columns, etc. // three-part name for typed xml schema and for udt names private string _typeSpecificNamePart1; private string _typeSpecificNamePart2; private string _typeSpecificNamePart3; [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use ctor without columns param." )] internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, SmiMetaData[] columns, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : // Implement as calling the new ctor this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3 ) { Debug.Assert( null == columns, "Row types not supported" ); } internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V200 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V220 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3 ): base( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties) { Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long"); _name = name; _typeSpecificNamePart1 = typeSpecificNamePart1; _typeSpecificNamePart2 = typeSpecificNamePart2; _typeSpecificNamePart3 = typeSpecificNamePart3; } internal string Name { get { return _name; } } internal string TypeSpecificNamePart1 { get { return _typeSpecificNamePart1; } } internal string TypeSpecificNamePart2 { get { return _typeSpecificNamePart2; } } internal string TypeSpecificNamePart3 { get { return _typeSpecificNamePart3; } } internal override string TraceString(int indent) { return String.Format(CultureInfo.InvariantCulture, "{2} Name={0}" +"{1}" +"{2}TypeSpecificNamePart1='{3}'\n\t" +"{2}TypeSpecificNamePart2='{4}'\n\t" +"{2}TypeSpecificNamePart3='{5}'\n\t", (null!=_name) ? _name : "<null>", base.TraceString(indent), new String(' ', indent), (null!=TypeSpecificNamePart1) ? TypeSpecificNamePart1:"<null>", (null!=TypeSpecificNamePart2) ? TypeSpecificNamePart2:"<null>", (null!=TypeSpecificNamePart3) ? TypeSpecificNamePart3:"<null>"); } } // SmiParameterMetaData // // MetaData class to send parameter definitions to server. // Sealed because we don't need to derive from it yet. // IMPORTANT DEVNOTE: This class is being used for parameter encryption functionality, to get the type_info TDS object from SqlParameter. // Please consider impact to that when changing this class. Refer to the callers of SqlParameter.GetMetadataForTypeInfo(). internal sealed class SmiParameterMetaData : SmiExtendedMetaData { private ParameterDirection _direction; [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use ctor without columns param." )] internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, SmiMetaData[] columns, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : // Implement as calling the new ctor this ( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, direction ) { Debug.Assert( null == columns, "Row types not supported" ); } // SMI V100 (aka V3) ctor internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, direction) { } // SMI V200 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, direction) { } // SMI V220 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : base( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { Debug.Assert( ParameterDirection.Input == direction || ParameterDirection.Output == direction || ParameterDirection.InputOutput == direction || ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction ); _direction = direction; } internal ParameterDirection Direction { get { return _direction; } } internal override string TraceString(int indent) { return String.Format(CultureInfo.InvariantCulture, "{0}" +"{1} Direction={2:g}\n\t", base.TraceString(indent), new String(' ', indent), Direction); } } // SmiStorageMetaData // // This class represents the addition of storage-level attributes to the heirarchy (i.e. attributes from // underlying table, source variables, or whatever). // // Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state. Selection // of which values allow "not specified" determined by backward compatibility. // // Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in. internal class SmiStorageMetaData : SmiExtendedMetaData { // AllowsDBNull is the only value required to be specified. private bool _allowsDBNull; // could the column return nulls? equivalent to TDS's IsNullable bit private string _serverName; // underlying column's server private string _catalogName; // underlying column's database private string _schemaName; // underlying column's schema private string _tableName; // underlying column's table private string _columnName; // underlying column's name private SqlBoolean _isKey; // Is this one of a set of key columns that uniquely identify an underlying table? private bool _isIdentity; // Is this from an identity column private bool _isColumnSet; // Is this column the XML representation of a columnset? [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use ctor without columns param." )] internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, SmiMetaData[] columns, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity) : // Implement as calling the new ctor this ( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity) { Debug.Assert( null == columns, "Row types not supported" ); } internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity) : this(dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity) { } // SMI V200 ctor. internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity, false) { } // SMI V220 ctor. internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity, bool isColumnSet) : base( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { _allowsDBNull = allowsDBNull; _serverName = serverName; _catalogName = catalogName; _schemaName = schemaName; _tableName = tableName; _columnName = columnName; _isKey = isKey; _isIdentity = isIdentity; _isColumnSet = isColumnSet; } internal bool AllowsDBNull { get { return _allowsDBNull; } } internal string ServerName { get { return _serverName; } } internal string CatalogName { get { return _catalogName; } } internal string SchemaName { get { return _schemaName; } } internal string TableName { get { return _tableName; } } internal string ColumnName { get { return _columnName; } } internal SqlBoolean IsKey { get { return _isKey; } } internal bool IsIdentity { get { return _isIdentity; } } internal bool IsColumnSet { get { return _isColumnSet; } } internal override string TraceString(int indent) { return String.Format(CultureInfo.InvariantCulture, "{0}" +"{1} AllowsDBNull={2}\n\t" +"{1} ServerName='{3}'\n\t" +"{1} CatalogName='{4}'\n\t" +"{1} SchemaName='{5}'\n\t" +"{1} TableName='{6}'\n\t" +"{1} ColumnName='{7}'\n\t" +"{1} IsKey={8}\n\t" +"{1} IsIdentity={9}\n\t", base.TraceString(indent), new String(' ', indent), AllowsDBNull, (null!=ServerName) ? ServerName:"<null>", (null!=CatalogName) ? CatalogName:"<null>", (null!=SchemaName) ? SchemaName:"<null>", (null!=TableName) ? TableName:"<null>", (null!=ColumnName) ? ColumnName:"<null>", IsKey, IsIdentity); } } // SmiQueryMetaData // // Adds Query-specific attributes. // Sealed since we don't need to extend it for now. // Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS. internal class SmiQueryMetaData : SmiStorageMetaData { private bool _isReadOnly; private SqlBoolean _isExpression; private SqlBoolean _isAliased; private SqlBoolean _isHidden; [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use ctor without columns param." )] internal SmiQueryMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, SmiMetaData[] columns, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity, bool isReadOnly, SqlBoolean isExpression, SqlBoolean isAliased, SqlBoolean isHidden ) : // Implement as calling the new ctor this ( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity, isReadOnly, isExpression, isAliased, isHidden ) { Debug.Assert( null == columns, "Row types not supported" ); } internal SmiQueryMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity, bool isReadOnly, SqlBoolean isExpression, SqlBoolean isAliased, SqlBoolean isHidden ) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity, isReadOnly, isExpression, isAliased, isHidden) { } // SMI V200 ctor. internal SmiQueryMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity, bool isReadOnly, SqlBoolean isExpression, SqlBoolean isAliased, SqlBoolean isHidden) : this( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity, false, isReadOnly, isExpression, isAliased, isHidden ) { } // SMI V220 ctor. internal SmiQueryMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, Type userDefinedType, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, bool allowsDBNull, string serverName, string catalogName, string schemaName, string tableName, string columnName, SqlBoolean isKey, bool isIdentity, bool isColumnSet, bool isReadOnly, SqlBoolean isExpression, SqlBoolean isAliased, SqlBoolean isHidden ) : base( dbType, maxLength, precision, scale, localeId, compareOptions, userDefinedType, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, allowsDBNull, serverName, catalogName, schemaName, tableName, columnName, isKey, isIdentity, isColumnSet ) { _isReadOnly = isReadOnly; _isExpression = isExpression; _isAliased = isAliased; _isHidden = isHidden; } internal bool IsReadOnly { get { return _isReadOnly; } } internal SqlBoolean IsExpression { get { return _isExpression; } } internal SqlBoolean IsAliased { get { return _isAliased; } } internal SqlBoolean IsHidden { get { return _isHidden; } } internal override string TraceString(int indent) { return String.Format(CultureInfo.InvariantCulture, "{0}" +"{1} IsReadOnly={2}\n\t" +"{1} IsExpression={3}\n\t" +"{1} IsAliased={4}\n\t" +"{1} IsHidden={5}", base.TraceString(indent), new String(' ', indent), AllowsDBNull, IsExpression, IsAliased, IsHidden); } } }
52.868068
219
0.418681
[ "MIT" ]
Abdalla-rabie/referencesource
System.Data/Microsoft/SqlServer/Server/SmiMetaData.cs
90,563
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace WInterop.Security { /// <summary> /// [ACL_SIZE_INFORMATION] /// </summary> public struct AclSizeInformation { public uint AceCount; public uint AclBytesInUse; public uint AclBytesFree; } }
25.5
101
0.666667
[ "MIT" ]
RussKie/WInterop
src/WInterop.Desktop/Security/AclSizeInformation.cs
410
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CheckPointFlag : MonoBehaviour { private bool[] _isThrough; // このチェックポイントを通過したかのフラグを保存 // Start is called before the first frame update void Start() { GameObject[] racingCars = GameObject.FindGameObjectsWithTag("RacingCar"); int _playerNum = racingCars.Length; _isThrough = new bool[_playerNum]; for (int idx = 0; idx < _playerNum; idx++) { _isThrough[idx] = false; } } public void ResetThroughFlag(int playerID) { _isThrough[playerID] = false; } private void OnTriggerEnter(Collider other) { GameObject throughObject = other.gameObject; int playerID = FindInfoByScene.Instance.GetPlayerID(throughObject.transform.parent.name); Debug.Log("プレイヤー" + playerID + "チェックポイント通過"); CheckPointCount cpCount = throughObject.GetComponent<CheckPointCount>(); int checkPointCnt = cpCount.GetNowThroughCheckPointNum(); Debug.Log("第" + (checkPointCnt + 1) + "チェックポイント"); Debug.Log("通過数:" + checkPointCnt); if (throughObject.tag == "RacingCar") { if (!_isThrough[playerID]) { if (gameObject.name == cpCount.GetNextCPName()) { // ゴール通過すると_checkPointCntが0に戻るのでここで特にmax時のif処理を書く必要はない Debug.Log("次チェックポイント:" + $"cp{(checkPointCnt + 2)}"); Debug.Log(gameObject.name); cpCount.CountCheckPoint(); _isThrough[playerID] = true; } } cpCount.LastThroughCheckPoint(this.name); } } }
31.140351
97
0.593803
[ "Unlicense" ]
mhigg/HCMs
HCMs/Assets/StageModel/GoalObject/Script/CheckPointFlag.cs
1,961
C#
using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; namespace TicketingSystem.Data { public class BaseRepository<T> : IRepository<T> where T : class { public BaseRepository(DbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository.", "context"); } this.Context = context; this.DbSet = this.Context.Set<T>(); } protected IDbSet<T> DbSet { get; set; } protected DbContext Context { get; set; } public virtual IQueryable<T> All() { //return this.DbSet.AsQueryable(); before return this.DbSet.AsQueryable().AsNoTracking(); //after } public virtual T GetById(object id) { return this.DbSet.Find(id); } public virtual void Add(T entity) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State != EntityState.Detached) { entry.State = EntityState.Added; } else { this.DbSet.Add(entity); } } public virtual void Update(T entity,params string[] excludProp) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State == EntityState.Detached) { this.DbSet.Attach(entity); entry.State = EntityState.Modified; foreach (var prop in excludProp) { entry.Property(prop).IsModified = false; } } //entry.State = EntityState.Modified; } public virtual void Delete(T entity) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State != EntityState.Deleted) { entry.State = EntityState.Deleted; } else { this.DbSet.Attach(entity); this.DbSet.Remove(entity); } } public virtual void Delete(object id) { var entity = this.GetById(id); if (entity != null) { this.Delete(entity); } } public virtual void Detach(T entity) { DbEntityEntry entry = this.Context.Entry(entity); entry.State = EntityState.Detached; } } }
26.927083
119
0.503675
[ "MIT" ]
Valersd/TicketingSystem
TicketingSystem.Data/BaseRepository.cs
2,587
C#
namespace Agatha.Common { public class AsyncRequestDispatcherFactoryStub : IAsyncRequestDispatcherFactory { private readonly AsyncRequestDispatcherStub asyncRequestDispatcherStub; public AsyncRequestDispatcherFactoryStub(AsyncRequestDispatcherStub asyncRequestDispatcherStub) { this.asyncRequestDispatcherStub = asyncRequestDispatcherStub; } public IAsyncRequestDispatcher CreateAsyncRequestDispatcher() { return asyncRequestDispatcherStub; } } }
27.705882
97
0.845011
[ "Apache-2.0" ]
davybrion/Agatha
Agatha.Common/AsyncRequestDispatcherFactoryStub.cs
471
C#
using AutoMapper; using BeboerWeb.Api.Application.Persistence.Repositories.PropertyManagement; using BeboerWeb.Api.Application.Services.PropertyManagement; using BeboerWeb.Api.Controllers.Bases; using BeboerWeb.Api.Domain.Models.PropertyManangement; using BeboerWeb.Api.Models.DTOs.PropertyManagement; using Microsoft.AspNetCore.Mvc; namespace BeboerWeb.Api.Controllers.PropertyManagement { [Route("api/propertymanagement/leaseperiod")] [ApiController] public class LeasePeriodController : CrudControllerBase<LeasePeriodDto, LeasePeriod, ILeasePeriodRepository, ILeasePeriodService> { public LeasePeriodController(ILeasePeriodService service, IMapper mapper) : base(service, mapper) { } } }
36.85
133
0.800543
[ "MIT" ]
nikcio/BeboerWeb
src/BeboerWeb.Api/Controllers/PropertyManagement/LeasePeriodController.cs
739
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("GOTO.BigDataAccess")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GOTO.BigDataAccess")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("35328bb5-814c-4ea7-9a80-ca6e69136e56")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.567568
59
0.719227
[ "Apache-2.0" ]
aryice/GOTO.Segment
GOTO.BigDataAccess/Properties/AssemblyInfo.cs
1,342
C#
using TMPro; using UnityEngine; using UnityEngine.XR; using System; using System.Collections.Generic; using VPG.Core; using VPG.Core.Configuration; namespace VPG.UX { /// <summary> /// Shows and hides the StandaloneCourseController prefab. /// </summary> public class StandaloneMenuHandler : MonoBehaviour { [Tooltip("Initial distance between this controller and the trainee.")] [SerializeField] protected float appearanceDistance = 2f; [SerializeField, HideInInspector] private string buttonTypeName = "bool"; [SerializeField, HideInInspector] private string buttonName = "MenuButton"; private Canvas canvas; private Type buttonType; private Transform trainee; private bool lastMenuState; private float defaultPressThreshold = 0.1f; private readonly List<InputDevice> controllers = new List<InputDevice>(); private readonly List<TMP_Dropdown> dropdownsList = new List<TMP_Dropdown>(); private void OnValidate() { // MenuButton does not exist in OpenVR, so it is switched to PrimaryButton (sandwich button). if (Application.isPlaying && buttonName == "MenuButton") { string deviceName = XRSettings.loadedDeviceName; if (string.IsNullOrEmpty(deviceName) == false && deviceName.ToLower().Contains("openvr")) { buttonName = "PrimaryButton"; } } buttonType = Type.GetType(buttonTypeName); } private void Start() { try { trainee = RuntimeConfigurator.Configuration.Trainee.GameObject.transform; canvas = GetComponentInChildren<Canvas>(); canvas.worldCamera = Camera.main; canvas.enabled = CourseRunner.Current != null; } catch (Exception exception) { Debug.LogError($"{exception.GetType().Name} while initializing {GetType().Name}.\n{exception.StackTrace}", gameObject); } Vector3 position = trainee.position + (trainee.forward * appearanceDistance); Quaternion rotation = new Quaternion(0.0f, trainee.rotation.y, 0.0f, trainee.rotation.w); position.y = 1f; transform.SetPositionAndRotation(position, rotation); dropdownsList.AddRange(GetComponentsInChildren<TMP_Dropdown>()); #if ENABLE_INPUT_SYSTEM && XRIT_0_10_OR_NEWER UnityEngine.InputSystem.UI.InputSystemUIInputModule inputSystem = FindObjectOfType<UnityEngine.InputSystem.UI.InputSystemUIInputModule>(); if (inputSystem) { Destroy(inputSystem); } #endif OnValidate(); } private void OnEnable() { InputDevices.deviceConnected += RegisterDevice; List<InputDevice> devices = new List<InputDevice>(); InputDevices.GetDevices(devices); foreach (InputDevice device in devices) { RegisterDevice(device); } } private void OnDisable() { InputDevices.deviceConnected -= RegisterDevice; } private void Update() { if (IsActionButtonPressDown()) { ToggleCourseControllerMenu(); } } private void RegisterDevice(InputDevice connectedDevice) { if (connectedDevice.isValid) { controllers.Add(connectedDevice); } } private void ToggleCourseControllerMenu() { canvas.enabled = !canvas.enabled; if (canvas.enabled) { Vector3 position = trainee.position + (trainee.forward * appearanceDistance); Quaternion rotation = new Quaternion(0.0f, trainee.rotation.y, 0.0f, trainee.rotation.w); position.y = trainee.position.y; transform.SetPositionAndRotation(position, rotation); } else { HideDropdowns(); } } private void HideDropdowns() { foreach (TMP_Dropdown dropdown in dropdownsList) { if (dropdown.IsExpanded) { dropdown.Hide(); } } } private bool IsActionButtonPressDown(float pressThreshold = -1.0f) { IsActionButtonPress(out bool isButtonPress); bool wasPressed = lastMenuState == false && isButtonPress; lastMenuState = isButtonPress; return wasPressed; } private bool IsActionButtonPress(out bool isPressed, float pressThreshold = -1.0f) { foreach (InputDevice controller in controllers) { if (controller.isValid == false) { return isPressed = false; } if (buttonType == typeof(bool)) { if (controller.TryGetFeatureValue(new InputFeatureUsage<bool>(buttonName), out bool value)) { isPressed = value; return true; } } else if (buttonType == typeof(float)) { if (controller.TryGetFeatureValue(new InputFeatureUsage<float>(buttonName), out float value)) { float threshold = (pressThreshold >= 0.0f) ? pressThreshold : defaultPressThreshold; isPressed = value >= threshold; return true; } } else if (buttonType == typeof(Vector2)) { if (controller.TryGetFeatureValue(new InputFeatureUsage<Vector2>(buttonName), out Vector2 value)) { float threshold = (pressThreshold >= 0.0f) ? pressThreshold : defaultPressThreshold; isPressed = value.x >= threshold; return true; } } } return isPressed = false; } } }
32.736041
150
0.537603
[ "Apache-2.0" ]
VaLiuM09/Basic-UI-Component
Runtime/CourseController/StandaloneMenuHandler.cs
6,451
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WispFramework.EventArguments; using WispFramework.Extensions; using WispFramework.Patterns; using WispFramework.Patterns.Observables; using WispFramework.Utility; namespace Tests { public class EventAwaiterTests { public static async void Run() { Sub<bool> hasCoffee = new Sub<bool>(false); Task.Run(() => NewMethod(hasCoffee)); string input; while ((input = Console.ReadLine()) != "exit") { if (input == "give coffee") { hasCoffee.Value = true; } } } private static async Task NewMethod(Sub<bool> hasCoffee) { var waitForCoffee = new EventAwaiter<ValueChangedEventArgs<bool>>( h => hasCoffee.ValueChanged += h, h => hasCoffee.ValueChanged -= h); await waitForCoffee.Task; try { Console.WriteLine($"Value changed for hasCoffee to {hasCoffee}"); } catch (TimeoutException) { Console.WriteLine("We did not get coffee in time!"); } } } }
26.411765
81
0.538233
[ "MIT" ]
ddolyniuk1/WispFramework
Tests/EventAwaiterTests.cs
1,349
C#
using Prism.Events; namespace Hypermint.Base.Events { public class SaveSettingsEvent : PubSubEvent<string> { } }
12.8
56
0.695313
[ "MIT" ]
horseyhorsey/Hypermint.2.0
src/Hypermint.Base/Events/SettingsFlyoutEvents.cs
130
C#
using System; namespace Dalssoft.DiagramNet { internal enum CornerPosition: int { Nothing = -1, BottomCenter = 0, BottomLeft = 1, BottomRight = 2, MiddleCenter = 3, MiddleLeft = 4, MiddleRight = 5, TopCenter = 6, TopLeft = 7, TopRight = 8, Undefined = 99 } public enum CardinalDirection { Nothing, North, South, East, West } public enum Orientation { Horizontal, Vertical } public enum ElementType { Rectangle, RectangleNode, Elipse, ElipseNode, CommentBox } public enum LinkType { Straight, RightAngle } internal enum LabelEditDirection { UpDown, Both } }
11.157895
34
0.66195
[ "MIT" ]
JackWangCUMT/Diagram.NET
DiagramNet/GeneralEnums.cs
636
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Kms.V1.Model { /// <summary> /// Response Object /// </summary> public class CreateParametersForImportResponse : SdkResponse { /// <summary> /// 密钥ID。 /// </summary> [JsonProperty("key_id", NullValueHandling = NullValueHandling.Ignore)] public string KeyId { get; set; } /// <summary> /// 密钥导入令牌。 /// </summary> [JsonProperty("import_token", NullValueHandling = NullValueHandling.Ignore)] public string ImportToken { get; set; } /// <summary> /// 导入参数到期时间,时间戳,即从1970年1月1日至该时间的总秒数。 /// </summary> [JsonProperty("expiration_time", NullValueHandling = NullValueHandling.Ignore)] public long? ExpirationTime { get; set; } /// <summary> /// 加密密钥材料的公钥,base64格式。 /// </summary> [JsonProperty("public_key", NullValueHandling = NullValueHandling.Ignore)] public string PublicKey { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CreateParametersForImportResponse {\n"); sb.Append(" keyId: ").Append(KeyId).Append("\n"); sb.Append(" importToken: ").Append(ImportToken).Append("\n"); sb.Append(" expirationTime: ").Append(ExpirationTime).Append("\n"); sb.Append(" publicKey: ").Append(PublicKey).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as CreateParametersForImportResponse); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(CreateParametersForImportResponse input) { if (input == null) return false; return ( this.KeyId == input.KeyId || (this.KeyId != null && this.KeyId.Equals(input.KeyId)) ) && ( this.ImportToken == input.ImportToken || (this.ImportToken != null && this.ImportToken.Equals(input.ImportToken)) ) && ( this.ExpirationTime == input.ExpirationTime || (this.ExpirationTime != null && this.ExpirationTime.Equals(input.ExpirationTime)) ) && ( this.PublicKey == input.PublicKey || (this.PublicKey != null && this.PublicKey.Equals(input.PublicKey)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.KeyId != null) hashCode = hashCode * 59 + this.KeyId.GetHashCode(); if (this.ImportToken != null) hashCode = hashCode * 59 + this.ImportToken.GetHashCode(); if (this.ExpirationTime != null) hashCode = hashCode * 59 + this.ExpirationTime.GetHashCode(); if (this.PublicKey != null) hashCode = hashCode * 59 + this.PublicKey.GetHashCode(); return hashCode; } } } }
33.161017
87
0.513928
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net
Services/Kms/V1/Model/CreateParametersForImportResponse.cs
4,013
C#
 #region Using Statements using Microsoft.Xna.Framework; using System; #endregion namespace Artemis.Engine.Maths.Geometry { public static class VectorUtils { public static Vector2 ComponentwiseProduct(Vector2 a, Vector2 b) { return new Vector2(a.X * b.X, a.Y * b.Y); } public static Vector2 ToVec(Point p) { return new Vector2(p.X, p.Y); } public static Vector2 ToVec(System.Drawing.Point p) { return new Vector2(p.X, p.Y); } /// <summary> /// The unit vector pointing left (<-1, 0>). /// </summary> public static Vector2 Left = new Vector2(-1, 0); /// <summary> /// The unit vector pointing right (<1, 0>). /// </summary> public static Vector2 Right = new Vector2(1, 0); /// <summary> /// The unit vector pointing up (<0, 1>). /// </summary> public static Vector2 Up = new Vector2(0, 1); /// <summary> /// The unit vector point down (<0, -1>). /// </summary> public static Vector2 Down = new Vector2(0, -1); /// <summary> /// The up direction relative to the game world. Since the game coordinate space is /// flipped on it's y-axis, this corresponds to the vector <0, -1>. /// </summary> public static Vector2 GameWorldUp = Down; /// <summary> /// The down direction relative to the game world. Since the game coordinate space is /// flipped on it's y-axis, this corresponds to the vector <0, 1>. /// </summary> public static Vector2 GameWorldDown = Up; public static Vector2 Ones = new Vector2(1, 1); /// <summary> /// Return the unit vector pointing at the given angle relative to the positive x-axis. /// </summary> /// <param name="angle"></param> /// <param name="degrees"></param> /// <returns></returns> public static Vector2 Polar(double angle, bool degrees = true) { if (degrees) angle *= System.Math.PI / 180f; return new Vector2((float)System.Math.Cos(angle), (float)System.Math.Sin(angle)); } /// <summary> /// Return the unit vector pointing at the given angle relative to the positive x-axis, /// centered at the given origin. /// </summary> /// <param name="angle"></param> /// <param name="origin"></param> /// <param name="degrees"></param> /// <returns></returns> public static Vector2 Polar(double angle, Vector2 origin, bool degrees = true) { if (degrees) angle *= System.Math.PI / 180f; return new Vector2((float)System.Math.Cos(angle) + origin.X, (float)System.Math.Sin(angle) + origin.Y); } /// <summary> /// Rotate a vector by the given amount relative to the given point, and return the result. /// </summary> public static Vector2 Rotate( Vector2 vec, double angle, Vector2 origin, bool degrees = true, bool absoluteOrigin = true) { if (degrees) angle *= System.Math.PI / 180f; double cos = System.Math.Cos(angle); double sin = System.Math.Sin(angle); if (absoluteOrigin) { double x = vec.X - origin.X; double y = vec.Y - origin.Y; double nx = x * cos - y * sin + origin.X; double ny = x * sin + y * cos + origin.Y; return new Vector2((float)nx, (float)ny); } else { double x = origin.X; double y = origin.Y; double nx = (1 - cos) * x + sin * y + vec.X; double ny = (1 - cos) * y - sin * x + vec.Y; return new Vector2((float)nx, (float)ny); } } /// <summary> /// Return the normalization of a given vector. /// </summary> /// <param name="vec"></param> /// <returns></returns> public static Vector2 ToNormalized(Vector2 vec) { return vec / vec.Length(); } /// <summary> /// Scale a vector by the given amount relative to the given point, and return the result. /// </summary> /// <param name="vec"></param> /// <param name="amount"></param> /// <param name="origin"></param> /// <param name="absoluteOrigin"></param> /// <returns></returns> public static Vector2 Scale( Vector2 vec, double amount, Vector2 origin, bool absoluteOrigin = true) { if (!absoluteOrigin) return vec + origin * (1f - (float)amount); return (vec - origin) * (float)amount + origin; } } }
32.246753
115
0.518727
[ "MIT" ]
ArtemisEngine/Artemis-Engine
Artemis.Engine/Maths/Geometry/VectorUtils.cs
4,968
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; public class Test12224 { // Regression test for EH getting stuck in an infinite loop when NullReferenceException // happens inside a handler of another NullReferenceException. static void ExecuteTest(object context) { string s = null; try { try { int x = s.Length; } catch (NullReferenceException) { int x = s.Length; } } catch (NullReferenceException) { } } public static int Main() { Thread thread = new Thread(new ParameterizedThreadStart(Test12224.ExecuteTest)); thread.IsBackground = true; thread.Start(null); // Give the thread 30 seconds to complete (it should be immediate). If it fails // to complete within that timeout, it has hung. bool terminated = thread.Join(new TimeSpan(0, 0, 30)); return terminated ? 100 : -1; } }
27.093023
91
0.5897
[ "MIT" ]
2m0nd/runtime
src/tests/Regressions/coreclr/GitHub_12224/test12224.cs
1,165
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SharePoint.Modernization.Scanner.Telemetry { public class VersionCheck { public const string versionFileUrl = "https://raw.githubusercontent.com/SharePoint/sp-dev-modernization/dev/Tools/SharePoint.Modernization/Releases/version.txt"; public const string newVersionDownloadUrl = "https://aka.ms/sppnp-modernizationscanner"; public static Tuple<string, string> LatestVersion() { string latestVersion = ""; string currentVersion = ""; try { var coreAssembly = Assembly.GetExecutingAssembly(); currentVersion = ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version; using (var wc = new System.Net.WebClient()) { Random random = new Random(); latestVersion = wc.DownloadString(versionFileUrl + "?random=" + random.Next().ToString()); } if (!string.IsNullOrEmpty(latestVersion)) { latestVersion = latestVersion.Replace("\\r", "").Replace("\\t", ""); var versionOld = new Version(currentVersion); if (Version.TryParse(latestVersion, out Version versionNew)) { if (versionOld.CompareTo(versionNew) >= 0) { // version is not newer latestVersion = null; } } else { // We could not get the version file latestVersion = null; } } } catch(Exception ex) { // Something went wrong latestVersion = null; } return new Tuple<string, string>(currentVersion, latestVersion); } } }
34.52381
169
0.522299
[ "MIT" ]
MartinHatch/sp-dev-modernization
Tools/SharePoint.Modernization/SharePointPnP.Modernization.Scanner/Telemetry/VersionCheck.cs
2,177
C#
using System.Collections; using System.Collections.Generic; using TUF.Core; using TUF.Entities.Shared; using UnityEngine; namespace TUF.Entities.Characters.States { public class CWallCling : EntityWallCling { public override bool CheckInterrupt() { if (controller.InputManager.GetButton((int)EntityInputs.Jump).firstPress) { controller.StateManager.ChangeState((int)BaseCharacterStates.WALL_JUMP); return true; } return base.CheckInterrupt(); } } }
26.952381
88
0.644876
[ "MIT" ]
christides11/touhou-unlimited-fantasies
Assets/_Project/Scripts/Entities/Characters/States/Walls&Ledges/CWallCling.cs
568
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Pages { #region Using using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web.UI.WebControls; using YAF.Configuration; using YAF.Core.BasePages; using YAF.Core.Model; using YAF.Core.Utilities; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Types.Models; using YAF.Utils; using YAF.Utils.Helpers; using YAF.Web.Controls; using YAF.Web.Extensions; using Forum = YAF.Types.Models.Forum; #endregion /// <summary> /// Forum Moderating Page. /// </summary> public partial class Moderating : ForumPage { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref = "Moderating" /> class. /// </summary> public Moderating() : base("MODERATING") { } #endregion #region Methods /// <summary> /// The On PreRender event. /// </summary> /// <param name="e"> /// the Event Arguments /// </param> protected override void OnPreRender([NotNull] EventArgs e) { this.PageContext.PageElements.RegisterJsBlockStartup( "TopicStarterPopoverJs", JavaScriptBlocks.TopicLinkPopoverJs( $"{this.GetText("TOPIC_STARTER")}&nbsp;...", ".topic-starter-popover", "hover")); this.PageContext.PageElements.RegisterJsBlockStartup( "TopicLinkPopoverJs", JavaScriptBlocks.TopicLinkPopoverJs( $"{this.GetText("LASTPOST")}&nbsp;{this.GetText("SEARCH", "BY")} ...", ".topic-link-popover", "focus hover")); base.OnPreRender(e); } /// <summary> /// Handles the Click event of the AddUser control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void AddUser_Click([NotNull] object sender, [NotNull] EventArgs e) { BuildLink.Redirect(ForumPages.ModForumUser, "f={0}", this.PageContext.PageForumID); } /// <summary> /// Binds the data /// </summary> protected void BindData() { this.PagerTop.PageSize = this.Get<BoardSettings>().TopicsPerPage; var baseSize = this.Get<BoardSettings>().TopicsPerPage; var currentPageIndex = this.PagerTop.CurrentPageIndex; var topicList = this.GetRepository<Topic>().ListAsDataTable( this.PageContext.PageForumID, null, DateTimeHelper.SqlDbMinTime(), DateTime.UtcNow, currentPageIndex, baseSize, false, true, false); this.topiclist.DataSource = topicList; this.UserList.DataSource = this.GetRepository<UserForum>().List(null, this.PageContext.PageForumID); if (topicList != null && topicList.HasRows()) { this.PagerTop.Count = topicList.AsEnumerable().First().Field<int>("TotalRows"); } var forumList = this.GetRepository<Forum>().ListAllSortedAsDataTable( this.PageContext.PageBoardID, this.PageContext.PageUserID); this.ForumList.AddForumAndCategoryIcons(forumList); this.DataBind(); var pageItem = this.ForumList.Items.FindByValue(this.PageContext.PageForumID.ToString()); if (pageItem != null) { pageItem.Selected = true; } } /// <summary> /// Deletes all the Selected Topics /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void DeleteTopics_Click([NotNull] object sender, [NotNull] EventArgs e) { var list = this.GetSelectedTopics(); if (!list.Any()) { this.PageContext.AddLoadMessage(this.GetText("MODERATE", "NOTHING"), MessageTypes.warning); } else { list.ForEach(x => this.GetRepository<Topic>().Delete(x.TopicRowID.Value)); this.PageContext.AddLoadMessage(this.GetText("moderate", "deleted"), MessageTypes.success); this.BindData(); } } /// <summary> /// Handles the Click event of the Move control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Move_Click([NotNull] object sender, [NotNull] EventArgs e) { int? linkDays = null; var ld = -2; if (this.LeavePointer.Checked && this.LinkDays.Text.IsSet() && !int.TryParse(this.LinkDays.Text, out ld)) { this.PageContext.AddLoadMessage(this.GetText("POINTER_DAYS_INVALID"), MessageTypes.warning); return; } if (this.ForumList.SelectedValue.ToType<int>() <= 0) { this.PageContext.AddLoadMessage(this.GetText("CANNOT_MOVE_TO_CATEGORY"), MessageTypes.warning); return; } // only move if it's a destination is a different forum. if (this.ForumList.SelectedValue.ToType<int>() != this.PageContext.PageForumID) { if (ld >= -2) { linkDays = ld; } var list = this.GetSelectedTopics(); if (!list.Any()) { this.PageContext.AddLoadMessage(this.GetText("MODERATE", "NOTHING"), MessageTypes.warning); } else { list.ForEach( x => this.GetRepository<Topic>().MoveTopic( x.TopicRowID.Value, this.ForumList.SelectedValue.ToType<int>(), this.LeavePointer.Checked, linkDays.Value)); this.PageContext.AddLoadMessage(this.GetText("MODERATE", "MOVED"), MessageTypes.success); this.BindData(); } } else { this.PageContext.AddLoadMessage(this.GetText("MODERATE", "MOVE_TO_DIFFERENT"), MessageTypes.danger); } } /// <summary> /// The page_ load. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (!this.PageContext.ForumModeratorAccess) { BuildLink.AccessDenied(); } if (!this.PageContext.IsForumModerator || !this.PageContext.IsAdmin) { this.ModerateUsersHolder.Visible = false; } if (!this.IsPostBack) { this.PagerTop.PageSize = 25; var showMoved = this.Get<BoardSettings>().ShowMoved; // Ederon : 7/14/2007 - by default, leave pointer is set on value defined on host level this.LeavePointer.Checked = showMoved; this.trLeaveLink.Visible = showMoved; this.trLeaveLinkDays.Visible = showMoved; if (showMoved) { this.LinkDays.Text = "1"; } } this.BindData(); } /// <summary> /// Create the Page links. /// </summary> protected override void CreatePageLinks() { if (this.PageContext.Settings.LockedForum == 0) { this.PageLinks.AddRoot(); this.PageLinks.AddLink( this.PageContext.PageCategoryName, BuildLink.GetLink(ForumPages.Board, "c={0}", this.PageContext.PageCategoryID)); } this.PageLinks.AddForum(this.PageContext.PageForumID); this.PageLinks.AddLink(this.GetText("MODERATE", "TITLE"), string.Empty); } /// <summary> /// The pager top_ page change. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void PagerTop_PageChange([NotNull] object sender, [NotNull] EventArgs e) { // rebind this.BindData(); } /// <summary> /// The user list_ item command. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param> protected void UserList_ItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e) { switch (e.CommandName) { case "edit": BuildLink.Redirect( ForumPages.ModForumUser, "f={0}&u={1}", this.PageContext.PageForumID, e.CommandArgument); break; case "remove": this.GetRepository<UserForum>().Delete(e.CommandArgument.ToType<int>(), this.PageContext.PageForumID); this.BindData(); // clear moderators cache this.Get<IDataCache>().Remove(Constants.Cache.ForumModerators); break; } } /// <summary> /// Gets the selected topics /// </summary> /// <returns> /// Returns the List of selected Topics /// </returns> private List<TopicContainer> GetSelectedTopics() { var list = new List<TopicContainer>(); this.topiclist.Items.Cast<RepeaterItem>().ForEach(item => { var check = item.FindControlAs<CheckBox>("topicCheck"); var topicContainer = item.FindControlAs<TopicContainer>("topicContainer"); if (check.Checked) { list.Add(topicContainer); } }); return list; } #endregion } }
35.198864
141
0.526231
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/YetAnotherForum.NET/Pages/Moderating.ascx.cs
12,040
C#
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC 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 EntitySpaces, LLC 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 EntitySpaces, LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- */ using System; using System.Collections.Generic; using System.Text; using System.EnterpriseServices.Internal; namespace esGacInstall { class Program { static void Main(string[] args) { try { if(args.Length == 0) return; Publish p = new Publish(); if(args[0] == "/install") { p.GacInstall("EntitySpaces.Common.dll"); p.GacInstall("EntitySpaces.MetadataEngine.dll"); p.GacInstall("EntitySpaces2012.AddIn.dll"); p.GacInstall("EntitySpaces.AddIn.TemplateUI.dll"); p.GacInstall("EntitySpaces.CodeGenerator.dll"); } else if(args[0] == "/remove") { p.GacRemove("EntitySpaces.MetadataEngine.dll"); p.GacRemove("EntitySpaces2012.AddIn.dll"); p.GacRemove("EntitySpaces.AddIn.TemplateUI.dll"); p.GacRemove("EntitySpaces.CodeGenerator.dll"); p.GacRemove("EntitySpaces.TemplateUI.dll"); p.GacRemove("EntitySpaces.MSDASC.dll"); p.GacRemove("EntitySpaces.Common.dll"); } } catch { } } } }
42.591549
79
0.619378
[ "Unlicense" ]
EntitySpaces/EntitySpaces-CompleteSource
CodeGeneration/esGacInstall/Program.cs
3,024
C#
namespace Rawr.Rogue { partial class RogueTalents { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBoxAssassination = new System.Windows.Forms.GroupBox(); this.groupBoxCombat = new System.Windows.Forms.GroupBox(); this.groupBoxSubtlety = new System.Windows.Forms.GroupBox(); this.panelAssassination = new System.Windows.Forms.Panel(); this.panelCombat = new System.Windows.Forms.Panel(); this.panelSubtlety = new System.Windows.Forms.Panel(); this.groupBoxAssassination.SuspendLayout(); this.groupBoxCombat.SuspendLayout(); this.groupBoxSubtlety.SuspendLayout(); this.SuspendLayout(); // // groupBoxAssassination // this.groupBoxAssassination.Controls.Add(this.panelAssassination); this.groupBoxAssassination.Location = new System.Drawing.Point(34, 12); this.groupBoxAssassination.Name = "groupBoxAssassination"; this.groupBoxAssassination.Size = new System.Drawing.Size(231, 666); this.groupBoxAssassination.TabIndex = 0; this.groupBoxAssassination.TabStop = false; this.groupBoxAssassination.Text = "Assassination"; // // groupBoxCombat // this.groupBoxCombat.Controls.Add(this.panelCombat); this.groupBoxCombat.Location = new System.Drawing.Point(297, 12); this.groupBoxCombat.Name = "groupBoxCombat"; this.groupBoxCombat.Size = new System.Drawing.Size(231, 666); this.groupBoxCombat.TabIndex = 1; this.groupBoxCombat.TabStop = false; this.groupBoxCombat.Text = "Combat"; // // groupBoxSubtlety // this.groupBoxSubtlety.Controls.Add(this.panelSubtlety); this.groupBoxSubtlety.Location = new System.Drawing.Point(560, 12); this.groupBoxSubtlety.Name = "groupBoxSubtlety"; this.groupBoxSubtlety.Size = new System.Drawing.Size(231, 666); this.groupBoxSubtlety.TabIndex = 1; this.groupBoxSubtlety.TabStop = false; this.groupBoxSubtlety.Text = "Subtlety"; // // panelAssassination // this.panelAssassination.Dock = System.Windows.Forms.DockStyle.Fill; this.panelAssassination.Location = new System.Drawing.Point(3, 16); this.panelAssassination.Name = "panelAssassination"; this.panelAssassination.Size = new System.Drawing.Size(225, 647); this.panelAssassination.TabIndex = 0; // // panelCombat // this.panelCombat.Dock = System.Windows.Forms.DockStyle.Fill; this.panelCombat.Location = new System.Drawing.Point(3, 16); this.panelCombat.Name = "panelCombat"; this.panelCombat.Size = new System.Drawing.Size(225, 647); this.panelCombat.TabIndex = 0; // // panelSubtlety // this.panelSubtlety.Dock = System.Windows.Forms.DockStyle.Fill; this.panelSubtlety.Location = new System.Drawing.Point(3, 16); this.panelSubtlety.Name = "panelSubtlety"; this.panelSubtlety.Size = new System.Drawing.Size(225, 647); this.panelSubtlety.TabIndex = 0; // // RogueTalents // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.ClientSize = new System.Drawing.Size(824, 690); this.Controls.Add(this.groupBoxSubtlety); this.Controls.Add(this.groupBoxCombat); this.Controls.Add(this.groupBoxAssassination); this.Name = "RogueTalents"; this.Text = "RogueTalents"; this.groupBoxAssassination.ResumeLayout(false); this.groupBoxCombat.ResumeLayout(false); this.groupBoxSubtlety.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBoxAssassination; private System.Windows.Forms.GroupBox groupBoxCombat; private System.Windows.Forms.GroupBox groupBoxSubtlety; private System.Windows.Forms.Panel panelAssassination; private System.Windows.Forms.Panel panelCombat; private System.Windows.Forms.Panel panelSubtlety; } }
46.830508
108
0.596996
[ "Apache-2.0" ]
satelliteprogrammer/rawr
Rawr.Rogue/Talent GUI.unused/RogueTalents.Designer.cs
5,528
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; namespace winFrac { public partial class FormBase : Form { private const string SEULEMENT_CARACTERES_AUTORISES = @"[^0-9,+\-\*/<>=!\?\s]"; // ajouter _ private const string CARRACTERES_DOUBLES_INTERDITS = @"(\s{2})|(\+{2})|(-{2})|(\*{2})|(/{2})|(<{2})|(>{2})|(={3})|(!{2})|(\?{2})|(_{2})"; private const string ESPACE_AU_DEBUT_INTERDIT = @"^\s"; private const string LIMITER_SAISIE_A_DEUX_FRACTIONS = @"^\S+\s\S+\s\S+\s"; private List<string> listeEnonceTests = null; private string formatF1; private string formatOp; private string formatF2; public FormBase() { InitializeComponent(); } private void textBoxEnonceArithmetique_TextChanged(object sender, EventArgs e) { if (Regex.IsMatch(textBoxEnonceArithmetique.Text, ESPACE_AU_DEBUT_INTERDIT) || Regex.IsMatch(textBoxEnonceArithmetique.Text, SEULEMENT_CARACTERES_AUTORISES) || Regex.IsMatch(textBoxEnonceArithmetique.Text, CARRACTERES_DOUBLES_INTERDITS) || Regex.IsMatch(textBoxEnonceArithmetique.Text, LIMITER_SAISIE_A_DEUX_FRACTIONS)) { //MessageBox.Show("Caractères autorisés :\n" + // "0-9 , + - * /\n" + // "< > <= >=\n" + // "== != ? _\n" + // "[espace]\n" + // "Voir menu \"Aide\""); textBoxEnonceArithmetique.Text = textBoxEnonceArithmetique.Text.Remove(textBoxEnonceArithmetique.Text.Length - 1); textBoxEnonceArithmetique.Select(textBoxEnonceArithmetique.Text.Length, 0); } if (Regex.IsMatch(textBoxEnonceArithmetique.Text, @"^\S+")) { listeEnonceTests = textBoxEnonceArithmetique.Text.Split(' ').ToList(); formatF1 = TesterSiEstUneFraction(listeEnonceTests[0], "F1"); statusLabelValideArithmetique.Text = $"{formatF1}"; listeEnonceTests = null; } if (Regex.IsMatch(textBoxEnonceArithmetique.Text, @"^\S+\s\S+")) { listeEnonceTests = textBoxEnonceArithmetique.Text.Split(' ').ToList(); if (Regex.IsMatch(listeEnonceTests[1], @"^\+$|^-$|^\*$|^/$|^<=?$|^>=?$|^={2}$|^!=$|^\?$")) // ajouter _ { formatOp = "Opérateur valide"; } else { formatOp = "Opérateur non valide"; } statusLabelValideArithmetique.Text = $"{formatF1} | {formatOp}"; listeEnonceTests = null; } if (Regex.IsMatch(textBoxEnonceArithmetique.Text, @"^\S+\s\S+\s\S+")) { listeEnonceTests = textBoxEnonceArithmetique.Text.Split(' ').ToList(); formatF2 = TesterSiEstUneFraction(listeEnonceTests[2], "F2"); statusLabelValideArithmetique.Text = $"{formatF1} | {formatOp} | {formatF2}"; listeEnonceTests = null; } if (Regex.IsMatch(textBoxEnonceArithmetique.Text, @"^$")) { statusLabelValideArithmetique.Text = "Message de validité du format"; } } private string TesterSiEstUneFraction(string pAtester, string pIndiceFraction) { if (Regex.IsMatch(pAtester, @"^[+-]?\d+(?:,\d+)?$")) // regex à vérifier pour decimal universal @"^[+-]?(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d*)?$" { return $"{pIndiceFraction} est une fraction (decimal)"; } else if (Regex.IsMatch(pAtester, @"^[+-]?\d+/[+-]?\d+$")) { return $"{pIndiceFraction} est une fraction (a/b)"; } else { return $"{pIndiceFraction} n'est pas une fraction"; } } private void textBoxEnonceArithmetique_MouseDown(object sender, MouseEventArgs e) { //textBoxEnonceArithmetique.Clear(); } private void buttonCalculArithmetique_Click(object sender, EventArgs e) { try { labelReponseArithmetique.Text = Calcul.CalculParEnonce(textBoxEnonceArithmetique.Text); } catch (Exception) { MessageBox.Show("Erreur de calcul"); } // faire un try catch si ça c'est bien passé Communication.EnvoyerDonneesAlaDAL(textBoxEnonceArithmetique.Text, labelReponseArithmetique.Text); } private void buttonClearArithmetique_Click(object sender, EventArgs e) { textBoxEnonceArithmetique.Clear(); textBoxEnonceArithmetique.Focus(); labelReponseArithmetique.Text = "Réponse"; } private void labelReponseArithmetique_DoubleClick(object sender, EventArgs e) { Clipboard.SetText(labelReponseArithmetique.Text); } private void labelReponseArithmetique_TextChanged(object sender, EventArgs e) { } private void labelReponseArithmetique_MouseHover(object sender, EventArgs e) { labelCopierArithmetique.Visible = true; } private void labelReponseArithmetique_MouseLeave(object sender, EventArgs e) { // augmenter le temps d'affichage labelCopierArithmetique.Visible = false; } private void nouveauToolStripMenuItem_Click(object sender, EventArgs e) { using (ListeOperations lstOp = new()) { lstOp.ShowDialog(); } } private void enregistrerLeRésultatObtenuToolStripMenuItem_Click(object sender, EventArgs e) { // enregistrer le fichier ailleurs et le vider //Outils.EnvoyerDonneesAlaDAL(textBoxEnonceArithmetique.Text, labelReponseArithmetique.Text); } private void FormBase_Load(object sender, EventArgs e) { textBoxEnonceArithmetique.Focus(); } } }
32.31875
145
0.689228
[ "Unlicense" ]
TwelveMonkeysCrewWarriorsOfTheCode/C-ba_winFrac
winFrac/FormBase.cs
5,184
C#
// // Copyright 2016 Bertrand Lorentz // // 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.ObjectModel; using System.Xml.Serialization; namespace EULex.Model { [XmlType (Namespace="http://eur-lex.europa.eu/search", IncludeInSchema=false)] public enum CaseLawDirectoryLevel { [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_1")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_1, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_2")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_2, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_3")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_3, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_4")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_4, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_5")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_5, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_6")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_6, [XmlEnum ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_7")] CASELAW_IS_ABOUT_CONCEPT_CASELAW_7, } [XmlType (AnonymousType=true, Namespace="http://eur-lex.europa.eu/search")] public partial class CaseLawDirectoryCode { [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_1", typeof (Concept))] public Concept Level1 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_2", typeof (Concept))] public Concept Level2 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_3", typeof (Concept))] public Concept Level3 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_4", typeof (Concept))] public Concept Level4 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_5", typeof (Concept))] public Concept Level5 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_6", typeof (Concept))] public Concept Level6 { get; set; } [XmlElement ("CASE-LAW_IS_ABOUT_CONCEPT_CASE-LAW_7", typeof (Concept))] public Concept Level7 { get; set; } } }
39.240506
82
0.719032
[ "MIT" ]
EULexNET/EULex.NET
src/EULex/Model/CaseLawDirectoryCode.cs
3,102
C#
// Copyright 2021 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Xunit; [Collection(nameof(StorageFixture))] public class SetPublicAccessPreventionUnspecifiedTest { private readonly StorageFixture _fixture; public SetPublicAccessPreventionUnspecifiedTest(StorageFixture fixture) { _fixture = fixture; } [Fact] public void TestSetPublicAccessPreventionUnspecified() { SetPublicAccessPreventionUnspecifiedSample setPublicAccessPreventionUnspecifiedSample = new SetPublicAccessPreventionUnspecifiedSample(); var bucketName = Guid.NewGuid().ToString(); // Create bucket _fixture.CreateBucket(bucketName); // Set public access prevention to unspecified. var updatedBucket = setPublicAccessPreventionUnspecifiedSample.SetPublicAccessPreventionUnspecified(bucketName); _fixture.SleepAfterBucketCreateUpdateDelete(); Assert.Equal("unspecified", updatedBucket.IamConfiguration.PublicAccessPrevention); } }
35.272727
145
0.755799
[ "Apache-2.0" ]
arun12nura/dotnet-docs-samples
storage/api/Storage.Samples.Tests/SetPublicAccessPreventionUnspecifiedTest.cs
1,554
C#
using System; using System.Collections.Generic; using System.Linq; using Statecharts.NET.Language.Builders.Transition; using Statecharts.NET.Model; using Statecharts.NET.Utilities; using static Statecharts.NET.Language.Keywords; namespace Statecharts.NET.Language.Builders { internal class StatenodeDefinitionData { public string Name { get; } internal IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions { get; set; } internal IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions { get; set; } internal IEnumerable<TransitionDefinition> Transitions { get; set; } internal IEnumerable<ServiceDefinition> Services { get; set; } internal InitialCompoundTransitionDefinition InitialTransition { get; set; } internal IEnumerable<StatenodeDefinition> States { get; set; } public StatenodeDefinitionData(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); EntryActions = Enumerable.Empty<OneOf<Model.ActionDefinition, ContextActionDefinition>>(); ExitActions = Enumerable.Empty<OneOf<Model.ActionDefinition, ContextActionDefinition>>(); Transitions = Enumerable.Empty<TransitionDefinition>(); Services = Enumerable.Empty<ServiceDefinition>(); States = Enumerable.Empty<StatenodeDefinition>(); } } public class StatenodeWithName : StatenodeWithEntryActions { public StatenodeWithName(string name) : base(name) { } public StatenodeWithEntryActions WithEntryActions( ActionDefinition action, params ActionDefinition[] actions) { Definition.EntryActions = action.Append(actions) .Select<ActionDefinition, OneOf<Model.ActionDefinition, ContextActionDefinition>>(a => a.ToDefinitionAction()); return this; } public StatenodeWithEntryActions WithEntryActions<TContext>( OneOf<ActionDefinition, ActionDefinition<TContext>> action, params OneOf<ActionDefinition, ActionDefinition<TContext>>[] actions) { Definition.EntryActions = action.Append(actions) .Select(a => a.Match<OneOf<Model.ActionDefinition, ContextActionDefinition>>( contextlessAction => contextlessAction.ToDefinitionAction(), contextAction => contextAction.ToDefinitionAction())); return this; } } public class StatenodeWithEntryActions : StatenodeWithExitActions { internal StatenodeWithEntryActions(string name) : base(name) { } public StatenodeWithExitActions WithExitActions( ActionDefinition action, params ActionDefinition[] actions) { Definition.ExitActions = action.Append(actions) .Select<ActionDefinition, OneOf<Model.ActionDefinition, ContextActionDefinition>>(a => a.ToDefinitionAction()); return this; } public StatenodeWithExitActions WithExitActions<TContext>( OneOf<ActionDefinition, ActionDefinition<TContext>> action, params OneOf<ActionDefinition, ActionDefinition<TContext>>[] actions) { Definition.ExitActions = action.Append(actions) .Select(a => a.Match<OneOf<Model.ActionDefinition, ContextActionDefinition>>( contextlessAction => contextlessAction.ToDefinitionAction(), contextAction => contextAction.ToDefinitionAction())); return this; } } public class StatenodeWithExitActions : StatenodeWithTransitions { internal StatenodeWithExitActions(string name) : base(name) { } public StatenodeWithTransitions WithTransitions( TransitionDefinition transitionDefinition, params TransitionDefinition[] transitionDefinitions) => WithTransitions(transitionDefinition.Append(transitionDefinitions)); public StatenodeWithTransitions WithTransitions(IEnumerable<TransitionDefinition> transitionDefinitions) { Definition.Transitions = transitionDefinitions; return this; } public FinalStatenode AsFinal() => new FinalStatenode(Definition); } public class StatenodeWithTransitions : StatenodeWithInvocations { internal StatenodeWithTransitions(string name) : base(name) { } public StatenodeWithInvocations WithInvocations( ServiceDefinition service, params ServiceDefinition[] services) { Definition.Services = service.Append(services); return this; } } public class StatenodeWithInvocations : AtomicStatenodeDefinition { private protected StatenodeDefinitionData Definition { get; } internal StatenodeWithInvocations(string name) => Definition = new StatenodeDefinitionData(name); public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public CompoundStatenode AsCompound() => new CompoundStatenode(Definition); public OrthogonalStatenode AsOrthogonal() => new OrthogonalStatenode(Definition); } public class FinalStatenode : FinalStatenodeDefinition { private StatenodeDefinitionData Definition { get; } internal FinalStatenode(StatenodeDefinitionData data) => Definition = data; public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; } public class CompoundStatenode { internal StatenodeDefinitionData Definition { get; } internal CompoundStatenode(StatenodeDefinitionData data) => Definition = data; public CompoundStatenodeWithInitialState WithInitialState(string stateName) { Definition.InitialTransition = new InitialCompoundTransitionDefinition(Child(stateName)); return new CompoundStatenodeWithInitialState(this); } } public class CompoundStatenodeWithInitialState { internal StatenodeDefinitionData Definition { get; } internal CompoundStatenodeWithInitialState(CompoundStatenode compound) => Definition = compound.Definition; public CompoundStatenodeWithInitialActions WithInitialActions( OneOf<Model.ActionDefinition, ContextActionDefinition> action, params OneOf<Model.ActionDefinition, ContextActionDefinition>[] actions) { Definition.InitialTransition = new InitialCompoundTransitionDefinition(Definition.InitialTransition.Target, action.Append(actions)); return new CompoundStatenodeWithInitialActions(this); } public CompoundStatenodeWithSubstates WithStates( OneOf<string, StatenodeDefinition> state, params OneOf<string, StatenodeDefinition>[] states) => WithStates(state.Append(states)); public CompoundStatenodeWithSubstates WithStates(IEnumerable<OneOf<string, StatenodeDefinition>> states) => WithStates(states.Select(definition => definition.Match(name => new StatenodeWithName(name), valid => valid))); public CompoundStatenodeWithSubstates WithStates(IEnumerable<string> states) => WithStates(states.Select(name => new StatenodeWithName(name))); public CompoundStatenodeWithSubstates WithStates(IEnumerable<StatenodeDefinition> states) { Definition.States = states; return new CompoundStatenodeWithSubstates(this); } } public class CompoundStatenodeWithInitialActions { internal StatenodeDefinitionData Definition { get; } internal CompoundStatenodeWithInitialActions(CompoundStatenodeWithInitialState compound) => Definition = compound.Definition; public CompoundStatenodeWithSubstates WithStates( OneOf<string, StatenodeDefinition> state, params OneOf<string, StatenodeDefinition>[] states) => WithStates(state.Append(states)); public CompoundStatenodeWithSubstates WithStates(IEnumerable<OneOf<string, StatenodeDefinition>> states) => WithStates(states.Select(definition => definition.Match(name => new StatenodeWithName(name), valid => valid))); public CompoundStatenodeWithSubstates WithStates(IEnumerable<string> states) => WithStates(states.Select(name => new StatenodeWithName(name))); public CompoundStatenodeWithSubstates WithStates(IEnumerable<StatenodeDefinition> states) { Definition.States = states; return new CompoundStatenodeWithSubstates(this); } } public class CompoundStatenodeWithSubstates : CompoundStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal CompoundStatenodeWithSubstates(CompoundStatenodeWithInitialState compoundWithInitialState) => Definition = compoundWithInitialState.Definition; internal CompoundStatenodeWithSubstates(CompoundStatenodeWithInitialActions compoundWithInitialActions) => Definition = compoundWithInitialActions.Definition; public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override InitialCompoundTransitionDefinition InitialTransition => Definition.InitialTransition; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override Option<DoneTransitionDefinition> DoneTransition => Option.None<DoneTransitionDefinition>(); public CompoundStatenodeWithOnDone OnDone => new CompoundStatenodeWithOnDone(this); } public class CompoundStatenodeWithOnDone { internal StatenodeDefinitionData Definition { get; } public CompoundStatenodeWithOnDone(CompoundStatenodeWithSubstates compound) => Definition = compound.Definition; public CompoundStatenodeWithDoneTransitionTo TransitionTo => new CompoundStatenodeWithDoneTransitionTo(this); } public class CompoundStatenodeWithDoneTransitionTo { internal StatenodeDefinitionData Definition { get; } public CompoundStatenodeWithDoneTransitionTo(CompoundStatenodeWithOnDone compound) => Definition = compound.Definition; public CompoundStatenodeWithDoneTransition Child(string stateName, params string[] childStatenodesNames) => new CompoundStatenodeWithDoneTransition(this, Keywords.Child(stateName, childStatenodesNames)); public CompoundStatenodeWithDoneTransition Sibling(string stateName, params string[] childStatenodesNames) => new CompoundStatenodeWithDoneTransition(this, Keywords.Sibling(stateName, childStatenodesNames)); public CompoundStatenodeWithDoneTransition Absolute(string statechartName, params string[] childStatenodesNames) => new CompoundStatenodeWithDoneTransition(this, Keywords.Absolute(statechartName, childStatenodesNames)); public CompoundStatenodeWithDoneTransition Target(Target target) => new CompoundStatenodeWithDoneTransition(this, target); public CompoundStatenodeWithDoneTransition Multiple(Target target, params Target[] targets) => new CompoundStatenodeWithDoneTransition(this, target, targets); } public class CompoundStatenodeWithDoneTransition : CompoundStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal UnguardedWithTarget DoneTransitionBuilder { get; } public CompoundStatenodeWithDoneTransition(CompoundStatenodeWithDoneTransitionTo compound, Target target, params Target[] targets) { Definition = compound.Definition; DoneTransitionBuilder = WithEvent.OnDone().TransitionTo.Multiple(target, targets); } public CompoundStatenodeWithDoneTransitionWithActions WithActions(ActionDefinition action, params ActionDefinition[] actions) => new CompoundStatenodeWithDoneTransitionWithActions(this, action, actions); public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override InitialCompoundTransitionDefinition InitialTransition => Definition.InitialTransition; public override Option<DoneTransitionDefinition> DoneTransition => new DoneTransitionDefinition(DoneTransitionBuilder.Targets).ToOption(); // TODO: improve this } public class CompoundStatenodeWithDoneTransitionWithActions : CompoundStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal UnguardedWithActions DoneTransitionBuilder { get; } public CompoundStatenodeWithDoneTransitionWithActions(CompoundStatenodeWithDoneTransition compound, ActionDefinition action, ActionDefinition[] actions) { Definition = compound.Definition; DoneTransitionBuilder = compound.DoneTransitionBuilder.WithActions(action, actions); } public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override InitialCompoundTransitionDefinition InitialTransition => Definition.InitialTransition; public override Option<DoneTransitionDefinition> DoneTransition => new DoneTransitionDefinition(DoneTransitionBuilder.Targets).ToOption(); // TODO: improve this } public class OrthogonalStatenode { internal StatenodeDefinitionData Definition { get; } internal OrthogonalStatenode(StatenodeDefinitionData data) => Definition = data; public OrthogonalStatenodeWithStates WithStates( OneOf<string, StatenodeDefinition> state, params OneOf<string, StatenodeDefinition>[] states) => WithStates(state.Append(states)); public OrthogonalStatenodeWithStates WithStates(IEnumerable<OneOf<string, StatenodeDefinition>> states) => WithStates(states.Select(definition => definition.Match(name => new StatenodeWithName(name), valid => valid))); public OrthogonalStatenodeWithStates WithStates(IEnumerable<string> states) => WithStates(states.Select(name => new StatenodeWithName(name))); public OrthogonalStatenodeWithStates WithStates(IEnumerable<StatenodeDefinition> states) { Definition.States = states; return new OrthogonalStatenodeWithStates(this); } } public class OrthogonalStatenodeWithStates : OrthogonalStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal OrthogonalStatenodeWithStates(OrthogonalStatenode orthogonal) => Definition = orthogonal.Definition; public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override Option<DoneTransitionDefinition> DoneTransition => Option.None<DoneTransitionDefinition>(); public OrthogonalStatenodeWithOnDone OnDone => new OrthogonalStatenodeWithOnDone(this); } public class OrthogonalStatenodeWithOnDone { internal StatenodeDefinitionData Definition { get; } public OrthogonalStatenodeWithOnDone(OrthogonalStatenodeWithStates orthogonal) => Definition = orthogonal.Definition; public OrthogonalStatenodeWithDoneTransitionTo TransitionTo => new OrthogonalStatenodeWithDoneTransitionTo(this); } public class OrthogonalStatenodeWithDoneTransitionTo { internal StatenodeDefinitionData Definition { get; } public OrthogonalStatenodeWithDoneTransitionTo(OrthogonalStatenodeWithOnDone orthogonal) => Definition = orthogonal.Definition; public OrthogonalStatenodeWithDoneTransition Child(string stateName, params string[] childStatenodesNames) => new OrthogonalStatenodeWithDoneTransition(this, Keywords.Child(stateName, childStatenodesNames)); public OrthogonalStatenodeWithDoneTransition Sibling(string stateName, params string[] childStatenodesNames) => new OrthogonalStatenodeWithDoneTransition(this, Keywords.Sibling(stateName, childStatenodesNames)); public OrthogonalStatenodeWithDoneTransition Absolute(string statechartName, params string[] childStatenodesNames) => new OrthogonalStatenodeWithDoneTransition(this, Keywords.Absolute(statechartName, childStatenodesNames)); public OrthogonalStatenodeWithDoneTransition Target(Target target) => new OrthogonalStatenodeWithDoneTransition(this, target); public OrthogonalStatenodeWithDoneTransition Multiple(Target target, params Target[] targets) => new OrthogonalStatenodeWithDoneTransition(this, target, targets); } public class OrthogonalStatenodeWithDoneTransition : OrthogonalStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal UnguardedWithTarget DoneTransitionBuilder { get; } public OrthogonalStatenodeWithDoneTransition(OrthogonalStatenodeWithDoneTransitionTo orthogonal, Target target, params Target[] targets) { Definition = orthogonal.Definition; DoneTransitionBuilder = WithEvent.OnDone().TransitionTo.Multiple(target, targets); } public OrthogonalStatenodeWithDoneTransitionWithActions WithActions(ActionDefinition action, params ActionDefinition[] actions) => new OrthogonalStatenodeWithDoneTransitionWithActions(this, action, actions); public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override Option<DoneTransitionDefinition> DoneTransition => new DoneTransitionDefinition(DoneTransitionBuilder.Targets).ToOption(); // TODO: improve this } public class OrthogonalStatenodeWithDoneTransitionWithActions : OrthogonalStatenodeDefinition { internal StatenodeDefinitionData Definition { get; } internal UnguardedWithActions DoneTransitionBuilder { get; } public OrthogonalStatenodeWithDoneTransitionWithActions(OrthogonalStatenodeWithDoneTransition orthogonal, ActionDefinition action, ActionDefinition[] actions) { Definition = orthogonal.Definition; DoneTransitionBuilder = orthogonal.DoneTransitionBuilder.WithActions(action, actions); } public override string Name => Definition.Name; public override Option<string> UniqueIdentifier => Option.None<string>(); public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> EntryActions => Definition.EntryActions; public override IEnumerable<OneOf<Model.ActionDefinition, ContextActionDefinition>> ExitActions => Definition.ExitActions; public override IEnumerable<TransitionDefinition> Transitions => Definition.Transitions; public override IEnumerable<ServiceDefinition> Services => Definition.Services; public override IEnumerable<StatenodeDefinition> Statenodes => Definition.States; public override Option<DoneTransitionDefinition> DoneTransition => new DoneTransitionDefinition(DoneTransitionBuilder.Targets).ToOption(); // TODO: improve this } }
57.61461
168
0.740961
[ "MIT" ]
bemayr/Statecharts.NET
Statecharts.NET.Language/Builders/StateNode.cs
22,875
C#
// // Encog(tm) Core v3.1 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2012 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.MathUtil.Matrices; using Encog.ML.Data; using Encog.ML.Data.Specific; using Encog.Util; namespace Encog.Neural.Thermal { /// <summary> /// Implements a Hopfield network. /// </summary> [Serializable] public class HopfieldNetwork : ThermalNetwork { /// <summary> /// Default constructor. /// </summary> /// public HopfieldNetwork() { } /// <summary> /// Construct a Hopfield with the specified neuron count. /// </summary> /// /// <param name="neuronCount">The neuron count.</param> public HopfieldNetwork(int neuronCount) : base(neuronCount) { } /// <inheritdoc/> public override int InputCount { get { return NeuronCount; } } /// <inheritdoc/> public override int OutputCount { get { return NeuronCount; } } /// <summary> /// Train the neural network for the specified pattern. The neural network /// can be trained for more than one pattern. To do this simply call the /// train method more than once. /// </summary> /// /// <param name="pattern">The pattern to train for.</param> public void AddPattern(IMLData pattern) { if (pattern.Count != NeuronCount) { throw new NeuralNetworkError("Network with " + NeuronCount + " neurons, cannot learn a pattern of size " + pattern.Count); } // Create a row matrix from the input, convert boolean to bipolar Matrix m2 = Matrix.CreateRowMatrix(pattern.Data); // Transpose the matrix and multiply by the original input matrix Matrix m1 = MatrixMath.Transpose(m2); Matrix m3 = MatrixMath.Multiply(m1, m2); // matrix 3 should be square by now, so create an identity // matrix of the same size. Matrix identity = MatrixMath.Identity(m3.Rows); // subtract the identity matrix Matrix m4 = MatrixMath.Subtract(m3, identity); // now add the calculated matrix, for this pattern, to the // existing weight matrix. ConvertHopfieldMatrix(m4); } /// <summary> /// Note: for Hopfield networks, you will usually want to call the "run" /// method to compute the output. /// This method can be used to copy the input data to the current state. A /// single iteration is then run, and the new current state is returned. /// </summary> /// /// <param name="input">The input pattern.</param> /// <returns>The new current state.</returns> public override sealed IMLData Compute(IMLData input) { var result = new BiPolarMLData(input.Count); EngineArray.ArrayCopy(input.Data, CurrentState.Data); Run(); for (int i = 0; i < CurrentState.Count; i++) { result.SetBoolean(i, BiPolarUtil.Double2bipolar(CurrentState[i])); } EngineArray.ArrayCopy(CurrentState.Data, result.Data); return result; } /// <summary> /// Update the Hopfield weights after training. /// </summary> /// /// <param name="delta">The amount to change the weights by.</param> private void ConvertHopfieldMatrix(Matrix delta) { // add the new weight matrix to what is there already for (int row = 0; row < delta.Rows; row++) { for (int col = 0; col < delta.Rows; col++) { AddWeight(row, col, delta[row, col]); } } } /// <summary> /// Perform one Hopfield iteration. /// </summary> /// public void Run() { for (int toNeuron = 0; toNeuron < NeuronCount; toNeuron++) { double sum = 0; for (int fromNeuron = 0; fromNeuron < NeuronCount; fromNeuron++) { sum += CurrentState[fromNeuron] *GetWeight(fromNeuron, toNeuron); } CurrentState[toNeuron] = sum; } } /// <summary> /// Run the network until it becomes stable and does not change from more /// runs. /// </summary> /// /// <param name="max">The maximum number of cycles to run before giving up.</param> /// <returns>The number of cycles that were run.</returns> public int RunUntilStable(int max) { bool done = false; String currentStateStr = (CurrentState.ToString()); int cycle = 0; do { Run(); cycle++; String lastStateStr = (CurrentState.ToString()); if (!currentStateStr.Equals(lastStateStr)) { if (cycle > max) { done = true; } } else { done = true; } currentStateStr = lastStateStr; } while (!done); return cycle; } /// <summary> /// /// </summary> /// public override void UpdateProperties() { // nothing needed here } } }
31.5311
91
0.52261
[ "BSD-3-Clause" ]
mpcoombes/MaterialPredictor
encog-core-cs/Neural/Thermal/HopfieldNetwork.cs
6,590
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("treeDiM.Stackbuilder.Graphics.BoxelOrder.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("treeDiM.Stackbuilder.Graphics.BoxelOrder.Test")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("859b82e9-014c-435e-a98e-cb50e321d9b9")]
45.541667
85
0.768527
[ "Unlicense", "MIT" ]
siranen/PalletBuilder
Test/TreeDim.Stackbuilder.Graphics.BoxelOrderer.Test/Properties/AssemblyInfo.cs
1,096
C#
using System.Collections.Generic; namespace MopsBot.Data.Tracker.APIResults.Steam { public class PlayerSummary { public string steamid { get; set; } public int communityvisibilitystate { get; set; } public int profilestate { get; set; } public string personaname { get; set; } public int lastlogoff { get; set; } public string profileurl { get; set; } public string avatar { get; set; } public string avatarmedium { get; set; } public string avatarfull { get; set; } public int personastate { get; set; } public string realname { get; set; } public string primaryclanid { get; set; } public int timecreated { get; set; } public int personastateflags { get; set; } public string gameextrainfo { get; set; } public string gameid { get; set; } } public class UserSummaryResponse { public List<PlayerSummary> players { get; set; } } public class UserSummary { public UserSummaryResponse response { get; set; } } public class VanityResponse { public string steamid { get; set; } public int success { get; set; } } public class Vanity { public VanityResponse response { get; set; } } public class RecentlyPlayedGame { public int appid { get; set; } public string name { get; set; } public int playtime_2weeks { get; set; } public int playtime_forever { get; set; } public string img_icon_url { get; set; } public string img_logo_url { get; set; } } public class RecentlyPlayedResponse { public int total_count { get; set; } public List<RecentlyPlayedGame> games { get; set; } } public class RecentlyPlayed { public RecentlyPlayedResponse response { get; set; } } public class StatsAchievement { public string apiname { get; set; } public int achieved { get; set; } public int unlocktime { get; set; } } public class PlayerstatsResponse { public string steamID { get; set; } public string gameName { get; set; } public List<StatsAchievement> achievements { get; set; } public bool success { get; set; } } public class PlayerStats { public PlayerstatsResponse playerstats { get; set; } } public class PercentageAchievement { public string name { get; set; } public double percent { get; set; } } public class Achievementpercentages { public List<PercentageAchievement> achievements { get; set; } } public class AchievementPercentage { public Achievementpercentages achievementpercentages { get; set; } } public class GameAchievement { public string name { get; set; } public long defaultvalue { get; set; } public string displayName { get; set; } public int hidden { get; set; } public string description { get; set; } public string icon { get; set; } public string icongray { get; set; } } public class GameStat { public string name { get; set; } public long defaultvalue { get; set; } public string displayName { get; set; } } public class AvailableGameStats { public List<GameAchievement> achievements { get; set; } public List<GameStat> stats { get; set; } } public class Game { public string gameName { get; set; } public string gameVersion { get; set; } public AvailableGameStats availableGameStats { get; set; } } public class GameStats { public Game game { get; set; } } public class Achievement{ public string name { get; set; } public long defaultvalue { get; set; } public string displayName { get; set; } public int hidden { get; set; } public string description { get; set; } public string icon { get; set; } public string icongray { get; set; } public double percent { get; set; } public string apiname { get; set; } public int achieved { get; set; } public int unlocktime { get; set; } } }
28.315789
74
0.597584
[ "MIT" ]
CaldeiraG/MopsBot-2.0
Data/Tracker/APIResults/SteamResult.cs
4,304
C#
using System.ComponentModel.DataAnnotations; namespace Bit.Core.Models.Api { public class PasswordHintRequestModel { [Required] [EmailAddress] [StringLength(50)] public string Email { get; set; } } }
18.923077
45
0.638211
[ "MPL-2.0" ]
carloskcheung/fossa-cli
test/fixtures/nuget/src/Core/Models/Api/Request/Accounts/PasswordHintRequestModel.cs
248
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PSTParse.NodeDatabaseLayer { public class SLENTRY { public ulong SubNodeNID; public ulong SubNodeBID; public ulong SubSubNodeBID; public SLENTRY(byte[] bytes) { this.SubNodeNID = BitConverter.ToUInt64(bytes, 0); this.SubNodeBID = BitConverter.ToUInt64(bytes, 8); this.SubSubNodeBID = BitConverter.ToUInt64(bytes, 16); } } }
23.590909
66
0.643545
[ "MIT" ]
Sharpiro/PST-Parser
PSTParse/NodeDatabaseLayer/SLENTRY.cs
521
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementIpSetReferenceStatementIpSetForwardedIpConfig { /// <summary> /// - Match status to assign to the web request if the request doesn't have a valid IP address in the specified position. Valid values include: `MATCH` or `NO_MATCH`. /// </summary> public readonly string FallbackBehavior; /// <summary> /// - Name of the HTTP header to use for the IP address. /// </summary> public readonly string HeaderName; /// <summary> /// - Position in the header to search for the IP address. Valid values include: `FIRST`, `LAST`, or `ANY`. If `ANY` is specified and the header contains more than 10 IP addresses, AWS WAFv2 inspects the last 10. /// </summary> public readonly string Position; [OutputConstructor] private WebAclRuleStatementRateBasedStatementScopeDownStatementIpSetReferenceStatementIpSetForwardedIpConfig( string fallbackBehavior, string headerName, string position) { FallbackBehavior = fallbackBehavior; HeaderName = headerName; Position = position; } } }
37.744186
220
0.674677
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementIpSetReferenceStatementIpSetForwardedIpConfig.cs
1,623
C#
using GoogleAnalyticsTracker.Simple; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using GoogleAnalyticsTracker.Core.Interface; using System.Net.NetworkInformation; using System.Xml; namespace ConvertLibrary { public static class GoogleAnalyticsTracker { public static async Task Tracker(string pageTitle, string pageUrl) { SimpleTrackerEnvironment ste = new SimpleTrackerEnvironment(Environment.OSVersion.ToString(), Environment.OSVersion.VersionString, ""); using (SimpleTracker tracker = new SimpleTracker("UA-97814311-2", ste)) { await tracker.TrackPageViewAsync(pageTitle, pageUrl, new Dictionary<int, string>()); } } } public class AnalyticsSession : IAnalyticsSession { [Obsolete] public string GenerateCacheBuster() { string uuid = ConfigurationSettings.AppSettings["uuid"]; if (string.IsNullOrWhiteSpace(uuid)) { SaveConfig("uuid", uuid); } return uuid; } [Obsolete] public string GenerateSessionId() { string uuid = ConfigurationSettings.AppSettings["uuid"]; if (string.IsNullOrWhiteSpace(uuid)) { SaveConfig("uuid", uuid); } return uuid; } private void SaveConfig(string key, string value) { XmlDocument doc = new XmlDocument(); //获得配置文件的全路径 string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "TestLinkConverter.exe.config"; doc.Load(strFileName); //找出名称为“add”的所有元素 XmlNodeList nodes = doc.GetElementsByTagName("add"); for (int i = 0; i < nodes.Count; i++) { //获得将当前元素的key属性 XmlAttribute att = nodes[i].Attributes["key"]; //根据元素的第一个属性来判断当前的元素是不是目标元素 if (att.Value == key) { //对目标元素中的第二个属性赋值 att = nodes[i].Attributes["value"]; att.Value = value; break; } } //保存上面的修改 doc.Save(strFileName); } } }
31.064935
147
0.562709
[ "Apache-2.0" ]
yaitza/TestLinkConverter
ConvertLibrary/GoogleAnalyticsTracker.cs
2,550
C#
using UnityEngine; using System; using System.Collections; using Wikitude; using System.Collections.Generic; using System.Runtime.InteropServices; /// <summary> /// Handles forwarding the camera frame to the custom renderer. /// </summary> public class CustomRenderingController : SampleController { private struct InputFrameData { public long Index; public Texture2D Texture; public InputFrameData(long index, Texture2D texture) { Index = index; Texture = texture; } } public WikitudeCamera WikitudeCam; protected WebCamTexture _feed; public const int FrameWidth = 640; public const int FrameHeight = 480; private int _frameDataSize = 0; private int _frameIndex = 0; private int _bufferWriteIndex = 0; private int _bufferReadIndex = 0; private int _bufferCount = 5; private List<InputFrameData> _ringBuffer; private Color32[] _colorData; public CustomCameraRenderer Renderer; public void OnInputPluginRegistered() { StartCoroutine(Initialize()); } public void OnInputPluginFailure(int errorCode, string errorMessage) { Debug.Log("Input plugin failed with error code: " + errorCode + " message: " + errorMessage); } public void OnEnterFieldOfVision(string targetName) { Renderer.IsEffectVisible = false; } public void OnExitFieldOfVision(string targetName) { Renderer.IsEffectVisible = true; } private IEnumerator Initialize() { foreach (var device in WebCamTexture.devices) { if (!device.isFrontFacing) { _feed = new WebCamTexture(device.name, FrameWidth, FrameHeight); _feed.Play(); break; } } if (_feed == null) { Debug.LogError("Could not find any cameras on the device."); } ResetBuffers(FrameWidth, FrameHeight, 4); // Wait a frame before getting the camera rotation, otherwise it might not be initialized yet yield return null; if (Application.platform == RuntimePlatform.Android) { bool rotatedSensor = false; switch (Screen.orientation) { case ScreenOrientation.Portrait: { rotatedSensor = _feed.videoRotationAngle == 270; break; } case ScreenOrientation.LandscapeLeft: { rotatedSensor = _feed.videoRotationAngle == 180; break; } case ScreenOrientation.LandscapeRight: { rotatedSensor = _feed.videoRotationAngle == 0; break; } case ScreenOrientation.PortraitUpsideDown: { rotatedSensor = _feed.videoRotationAngle == 90; break; } } Debug.Log("RotatedSensor: " + rotatedSensor); if (rotatedSensor) { // Normally, we use InvertedFrame = true, because textures in Unity are mirrored vertically, when compared with the ones the camera provides. // However, when we detect that the camera sensor is rotated by 180 degrees, as is the case for the Nexus 5X for example, // We turn off inverted frame and enable mirrored frame, which has the effect of rotating the frame upside down. // We use the MirroredFrame property and not the EnableMirroring property because the first one actually changes the data that // is being processed, while the second one only changes how the frame is rendered, leaving the frame data intact. WikitudeCam.InvertedFrame = false; WikitudeCam.MirroredFrame = true; // Additionally, because we are doing the rendering in Unity, we need to instruct the renderer to flip the image. Renderer.FlipImage = true; } } } private void ResetBuffers(int width, int height, int bytesPerPixel) { _frameDataSize = width * height * bytesPerPixel; _ringBuffer = new List<InputFrameData>(10); for (int i = 0; i < _bufferCount; ++i) { _ringBuffer.Add(new InputFrameData(-1 , new Texture2D(width, height))); } _colorData = new Color32[width * height]; WikitudeCam.InputFrameWidth = width; WikitudeCam.InputFrameHeight = height; Renderer.CurrentFrame = _ringBuffer[0].Texture; } protected override void Update() { base.Update(); if (_feed == null || !_feed.didUpdateThisFrame) { return; } if (_feed.width != FrameWidth || _feed.height != FrameHeight) { Debug.LogError("Camera feed has unexpected size."); return; } int newFrameDataSize = _feed.width * _feed.height * 4; if (newFrameDataSize != _frameDataSize) { ResetBuffers(_feed.width, _feed.height, 4); } _feed.GetPixels32(_colorData); _ringBuffer[_bufferWriteIndex].Texture.SetPixels32(_colorData); _ringBuffer[_bufferWriteIndex].Texture.Apply(); SendNewCameraFrame(); var data = _ringBuffer[_bufferWriteIndex]; data.Index = _frameIndex; _ringBuffer[_bufferWriteIndex] = data; long presentableIndex = WikitudeCam.GetPresentableInputFrameIndex(); // Default to the last written buffer _bufferReadIndex = _bufferWriteIndex; if (presentableIndex != -1) { for (int i = 0; i < _bufferCount; ++i) { if (_ringBuffer[i].Index == presentableIndex) { _bufferReadIndex = i; } } } Renderer.CurrentFrame = _ringBuffer[_bufferReadIndex].Texture; _bufferWriteIndex = (_bufferWriteIndex + 1) % _bufferCount; } private void SendNewCameraFrame() { GCHandle handle = default(GCHandle); try { handle = GCHandle.Alloc(_colorData, GCHandleType.Pinned); IntPtr frameData = handle.AddrOfPinnedObject(); WikitudeCam.NewCameraFrame(++_frameIndex, _frameDataSize, frameData); } finally { if (handle != default(GCHandle)) { handle.Free(); } } } protected virtual void Cleanup() { _frameDataSize = 0; if (_feed != null) { _feed.Stop(); _feed = null; } if (Renderer) { Renderer.CurrentFrame = null; } } private void OnApplicationPause(bool paused) { if (paused) { Cleanup(); } else { StartCoroutine(Initialize()); } } private void OnDestroy() { Cleanup(); } }
28
145
0.715686
[ "MIT" ]
Aries0331/Corgi-VoiceControl
Corgi_Markerless/Assets/Wikitude/Samples/Scripts/InputPlugin/CustomRenderingController.cs
5,714
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 sagemaker-a2i-runtime-2019-11-07.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.AugmentedAIRuntime.Model { /// <summary> /// Container for the parameters to the StopHumanLoop operation. /// Stops the specified human loop. /// </summary> public partial class StopHumanLoopRequest : AmazonAugmentedAIRuntimeRequest { private string _humanLoopName; /// <summary> /// Gets and sets the property HumanLoopName. /// <para> /// The name of the human loop that you want to stop. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=63)] public string HumanLoopName { get { return this._humanLoopName; } set { this._humanLoopName = value; } } // Check to see if HumanLoopName property is set internal bool IsSetHumanLoopName() { return this._humanLoopName != null; } } }
31.389831
120
0.645248
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AugmentedAIRuntime/Generated/Model/StopHumanLoopRequest.cs
1,852
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SDPCRL.COM { [Serializable] public class LibClientInfo { //public string AccoutId { get; set; } public Language Language { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public string IP { get; set; } public string ClientNm { get; set; } } }
22.15
46
0.620767
[ "Apache-2.0" ]
zyylonghai/BWYSDP
SDPCRL.COM/LibClientInfo.cs
445
C#
/* * CGEventSource.cs: bindings to the ApplicationServices framework's CoreGraphics CGEventSource API * * Copyright 2013, 2014 Xamarin Inc * All Rights Reserved * * Authors: * Miguel de Icaza */ #if MONOMAC using System; using System.Runtime.InteropServices; #if !NO_SYSTEM_DRAWING using System.Drawing; #endif using XamCore.CoreFoundation; using XamCore.ObjCRuntime; using XamCore.Foundation; namespace XamCore.CoreGraphics { public sealed class CGEventSource : IDisposable, INativeObject { IntPtr handle; #region Lifecycle public CGEventSource (IntPtr handle) : this (handle, false) { } public CGEventSource (IntPtr handle, bool ownsHandle) { if (!ownsHandle) CFObject.CFRetain (handle); this.handle = handle; } ~CGEventSource () { Dispose (false); } public IntPtr Handle { get { return handle; } } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public void Dispose (bool disposing) { if (handle != IntPtr.Zero) { CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #endregion [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSourceCreate (CGEventSourceStateID stateID); public CGEventSource (CGEventSourceStateID stateID) { handle = CGEventSourceCreate (stateID); } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static int /* CGEventSourceKeyboardType = uint32_t */ CGEventSourceGetKeyboardType (IntPtr handle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetKeyboardType (IntPtr handle, int /* CGEventSourceKeyboardType = uint32_t */ keyboardType); public int KeyboardType { get { return CGEventSourceGetKeyboardType (handle); } set { CGEventSourceSetKeyboardType (handle, value); } } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventSourceStateID CGEventSourceGetSourceStateID (IntPtr handle); public CGEventSourceStateID StateID { get { return CGEventSourceGetSourceStateID (handle); } } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static double CGEventSourceGetPixelsPerLine (IntPtr handle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetPixelsPerLine (IntPtr handle, double value); public double PixelsPerLine { get { return CGEventSourceGetPixelsPerLine (handle); } set { CGEventSourceSetPixelsPerLine (handle, value); } } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceButtonState")] public extern static bool GetButtonState (CGEventSourceStateID stateID, CGMouseButton button); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceKeyState")] public extern static bool GetKeyState (CGEventSourceStateID stateID, ushort keycode); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceFlagsState")] public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceSecondsSinceLastEventType")] public extern static double GetSecondsSinceLastEventType (CGEventSourceStateID stateID, CGEventType eventType); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceCounterForEventType")] public extern static uint /* uint32_t */ GetCounterForEventType (CGEventSourceStateID stateID, CGEventType eventType); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetUserData (IntPtr handle, long data); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static long CGEventSourceGetUserData (IntPtr handle); public long UserData { get { return CGEventSourceGetUserData (handle); } set { CGEventSourceSetUserData (handle, value); } } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetLocalEventsFilterDuringSuppressionState (IntPtr handle, CGEventFilterMask filter, CGEventSuppressionState state); public void SetLocalEventsFilterDuringSupressionState (CGEventFilterMask filter, CGEventSuppressionState state) { CGEventSourceSetLocalEventsFilterDuringSuppressionState (handle, filter, state); } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventFilterMask CGEventSourceGetLocalEventsFilterDuringSuppressionState (IntPtr handle, CGEventSuppressionState state); public CGEventFilterMask GetLocalEventsFilterDuringSupressionState (CGEventSuppressionState state) { return CGEventSourceGetLocalEventsFilterDuringSuppressionState (handle, state); } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetLocalEventsSuppressionInterval (IntPtr handle, double seconds); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static double CGEventSourceGetLocalEventsSuppressionInterval (IntPtr handle); public double LocalEventsSupressionInterval { get { return CGEventSourceGetLocalEventsSuppressionInterval (handle); } set { CGEventSourceSetLocalEventsSuppressionInterval (handle, value); } } } } #endif // MONOMAC
30.830508
150
0.788162
[ "BSD-3-Clause" ]
Acidburn0zzz/xamarin-macios
src/CoreGraphics/CGEventSource.cs
5,457
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.As.V20180419.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ModifyAutoScalingGroupResponse : AbstractModel { /// <summary> /// The unique request ID, which is returned for each request. RequestId is required for locating a problem. /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.795455
116
0.670479
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/As/V20180419/Models/ModifyAutoScalingGroupResponse.cs
1,399
C#
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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. */ //package org.jasig.cas.ticket.support; //import org.jasig.cas.authentication.principal.RememberMeCredentials; //import org.jasig.cas.ticket.ExpirationPolicy; //import org.jasig.cas.ticket.TicketState; //import javax.validation.constraints.NotNull; /** * Delegates to different expiration policies depending on whether remember me * is true or not. * * @author Scott Battaglia * @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $ * @since 3.2.1 * */ using System.Linq; using NCAS.jasig.authentication.principal; namespace NCAS.jasig.ticket.support { public class RememberMeDelegatingExpirationPolicy : ExpirationPolicy { /** Unique Id for Serialization */ private static long serialVersionUID = -575145836880428365L; ////@NotNull private ExpirationPolicy rememberMeExpirationPolicy; ////@NotNull private ExpirationPolicy sessionExpirationPolicy; public bool isExpired(TicketState ticketState) { bool b = (bool) ticketState.getAuthentication().getAttributes().FirstOrDefault( x => x.Key == typeof(RememberMeCredentials).FullName).Value; if (b == null || b.Equals(false)) { return this.sessionExpirationPolicy.isExpired(ticketState); } return this.rememberMeExpirationPolicy.isExpired(ticketState); } public void setRememberMeExpirationPolicy( ExpirationPolicy rememberMeExpirationPolicy) { this.rememberMeExpirationPolicy = rememberMeExpirationPolicy; } public void setSessionExpirationPolicy(ExpirationPolicy sessionExpirationPolicy) { this.sessionExpirationPolicy = sessionExpirationPolicy; } } }
33.296296
89
0.673341
[ "Apache-2.0" ]
zbw911/CasServer
CASLIB/NCAS/jasig/ticket/support/RememberMeDelegatingExpirationPolicy.cs
2,697
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Cmq.V20190304.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class QueueSet : AbstractModel { /// <summary> /// 消息队列ID。 /// </summary> [JsonProperty("QueueId")] public string QueueId{ get; set; } /// <summary> /// 回溯队列的消息回溯时间最大值,取值范围0 - 43200秒,0表示不开启消息回溯。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("RewindSeconds")] public ulong? RewindSeconds{ get; set; } /// <summary> /// 创建者Uin。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("CreateUin")] public ulong? CreateUin{ get; set; } /// <summary> /// 最后一次修改队列属性的时间。返回 Unix 时间戳,精确到秒。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("LastModifyTime")] public ulong? LastModifyTime{ get; set; } /// <summary> /// 消息可见性超时。取值范围1 - 43200秒(即12小时内),默认值30。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("VisibilityTimeout")] public ulong? VisibilityTimeout{ get; set; } /// <summary> /// 消息队列名字。 /// </summary> [JsonProperty("QueueName")] public string QueueName{ get; set; } /// <summary> /// 消息轨迹。true表示开启,false表示不开启。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Trace")] public bool? Trace{ get; set; } /// <summary> /// 关联的标签。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Tags")] public Tag[] Tags{ get; set; } /// <summary> /// 已调用 DelMsg 接口删除,但还在回溯保留时间内的消息数量。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("RewindMsgNum")] public ulong? RewindMsgNum{ get; set; } /// <summary> /// 飞行消息最大保留时间。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("MaxDelaySeconds")] public ulong? MaxDelaySeconds{ get; set; } /// <summary> /// 事务消息策略。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("TransactionPolicy")] public TransactionPolicy TransactionPolicy{ get; set; } /// <summary> /// 消息保留周期。取值范围60-1296000秒(1min-15天),默认值345600秒(4 天)。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("MsgRetentionSeconds")] public ulong? MsgRetentionSeconds{ get; set; } /// <summary> /// 延迟消息数。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("DelayMsgNum")] public ulong? DelayMsgNum{ get; set; } /// <summary> /// 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("MaxMsgHeapNum")] public ulong? MaxMsgHeapNum{ get; set; } /// <summary> /// 消息接收长轮询等待时间。取值范围0 - 30秒,默认值0。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("PollingWaitSeconds")] public ulong? PollingWaitSeconds{ get; set; } /// <summary> /// 带宽限制。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Bps")] public ulong? Bps{ get; set; } /// <summary> /// 在队列中处于 Inactive 状态(正处于被消费状态)的消息总数,为近似值。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("InactiveMsgNum")] public ulong? InactiveMsgNum{ get; set; } /// <summary> /// 死信队列策略。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("DeadLetterPolicy")] public DeadLetterPolicy DeadLetterPolicy{ get; set; } /// <summary> /// 在队列中处于 Active 状态(不处于被消费状态)的消息总数,为近似值。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("ActiveMsgNum")] public ulong? ActiveMsgNum{ get; set; } /// <summary> /// 消息最大长度。取值范围1024 - 1048576 Byte(即1K - 1024K),默认值65536。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("MaxMsgSize")] public ulong? MaxMsgSize{ get; set; } /// <summary> /// 消息最小未消费时间,单位为秒。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("MinMsgTime")] public ulong? MinMsgTime{ get; set; } /// <summary> /// 死信队列。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("DeadLetterSource")] public DeadLetterSource[] DeadLetterSource{ get; set; } /// <summary> /// 事务消息队列。true表示是事务消息,false表示不是事务消息。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Transaction")] public bool? Transaction{ get; set; } /// <summary> /// 每秒钟生产消息条数的限制,消费消息的大小是该值的1.1倍。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Qps")] public ulong? Qps{ get; set; } /// <summary> /// 队列的创建时间。返回 Unix 时间戳,精确到秒。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("CreateTime")] public ulong? CreateTime{ get; set; } /// <summary> /// 是否迁移到新版本。0 表示仅同步元数据,1 表示迁移中,2 表示已经迁移完毕,3 表示回切状态,曾经迁移过,4 未迁移。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Migrate")] public long? Migrate{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "QueueId", this.QueueId); this.SetParamSimple(map, prefix + "RewindSeconds", this.RewindSeconds); this.SetParamSimple(map, prefix + "CreateUin", this.CreateUin); this.SetParamSimple(map, prefix + "LastModifyTime", this.LastModifyTime); this.SetParamSimple(map, prefix + "VisibilityTimeout", this.VisibilityTimeout); this.SetParamSimple(map, prefix + "QueueName", this.QueueName); this.SetParamSimple(map, prefix + "Trace", this.Trace); this.SetParamArrayObj(map, prefix + "Tags.", this.Tags); this.SetParamSimple(map, prefix + "RewindMsgNum", this.RewindMsgNum); this.SetParamSimple(map, prefix + "MaxDelaySeconds", this.MaxDelaySeconds); this.SetParamObj(map, prefix + "TransactionPolicy.", this.TransactionPolicy); this.SetParamSimple(map, prefix + "MsgRetentionSeconds", this.MsgRetentionSeconds); this.SetParamSimple(map, prefix + "DelayMsgNum", this.DelayMsgNum); this.SetParamSimple(map, prefix + "MaxMsgHeapNum", this.MaxMsgHeapNum); this.SetParamSimple(map, prefix + "PollingWaitSeconds", this.PollingWaitSeconds); this.SetParamSimple(map, prefix + "Bps", this.Bps); this.SetParamSimple(map, prefix + "InactiveMsgNum", this.InactiveMsgNum); this.SetParamObj(map, prefix + "DeadLetterPolicy.", this.DeadLetterPolicy); this.SetParamSimple(map, prefix + "ActiveMsgNum", this.ActiveMsgNum); this.SetParamSimple(map, prefix + "MaxMsgSize", this.MaxMsgSize); this.SetParamSimple(map, prefix + "MinMsgTime", this.MinMsgTime); this.SetParamArrayObj(map, prefix + "DeadLetterSource.", this.DeadLetterSource); this.SetParamSimple(map, prefix + "Transaction", this.Transaction); this.SetParamSimple(map, prefix + "Qps", this.Qps); this.SetParamSimple(map, prefix + "CreateTime", this.CreateTime); this.SetParamSimple(map, prefix + "Migrate", this.Migrate); } } }
35.308642
128
0.577156
[ "Apache-2.0" ]
tencentcloudapi-test/tencentcloud-sdk-dotnet
TencentCloud/Cmq/V20190304/Models/QueueSet.cs
10,516
C#
using System; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that indicate the type of type(?). /// </summary> public class IsTypeFunction : PatternFunction { internal const string FnName = "is-type"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { TypeDef type = definition as TypeDef; if (type == null) return false; string typeType = Arguments[0].Evaluate(definition).ToString(); if (type.IsEnum) return StringComparer.OrdinalIgnoreCase.Compare(typeType, "enum") == 0; if (type.IsInterface) return StringComparer.OrdinalIgnoreCase.Compare(typeType, "interface") == 0; if (type.IsValueType) return StringComparer.OrdinalIgnoreCase.Compare(typeType, "valuetype") == 0; if (type.IsDelegate()) return StringComparer.OrdinalIgnoreCase.Compare(typeType, "delegate") == 0; if (type.IsAbstract) return StringComparer.OrdinalIgnoreCase.Compare(typeType, "abstract") == 0; return false; } } }
25.617021
80
0.690199
[ "MIT" ]
AgileJoshua/ConfuserEx
Confuser.Core/Project/Patterns/IsTypeFunction.cs
1,206
C#
/* * Copyright (c) Contributors, http://virtual-planets.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * 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 Virtual Universe Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // PriorityQueue.cs // // Jim Mischel using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Universe.Framework.ConsoleFramework; namespace Universe.Framework.Utilities { //A priority queue from http://www.devsource.com/c/a/Languages/A-Priority-Queue-Implementation-in-C/ // Writen by Jim Mischel [Serializable] [ComVisible (false)] public struct PriorityQueueItem<TValue, TPriority> { public TPriority _priority; TValue _value; public PriorityQueueItem (TValue val, TPriority pri) { _value = val; _priority = pri; } public TValue Value { get { return _value; } set { _value = value; } } public TPriority Priority { get { return _priority; } set { _priority = value; } } } [Serializable] [ComVisible (false)] public class PriorityQueue<TValue, TPriority> : ICollection, IEnumerable<PriorityQueueItem<TValue, TPriority>> { const int DefaultCapacity = 16; int capacity; Comparison<TPriority> compareFunc; PriorityQueueItem<TValue, TPriority> [] items; int numItems; /// <summary> /// Initializes a new instance of the PriorityQueue class that is empty, /// has the default initial capacity, and uses the default IComparer. /// </summary> public PriorityQueue () : this (DefaultCapacity, Comparer<TPriority>.Default) { } public PriorityQueue (int initialCapacity) : this (initialCapacity, Comparer<TPriority>.Default) { } public PriorityQueue (IComparer<TPriority> comparer) : this (DefaultCapacity, comparer) { } public PriorityQueue (int initialCapacity, IComparer<TPriority> comparer) { Init (initialCapacity, comparer.Compare); } public PriorityQueue (Comparison<TPriority> comparison) : this (DefaultCapacity, comparison) { } public PriorityQueue (int initialCapacity, Comparison<TPriority> comparison) { Init (initialCapacity, comparison); } public PriorityQueueItem<TValue, TPriority> [] Items { get { return items; } } public int Capacity { get { return items.Length; } set { SetCapacity (value); } } #region ICollection Members public int Count { get { return numItems; } } public void CopyTo (Array array, int index) { CopyTo ((PriorityQueueItem<TValue, TPriority> [])array, index); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return items.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } #endregion #region IEnumerable<PriorityQueueItem<TValue,TPriority>> Members public IEnumerator<PriorityQueueItem<TValue, TPriority>> GetEnumerator () { for (int i = 0; i < numItems; i++) { yield return items [i]; } } #endregion void Init (int initialCapacity, Comparison<TPriority> comparison) { numItems = 0; compareFunc = comparison; SetCapacity (initialCapacity); } void SetCapacity (int newCapacity) { int newCap = newCapacity; if (newCap < DefaultCapacity) newCap = DefaultCapacity; // throw exception if newCapacity < NumItems if (newCap < numItems) { MainConsole.Instance.Warn ("[Priority Queue]: New capacity is less than Count"); return; } capacity = newCap; if (items == null) { items = new PriorityQueueItem<TValue, TPriority> [newCap]; return; } // Resize the array. Array.Resize (ref items, newCap); } public void Enqueue (PriorityQueueItem<TValue, TPriority> newItem) { if (numItems == capacity) { // need to increase capacity // grow by 50 percent SetCapacity ((3 * Capacity) / 2); } int i = numItems; ++numItems; while ((i > 0) && (compareFunc (items [(i - 1) / 2].Priority, newItem.Priority) < 0)) { items [i] = items [(i - 1) / 2]; i = (i - 1) / 2; } items [i] = newItem; //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} } public void Enqueue (TValue value, TPriority priority) { Enqueue (new PriorityQueueItem<TValue, TPriority> (value, priority)); } PriorityQueueItem<TValue, TPriority> RemoveAt (int index) { PriorityQueueItem<TValue, TPriority> o = items [index]; --numItems; // move the last item to fill the hole PriorityQueueItem<TValue, TPriority> tmp = items [numItems]; // If you forget to clear this, you have a potential memory leak. items [numItems] = default (PriorityQueueItem<TValue, TPriority>); if (numItems > 0 && index != numItems) { // If the new item is greater than its parent, bubble up. int i = index; int parent = (i - 1) / 2; while (compareFunc (tmp.Priority, items [parent].Priority) > 0) { items [i] = items [parent]; i = parent; parent = (i - 1) / 2; } // if i == index, then we didn't move the item up if (i == index) { // bubble down ... while (i < (numItems) / 2) { int j = (2 * i) + 1; if ((j < numItems - 1) && (compareFunc (items [j].Priority, items [j + 1].Priority) < 0)) { ++j; } if (compareFunc (items [j].Priority, tmp.Priority) <= 0) { break; } items [i] = items [j]; i = j; } } // Be sure to store the item in its place. items [i] = tmp; } //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} return o; } // Function to check that the queue is coherent. public bool VerifyQueue () { int i = 0; while (i < numItems / 2) { int leftChild = (2 * i) + 1; int rightChild = leftChild + 1; if (compareFunc (items [i].Priority, items [leftChild].Priority) < 0) { return false; } if (rightChild < numItems && compareFunc (items [i].Priority, items [rightChild].Priority) < 0) { return false; } ++i; } return true; } public PriorityQueueItem<TValue, TPriority> Dequeue () { if (Count == 0) MainConsole.Instance.Warn ("[Priority Queue]: The queue is empty"); return RemoveAt (0); } public bool TryDequeue (out PriorityQueueItem<TValue, TPriority> value) { value = new PriorityQueueItem<TValue, TPriority> (); if (Count == 0) return false; value = RemoveAt (0); return true; } /// <summary> /// Removes the item with the specified value from the queue. /// The passed equality comparison is used. /// </summary> /// <param name="item">The item to be removed.</param> /// <param name="comparer"> /// An object that implements the IEqualityComparer interface /// for the type of item in the collection. /// </param> public void Remove (TValue item, IEqualityComparer comparer) { // need to find the PriorityQueueItem that has the Data value of o for (int index = 0; index < numItems; ++index) { if (comparer.Equals (item, items [index].Value)) { RemoveAt (index); return; } } MainConsole.Instance.Warn ("[Priority Queue]: The specified item is not in the queue."); } /// <summary> /// Removes the item with the specified value from the queue. /// The passed equality comparison is used. /// </summary> /// <param name="item">The item to be removed.</param> /// <param name="comparer"> /// An object that implements the IComparer interface /// for the type of item in the collection. /// </param> public TValue Find (TValue item, IComparer<TValue> comparer) { // need to find the PriorityQueueItem that has the Data value of o for (int index = 0; index < numItems; ++index) { if (comparer.Compare (item, items [index].Value) > 1) { return items [index].Value; } } return default (TValue); } /// <summary> /// Removes the item with the specified value from the queue. /// The default type comparison function is used. /// </summary> /// <param name="item">The item to be removed.</param> public void Remove (TValue item) { Remove (item, EqualityComparer<TValue>.Default); } public PriorityQueueItem<TValue, TPriority> Peek () { if (Count == 0) MainConsole.Instance.Warn ("[Priority Queue]: The queue is empty"); return items [0]; } // Clear public void Clear () { for (int i = 0; i < numItems; ++i) { items [i] = default (PriorityQueueItem<TValue, TPriority>); } numItems = 0; TrimExcess (); } /// <summary> /// Set the capacity to the actual number of items, if the current /// number of items is less than 90 percent of the current capacity. /// </summary> public void TrimExcess () { if (numItems < (float)0.9 * capacity) { SetCapacity (numItems); } } // Contains public bool Contains (TValue o) { return items.Any (x => x.Value.Equals (o)); } public void CopyTo (PriorityQueueItem<TValue, TPriority> [] array, int arrayIndex) { if (array == null) { MainConsole.Instance.Error ("[Priority Queue]: Array is null"); return; } if (arrayIndex < 0) { MainConsole.Instance.Error ("[Priority Queue]: arrayIndex is less than 0."); return; } if (array.Rank > 1) { MainConsole.Instance.Error ("[Priority Queue]: array is multidimensional."); return; } if (numItems == 0) return; if (arrayIndex >= array.Length) { MainConsole.Instance.Error ("[Priority Queue]: ArrayIndex is equal to or greater than the length of the array."); return; } if (numItems > (array.Length - arrayIndex)) { MainConsole.Instance.Error ("[Priority Queue]: " + " The number of elements in the source ICollection is greater than the available space" + " from arrayIndex to the end of the destination array."); return; } for (int i = 0; i < numItems; i++) { array [arrayIndex + i] = items [i]; } } } #region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion /// <summary> /// Represents the priority queue data structure. /// </summary> public class LPriorityQueue : ICollection { #region Fields // The maximum level of the skip list. const int LevelMaxValue = 16; // The probability value used to randomly select the next level value. const double Probability = 0.5; readonly IComparer comparer; // The current level of the skip list. // Used to generate node levels. readonly Random rand = new Random (); // The number of elements in the PriorityQueue. int count; int currentLevel = 1; // The header node of the skip list. Node header = new Node (null, LevelMaxValue); // The version of this PriorityQueue. long version; // Used for comparing and sorting elements. #endregion #region Construction /// <summary> /// Initializes a new instance of the PriorityQueue class. /// </summary> /// <remarks> /// The PriorityQueue will cast its elements to the IComparable /// interface when making comparisons. /// </remarks> public LPriorityQueue () { comparer = new DefaultComparer (); } /// <summary> /// Initializes a new instance of the PriorityQueue class with the /// specified IComparer. /// </summary> /// <param name="comparer"> /// The IComparer to use for comparing and ordering elements. /// </param> /// <remarks> /// If the specified IComparer is null, the PriorityQueue will cast its /// elements to the IComparable interface when making comparisons. /// </remarks> public LPriorityQueue (IComparer comparer) { // If no comparer was provided. if (comparer == null) { // Use the DefaultComparer. this.comparer = new DefaultComparer (); } // Else a comparer was provided. else { // Use the provided comparer. this.comparer = comparer; } } #endregion #region Methods /// <summary> /// Enqueues the specified element into the PriorityQueue. /// </summary> /// <param name="element"> /// The element to enqueue into the PriorityQueue. /// </param> /// <exception cref="ArgumentNullException"> /// If element is null. /// </exception> public virtual void Enqueue (object element) { #region Require if (element == null) { throw new ArgumentNullException ("element"); } #endregion Node x = header; Node [] update = new Node [LevelMaxValue]; int nextLevel = NextLevel (); // Find the place in the queue to insert the new element. for (int i = currentLevel - 1; i >= 0; i--) { while (x [i] != null && comparer.Compare (x [i].Element, element) > 0) { x = x [i]; } update [i] = x; } // If the new node's level is greater than the current level. if (nextLevel > currentLevel) { for (int i = currentLevel; i < nextLevel; i++) { update [i] = header; } // Update level. currentLevel = nextLevel; } // Create new node. Node newNode = new Node (element, nextLevel); // Insert the new node into the list. for (int i = 0; i < nextLevel; i++) { newNode [i] = update [i] [i]; update [i] [i] = newNode; } // Keep track of the number of elements in the PriorityQueue. count++; version++; } /// <summary> /// Removes the element at the head of the PriorityQueue. /// </summary> /// <returns> /// The element at the head of the PriorityQueue. /// </returns> /// <exception cref="InvalidOperationException"> /// If Count is zero. /// </exception> public virtual object Dequeue () { #region Require if (Count == 0) { throw new InvalidOperationException ( "Cannot dequeue into an empty PriorityQueue."); } #endregion // Get the first item in the queue. object element = header [0].Element; // Keep track of the node that is about to be removed. Node oldNode = header [0]; // Update the header so that its pointers that pointed to the // node to be removed now point to the node that comes after it. for (int i = 0; i < currentLevel && header [i] == oldNode; i++) { header [i] = oldNode [i]; } // Update the current level of the list in case the node that // was removed had the highest level. while (currentLevel > 1 && header [currentLevel - 1] == null) { currentLevel--; } // Keep track of how many items are in the queue. count--; version++; return element; } /// <summary> /// Removes the specified element from the PriorityQueue. /// </summary> /// <param name="element"> /// The element to remove. /// </param> /// <exception cref="ArgumentNullException"> /// If element is null /// </exception> public virtual void Remove (object element) { #region Require if (element == null) { MainConsole.Instance.Error ("[Priority Queue]: Element is null"); return; } #endregion Node x = header; Node [] update = new Node [LevelMaxValue]; // Find the specified element. for (int i = currentLevel - 1; i >= 0; i--) { while (x [i] != null && comparer.Compare (x [i].Element, element) > 0) { x = x [i]; } update [i] = x; } x = x [0]; // If the specified element was found. if (x != null && comparer.Compare (x.Element, element) == 0) { // Remove element. for (int i = 0; i < currentLevel && update [i] [i] == x; i++) { update [i] [i] = x [i]; } // Update list level. while (currentLevel > 1 && header [currentLevel - 1] == null) { currentLevel--; } // Keep track of the number of elements in the PriorityQueue. count--; version++; } } /// <summary> /// Returns a value indicating whether the specified element is in the /// PriorityQueue. /// </summary> /// <param name="element"> /// The element to test. /// </param> /// <returns> /// <b>true</b> if the element is in the PriorityQueue; otherwise /// <b>false</b>. /// </returns> public virtual bool Contains (object element) { #region Guard if (element == null) { return false; } #endregion bool found; Node x = header; // Find the specified element. for (int i = currentLevel - 1; i >= 0; i--) { while (x [i] != null && comparer.Compare (x [i].Element, element) > 0) { x = x [i]; } } x = x [0]; // If the element is in the PriorityQueue. if (x != null && comparer.Compare (x.Element, element) == 0) { found = true; } // Else the element is not in the PriorityQueue. else { found = false; } return found; } /// <summary> /// Returns the element at the head of the PriorityQueue without /// removing it. /// </summary> /// <returns> /// The element at the head of the PriorityQueue. /// </returns> public virtual object Peek () { #region Require if (Count == 0) { MainConsole.Instance.Warn ("[Priority Queue]: Cannot peek into an empty PriorityQueue."); return new object (); } #endregion return header [0].Element; } /// <summary> /// Removes all elements from the PriorityQueue. /// </summary> public virtual void Clear () { header = new Node (null, LevelMaxValue); currentLevel = 1; count = 0; version++; } /// <summary> /// Returns a synchronized wrapper of the specified PriorityQueue. /// </summary> /// <param name="queue"> /// The PriorityQueue to synchronize. /// </param> /// <returns> /// A synchronized PriorityQueue. /// </returns> /// <exception cref="ArgumentNullException"> /// If queue is null. /// </exception> public static LPriorityQueue Synchronized (LPriorityQueue queue) { #region Require if (queue == null) { MainConsole.Instance.Warn ("[Priority Queue]: Queue is null"); return null; } #endregion return new SynchronizedPriorityQueue (queue); } // Generates a random level for the next node. int NextLevel () { int nextLevel = 1; while (rand.NextDouble () < Probability && nextLevel < LevelMaxValue && nextLevel <= currentLevel) { nextLevel++; } return nextLevel; } #endregion #region Private Classes #region SynchronizedPriorityQueue Class // A synchronized wrapper for the PriorityQueue class. class SynchronizedPriorityQueue : LPriorityQueue { readonly LPriorityQueue queue; readonly object root; public SynchronizedPriorityQueue (LPriorityQueue queue) { #region Require if (queue == null) { MainConsole.Instance.Error ("[Priority Queue]: Queue is null"); return; } #endregion this.queue = queue; root = queue.SyncRoot; } public override int Count { get { lock (root) { return queue.Count; } } } public override bool IsSynchronized { get { return true; } } public override object SyncRoot { get { return root; } } public override void Enqueue (object element) { lock (root) { queue.Enqueue (element); } } public override object Dequeue () { lock (root) { return queue.Dequeue (); } } public override void Remove (object element) { lock (root) { queue.Remove (element); } } public override void Clear () { lock (root) { queue.Clear (); } } public override bool Contains (object element) { lock (root) { return queue.Contains (element); } } public override object Peek () { lock (root) { return queue.Peek (); } } public override void CopyTo (Array array, int index) { lock (root) { queue.CopyTo (array, index); } } public override IEnumerator GetEnumerator () { lock (root) { return queue.GetEnumerator (); } } } #endregion #region DefaultComparer Class // The IComparer to use of no comparer was provided. class DefaultComparer : IComparer { #region IComparer Members public int Compare (object x, object y) { #region Require if (!(y is IComparable)) { throw new ArgumentException ( "Item does not implement IComparable."); } #endregion IComparable a = x as IComparable; return a.CompareTo (y); } #endregion } #endregion #region Node Class // Represents a node in the list of nodes. class Node { readonly object element; readonly Node [] forward; public Node (object nodeEelement, int level) { forward = new Node [level]; element = nodeEelement; } public Node this [int index] { get { return forward [index]; } set { forward [index] = value; } } public object Element { get { return element; } } } #endregion #region PriorityQueueEnumerator Class // Implements the IEnumerator interface for the PriorityQueue class. class PriorityQueueEnumerator : IEnumerator { readonly Node head; readonly LPriorityQueue owner; readonly long version; Node currentNode; bool moveResult; public PriorityQueueEnumerator (LPriorityQueue pqOwner) { owner = pqOwner; version = pqOwner.version; head = pqOwner.header; Reset (); } #region IEnumerator Members public void Reset () { #region Require if (version != owner.version) { MainConsole.Instance.Error ("[Priority Queue]: " + "The PriorityQueue was modified after the enumerator was created."); moveResult = false; return; } #endregion currentNode = head; moveResult = true; } public object Current { get { #region Require if (currentNode == head || currentNode == null) { throw new InvalidOperationException ( "The enumerator is positioned before the first " + "element of the collection or after the last element."); } #endregion return currentNode.Element; } } public bool MoveNext () { #region Require if (version != owner.version) { MainConsole.Instance.Warn ("[Priority Queue]: The PriorityQueue was modified after the enumerator was created."); return false; } #endregion if (moveResult) { currentNode = currentNode [0]; } if (currentNode == null) { moveResult = false; } return moveResult; } #endregion } #endregion #endregion #region ICollection Members public virtual bool IsSynchronized { get { return false; } } public virtual int Count { get { return count; } } public virtual void CopyTo (Array array, int index) { #region Require if (array == null) { MainConsole.Instance.Warn ("[Priority Queue]: Array is null"); return; } if (index < 0) { MainConsole.Instance.WarnFormat ("[Priority Queue]: Array index '{0}' is out of range.", index); return; } if (array.Rank > 1) { MainConsole.Instance.WarnFormat ("[Priority Queue]: Array '{0}' has more than one dimension.", array); return; } if (index >= array.Length) { MainConsole.Instance.WarnFormat ("[Priority Queue]: index '{0}' is equal to or greater than the length of array.", index); return; } if (Count > array.Length - index) { MainConsole.Instance.WarnFormat ("[Priority Queue]: The number of elements in the PriorityQueue is greater " + "than the available space from index '{0}' to the end of the " + "destination array.", "index"); return; } #endregion int i = index; foreach (object element in this) { array.SetValue (element, i); i++; } } public virtual object SyncRoot { get { return this; } } public virtual IEnumerator GetEnumerator () { return new PriorityQueueEnumerator (this); } #endregion } }
32.114234
139
0.479787
[ "MIT" ]
johnfelipe/Virtual-Universe
Universe/Framework/Utilities/PriorityQueue.cs
35,422
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Add a collaborate bridge to a group. /// The domain is required in the serviceUserId. /// The request fails when supportOutdial is enabled and the system-level collaborate supportOutdial setting is disabled. /// If the phoneNumber has not been assigned to the group and addPhoneNumberToGroup is set to true, /// it will be added to group if the command is executed by a service provider administrator or above /// and the number is already assigned to the service provider. The command will fail otherwise. /// /// The response is either SuccessResponse or ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""939fd5846dfae8bdf58308d6cb9ebb12:103""}]")] public class GroupCollaborateBridgeConsolidatedAddInstanceRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private string _groupId; [XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinLength(1)] [MaxLength(30)] public string GroupId { get => _groupId; set { GroupIdSpecified = true; _groupId = value; } } [XmlIgnore] protected bool GroupIdSpecified { get; set; } private string _serviceUserId; [XmlElement(ElementName = "serviceUserId", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinLength(1)] [MaxLength(161)] public string ServiceUserId { get => _serviceUserId; set { ServiceUserIdSpecified = true; _serviceUserId = value; } } [XmlIgnore] protected bool ServiceUserIdSpecified { get; set; } private bool _addPhoneNumberToGroup; [XmlElement(ElementName = "addPhoneNumberToGroup", IsNullable = false, Namespace = "")] [Optional] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] public bool AddPhoneNumberToGroup { get => _addPhoneNumberToGroup; set { AddPhoneNumberToGroupSpecified = true; _addPhoneNumberToGroup = value; } } [XmlIgnore] protected bool AddPhoneNumberToGroupSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceInstanceAddProfile _serviceInstanceProfile; [XmlElement(ElementName = "serviceInstanceProfile", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] public BroadWorksConnector.Ocip.Models.ServiceInstanceAddProfile ServiceInstanceProfile { get => _serviceInstanceProfile; set { ServiceInstanceProfileSpecified = true; _serviceInstanceProfile = value; } } [XmlIgnore] protected bool ServiceInstanceProfileSpecified { get; set; } private BroadWorksConnector.Ocip.Models.CollaborateBridgeMaximumParticipants _maximumBridgeParticipants; [XmlElement(ElementName = "maximumBridgeParticipants", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] public BroadWorksConnector.Ocip.Models.CollaborateBridgeMaximumParticipants MaximumBridgeParticipants { get => _maximumBridgeParticipants; set { MaximumBridgeParticipantsSpecified = true; _maximumBridgeParticipants = value; } } [XmlIgnore] protected bool MaximumBridgeParticipantsSpecified { get; set; } private string _networkClassOfService; [XmlElement(ElementName = "networkClassOfService", IsNullable = false, Namespace = "")] [Optional] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinLength(1)] [MaxLength(40)] public string NetworkClassOfService { get => _networkClassOfService; set { NetworkClassOfServiceSpecified = true; _networkClassOfService = value; } } [XmlIgnore] protected bool NetworkClassOfServiceSpecified { get; set; } private int _maxCollaborateRoomParticipants; [XmlElement(ElementName = "maxCollaborateRoomParticipants", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinInclusive(3)] [MaxInclusive(145)] public int MaxCollaborateRoomParticipants { get => _maxCollaborateRoomParticipants; set { MaxCollaborateRoomParticipantsSpecified = true; _maxCollaborateRoomParticipants = value; } } [XmlIgnore] protected bool MaxCollaborateRoomParticipantsSpecified { get; set; } private bool _supportOutdial; [XmlElement(ElementName = "supportOutdial", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] public bool SupportOutdial { get => _supportOutdial; set { SupportOutdialSpecified = true; _supportOutdial = value; } } [XmlIgnore] protected bool SupportOutdialSpecified { get; set; } private List<string> _collaborateOwnerUserId = new List<string>(); [XmlElement(ElementName = "collaborateOwnerUserId", IsNullable = false, Namespace = "")] [Optional] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] [MinLength(1)] [MaxLength(161)] public List<string> CollaborateOwnerUserId { get => _collaborateOwnerUserId; set { CollaborateOwnerUserIdSpecified = true; _collaborateOwnerUserId = value; } } [XmlIgnore] protected bool CollaborateOwnerUserIdSpecified { get; set; } private List<BroadWorksConnector.Ocip.Models.ConsolidatedUserServiceAssignment> _service = new List<BroadWorksConnector.Ocip.Models.ConsolidatedUserServiceAssignment>(); [XmlElement(ElementName = "service", IsNullable = false, Namespace = "")] [Optional] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:103")] public List<BroadWorksConnector.Ocip.Models.ConsolidatedUserServiceAssignment> Service { get => _service; set { ServiceSpecified = true; _service = value; } } [XmlIgnore] protected bool ServiceSpecified { get; set; } } }
33.639485
177
0.611763
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupCollaborateBridgeConsolidatedAddInstanceRequest.cs
7,838
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace DataWF.Test.Web.Service { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
25.72
77
0.66874
[ "MIT" ]
alexandrvslv/datawf
DataWF.Test.Web.Service/Program.cs
645
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable UnusedMember.Global // ReSharper disable UnusedType.Global /* NopCommand.cs -- * Ars Magna project, http://arsmagna.ru */ #region Using directives #endregion #nullable enable namespace ManagedIrbis.Mx.Commands { /// <summary> /// /// </summary> public sealed class NopCommand : MxCommand { #region Construction /// <summary> /// Constructor. /// </summary> public NopCommand() : base("Nop") { } #endregion #region MxCommand members /// <inheritdoc cref="MxCommand.Execute" /> public override bool Execute ( MxExecutive executive, MxArgument[] arguments ) { OnBeforeExecute(); executive.WriteMessage("Nop"); OnAfterExecute(); return true; } #endregion } }
19.967213
84
0.573071
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Libs/ManagedIrbis5/Source/Mx/Commands/NopCommand.cs
1,220
C#
using System; namespace Game.Pong { internal class Ball : GameElement, IBall { private readonly IGameField _gameField; private int _x; private int _y; private int _impulsX; private int _impulsY; private int _oldX; private int _oldY; public Ball(IGameField gameField, int x, int y, string symbol = "B") { _gameField = gameField; _impulsX = 1; _impulsY = 1; _x = x; _oldX = x; _y = y; _oldY = y; Symbol = symbol; } public override int X { get => _x; set => _x += (_x - value) * _impulsX; } public override int Y { get => _y; set { if (value <= _gameField.GetStartYPosition()) { _impulsY = -_impulsY; } else if (value >= _gameField.GetStartYPosition() + _gameField.GetHeight()) { _impulsY = -_impulsY; } _y += (_y - value) * _impulsY; } } /// <inheritdoc /> public override void Draw() { X++; Y++; Console.SetCursorPosition(_oldX, _oldY); Console.WriteLine(" "); Console.SetCursorPosition(X, Y); Console.WriteLine(Symbol); _oldX = X; _oldY = Y; } /// <inheritdoc cref="IBall" /> public bool DetectHit(GameElement gameElement) { for (var i = 0; i < gameElement.Size; i++) { if (_x == gameElement.X && _y == gameElement.Y + i) { return true; } } return false; } /// <inheritdoc /> public bool DetectDeparture() { return _x < _gameField.GetStartXPosition() || _x == _gameField.GetStartXPosition() + _gameField.GetWidth(); } /// <inheritdoc /> public void Bounce() { _impulsX = -_impulsX; } } }
15.757282
78
0.586568
[ "MIT" ]
AstreyRize/Game.Pong
Ball.cs
1,625
C#
// Copyright 2012 Max Toro Q. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.Web.WebPages; namespace MvcPages { public abstract class MvcViewPage<TModel> : WebViewPage<TModel> { protected override void ConfigurePage(WebPageBase parentPage) { MvcViewPage.CopyParentState(this, parentPage); } } }
31.032258
75
0.739085
[ "Apache-2.0" ]
maxtoroq/MvcPages
src/MvcPages/MvcViewPage`1.cs
964
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; namespace Amazon.PowerShell.Cmdlets.KMS { /// <summary> /// Creates a display name for a customer managed customer master key (CMK). You can use /// an alias to identify a CMK in cryptographic operations, such as <a>Encrypt</a> and /// <a>GenerateDataKey</a>. You can change the CMK associated with the alias at any time. /// /// /// <para> /// Aliases are easier to remember than key IDs. They can also help to simplify your applications. /// For example, if you use an alias in your code, you can change the CMK your code uses /// by associating a given alias with a different CMK. /// </para><para> /// To run the same code in multiple AWS regions, use an alias in your code, such as <code>alias/ApplicationKey</code>. /// Then, in each AWS Region, create an <code>alias/ApplicationKey</code> alias that is /// associated with a CMK in that Region. When you run your code, it uses the <code>alias/ApplicationKey</code> /// CMK for that AWS Region without any Region-specific code. /// </para><para> /// This operation does not return a response. To get the alias that you created, use /// the <a>ListAliases</a> operation. /// </para><para> /// To use aliases successfully, be aware of the following information. /// </para><ul><li><para> /// Each alias points to only one CMK at a time, although a single CMK can have multiple /// aliases. The alias and its associated CMK must be in the same AWS account and Region. /// /// </para></li><li><para> /// You can associate an alias with any customer managed CMK in the same AWS account and /// Region. However, you do not have permission to associate an alias with an <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk">AWS /// managed CMK</a> or an <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-owned-cmk">AWS /// owned CMK</a>. /// </para></li><li><para> /// To change the CMK associated with an alias, use the <a>UpdateAlias</a> operation. /// The current CMK and the new CMK must be the same type (both symmetric or both asymmetric) /// and they must have the same key usage (<code>ENCRYPT_DECRYPT</code> or <code>SIGN_VERIFY</code>). /// This restriction prevents cryptographic errors in code that uses aliases. /// </para></li><li><para> /// The alias name must begin with <code>alias/</code> followed by a name, such as <code>alias/ExampleAlias</code>. /// It can contain only alphanumeric characters, forward slashes (/), underscores (_), /// and dashes (-). The alias name cannot begin with <code>alias/aws/</code>. The <code>alias/aws/</code> /// prefix is reserved for <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk">AWS /// managed CMKs</a>. /// </para></li><li><para> /// The alias name must be unique within an AWS Region. However, you can use the same /// alias name in multiple Regions of the same AWS account. Each instance of the alias /// is associated with a CMK in its Region. /// </para></li><li><para> /// After you create an alias, you cannot change its alias name. However, you can use /// the <a>DeleteAlias</a> operation to delete the alias and then create a new alias with /// the desired name. /// </para></li><li><para> /// You can use an alias name or alias ARN to identify a CMK in AWS KMS cryptographic /// operations and in the <a>DescribeKey</a> operation. However, you cannot use alias /// names or alias ARNs in API operations that manage CMKs, such as <a>DisableKey</a> /// or <a>GetKeyPolicy</a>. For information about the valid CMK identifiers for each AWS /// KMS API operation, see the descriptions of the <code>KeyId</code> parameter in the /// API operation documentation. /// </para></li></ul><para> /// Because an alias is not a property of a CMK, you can delete and change the aliases /// of a CMK without affecting the CMK. Also, aliases do not appear in the response from /// the <a>DescribeKey</a> operation. To get the aliases and alias ARNs of CMKs in each /// AWS account and Region, use the <a>ListAliases</a> operation. /// </para><para> /// The CMK that you use for this operation must be in a compatible key state. For details, /// see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">How /// Key State Affects Use of a Customer Master Key</a> in the <i>AWS Key Management Service /// Developer Guide</i>. /// </para> /// </summary> [Cmdlet("New", "KMSAlias", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS Key Management Service CreateAlias API operation.", Operation = new[] {"CreateAlias"}, SelectReturnType = typeof(Amazon.KeyManagementService.Model.CreateAliasResponse))] [AWSCmdletOutput("None or Amazon.KeyManagementService.Model.CreateAliasResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.KeyManagementService.Model.CreateAliasResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class NewKMSAliasCmdlet : AmazonKeyManagementServiceClientCmdlet, IExecutor { #region Parameter AliasName /// <summary> /// <para> /// <para>Specifies the alias name. This value must begin with <code>alias/</code> followed /// by a name, such as <code>alias/ExampleAlias</code>. The alias name cannot begin with /// <code>alias/aws/</code>. The <code>alias/aws/</code> prefix is reserved for AWS managed /// CMKs.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AliasName { get; set; } #endregion #region Parameter TargetKeyId /// <summary> /// <para> /// <para>Identifies the CMK to which the alias refers. Specify the key ID or the Amazon Resource /// Name (ARN) of the CMK. You cannot specify another alias. For help finding the key /// ID and ARN, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html#find-cmk-id-arn">Finding /// the Key ID and ARN</a> in the <i>AWS Key Management Service Developer Guide</i>.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String TargetKeyId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.KeyManagementService.Model.CreateAliasResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the TargetKeyId parameter. /// The -PassThru parameter is deprecated, use -Select '^TargetKeyId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^TargetKeyId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.TargetKeyId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-KMSAlias (CreateAlias)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.KeyManagementService.Model.CreateAliasResponse, NewKMSAliasCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.TargetKeyId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AliasName = this.AliasName; #if MODULAR if (this.AliasName == null && ParameterWasBound(nameof(this.AliasName))) { WriteWarning("You are passing $null as a value for parameter AliasName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.TargetKeyId = this.TargetKeyId; #if MODULAR if (this.TargetKeyId == null && ParameterWasBound(nameof(this.TargetKeyId))) { WriteWarning("You are passing $null as a value for parameter TargetKeyId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.KeyManagementService.Model.CreateAliasRequest(); if (cmdletContext.AliasName != null) { request.AliasName = cmdletContext.AliasName; } if (cmdletContext.TargetKeyId != null) { request.TargetKeyId = cmdletContext.TargetKeyId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.KeyManagementService.Model.CreateAliasResponse CallAWSServiceOperation(IAmazonKeyManagementService client, Amazon.KeyManagementService.Model.CreateAliasRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Key Management Service", "CreateAlias"); try { #if DESKTOP return client.CreateAlias(request); #elif CORECLR return client.CreateAliasAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AliasName { get; set; } public System.String TargetKeyId { get; set; } public System.Func<Amazon.KeyManagementService.Model.CreateAliasResponse, NewKMSAliasCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
51.200637
282
0.631648
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/KeyManagementService/Basic/New-KMSAlias-Cmdlet.cs
16,077
C#
namespace DataFactorySamples.Settings { public class TriggerSettings { public string ResourceGroupName { get;set;} public string FactoryName { get;set;} public string TriggerName { get;set;} } }
20.166667
51
0.636364
[ "MIT" ]
mvelosop/explore-azure-sdk
src/samples/DataFactorySamples/Settings/TriggerSettings.cs
244
C#
//Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements. using System; class MaximalSum { static void Main() { Console.Write("Enter N = "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter M = "); int m = int.Parse(Console.ReadLine()); int[,] matrix = new int[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write("Matrix[{0},{1}] = ", i, j); matrix[i, j] = int.Parse(Console.ReadLine()); } } int currSum = 0; int maxSum = 0; int maxX = 0; int maxY = 0; int p = 3; int q = 3; for (int i = 0; i < n - p + 1; i++) { for (int j = 0; j < m - q + 1; j++) { currSum = 0; for (int k = 0; k < p; k++) { for (int l = 0; l < q; l++) { currSum += matrix[i + k, j + l]; } } if (currSum > maxSum) { maxSum = currSum; maxX = i; maxY = j; } } } for (int i = 0; i < n; i++) { Console.WriteLine(); for (int j = 0; j < m; j++) { Console.Write(matrix[i, j] + " "); } } Console.WriteLine(); Console.WriteLine("Maximal sum is in window[{0},{1}-{2},{3}] in the array is: {4}", maxX, maxY, maxX + p - 1, maxY + q - 1, maxSum); } }
25.333333
140
0.363844
[ "MIT" ]
BiserSirakov/TelerikAcademyHomeworks
C# - Part 2/Multidimensional Arrays/02.MaximalSum/MaximalSum.cs
1,750
C#
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using Microsoft.Bot.Connector; using Newtonsoft.Json; namespace LuisDialog_Stock_Bot { [BotAuthentication] public class MessagesController : ApiController { /// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task<HttpResponseMessage> Post([FromBody]Activity activity) { if (activity.Type == ActivityTypes.Message) { await Microsoft.Bot.Builder.Dialogs.Conversation.SendAsync(activity, () => new StockLuisDlg.StockDialog()); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return response; } private Activity HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { } return null; } } }
33.238095
123
0.574499
[ "MIT" ]
Aaron-Strong/BotBuilder
CSharp/Samples/Stock_Bot/LuisDialog_Stock_Bot/Controllers/MessagesController.cs
2,096
C#
using alexbegh.vMerge.Model.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace alexbegh.vMerge.StudioIntegration.Framework { class vMergeUIProvider : IVMergeUIProvider { private vMergePackage vMergePackage { get; set; } public vMergeUIProvider(vMergePackage package) { vMergePackage = package; } public void FocusChangesetWindow() { vMergePackage.ShowChangesetView(); } public void FocusWorkItemWindow() { vMergePackage.ShowWorkItemView(); } public void FocusMergeWindow() { vMergePackage.ShowMergeView(); } public bool IsMergeWindowVisible() { return vMergePackage.MergeToolWindowIsVisible; } public event EventHandler MergeWindowVisibilityChanged { add { vMergePackage.MergeToolWindowVisibilityChanged += value; } remove { vMergePackage.MergeToolWindowVisibilityChanged -= value; } } } }
22.375
72
0.574621
[ "BSD-3-Clause" ]
ChristopherGe/vmerge
vMerge/StudioIntegration/Framework/vMergeUIProvider.cs
1,255
C#
using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Analysis { /* * 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> /// An <see cref="Analyzer"/> builds <see cref="Analysis.TokenStream"/>s, which analyze text. It thus represents a /// policy for extracting index terms from text. /// <para/> /// In order to define what analysis is done, subclasses must define their /// <see cref="TokenStreamComponents"/> in <see cref="CreateComponents(string, TextReader)"/>. /// The components are then reused in each call to <see cref="GetTokenStream(string, TextReader)"/>. /// <para/> /// Simple example: /// <code> /// Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }); /// </code> /// For more examples, see the <see cref="Lucene.Net.Analysis"/> namespace documentation. /// <para/> /// For some concrete implementations bundled with Lucene, look in the analysis modules: /// <list type="bullet"> /// <item><description>Common: /// Analyzers for indexing content in different languages and domains.</description></item> /// <item><description>ICU: /// Exposes functionality from ICU to Apache Lucene.</description></item> /// <item><description>Kuromoji: /// Morphological analyzer for Japanese text.</description></item> /// <item><description>Morfologik: /// Dictionary-driven lemmatization for the Polish language.</description></item> /// <item><description>Phonetic: /// Analysis for indexing phonetic signatures (for sounds-alike search).</description></item> /// <item><description>Smart Chinese: /// Analyzer for Simplified Chinese, which indexes words.</description></item> /// <item><description>Stempel: /// Algorithmic Stemmer for the Polish Language.</description></item> /// <item><description>UIMA: /// Analysis integration with Apache UIMA.</description></item> /// </list> /// </summary> public abstract class Analyzer : IDisposable { private readonly ReuseStrategy reuseStrategy; // non readonly as it gets nulled if closed; internal for access by ReuseStrategy's final helper methods: internal DisposableThreadLocal<object> storedValue = new DisposableThreadLocal<object>(); /// <summary> /// Create a new <see cref="Analyzer"/>, reusing the same set of components per-thread /// across calls to <see cref="GetTokenStream(string, TextReader)"/>. /// </summary> public Analyzer() : this(GLOBAL_REUSE_STRATEGY) { } /// <summary> /// Expert: create a new Analyzer with a custom <see cref="ReuseStrategy"/>. /// <para/> /// NOTE: if you just want to reuse on a per-field basis, its easier to /// use a subclass of <see cref="AnalyzerWrapper"/> such as /// <c>Lucene.Net.Analysis.Common.Miscellaneous.PerFieldAnalyzerWrapper</c> /// instead. /// </summary> public Analyzer(ReuseStrategy reuseStrategy) { this.reuseStrategy = reuseStrategy; } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents) { return NewAnonymous(createComponents, GLOBAL_REUSE_STRATEGY); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter and allows the use of a <see cref="ReuseStrategy"/>. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, reuseStrategy); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// An delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, ReuseStrategy reuseStrategy) { return NewAnonymous(createComponents, null, reuseStrategy); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter and the body of the <see cref="InitReader(string, TextReader)"/> /// method through the <paramref name="initReader"/> parameter. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, initReader: (fieldName, reader) => /// { /// return new HTMLStripCharFilter(reader); /// }); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader) { return NewAnonymous(createComponents, initReader, GLOBAL_REUSE_STRATEGY); } /// <summary> /// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/> /// method through the <paramref name="createComponents"/> parameter, the body of the <see cref="InitReader(string, TextReader)"/> /// method through the <paramref name="initReader"/> parameter, and allows the use of a <see cref="ReuseStrategy"/>. /// Simple example: /// <code> /// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => /// { /// Tokenizer source = new FooTokenizer(reader); /// TokenStream filter = new FooFilter(source); /// filter = new BarFilter(filter); /// return new TokenStreamComponents(source, filter); /// }, initReader: (fieldName, reader) => /// { /// return new HTMLStripCharFilter(reader); /// }, reuseStrategy); /// </code> /// <para/> /// LUCENENET specific /// </summary> /// <param name="createComponents"> /// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TokenStreamComponents"/> for this analyzer. /// </param> /// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/> /// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and /// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param> /// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param> /// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns> public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy) { return new AnonymousAnalyzer(createComponents, initReader, reuseStrategy); } /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance for this analyzer. /// </summary> /// <param name="fieldName"> /// the name of the fields content passed to the /// <see cref="TokenStreamComponents"/> sink as a reader </param> /// <param name="reader"> /// the reader passed to the <see cref="Tokenizer"/> constructor </param> /// <returns> the <see cref="TokenStreamComponents"/> for this analyzer. </returns> protected internal abstract TokenStreamComponents CreateComponents(string fieldName, TextReader reader); /// <summary> /// Returns a <see cref="TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing /// the contents of <c>text</c>. /// <para/> /// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an /// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the /// components and stores the components internally. Subsequent calls to this /// method will reuse the previously stored components after resetting them /// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>. /// <para/> /// <b>NOTE:</b> After calling this method, the consumer must follow the /// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents. /// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for /// some examples demonstrating this. /// </summary> /// <param name="fieldName"> the name of the field the created <see cref="Analysis.TokenStream"/> is used for </param> /// <param name="reader"> the reader the streams source reads from </param> /// <returns> <see cref="Analysis.TokenStream"/> for iterating the analyzed content of <see cref="TextReader"/> </returns> /// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception> /// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception> /// <seealso cref="GetTokenStream(string, string)"/> public TokenStream GetTokenStream(string fieldName, TextReader reader) { TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName); TextReader r = InitReader(fieldName, reader); if (components == null) { components = CreateComponents(fieldName, r); reuseStrategy.SetReusableComponents(this, fieldName, components); } else { components.SetReader(r); } return components.TokenStream; } /// <summary> /// Returns a <see cref="Analysis.TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing /// the contents of <paramref name="text"/>. /// <para/> /// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an /// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the /// components and stores the components internally. Subsequent calls to this /// method will reuse the previously stored components after resetting them /// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>. /// <para/> /// <b>NOTE:</b> After calling this method, the consumer must follow the /// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents. /// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for /// some examples demonstrating this. /// </summary> /// <param name="fieldName">the name of the field the created <see cref="Analysis.TokenStream"/> is used for</param> /// <param name="text">the <see cref="string"/> the streams source reads from </param> /// <returns><see cref="Analysis.TokenStream"/> for iterating the analyzed content of <c>reader</c></returns> /// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception> /// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception> /// <seealso cref="GetTokenStream(string, TextReader)"/> public TokenStream GetTokenStream(string fieldName, string text) { TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName); ReusableStringReader strReader = (components == null || components.reusableStringReader == null) ? new ReusableStringReader() : components.reusableStringReader; strReader.SetValue(text); var r = InitReader(fieldName, strReader); if (components == null) { components = CreateComponents(fieldName, r); reuseStrategy.SetReusableComponents(this, fieldName, components); } else { components.SetReader(r); } components.reusableStringReader = strReader; return components.TokenStream; } /// <summary> /// Override this if you want to add a <see cref="CharFilter"/> chain. /// <para/> /// The default implementation returns <paramref name="reader"/> /// unchanged. /// </summary> /// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed </param> /// <param name="reader"> original <see cref="TextReader"/> </param> /// <returns> reader, optionally decorated with <see cref="CharFilter"/>(s) </returns> protected internal virtual TextReader InitReader(string fieldName, TextReader reader) { return reader; } /// <summary> /// Invoked before indexing a <see cref="Index.IIndexableField"/> instance if /// terms have already been added to that field. This allows custom /// analyzers to place an automatic position increment gap between /// <see cref="Index.IIndexableField"/> instances using the same field name. The default value /// position increment gap is 0. With a 0 position increment gap and /// the typical default token position increment of 1, all terms in a field, /// including across <see cref="Index.IIndexableField"/> instances, are in successive positions, allowing /// exact <see cref="Search.PhraseQuery"/> matches, for instance, across <see cref="Index.IIndexableField"/> instance boundaries. /// </summary> /// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed. </param> /// <returns> position increment gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>. /// this value must be <c>&gt;= 0</c>.</returns> public virtual int GetPositionIncrementGap(string fieldName) { return 0; } /// <summary> /// Just like <see cref="GetPositionIncrementGap"/>, except for /// <see cref="Token"/> offsets instead. By default this returns 1. /// this method is only called if the field /// produced at least one token for indexing. /// </summary> /// <param name="fieldName"> the field just indexed </param> /// <returns> offset gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>. /// this value must be <c>&gt;= 0</c>. </returns> public virtual int GetOffsetGap(string fieldName) { return 1; } /// <summary> /// Returns the used <see cref="ReuseStrategy"/>. /// </summary> public ReuseStrategy Strategy => reuseStrategy; /// <summary> /// Frees persistent resources used by this <see cref="Analyzer"/> /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Frees persistent resources used by this <see cref="Analyzer"/> /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { if (storedValue != null) { storedValue.Dispose(); storedValue = null; } } } // LUCENENET specific - de-nested TokenStreamComponents and ReuseStrategy // so they don't need to be qualified when used outside of Analyzer subclasses. /// <summary> /// A predefined <see cref="ReuseStrategy"/> that reuses the same components for /// every field. /// </summary> public static readonly ReuseStrategy GLOBAL_REUSE_STRATEGY = #pragma warning disable 612, 618 new GlobalReuseStrategy(); #pragma warning restore 612, 618 /// <summary> /// Implementation of <see cref="ReuseStrategy"/> that reuses the same components for /// every field. </summary> [Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.GLOBAL_REUSE_STRATEGY instead!")] public sealed class GlobalReuseStrategy : ReuseStrategy { /// <summary> /// Sole constructor. (For invocation by subclass constructors, typically implicit.) </summary> [Obsolete("Don't create instances of this class, use Analyzer.GLOBAL_REUSE_STRATEGY")] public GlobalReuseStrategy() { } public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName) { return (TokenStreamComponents)GetStoredValue(analyzer); } public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components) { SetStoredValue(analyzer, components); } } /// <summary> /// A predefined <see cref="ReuseStrategy"/> that reuses components per-field by /// maintaining a Map of <see cref="TokenStreamComponents"/> per field name. /// </summary> public static readonly ReuseStrategy PER_FIELD_REUSE_STRATEGY = #pragma warning disable 612, 618 new PerFieldReuseStrategy(); #pragma warning restore 612, 618 /// <summary> /// Implementation of <see cref="ReuseStrategy"/> that reuses components per-field by /// maintaining a Map of <see cref="TokenStreamComponents"/> per field name. /// </summary> [Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.PER_FIELD_REUSE_STRATEGY instead!")] public class PerFieldReuseStrategy : ReuseStrategy { /// <summary> /// Sole constructor. (For invocation by subclass constructors, typically implicit.) /// </summary> [Obsolete("Don't create instances of this class, use Analyzer.PER_FIELD_REUSE_STRATEGY")] public PerFieldReuseStrategy() { } public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName) { var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer); if (componentsPerField != null) { TokenStreamComponents ret; componentsPerField.TryGetValue(fieldName, out ret); return ret; } return null; } public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components) { var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer); if (componentsPerField == null) { // LUCENENET-615: This needs to support nullable keys componentsPerField = new JCG.Dictionary<string, TokenStreamComponents>(); SetStoredValue(analyzer, componentsPerField); } componentsPerField[fieldName] = components; } } /// <summary> /// LUCENENET specific helper class to mimick Java's ability to create anonymous classes. /// Clearly, the design of <see cref="Analyzer"/> took this feature of Java into consideration. /// Since it doesn't exist in .NET, we can use a delegate method to call the constructor of /// this concrete instance to fake it (by calling an overload of /// <see cref="Analyzer.NewAnonymous(Func{string, TextReader, TokenStreamComponents})"/>). /// </summary> private class AnonymousAnalyzer : Analyzer { private readonly Func<string, TextReader, TokenStreamComponents> createComponents; private readonly Func<string, TextReader, TextReader> initReader; public AnonymousAnalyzer(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy) : base(reuseStrategy) { if (createComponents == null) throw new ArgumentNullException("createComponents"); this.createComponents = createComponents; this.initReader = initReader; } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { return this.createComponents(fieldName, reader); } protected internal override TextReader InitReader(string fieldName, TextReader reader) { if (this.initReader != null) { return this.initReader(fieldName, reader); } return base.InitReader(fieldName, reader); } } } /// <summary> /// This class encapsulates the outer components of a token stream. It provides /// access to the source (<see cref="Analysis.Tokenizer"/>) and the outer end (sink), an /// instance of <see cref="TokenFilter"/> which also serves as the /// <see cref="Analysis.TokenStream"/> returned by /// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>. /// </summary> public class TokenStreamComponents { /// <summary> /// Original source of the tokens. /// </summary> protected readonly Tokenizer m_source; /// <summary> /// Sink tokenstream, such as the outer tokenfilter decorating /// the chain. This can be the source if there are no filters. /// </summary> protected readonly TokenStream m_sink; /// <summary> /// Internal cache only used by <see cref="Analyzer.GetTokenStream(string, string)"/>. </summary> internal ReusableStringReader reusableStringReader; /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance. /// </summary> /// <param name="source"> /// the analyzer's tokenizer </param> /// <param name="result"> /// the analyzer's resulting token stream </param> public TokenStreamComponents(Tokenizer source, TokenStream result) { this.m_source = source; this.m_sink = result; } /// <summary> /// Creates a new <see cref="TokenStreamComponents"/> instance. /// </summary> /// <param name="source"> /// the analyzer's tokenizer </param> public TokenStreamComponents(Tokenizer source) { this.m_source = source; this.m_sink = source; } /// <summary> /// Resets the encapsulated components with the given reader. If the components /// cannot be reset, an Exception should be thrown. /// </summary> /// <param name="reader"> /// a reader to reset the source component </param> /// <exception cref="IOException"> /// if the component's reset method throws an <seealso cref="IOException"/> </exception> protected internal virtual void SetReader(TextReader reader) { m_source.SetReader(reader); } /// <summary> /// Returns the sink <see cref="Analysis.TokenStream"/> /// </summary> /// <returns> the sink <see cref="Analysis.TokenStream"/> </returns> public virtual TokenStream TokenStream => m_sink; /// <summary> /// Returns the component's <see cref="Analysis.Tokenizer"/> /// </summary> /// <returns> Component's <see cref="Analysis.Tokenizer"/> </returns> public virtual Tokenizer Tokenizer => m_source; } /// <summary> /// Strategy defining how <see cref="TokenStreamComponents"/> are reused per call to /// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>. /// </summary> public abstract class ReuseStrategy { /// <summary> /// Gets the reusable <see cref="TokenStreamComponents"/> for the field with the given name. /// </summary> /// <param name="analyzer"> <see cref="Analyzer"/> from which to get the reused components. Use /// <see cref="GetStoredValue(Analyzer)"/> and <see cref="SetStoredValue(Analyzer, object)"/> /// to access the data on the <see cref="Analyzer"/>. </param> /// <param name="fieldName"> Name of the field whose reusable <see cref="TokenStreamComponents"/> /// are to be retrieved </param> /// <returns> Reusable <see cref="TokenStreamComponents"/> for the field, or <c>null</c> /// if there was no previous components for the field </returns> public abstract TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName); /// <summary> /// Stores the given <see cref="TokenStreamComponents"/> as the reusable components for the /// field with the give name. /// </summary> /// <param name="analyzer"> Analyzer </param> /// <param name="fieldName"> Name of the field whose <see cref="TokenStreamComponents"/> are being set </param> /// <param name="components"> <see cref="TokenStreamComponents"/> which are to be reused for the field </param> public abstract void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components); /// <summary> /// Returns the currently stored value. /// </summary> /// <returns> Currently stored value or <c>null</c> if no value is stored </returns> /// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception> protected internal object GetStoredValue(Analyzer analyzer) { if (analyzer.storedValue == null) { throw new ObjectDisposedException(this.GetType().FullName, "this Analyzer is closed"); } return analyzer.storedValue.Get(); } /// <summary> /// Sets the stored value. /// </summary> /// <param name="analyzer"> Analyzer </param> /// <param name="storedValue"> Value to store </param> /// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception> protected internal void SetStoredValue(Analyzer analyzer, object storedValue) { if (analyzer.storedValue == null) { throw new ObjectDisposedException("this Analyzer is closed"); } analyzer.storedValue.Set(storedValue); } } }
50.284591
187
0.61105
[ "Apache-2.0" ]
Ref12/lucenenet
src/Lucene.Net/Analysis/Analyzer.cs
31,981
C#
using System; using Ultraviolet.Core; namespace Ultraviolet.Graphics { /// <summary> /// Represents a factory method which constructs instances of the <see cref="Texture2D"/> class. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="pixels">A pointer to the raw pixel data with which to populate the texture.</param> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="bytesPerPixel">The number of bytes which represent each pixel in the raw data.</param> /// <param name="options">The texture's configuration options.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public delegate Texture2D Texture2DFromRawDataFactory(UltravioletContext uv, IntPtr pixels, Int32 width, Int32 height, Int32 bytesPerPixel, TextureOptions options); /// <summary> /// Represents a factory method which constructs instances of the <see cref="Texture2D"/> class. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="options">The texture's configuration options.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public delegate Texture2D Texture2DFactory(UltravioletContext uv, Int32 width, Int32 height, TextureOptions options); /// <summary> /// Represents a two-dimensional texture. /// </summary> public abstract class Texture2D : Texture { /// <summary> /// Initializes a new instance of the <see cref="Texture2D"/> class. /// </summary> /// <param name="uv">The Ultraviolet context.</param> public Texture2D(UltravioletContext uv) : base(uv) { } /// <summary> /// Creates a new instance of the <see cref="Texture2D"/> class. /// </summary> /// <param name="pixels">A pointer to the raw pixel data with which to populate the texture.</param> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="bytesPerPixel">The number of bytes which represent each pixel in the raw data.</param> /// <param name="options">The texture's configuration options.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public static Texture2D CreateTexture(IntPtr pixels, Int32 width, Int32 height, Int32 bytesPerPixel, TextureOptions options = TextureOptions.Default) { Contract.EnsureRange(width > 0, nameof(width)); Contract.EnsureRange(height > 0, nameof(height)); var uv = UltravioletContext.DemandCurrent(); return uv.GetFactoryMethod<Texture2DFromRawDataFactory>()(uv, pixels, width, height, bytesPerPixel, options); } /// <summary> /// Creates a new instance of the <see cref="Texture2D"/> class. /// </summary> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="options">The texture's configuration options.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public static Texture2D CreateTexture(Int32 width, Int32 height, TextureOptions options = TextureOptions.Default) { Contract.EnsureRange(width > 0, nameof(width)); Contract.EnsureRange(height > 0, nameof(height)); var uv = UltravioletContext.DemandCurrent(); return uv.GetFactoryMethod<Texture2DFactory>()(uv, width, height, options); } /// <summary> /// Creates a new instance of the <see cref="Texture2D"/> class which is designed to be /// dynamically updated from data on the CPU. /// </summary> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="state">An arbitrary state object which will be passed to the flush handler.</param> /// <param name="flushed">The handler to invoke when the texture is flushed.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public static Texture2D CreateDynamicTexture(Int32 width, Int32 height, Object state, Action<Texture2D, Object> flushed) { return CreateDynamicTexture(width, height, TextureOptions.Default, state, flushed); } /// <summary> /// Creates a new instance of the <see cref="Texture2D"/> class which is designed to be /// dynamically updated from data on the CPU. /// </summary> /// <param name="width">The texture's width in pixels.</param> /// <param name="height">The texture's height in pixels.</param> /// <param name="options">The texture's configuration options.</param> /// <param name="state">An arbitrary state object which will be passed to the flush handler.</param> /// <param name="flushed">The handler to invoke when the texture is flushed.</param> /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns> public static Texture2D CreateDynamicTexture(Int32 width, Int32 height, TextureOptions options, Object state, Action<Texture2D, Object> flushed) { Contract.EnsureRange(width > 0, nameof(width)); Contract.EnsureRange(height > 0, nameof(height)); Contract.Require(flushed, nameof(flushed)); var uv = UltravioletContext.DemandCurrent(); return uv.GetFactoryMethod<DynamicTexture2DFactory>()(uv, width, height, options, state, flushed); } /// <summary> /// Creates a new instance of the <see cref="RenderBuffer2D"/> that represents a color buffer. /// </summary> /// <param name="width">The render buffer's width in pixels.</param> /// <param name="height">The render buffer's height in pixels.</param> /// <param name="options">The render buffer's configuration options.</param> /// <returns>The instance of <see cref="RenderBuffer2D"/> that was created.</returns> public static RenderBuffer2D CreateRenderBuffer(Int32 width, Int32 height, RenderBufferOptions options = RenderBufferOptions.Default) { return CreateRenderBuffer(RenderBufferFormat.Color, width, height, options); } /// <summary> /// Creates a new instance of the <see cref="RenderBuffer2D"/> class. /// </summary> /// <param name="format">A <see cref="RenderBufferFormat"/> value specifying the render buffer's data format.</param> /// <param name="width">The render buffer's width in pixels.</param> /// <param name="height">The render buffer's height in pixels.</param> /// <param name="options">The render buffer's configuration options.</param> /// <returns>The instance of <see cref="RenderBuffer2D"/> that was created.</returns> public static RenderBuffer2D CreateRenderBuffer(RenderBufferFormat format, Int32 width, Int32 height, RenderBufferOptions options = RenderBufferOptions.Default) { Contract.EnsureRange(width > 0, nameof(width)); Contract.EnsureRange(height > 0, nameof(height)); var uv = UltravioletContext.DemandCurrent(); return uv.GetFactoryMethod<RenderBuffer2DFactory>()(uv, format, width, height, options); } /// <summary> /// Resizes the texture. /// </summary> /// <param name="width">The texture's new width in pixels.</param> /// <param name="height">The texture's new height in pixels.</param> public abstract void Resize(Int32 width, Int32 height); /// <summary> /// Sets the texture's data. /// </summary> /// <typeparam name="T">The type of the elements in the array being set as the texture's data.</typeparam> /// <param name="data">An array containing the data to set.</param> public abstract void SetData<T>(T[] data) where T : struct; /// <summary> /// Sets the texture's data. /// </summary> /// <typeparam name="T">The type of the elements in the array being set as the texture's data.</typeparam> /// <param name="data">An array containing the data to set.</param> /// <param name="startIndex">The index of the first element to set.</param> /// <param name="elementCount">The number of elements to set.</param> public abstract void SetData<T>(T[] data, Int32 startIndex, Int32 elementCount) where T : struct; /// <summary> /// Sets the texture's data. /// </summary> /// <typeparam name="T">The type of the elements in the array being set as the texture's data.</typeparam> /// <param name="level">The mipmap level to set.</param> /// <param name="rect">A bounding box that defines the position and location (in pixels) of the data.</param> /// <param name="data">An array containing the data to set.</param> /// <param name="startIndex">The index of the first element to set.</param> /// <param name="elementCount">The number of elements to set.</param> public abstract void SetData<T>(Int32 level, Rectangle? rect, T[] data, Int32 startIndex, Int32 elementCount) where T : struct; /// <summary> /// Sets the texture's data. /// </summary> /// <typeparam name="T">The type of the elements in the buffer being set as the texture's data.</typeparam> /// <param name="data">A pointer to the data to set.</param> /// <param name="startIndex">The index of the first element to set.</param> /// <param name="elementCount">The number of elements to set.</param> public abstract void SetData<T>(IntPtr data, Int32 startIndex, Int32 elementCount) where T : struct; /// <summary> /// Sets the texture's data. /// </summary> /// <typeparam name="T">The type of the elements in the buffer being set as the texture's data.</typeparam> /// <param name="level">The mipmap level to set.</param> /// <param name="rect">A bounding box that defines the position and location (in pixels) of the data.</param> /// <param name="data">A pointer to the data to set.</param> /// <param name="startIndex">The index of the first element to set.</param> /// <param name="elementCount">The number of elements to set.</param> public abstract void SetData<T>(Int32 level, Rectangle? rect, IntPtr data, Int32 startIndex, Int32 elementCount) where T : struct; /// <summary> /// Sets the texture's data from the data at the specified pointer. /// </summary> /// <param name="data">A pointer to the data to set.</param> /// <param name="offsetInBytes">The offset from the start of <paramref name="data"/>, in bytes, at which to begin copying data.</param> /// <param name="sizeInBytes">The number of bytes to copy.</param> public abstract void SetRawData(IntPtr data, Int32 offsetInBytes, Int32 sizeInBytes); /// <summary> /// Sets the texture's data from the data at the specified pointer. /// </summary> /// <param name="level">The mipmap level to set.</param> /// <param name="rect">A bounding box that defines the position and location (in pixels) of the data.</param> /// <param name="data">A pointer to the data to set.</param> /// <param name="offsetInBytes">The offset from the start of <paramref name="data"/>, in bytes, at which to begin copying data.</param> /// <param name="sizeInBytes">The number of bytes to copy.</param> public abstract void SetRawData(Int32 level, Rectangle? rect, IntPtr data, Int32 offsetInBytes, Int32 sizeInBytes); /// <summary> /// Sets the texture's data. /// </summary> /// <param name="surface">The <see cref="Surface2D"/> which contains the data to set.</param> public abstract void SetData(Surface2D surface); /// <summary> /// Gets a value indicating whether this is an SRGB encoded texture. /// </summary> public abstract Boolean SrgbEncoded { get; } /// <summary> /// Gets the texture's width in pixels. /// </summary> public abstract Int32 Width { get; } /// <summary> /// Gets the texture's height in pixels. /// </summary> public abstract Int32 Height { get; } } }
54.445833
168
0.633198
[ "Apache-2.0", "MIT" ]
MicroWorldwide/ultraviolet
Source/Ultraviolet/Shared/Graphics/Texture2D.cs
13,069
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Week5_InterstellarTravel { public partial class RegisterInterest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { dateToGoCompareValidator.ValueToCompare = DateTime.Today.ToShortDateString(); } } protected void SubmitButton_Click(object sender, EventArgs e) { if (IsValid) { Models.CustomerQuery query = new Models.CustomerQuery(); DateTime date; if (DateTime.TryParse(dateToGoText.Text, out date)) { query.Date = date; query.Name = nameText.Text; query.Email = email1Text.Text; Session["customerQuery"] = query; Response.Redirect("Thanks.aspx"); } } } } }
27.846154
93
0.541436
[ "MIT" ]
UNEW-INFT3050/INFT3050_19Sem2
Week5_InterstellarTravel/Week5_InterstellarTravel/RegisterInterest.aspx.cs
1,088
C#
using UnityEngine; // Common Joystick control // There're lots of these, you know [ExecuteInEditMode] public class CNJoystick : CNAbstractController { // --------------------------------- // Editor visible public properties // --------------------------------- /// <summary> /// Drag radius is a maximum distance on which you can drag the stick relative to the center of the base /// </summary> public float DragRadius { get { return _dragRadius; } set { _dragRadius = value; } } /// <summary> /// Indicates whether the joystick should "Snap" to the finger, placing itself on the touch position /// </summary> public bool SnapsToFinger { get { return _snapsToFinger; } set { _snapsToFinger = value; } } /// <summary> /// Indicates whether it should disappear when it's not being tweaked /// </summary> public bool IsHiddenIfNotTweaking { get { return _isHiddenIfNotTweaking; } set { _isHiddenIfNotTweaking = value; } } // Serialized fields (user preferences) // We also hide them in the inspector so it's not shown automatically [SerializeField] [HideInInspector] private float _dragRadius = 1.5f; [SerializeField] [HideInInspector] private bool _snapsToFinger = true; [SerializeField] [HideInInspector] private bool _isHiddenIfNotTweaking; // Runtime used fields /// <summary> /// Transform component of a stick /// </summary> private Transform _stickTransform; /// <summary> /// Transform component of a base /// </summary> private Transform _baseTransform; /// <summary> /// GameObject of a stick. Used for hiding /// </summary> private GameObject _stickGameObject; /// <summary> /// GameObject of a stick. Used for hiding /// </summary> private GameObject _baseGameObject; /// <summary> /// Neat initialization method /// </summary> public override void OnEnable() { base.OnEnable(); // Getting needed components // Hardcoded names. We have no need of renaming these objects anyway _stickTransform = TransformCache.Find("Stick").GetComponent<Transform>(); _baseTransform = TransformCache.Find("Base").GetComponent<Transform>(); _stickGameObject = _stickTransform.gameObject; _baseGameObject = _baseTransform.gameObject; // Initial hiding of we should hide it if (IsHiddenIfNotTweaking) { _baseGameObject.gameObject.SetActive(false); _stickGameObject.gameObject.SetActive(false); } else { _baseGameObject.gameObject.SetActive(true); _stickGameObject.gameObject.SetActive(true); } } /// <summary> /// In this method we also need to set the stick and base local transforms back to zero /// </summary> protected override void ResetControlState() { base.ResetControlState(); // Setting the stick and base local positions back to local zero _stickTransform.localPosition = _baseTransform.localPosition = Vector3.zero; } /// <summary> /// We also check if we should hide the joystick /// </summary> protected override void OnFingerLifted() { base.OnFingerLifted(); if (!IsHiddenIfNotTweaking) return; _baseGameObject.gameObject.SetActive(false); _stickGameObject.gameObject.SetActive(false); } /// <summary> /// We also check if we should show the joystick /// </summary> protected override void OnFingerTouched() { base.OnFingerTouched(); if (!IsHiddenIfNotTweaking) return; _baseGameObject.gameObject.SetActive(true); _stickGameObject.gameObject.SetActive(true); } /// <summary> /// Your favorite Update method where all the magic happens /// </summary> protected virtual void Update() { // Check for touches if (TweakIfNeeded()) return; Touch currentTouch; if (IsTouchCaptured(out currentTouch)) // Place joystick under the finger // "No jumping" logic is also in this method PlaceJoystickBaseUnderTheFinger(currentTouch); } /// <summary> /// Function for joystick tweaking (moving with the finger) /// The values of the Axis are also calculated here /// </summary> /// <param name="touchPosition">Current touch position in screen cooridnates (pixels) /// It's recalculated in units so it's resolution-independent</param> protected override void TweakControl(Vector2 touchPosition) { // First, let's find our current touch position in world space Vector3 worldTouchPosition = ParentCamera.ScreenToWorldPoint(touchPosition); // Now we need to find a directional vector from the center of the joystick // to the touch position Vector3 differenceVector = (worldTouchPosition - _baseTransform.position); // If we're out of the drag range if (differenceVector.sqrMagnitude > DragRadius * DragRadius) { // Normalize this directional vector differenceVector.Normalize(); // And place the stick to it's extremum position _stickTransform.position = _baseTransform.position + differenceVector * DragRadius; } else { // If we're inside the drag range, just place it under the finger _stickTransform.position = worldTouchPosition; } // Store calculated axis values to our private variable CurrentAxisValues = differenceVector; // We also fire our event if there are subscribers OnControllerMoved(differenceVector); } /// <summary> /// Snap the joystick under the finger if it's expected /// </summary> /// <param name="touch">Current touch position in screen pixels /// It converts pixels to world space coordinates so it's resolution independent</param> protected virtual void PlaceJoystickBaseUnderTheFinger(Touch touch) { if (!_snapsToFinger) return; _stickTransform.position = _baseTransform.position = ParentCamera.ScreenToWorldPoint(touch.position); } }
34.925134
121
0.622416
[ "MIT" ]
bryanoliveira/unity-zombit
Assets/Scripts/CNControls/CNJoystick.cs
6,533
C#
using System; // ReSharper disable InconsistentNaming // ReSharper disable IdentifierTypo // ReSharper disable CommentTypo namespace OpenCvSharp.Quality { /// <summary> /// Full reference GMSD algorithm /// </summary> public class QualityGMSD : QualityBase { private Ptr? ptrObj; /// <summary> /// Creates instance by raw pointer /// </summary> protected QualityGMSD(IntPtr p) { ptrObj = new Ptr(p); ptr = ptrObj.Get(); } /// <summary> /// Create an object which calculates quality /// </summary> /// <param name="ref">input image to use as the source for comparison</param> /// <returns></returns> public static QualityGMSD Create(InputArray @ref) { if (@ref == null) throw new ArgumentNullException(nameof(@ref)); @ref.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.quality_createQualityGMSD(@ref.CvPtr, out var ptr)); GC.KeepAlive(@ref); return new QualityGMSD(ptr); } /// <summary> /// static method for computing quality /// </summary> /// <param name="ref"></param> /// <param name="cmp"></param> /// <param name="qualityMap">output quality map, or null</param> /// <returns>cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best)</returns> public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray? qualityMap) { if (@ref == null) throw new ArgumentNullException(nameof(@ref)); if (cmp == null) throw new ArgumentNullException(nameof(cmp)); @ref.ThrowIfDisposed(); cmp.ThrowIfDisposed(); qualityMap?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.quality_QualityGMSD_staticCompute( @ref.CvPtr, cmp.CvPtr, qualityMap?.CvPtr ?? IntPtr.Zero, out var ret)); GC.KeepAlive(@ref); GC.KeepAlive(cmp); qualityMap?.Fix(); return ret; } /// <summary> /// Releases managed resources /// </summary> protected override void DisposeManaged() { ptrObj?.Dispose(); ptrObj = null; base.DisposeManaged(); } internal class Ptr : OpenCvSharp.Ptr { public Ptr(IntPtr ptr) : base(ptr) { } public override IntPtr Get() { NativeMethods.HandleException( NativeMethods.quality_Ptr_QualityGMSD_get(ptr, out var ret)); GC.KeepAlive(this); return ret; } protected override void DisposeUnmanaged() { NativeMethods.HandleException( NativeMethods.quality_Ptr_QualityGMSD_delete(ptr)); base.DisposeUnmanaged(); } } } }
31.168317
115
0.536213
[ "BSD-3-Clause" ]
AJEETX/opencvsharp
src/OpenCvSharp/Modules/quality/QualityGMSD.cs
3,150
C#
namespace pipe.test.TestDoubles { public class StubFileSystem : IFileSystem { private readonly string _localFile; private readonly bool _fileExists; private readonly string[] _fileContents; public StubFileSystem(string localFile = null, string[] fileContents = null) { _fileContents = fileContents; _localFile = localFile ?? (fileContents != null ? "dummy-file" : null); _fileExists = fileContents != null; } public string GetPathForLocalFile(string fileName) => _localFile; public bool DoesFileExists(string filePath) => _fileExists; public string[] ReadFileContents(string filePath) => _fileContents; } }
36.8
84
0.650815
[ "MIT" ]
jensandresen/dotnet-pipe
src/pipe.test/TestDoubles/StubFileSystem.cs
736
C#
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Distributions.Univariate { using System; using Accord.Math; using AForge; /// <summary> /// Logistic distribution. /// </summary> /// /// <remarks> /// <para> /// In probability theory and statistics, the logistic distribution is a continuous /// probability distribution. Its cumulative distribution function is the logistic /// function, which appears in logistic regression and feedforward neural networks. /// It resembles the normal distribution in shape but has heavier tails (higher /// kurtosis). The <see cref="TukeyLambdaDistribution">Tukey lambda distribution</see> /// can be considered a generalization of the logistic distribution since it adds a /// shape parameter, λ (the Tukey distribution becomes logistic when λ is zero).</para> /// /// <para> /// References: /// <list type="bullet"> /// <item><description><a href="http://en.wikipedia.org/wiki/Logistic_distribution"> /// Wikipedia, The Free Encyclopedia. Logistic distribution. Available on: /// http://en.wikipedia.org/wiki/Logistic_distribution </a></description></item> /// </list></para> /// </remarks> /// /// <example> /// <para> /// This examples shows how to create a Logistic distribution, /// compute some of its properties and generate a number of /// random samples from it.</para> /// /// <code> /// // Create a logistic distribution with μ = 0.42 and scale = 3 /// var log = new LogisticDistribution(location: 0.42, scale: 1.2); /// /// double mean = log.Mean; // 0.42 /// double median = log.Median; // 0.42 /// double mode = log.Mode; // 0.42 /// double var = log.Variance; // 4.737410112522892 /// /// double cdf = log.DistributionFunction(x: 1.4); // 0.693528308197921 /// double pdf = log.ProbabilityDensityFunction(x: 1.4); // 0.17712232827170876 /// double lpdf = log.LogProbabilityDensityFunction(x: 1.4); // -1.7309146649427332 /// /// double ccdf = log.ComplementaryDistributionFunction(x: 1.4); // 0.306471691802079 /// double icdf = log.InverseDistributionFunction(p: cdf); // 1.3999999999999997 /// /// double hf = log.HazardFunction(x: 1.4); // 0.57794025683160088 /// double chf = log.CumulativeHazardFunction(x: 1.4); // 1.1826298874077226 /// /// string str = log.ToString(CultureInfo.InvariantCulture); // Logistic(x; μ = 0.42, scale = 1.2) /// </code> /// </example> /// /// <seealso cref="TukeyLambdaDistribution"/> /// [Serializable] public class LogisticDistribution : UnivariateContinuousDistribution { // Distribution parameters private double mu; // location μ private double s; // scale s /// <summary> /// Constructs a Logistic distribution /// with zero location and unit scale. /// </summary> /// public LogisticDistribution() { initialize(0, 1); } /// <summary> /// Constructs a Logistic distribution /// with given location and unit scale. /// </summary> /// /// <param name="location">The distribution's location value μ (mu).</param> /// public LogisticDistribution([Real] double location) { initialize(location, 1); } /// <summary> /// Constructs a Logistic distribution /// with given location and scale parameters. /// </summary> /// /// <param name="location">The distribution's location value μ (mu).</param> /// <param name="scale">The distribution's scale value s.</param> /// public LogisticDistribution([Real] double location, [Positive] double scale) { if (scale <= 0) throw new ArgumentOutOfRangeException("scale", "Scale must be positive."); initialize(location, scale); } /// <summary> /// Gets the location value μ (mu). /// </summary> /// /// <value> /// The distribution's mean value. /// </value> /// public override double Mean { get { return mu; } } /// <summary> /// Gets the distribution's scale value (s). /// </summary> /// public double Scale { get { return s; } } /// <summary> /// Gets the median for this distribution. /// </summary> /// /// <value> /// The distribution's median value. /// </value> /// public override double Median { get { System.Diagnostics.Debug.Assert(mu == base.Median); return mu; } } /// <summary> /// Gets the variance for this distribution. /// </summary> /// /// <value> /// The distribution's variance. /// </value> /// public override double Variance { get { return (s * s * Math.PI * Math.PI) / 3.0; } } /// <summary> /// Gets the mode for this distribution. /// </summary> /// /// <remarks> /// In the logistic distribution, the mode is equal /// to the distribution <see cref="Mean"/> value. /// </remarks> /// /// <value> /// The distribution's mode value. /// </value> /// public override double Mode { get { return mu; } } /// <summary> /// Gets the support interval for this distribution. /// </summary> /// /// <value> /// A <see cref="AForge.DoubleRange" /> containing /// the support interval for this distribution. /// </value> /// public override DoubleRange Support { get { return new DoubleRange(Double.NegativeInfinity, Double.PositiveInfinity); } } /// <summary> /// Gets the entropy for this distribution. /// </summary> /// /// <remarks> /// In the logistic distribution, the entropy is /// equal to <c>ln(<see cref="Scale">s</see>) + 2</c>. /// </remarks> /// /// <value> /// The distribution's entropy. /// </value> /// public override double Entropy { get { return Math.Log(s) + 2; } } /// <summary> /// Gets the cumulative distribution function (cdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// public override double DistributionFunction(double x) { double z = (x - mu) / s; return 1.0 / (1 + Math.Exp(-z)); } /// <summary> /// Gets the probability density function (pdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// /// <returns> /// The probability of <c>x</c> occurring /// in the current distribution. /// </returns> /// public override double ProbabilityDensityFunction(double x) { double z = (x - mu) / s; double num = Math.Exp(-z); double a = (1 + num); double den = s * a * a; return num / den; } /// <summary> /// Gets the log-probability density function (pdf) for /// this distribution evaluated at point <c>x</c>. /// </summary> /// /// <param name="x">A single point in the distribution range.</param> /// /// <returns> /// The logarithm of the probability of <c>x</c> /// occurring in the current distribution. /// </returns> /// public override double LogProbabilityDensityFunction(double x) { double z = (x - mu) / s; double result = -z - (Math.Log(s) + 2 * Special.Log1p(Math.Exp(-z))); return result; } /// <summary> /// Gets the inverse of the cumulative distribution function (icdf) for /// this distribution evaluated at probability <c>p</c>. This function /// is also known as the Quantile function. /// </summary> /// /// <param name="p">A probability value between 0 and 1.</param> /// /// <returns> /// A sample which could original the given probability /// value when applied in the <see cref="DistributionFunction"/>. /// </returns> /// public override double InverseDistributionFunction(double p) { return mu + s * Math.Log(p / (1 - p)); } /// <summary> /// Gets the first derivative of the <see cref="InverseDistributionFunction"> /// inverse distribution function</see> (icdf) for this distribution evaluated /// at probability <c>p</c>. /// </summary> /// /// <param name="p">A probability value between 0 and 1.</param> /// public override double QuantileDensityFunction(double p) { return s / (p * (1 - p)); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> /// public override object Clone() { return new LogisticDistribution(mu, s); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// public override string ToString() { return String.Format("Logistic(x; μ = {0}, s = {1})", mu, s); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// public string ToString(IFormatProvider formatProvider) { return String.Format(formatProvider, "Logistic(x; μ = {0}, s = {1})", mu, s); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// public string ToString(string format, IFormatProvider formatProvider) { return String.Format(formatProvider, "Logistic(x; μ = {0}, s = {1})", mu.ToString(format, formatProvider), s.ToString(format, formatProvider)); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> /// public string ToString(string format) { return String.Format("Logistic(x; μ = {0}, s = {1})", mu.ToString(format), s.ToString(format)); } private void initialize(double mean, double scale) { this.mu = mean; this.s = scale; } } }
33.829146
103
0.511364
[ "MIT" ]
kpandya3/WakeUpWithKinect
Accord.NET projects/Accord.Statistics/Distributions/Univariate/Continuous/LogisticDistribution.cs
13,480
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlazorFluentUI.Demo.Shared.Models { class SearchItem { public string Name { get; set; } public string JobDescription { get; set; } } }
19.4
50
0.697595
[ "MIT" ]
Frank67618/BlazorFluentUI
Demo/BlazorFluentUI.Demo.Shared/Models/SearchItem.cs
293
C#
using System.IO; using Microsoft.AspNetCore.Hosting; namespace TreatBox { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
19.8
57
0.583333
[ "MIT" ]
taylulz/TreatBox
TreatBox/Program.cs
398
C#
using MaxMix.ViewModels; using Sentry; using Sentry.Protocol; using System; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Windows; using System.Windows.Threading; namespace MaxMix { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { IDisposable _errorReporter; private static Mutex _singleInstanceMutex = null; private void InitErrorReporting() { _errorReporter = SentrySdk.Init("https://54cf266b03ed4ee380b0577653172a98@o431430.ingest.sentry.io/5382488"); SentrySdk.ConfigureScope(scope => { scope.User = new User { Username = Environment.MachineName }; }); } void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { SentrySdk.CaptureException(e.Exception); _errorReporter.Dispose(); } private bool IsApplicationRunning() { var assemblyName = Assembly.GetExecutingAssembly().GetName().Name; _singleInstanceMutex = new Mutex(true, assemblyName, out bool mutexAcquired); return mutexAcquired; } private void ApplicationStartup(object sender, StartupEventArgs e) { if (!IsApplicationRunning()) { // Application is already running Debug.WriteLine("[App] Application is already running, exiting."); Current.Shutdown(); return; } if (!Debugger.IsAttached) { // Initialize error reporing only if not running from Visual Studio. InitErrorReporting(); DispatcherUnhandledException += OnDispatcherUnhandledException; } var window = new MainWindow(); var assemblyName = Assembly.GetExecutingAssembly().GetName().Name; string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); window.Title = string.Format("{0} {1}", assemblyName, assemblyVersion); var dataContext = new MainViewModel(); dataContext.ExitRequested += OnExitRequested; window.DataContext = dataContext; dataContext.Start(); } private void OnExitRequested(object sender, EventArgs e) { var viewModel = (MainViewModel)sender; viewModel.Stop(); // Calling dispose explicitly on closing so the icon dissapears from the windows task bar. var window = (MainWindow)Current.MainWindow; window.taskbarIcon.Dispose(); if (_errorReporter != null) { _errorReporter.Dispose(); } _singleInstanceMutex.Dispose(); Current.Shutdown(); } } }
32.119565
121
0.601354
[ "Apache-2.0" ]
SchemingWeasels/maxmix-software
Desktop/Application/MaxMix/App.xaml.cs
2,957
C#