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
namespace InsanityBot.Utility.Reference; using System; using InsanityBot.Utility.Datafixers.Reference; public interface IDatafixer { public DatafixerLoadingResult Load() => DatafixerLoadingResult.Success; public String NewDataVersion { get; } public String OldDataVersion { get; } public UInt32 DatafixerId { get; } public Boolean BreakingChange { get; } }
26.071429
72
0.791781
[ "MIT" ]
InsanityBot/InsanityBot
InsanityBot.Utility/Reference/IDatafixer.cs
367
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using BO; using BE; using System.Web.Http.Cors; namespace ApiSeguraEventos.Controllers { [EnableCors("*", "*", "*")] public class DetEvento_LocalController : ApiController { DetEvento_LocalBO gestorDetEvento_Local = new DetEvento_LocalBO(); // GET: api/DetEvento_Local [HttpGet] public IEnumerable<DetEvento_Local> Get() { return gestorDetEvento_Local.ListarDetEvento_Local(); } // GET: api/DetEvento_Local/5/4 [HttpGet] public DetEvento_Local Get(int IdEvento, int IdLocal) { return gestorDetEvento_Local.ListarDetEvento_Local(IdEvento, IdLocal); } [HttpGet] public LocalModelView Get(int IdEvento) { return gestorDetEvento_Local.getLocal(IdEvento); } // POST: api/DetEvento_Local // PUT: api/DetEvento_Local [HttpPut] [Route("api/actualizarLocal")] public string Put([FromBody]DetEvento_Local value) { return gestorDetEvento_Local.ActualizarDetEvento_Local(value); } [HttpPost] [Route("api/asignarLocal")] public string Post([FromBody]DetEvento_Local value) { return gestorDetEvento_Local.IngresarDetEvento_Local(value); } // DELETE: api/DetEvento_Local/5/4 [HttpDelete] public string Delete(int IdEvento, int IdLocal) { return gestorDetEvento_Local.EiminarDetEvento_Local(IdEvento, IdLocal); } } }
28.627119
83
0.631143
[ "MIT" ]
carloseip/ApiEventos
appGetorEventos/Controllers/DetEvento_LocalController.cs
1,691
C#
// Copyright © 2020 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using ExtCore.Infrastructure; namespace Platformus.Website { /// <summary> /// Overrides the <see cref="ExtensionBase">ExtensionBase</see> class and provides the Platformus.Website extension information. /// </summary> public class WebsiteExtension : ExtensionBase { /// <summary> /// Gets the name of the extension. /// </summary> public override string Name => "Platformus.Website"; /// <summary> /// Gets the URL of the extension. /// </summary> public override string Url => "http://platformus.net/"; /// <summary> /// Gets the version of the extension. /// </summary> public override string Version => "2.0.0-beta1"; /// <summary> /// Gets the authors of the extension (separated by commas). /// </summary> public override string Authors => "Dmitry Sikorsky"; } }
30.909091
130
0.663725
[ "Apache-2.0" ]
alokshukla1978/Platformus
src/Platformus.Website/WebsiteExtension.cs
1,023
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class AutomaticWeaponInputHandler : WeaponInputHandler { public override bool FireInputReceived() { return Input.GetButton("Fire1"); } }
21.25
61
0.760784
[ "MIT" ]
nagahole/scope
SCOPE/Assets/Scripts/Weapon System/Modules/Functional Modules/Input Handlers/AutomaticWeaponInputHandler.cs
257
C#
namespace ModernDesignTemplate { public interface IViewModelSwitcher { ISwitchableViewModel CurrentView { get; set; } void Switch(object sender, SwitchViewEventArgs e); } }
22.333333
58
0.701493
[ "MIT" ]
TedMANNERs/ModernDesignTemplate
ModernDesignTemplate/IViewModelSwitcher.cs
201
C#
using UnityEngine; using Dest.Math; namespace Dest.Math.Tests { [ExecuteInEditMode] public class Test_IntrPlane3Plane3 : Test_Base { public Transform Plane0; public Transform Plane1; private void OnDrawGizmos() { Plane3 plane0 = CreatePlane3(Plane0); Plane3 plane1 = CreatePlane3(Plane1); bool test = Intersection.TestPlane3Plane3(ref plane0, ref plane1); Plane3Plane3Intr info; bool find = Intersection.FindPlane3Plane3(ref plane0, ref plane1, out info); FiguresColor(); DrawPlane(ref plane0, Plane0); DrawPlane(ref plane1, Plane1); if (find) { if (info.IntersectionType == IntersectionTypes.Line) { ResultsColor(); DrawLine(ref info.Line); } } LogInfo("test: " + test + " find: " + info.IntersectionType); } } }
20.868421
79
0.691047
[ "MIT" ]
zhlnpu/SmartphoneVR2-ARinVR
SmartPhoneVR-stage2-pc-ARinVR/Assets/MathLibraryForUnity/Tests/Scripts/Intersection/3D/Test_IntrPlane3Plane3.cs
795
C#
using FluentAssertions; using FluentAssertions.Common; using KorDevAus.Entities; using KorDevAus.Orm.Configurations; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace KorDevAus.Orm.Tests.Configurations { [TestClass] public class MemberConfigurationTests { [TestMethod] public void Given_Type_Should_NotBeAbstract() { typeof(MemberConfiguration) .Should().HaveAccessModifier(CSharpAccessModifier.Public) .And.Should().NotBeAbstract() .And.BeDerivedFrom<BaseEntityConfiguration<Member>>(); } } }
27
74
0.68277
[ "MIT" ]
TeamKDA/KorDevAus-Database
test/KorDevAus.Orm.Tests/Configurations/MemberConfigurationTests.cs
623
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ws_lab_08.Models { public class ReqJsonRPC { public string Id { get; set; } public string Jsonrpc { get; set; } public string Method { get; set; } public ISM Params { get; set; } } }
24.538462
43
0.639498
[ "MIT" ]
syarhei/web-services
ws_lab_08/ws_lab_08/Models/ReqJsonRPC.cs
321
C#
#pragma checksum "C:\Users\kobe9\source\repos\WinUI_UWP\XamlControlsGallery\SamplePages\SamplePage2.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "324A2D11F4A664E8F61626FB9B095ECB642CE98D8AC15DDDE5F3360FFCFD32A9" //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace AppUIBasics.SamplePages { partial class SamplePage2 : global::Microsoft.UI.Xaml.Controls.Page { #pragma warning disable 0169 // Proactively suppress unused/uninitialized field warning in case they aren't used, for things like x:Name #pragma warning disable 0649 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")] private global::Microsoft.UI.Xaml.Controls.Grid DestinationElement; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")] private global::Microsoft.UI.Xaml.Controls.StackPanel ContentPanel; #pragma warning restore 0649 #pragma warning restore 0169 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///SamplePages/SamplePage2.xaml"); global::Microsoft.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Microsoft.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application); } partial void UnloadObject(global::Microsoft.UI.Xaml.DependencyObject unloadableObject); } }
45.2
214
0.665044
[ "MIT" ]
kobe9936/WinUI_UWP
XamlControlsGallery/obj/XamlControlsGallery/x64/Debug/SamplePages/SamplePage2.g.i.cs
2,262
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.dataworks_public.Model.V20200518 { public class GetConnectionMetaResponse : AcsResponse { private string requestId; private bool? success; private GetConnectionMeta_Data data; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public GetConnectionMeta_Data Data { get { return data; } set { data = value; } } public class GetConnectionMeta_Data { private string meta; public string Meta { get { return meta; } set { meta = value; } } } } }
18.719101
63
0.644658
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-dataworks-public/Dataworks_public/Model/V20200518/GetConnectionMetaResponse.cs
1,666
C#
/** * https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374 * https://gist.github.com/RonildoSouza/4314d279a02a3214acc59c2cf6bf9b12 */ using Curupira2D.ECS; using Curupira2D.Extensions; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; namespace Curupira2D { public sealed class Quadtree : IDisposable { private const int MAX_OBJECTS = 10; private const int MAX_LEVELS = 5; private Rectangle _bounds; private readonly int _level; /// <summary> /// The list of objects in our current node /// </summary> private List<Entity> _objects; /// <summary> /// The four subnodes. Nodes fill out in a counter clockwise mannor /// </summary> private readonly Quadtree[] _nodes; /// <summary></summary> /// <param name="bounds">The 2D space that the node occupies</param> /// <param name="level">The current node level (0 being the topmost)</param> public Quadtree(Rectangle bounds, int level = 0) { _bounds = bounds; _level = level; _objects = new List<Entity>(); _nodes = new Quadtree[4]; } /// <summary> /// Gets the count of how many objects are in this current node. /// </summary> public int Count => _objects.Count; /// <summary> /// Clears the quadtree recursively /// </summary> public void Clear() { _objects.Clear(); for (var i = 0; i < _nodes.Length; i++) { if (_nodes[i] != null) { _nodes[i].Clear(); _nodes[i] = null; } } } /// <summary> /// Insert the object into the quad tree. If the node exceeds the capacity, /// it will split and add all objects to their corresponding nodes. /// </summary> /// <param name="entity"><see cref="Entity"/></param> public void Insert(Entity entity) { if (_nodes[0] != null) { var index = GetIndex(entity.GetHitBox()); if (index != -1) { _nodes[index].Insert(entity); return; } } _objects.Add(entity); if (_objects.Count > MAX_OBJECTS && _level < MAX_LEVELS) { if (_nodes[0] == null) Split(); foreach (var entityCurrentNode in _objects.GetRange(0, _objects.Count)) { var index = GetIndex(entityCurrentNode.GetHitBox()); if (index != -1) { _nodes[index].Insert(entityCurrentNode); _objects.Remove(entityCurrentNode); } } } } /// <summary> /// Deletes the item from this QuadTree. If the object is removed causes the Quadtree to have /// no objects in its children, they will also be removed. /// </summary> /// <param name="entity"><see cref="Entity"/></param> public void Delete(Entity entity) { // If this level contains the object, remove it var objectRemoved = false; if (_objects != null && _objects.Contains(entity)) { _objects.Remove(entity); objectRemoved = true; } // If we didn't find the object in this tree, try and delete it from its children. if (_nodes[0] != null && !objectRemoved) { _nodes[0].Delete(entity); _nodes[1].Delete(entity); _nodes[2].Delete(entity); _nodes[3].Delete(entity); } if (_nodes[0] != null) { // If all the children are empty, delete all the children if (_nodes[0].Count == 0 && _nodes[1].Count == 0 && _nodes[2].Count == 0 && _nodes[3].Count == 0) { _nodes[0] = null; _nodes[1] = null; _nodes[2] = null; _nodes[3] = null; } } } /// <summary> /// Returns all objects that could collide with the given object /// </summary> /// <param name="entity"><see cref="Entity"/></param> public IEnumerable<Entity> Retrieve(Entity entity) { var returnObjects = new List<Entity>(_objects); // if we have Subnodes if (_nodes[0] != null) { var index = GetIndex(entity.GetHitBox()); // If the entity hit box fits into a sub node if (index != -1) returnObjects.AddRange(_nodes[index].Retrieve(entity)); // If the entity hit box does not fit into a sub node, check it against all subnodes else { for (var i = 0; i < _nodes.Length; i++) returnObjects.AddRange(_nodes[i].Retrieve(entity)); } } return returnObjects.Where(_ => _.UniqueId != entity.UniqueId && _.Active && _.IsCollidable); } public void Dispose() { Clear(); _objects = null; } /// <summary> /// Splits the node into 4 subnodes, dividing the node into four equal parts and initializing /// the four subnodes with the new bounds. /// </summary> private void Split() { var subWidth = _bounds.Width / 2; var subHeight = _bounds.Height / 2; var x = _bounds.X; var y = _bounds.Y; var newLevel = _level + 1; //Right/Top _nodes[0] = new Quadtree(new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight), newLevel); //Left/Top _nodes[1] = new Quadtree(new Rectangle(x, y + subHeight, subWidth, subHeight), newLevel); //Left/Bottom _nodes[2] = new Quadtree(new Rectangle(x, y, subWidth, subHeight), newLevel); //Right/Bottom _nodes[3] = new Quadtree(new Rectangle(x + subWidth, y, subWidth, subHeight), newLevel); } /// <summary> /// A helper function of the quadtree. It determines where an object belongs in the quadtree /// by determining which node the object can fit into. /// </summary> /// <param name="hitBox">The rectangle being checked</param> /// <returns>The node that the object fits into, -1 means it fits in the parent node</returns> private int GetIndex(Rectangle hitBox) { double verticalMidpoint = _bounds.X + _bounds.Width / 2; double horizontalMidpoint = _bounds.Y + _bounds.Height / 2; // Object can completely fit within the top quadrants var topQuadrant = hitBox.Y < horizontalMidpoint && hitBox.Y + hitBox.Height < horizontalMidpoint; // Object can completely fit within the bottom quadrants var bottomQuadrant = hitBox.Y > horizontalMidpoint; // Object can completely fit within the left quadrants var leftQuadrant = hitBox.X < verticalMidpoint && hitBox.X + hitBox.Width < verticalMidpoint; // Object can completely fit within the right quadrants var rightQuadrant = hitBox.X > verticalMidpoint; if (rightQuadrant && topQuadrant) return 0; if (leftQuadrant && topQuadrant) return 1; if (leftQuadrant && bottomQuadrant) return 2; if (rightQuadrant && bottomQuadrant) return 3; return -1; } } }
34.158996
125
0.514209
[ "MIT" ]
RonildoSouza/MonoGame.Helper
src/Curupira2D/Quadtree.cs
8,166
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.IO; using System.Runtime.InteropServices; namespace System { public static partial class PlatformDetection { // // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, // do it in a way that failures don't cascade. // private static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); public static bool IsOpenSUSE => IsDistroAndVersion("opensuse"); public static bool IsUbuntu => IsDistroAndVersion("ubuntu"); public static bool IsDebian => IsDistroAndVersion("debian"); public static bool IsAlpine => IsDistroAndVersion("alpine"); public static bool IsDebian8 => IsDistroAndVersion("debian", 8); public static bool IsDebian10 => IsDistroAndVersion("debian", 10); public static bool IsUbuntu1604 => IsDistroAndVersion("ubuntu", 16, 4); public static bool IsUbuntu1704 => IsDistroAndVersion("ubuntu", 17, 4); public static bool IsUbuntu1710 => IsDistroAndVersion("ubuntu", 17, 10); public static bool IsUbuntu1710OrHigher => IsDistroAndVersionOrHigher("ubuntu", 17, 10); public static bool IsUbuntu1804 => IsDistroAndVersion("ubuntu", 18, 04); public static bool IsUbuntu1810OrHigher => IsDistroAndVersionOrHigher("ubuntu", 18, 10); public static bool IsTizen => IsDistroAndVersion("tizen"); public static bool IsFedora => IsDistroAndVersion("fedora"); // OSX family public static bool IsOSXLike => RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Create("TVOS")); public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsNotOSX => !IsOSX; public static bool IsMacOsMojaveOrHigher => IsOSX && Environment.OSVersion.Version >= new Version(10, 14); public static bool IsMacOsCatalinaOrHigher => IsOSX && Environment.OSVersion.Version >= new Version(10, 15); // RedHat family covers RedHat and CentOS public static bool IsRedHatFamily => IsRedHatFamilyAndVersion(); public static bool IsNotRedHatFamily => !IsRedHatFamily; public static bool IsRedHatFamily7 => IsRedHatFamilyAndVersion(7); public static bool IsNotFedoraOrRedHatFamily => !IsFedora && !IsRedHatFamily; public static bool IsNotDebian10 => !IsDebian10; public static bool IsSuperUser => !IsWindows ? libc.geteuid() == 0 : throw new PlatformNotSupportedException(); public static Version OpenSslVersion => !IsOSXLike && !IsWindows ? GetOpenSslVersion() : throw new PlatformNotSupportedException(); /// <summary> /// If gnulibc is available, returns the release, such as "stable". /// Otherwise returns "glibc_not_found". /// </summary> public static string LibcRelease { get { if (IsWindows) { return "glibc_not_found"; } try { return Marshal.PtrToStringAnsi(libc.gnu_get_libc_release()); } catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException) { return "glibc_not_found"; } } } /// <summary> /// If gnulibc is available, returns the version, such as "2.22". /// Otherwise returns "glibc_not_found". (In future could run "ldd -version" for musl) /// </summary> public static string LibcVersion { get { if (IsWindows) { return "glibc_not_found"; } try { return Marshal.PtrToStringAnsi(libc.gnu_get_libc_version()); } catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException) { return "glibc_not_found"; } } } private static Version s_opensslVersion; private static Version GetOpenSslVersion() { if (s_opensslVersion == null) { // OpenSSL version numbers are encoded as // 0xMNNFFPPS: major (one nybble), minor (one byte, unaligned), // "fix" (one byte, unaligned), patch (one byte, unaligned), status (one nybble) // // e.g. 1.0.2a final is 0x1000201F // // Currently they don't exceed 29-bit values, but we use long here to account // for the expanded range on their 64-bit C-long return value. long versionNumber = Interop.OpenSsl.OpenSslVersionNumber(); int major = (int)((versionNumber >> 28) & 0xF); int minor = (int)((versionNumber >> 20) & 0xFF); int fix = (int)((versionNumber >> 12) & 0xFF); s_opensslVersion = new Version(major, minor, fix); } return s_opensslVersion; } private static Version ToVersion(string versionString) { // In some distros/versions we cannot discover the distro version; return something valid. // Pick a high version number, since this seems to happen on newer distros. if (string.IsNullOrEmpty(versionString)) { versionString = new Version(Int32.MaxValue, Int32.MaxValue).ToString(); } try { if (versionString.IndexOf('.') != -1) return new Version(versionString); // minor version is required by Version // let's default it to 0 return new Version(int.Parse(versionString), 0); } catch (Exception exc) { throw new FormatException($"Failed to parse version string: '{versionString}'", exc); } } private static DistroInfo GetDistroInfo() { DistroInfo result = new DistroInfo(); if (IsFreeBSD) { result.Id = "FreeBSD"; // example: // FreeBSD 11.0-RELEASE-p1 FreeBSD 11.0-RELEASE-p1 #0 r306420: Thu Sep 29 01:43:23 UTC 2016 root@releng2.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC // What we want is major release as minor releases should be compatible. result.VersionId = ToVersion(RuntimeInformation.OSDescription.Split()[1].Split('.')[0]); } else if (IsIllumos) { // examples: // on OmniOS // SunOS 5.11 omnios-r151018-95eaa7e // on OpenIndiana Hipster: // SunOS 5.11 illumos-63878f749f // on SmartOS: // SunOS 5.11 joyent_20200408T231825Z var versionDescription = RuntimeInformation.OSDescription.Split(' ')[2]; switch (versionDescription) { case string version when version.StartsWith("omnios"): result.Id = "OmniOS"; result.VersionId = ToVersion(version.Substring("omnios-r".Length, 2)); // e.g. 15 break; case string version when version.StartsWith("joyent"): result.Id = "SmartOS"; result.VersionId = ToVersion(version.Substring("joyent_".Length, 4)); // e.g. 2020 break; case string version when version.StartsWith("illumos"): result.Id = "OpenIndiana"; // version-less break; } } else if (IsSolaris) { // example: // SunOS 5.11 11.3 result.Id = "Solaris"; result.VersionId = ToVersion(RuntimeInformation.OSDescription.Split(' ')[2]); // e.g. 11.3 } else if (File.Exists("/etc/os-release")) { foreach (string line in File.ReadAllLines("/etc/os-release")) { if (line.StartsWith("ID=", StringComparison.Ordinal)) { result.Id = line.Substring(3).Trim('"', '\''); } else if (line.StartsWith("VERSION_ID=", StringComparison.Ordinal)) { result.VersionId = ToVersion(line.Substring(11).Trim('"', '\'')); } } } result.Id ??= "Linux"; result.VersionId ??= ToVersion(string.Empty); return result; } private static bool IsRedHatFamilyAndVersion(int major = -1, int minor = -1, int build = -1, int revision = -1) { return IsDistroAndVersion((distro) => distro == "rhel" || distro == "centos", major, minor, build, revision); } /// <summary> /// Get whether the OS platform matches the given Linux distro and optional version. /// </summary> /// <param name="distroId">The distribution id.</param> /// <param name="major">The distro major version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="minor">The distro minor version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="build">The distro build version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="revision">The distro revision version. If omitted, this portion of the version is not included in the comparison.</param> /// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns> private static bool IsDistroAndVersion(string distroId, int major = -1, int minor = -1, int build = -1, int revision = -1) { return IsDistroAndVersion(distro => (distro == distroId), major, minor, build, revision); } /// <summary> /// Get whether the OS platform matches the given Linux distro and optional version is same or higher. /// </summary> /// <param name="distroId">The distribution id.</param> /// <param name="major">The distro major version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="minor">The distro minor version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="build">The distro build version. If omitted, this portion of the version is not included in the comparison.</param> /// <param name="revision">The distro revision version. If omitted, this portion of the version is not included in the comparison.</param> /// <returns>Whether the OS platform matches the given Linux distro and optional version is same or higher.</returns> private static bool IsDistroAndVersionOrHigher(string distroId, int major = -1, int minor = -1, int build = -1, int revision = -1) { return IsDistroAndVersionOrHigher(distro => (distro == distroId), major, minor, build, revision); } private static bool IsDistroAndVersion(Predicate<string> distroPredicate, int major = -1, int minor = -1, int build = -1, int revision = -1) { if (IsLinux) { DistroInfo v = GetDistroInfo(); if (distroPredicate(v.Id) && VersionEquivalentTo(major, minor, build, revision, v.VersionId)) { return true; } } return false; } private static bool IsDistroAndVersionOrHigher(Predicate<string> distroPredicate, int major = -1, int minor = -1, int build = -1, int revision = -1) { if (IsLinux) { DistroInfo v = GetDistroInfo(); if (distroPredicate(v.Id) && VersionEquivalentToOrHigher(major, minor, build, revision, v.VersionId)) { return true; } } return false; } private static bool VersionEquivalentTo(int major, int minor, int build, int revision, Version actualVersionId) { return (major == -1 || major == actualVersionId.Major) && (minor == -1 || minor == actualVersionId.Minor) && (build == -1 || build == actualVersionId.Build) && (revision == -1 || revision == actualVersionId.Revision); } private static bool VersionEquivalentToOrHigher(int major, int minor, int build, int revision, Version actualVersionId) { return VersionEquivalentTo(major, minor, build, revision, actualVersionId) || (actualVersionId.Major > major || (actualVersionId.Major == major && (actualVersionId.Minor > minor || (actualVersionId.Minor == minor && (actualVersionId.Build > build || (actualVersionId.Build == build && (actualVersionId.Revision > revision || (actualVersionId.Revision == revision)))))))); } private struct DistroInfo { public string Id { get; set; } public Version VersionId { get; set; } } private static class libc { [DllImport("libc", SetLastError = true)] public static extern unsafe uint geteuid(); [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr gnu_get_libc_release(); [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr gnu_get_libc_version(); } } }
46.35
169
0.566073
[ "MIT" ]
06needhamt/runtime
src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs
14,832
C#
using System.ComponentModel.DataAnnotations; namespace Sikiro.Interface.Customer.User { public class UpdateUserStatusRequest { [Required] public string Id { get; set; } [Required] public int Status { get; set; } } }
18.785714
45
0.634981
[ "MIT" ]
SkyChenSky/Sikiro
samples/客户系统解决方案-新分层/Sikiro.Interface.Customer/User/UpdateUserStatusRequest.cs
265
C#
using System; namespace IdentityServer4.Admin.ViewModels.User { public class ListUserItemViewModel { public string UserName { get; set; } public string Email { get; set; } public string GivenName { get; set; } public string FamilyName { get; set; } public string PhoneNumber { get; set; } public string Roles { get; set; } public bool IsLockedOut { get; set; } public Guid Id { get; set; } } }
27.111111
47
0.588115
[ "MIT" ]
ERP-CI-CD-Organization/identityserver
src/IdentityServer4.Admin/ViewModels/User/ListUserItemViewModel.cs
488
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace ImpulsoProject.Migrations { public partial class Upgraded_To_Abp_v3_5_0 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Value", table: "AbpUserTokens", maxLength: 512, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "AbpUserTokens", maxLength: 128, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AbpUserTokens", maxLength: 64, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "SecurityStamp", table: "AbpUsers", maxLength: 128, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "PhoneNumber", table: "AbpUsers", maxLength: 32, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ConcurrencyStamp", table: "AbpUsers", maxLength: 128, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ConcurrencyStamp", table: "AbpRoles", maxLength: 128, nullable: true, oldClrType: typeof(string), oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Value", table: "AbpUserTokens", nullable: true, oldClrType: typeof(string), oldMaxLength: 512, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "AbpUserTokens", nullable: true, oldClrType: typeof(string), oldMaxLength: 128, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AbpUserTokens", nullable: true, oldClrType: typeof(string), oldMaxLength: 64, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "SecurityStamp", table: "AbpUsers", nullable: true, oldClrType: typeof(string), oldMaxLength: 128, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "PhoneNumber", table: "AbpUsers", nullable: true, oldClrType: typeof(string), oldMaxLength: 32, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ConcurrencyStamp", table: "AbpUsers", nullable: true, oldClrType: typeof(string), oldMaxLength: 128, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ConcurrencyStamp", table: "AbpRoles", nullable: true, oldClrType: typeof(string), oldMaxLength: 128, oldNullable: true); } } }
32.640625
71
0.486836
[ "MIT" ]
Escandiuzzi/ImpulsoProject
aspnet-core/src/ImpulsoProject.EntityFrameworkCore/Migrations/20180320131229_Upgraded_To_Abp_v3_5_0.cs
4,180
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.Configuration.Internal; using System.Diagnostics; namespace System.Configuration { public sealed class SectionInformation { // Flags private const int FlagAttached = 0x00000001; private const int FlagDeclared = 0x00000002; private const int FlagDeclarationRequired = 0x00000004; private const int FlagAllowLocation = 0x00000008; private const int FlagRestartOnExternalChanges = 0x00000010; private const int FlagRequirePermission = 0x00000020; private const int FlagLocationLocked = 0x00000040; private const int FlagChildrenLocked = 0x00000080; private const int FlagInheritInChildApps = 0x00000100; private const int FlagIsParentSection = 0x00000200; private const int FlagRemoved = 0x00000400; private const int FlagProtectionProviderDetermined = 0x00000800; private const int FlagForceSave = 0x00001000; private const int FlagIsUndeclared = 0x00002000; private const int FlagChildrenLockWithoutFileInput = 0x00004000; private const int FlagAllowExeDefinitionModified = 0x00010000; private const int FlagAllowDefinitionModified = 0x00020000; private const int FlagConfigSourceModified = 0x00040000; private const int FlagProtectionProviderModified = 0x00080000; private const int FlagOverrideModeDefaultModified = 0x00100000; private const int FlagOverrideModeModified = 0x00200000; // Used only for modified tracking private readonly ConfigurationSection _configurationSection; private ConfigurationAllowDefinition _allowDefinition; private ConfigurationAllowExeDefinition _allowExeDefinition; private MgmtConfigurationRecord _configRecord; private string _configSource; private SafeBitVector32 _flags; private SimpleBitVector32 _modifiedFlags; private OverrideModeSetting _overrideMode; // The override mode at the current config path private OverrideModeSetting _overrideModeDefault; // The default mode for the section in _configurationSection private ProtectedConfigurationProvider _protectionProvider; private string _typeName; internal SectionInformation(ConfigurationSection associatedConfigurationSection) { ConfigKey = string.Empty; Name = string.Empty; _configurationSection = associatedConfigurationSection; _allowDefinition = ConfigurationAllowDefinition.Everywhere; _allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication; _overrideModeDefault = OverrideModeSetting.s_sectionDefault; _overrideMode = OverrideModeSetting.s_locationDefault; _flags[FlagAllowLocation] = true; _flags[FlagRestartOnExternalChanges] = true; _flags[FlagRequirePermission] = true; _flags[FlagInheritInChildApps] = true; _flags[FlagForceSave] = false; _modifiedFlags = default; } private bool IsRuntime => _flags[FlagAttached] && (_configRecord == null); internal bool Attached => _flags[FlagAttached]; internal string ConfigKey { get; private set; } internal bool Removed { get { return _flags[FlagRemoved]; } set { _flags[FlagRemoved] = value; } } public string SectionName => ConfigKey; public string Name { get; private set; } public ConfigurationAllowDefinition AllowDefinition { get { return _allowDefinition; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow AllowDefinition to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.AllowDefinition != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _allowDefinition = value; _modifiedFlags[FlagAllowDefinitionModified] = true; } } internal bool AllowDefinitionModified => _modifiedFlags[FlagAllowDefinitionModified]; public ConfigurationAllowExeDefinition AllowExeDefinition { get { return _allowExeDefinition; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow AllowDefinition to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.AllowExeDefinition != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _allowExeDefinition = value; _modifiedFlags[FlagAllowExeDefinitionModified] = true; } } internal bool AllowExeDefinitionModified => _modifiedFlags[FlagAllowExeDefinitionModified]; public OverrideMode OverrideModeDefault { get { return _overrideModeDefault.OverrideMode; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow OverrideModeDefault to be different from current value, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.OverrideModeDefault.OverrideMode != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); // Threat "Inherit" as "Allow" as "Inherit" does not make sense as a default if (value == OverrideMode.Inherit) value = OverrideMode.Allow; _overrideModeDefault.OverrideMode = value; _modifiedFlags[FlagOverrideModeDefaultModified] = true; } } internal OverrideModeSetting OverrideModeDefaultSetting => _overrideModeDefault; internal bool OverrideModeDefaultModified => _modifiedFlags[FlagOverrideModeDefaultModified]; public bool AllowLocation { get { return _flags[FlagAllowLocation]; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow AllowLocation to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.AllowLocation != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagAllowLocation] = value; _modifiedFlags[FlagAllowLocation] = true; } } internal bool AllowLocationModified => _modifiedFlags[FlagAllowLocation]; public bool AllowOverride { get { return _overrideMode.AllowOverride; } set { VerifyIsEditable(); VerifySupportsLocation(); _overrideMode.AllowOverride = value; _modifiedFlags[FlagOverrideModeModified] = true; } } public OverrideMode OverrideMode { get { return _overrideMode.OverrideMode; } set { VerifyIsEditable(); VerifySupportsLocation(); _overrideMode.OverrideMode = value; _modifiedFlags[FlagOverrideModeModified] = true; // Modify the state of OverrideModeEffective according to the changes to the current mode switch (value) { case OverrideMode.Inherit: // Wehen the state is changing to inherit - apply the value from parent which does not // include the file input lock mode _flags[FlagChildrenLocked] = _flags[FlagChildrenLockWithoutFileInput]; break; case OverrideMode.Allow: _flags[FlagChildrenLocked] = false; break; case OverrideMode.Deny: _flags[FlagChildrenLocked] = true; break; default: Debug.Fail("Unexpected value for OverrideMode"); break; } } } public OverrideMode OverrideModeEffective => _flags[FlagChildrenLocked] ? OverrideMode.Deny : OverrideMode.Allow ; internal OverrideModeSetting OverrideModeSetting => _overrideMode; // LocationAttributesAreDefault // // Are the location attributes for this section set to the // default settings? internal bool LocationAttributesAreDefault => _overrideMode.IsDefaultForLocationTag && _flags[FlagInheritInChildApps]; public string ConfigSource { get { return _configSource ?? string.Empty; } set { VerifyIsEditable(); string configSource = !string.IsNullOrEmpty(value) ? BaseConfigurationRecord.NormalizeConfigSource(value, null) : null; // return early if there is no change if (configSource == _configSource) return; _configRecord?.ChangeConfigSource(this, _configSource, ConfigSourceStreamName, configSource); _configSource = configSource; _modifiedFlags[FlagConfigSourceModified] = true; } } internal bool ConfigSourceModified => _modifiedFlags[FlagConfigSourceModified]; internal string ConfigSourceStreamName { get; set; } public bool InheritInChildApplications { get { return _flags[FlagInheritInChildApps]; } set { VerifyIsEditable(); VerifySupportsLocation(); _flags[FlagInheritInChildApps] = value; } } // True if the section is declared at the current level public bool IsDeclared { get { VerifyNotParentSection(); return _flags[FlagDeclared]; } } // Is the Declaration Required. It is required if it is not set // in a parent, or the parent entry does not have the type public bool IsDeclarationRequired { get { VerifyNotParentSection(); return _flags[FlagDeclarationRequired]; } } // Is the Definition Allowed at this point. This is all depending // on the Definition that is allowed, and what context we are // writing the file private bool IsDefinitionAllowed => (_configRecord == null) || _configRecord.IsDefinitionAllowed(_allowDefinition, _allowExeDefinition); public bool IsLocked => _flags[FlagLocationLocked] || !IsDefinitionAllowed || _configurationSection.ElementInformation.IsLocked; public bool IsProtected => ProtectionProvider != null; public ProtectedConfigurationProvider ProtectionProvider { get { if (!_flags[FlagProtectionProviderDetermined] && (_configRecord != null)) { _protectionProvider = _configRecord.GetProtectionProviderFromName(ProtectionProviderName, false); _flags[FlagProtectionProviderDetermined] = true; } return _protectionProvider; } } internal string ProtectionProviderName { get; private set; } public bool RestartOnExternalChanges { get { return _flags[FlagRestartOnExternalChanges]; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow RestartOnExternalChanges to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.RestartOnExternalChanges != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagRestartOnExternalChanges] = value; _modifiedFlags[FlagRestartOnExternalChanges] = true; } } internal bool RestartOnExternalChangesModified => _modifiedFlags[FlagRestartOnExternalChanges]; public bool RequirePermission { get { return _flags[FlagRequirePermission]; } set { VerifyIsEditable(); VerifyIsEditableFactory(); // allow RequirePermission to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if ((factoryRecord != null) && (factoryRecord.RequirePermission != value)) throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); _flags[FlagRequirePermission] = value; _modifiedFlags[FlagRequirePermission] = true; } } internal bool RequirePermissionModified => _modifiedFlags[FlagRequirePermission]; public string Type { get { return _typeName; } set { if (string.IsNullOrEmpty(value)) throw ExceptionUtil.PropertyNullOrEmpty(nameof(Type)); VerifyIsEditable(); VerifyIsEditableFactory(); // allow type to be different from current type, // so long as it doesn't conflict with a type already defined FactoryRecord factoryRecord = FindParentFactoryRecord(false); if (factoryRecord != null) { IInternalConfigHost host = null; if (_configRecord != null) host = _configRecord.Host; if (!factoryRecord.IsEquivalentType(host, value)) { throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey)); } } _typeName = value; } } internal string RawXml { get; set; } // True if the section will be serialized to the current hierarchy level, regardless of // ConfigurationSaveMode. public bool ForceSave { get { return _flags[FlagForceSave]; } set { VerifyIsEditable(); _flags[FlagForceSave] = value; } } internal void ResetModifiedFlags() { _modifiedFlags = default; } internal bool IsModifiedFlags() { return _modifiedFlags.Data != 0; } // for instantiation of a ConfigurationSection from GetConfig internal void AttachToConfigurationRecord(MgmtConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord) { SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord); _configRecord = configRecord; } internal void SetRuntimeConfigurationInformation(BaseConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord) { _flags[FlagAttached] = true; // factory info ConfigKey = factoryRecord.ConfigKey; Name = factoryRecord.Name; _typeName = factoryRecord.FactoryTypeName; _allowDefinition = factoryRecord.AllowDefinition; _allowExeDefinition = factoryRecord.AllowExeDefinition; _flags[FlagAllowLocation] = factoryRecord.AllowLocation; _flags[FlagRestartOnExternalChanges] = factoryRecord.RestartOnExternalChanges; _flags[FlagRequirePermission] = factoryRecord.RequirePermission; _overrideModeDefault = factoryRecord.OverrideModeDefault; if (factoryRecord.IsUndeclared) { _flags[FlagIsUndeclared] = true; _flags[FlagDeclared] = false; _flags[FlagDeclarationRequired] = false; } else { _flags[FlagIsUndeclared] = false; _flags[FlagDeclared] = configRecord.GetFactoryRecord(factoryRecord.ConfigKey, false) != null; _flags[FlagDeclarationRequired] = configRecord.IsRootDeclaration(factoryRecord.ConfigKey, false); } // section info _flags[FlagLocationLocked] = sectionRecord.Locked; _flags[FlagChildrenLocked] = sectionRecord.LockChildren; _flags[FlagChildrenLockWithoutFileInput] = sectionRecord.LockChildrenWithoutFileInput; if (sectionRecord.HasFileInput) { SectionInput fileInput = sectionRecord.FileInput; _flags[FlagProtectionProviderDetermined] = fileInput.IsProtectionProviderDetermined; _protectionProvider = fileInput.ProtectionProvider; SectionXmlInfo sectionXmlInfo = fileInput.SectionXmlInfo; _configSource = sectionXmlInfo.ConfigSource; ConfigSourceStreamName = sectionXmlInfo.ConfigSourceStreamName; _overrideMode = sectionXmlInfo.OverrideModeSetting; _flags[FlagInheritInChildApps] = !sectionXmlInfo.SkipInChildApps; ProtectionProviderName = sectionXmlInfo.ProtectionProviderName; } else { _flags[FlagProtectionProviderDetermined] = false; _protectionProvider = null; } // element context information _configurationSection.AssociateContext(configRecord); } internal void DetachFromConfigurationRecord() { RevertToParent(); _flags[FlagAttached] = false; _configRecord = null; } private void VerifyDesigntime() { if (IsRuntime) throw new InvalidOperationException(SR.Config_operation_not_runtime); } private void VerifyIsAttachedToConfigRecord() { if (_configRecord == null) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_not_attached); } // VerifyIsEditable // // Verify the section is Editable. // It may not be editable for the following reasons: // - We are in Runtime mode, not Design time // - The section is not attached to a _configRecord. // - We are locked (ie. allowOveride = false ) // - We are a parent section (ie. Retrieved from GetParentSection) // internal void VerifyIsEditable() { VerifyDesigntime(); if (IsLocked) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_locked); if (_flags[FlagIsParentSection]) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_parentsection); if (!_flags[FlagAllowLocation] && (_configRecord != null) && _configRecord.IsLocationConfig) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_location_locked); } private void VerifyNotParentSection() { if (_flags[FlagIsParentSection]) throw new InvalidOperationException(SR.Config_configsection_parentnotvalid); } // Verify that we support the location tag. This is true either // in machine.config, or in any place for the web config system private void VerifySupportsLocation() { if ((_configRecord != null) && !_configRecord.RecordSupportsLocation) throw new InvalidOperationException(SR.Config_cannot_edit_locationattriubtes); } internal void VerifyIsEditableFactory() { if ((_configRecord != null) && _configRecord.IsLocationConfig) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_in_location_config); // Can't edit factory if the section is built-in if (BaseConfigurationRecord.IsImplicitSection(ConfigKey)) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_implicit); // Can't edit undeclared section if (_flags[FlagIsUndeclared]) throw new InvalidOperationException(SR.Config_cannot_edit_configurationsection_when_it_is_undeclared); } private FactoryRecord FindParentFactoryRecord(bool permitErrors) { FactoryRecord factoryRecord = null; if ((_configRecord != null) && !_configRecord.Parent.IsRootConfig) factoryRecord = _configRecord.Parent.FindFactoryRecord(ConfigKey, permitErrors); return factoryRecord; } // Force the section declaration to be written out during Save. public void ForceDeclaration() { ForceDeclaration(true); } // If force==false, it actually means don't declare it at // the current level. public void ForceDeclaration(bool force) { VerifyIsEditable(); if ((force == false) && _flags[FlagDeclarationRequired]) { // Since it is required, we can not remove it } else { // CONSIDER: There is no apriori way to determine if a section // is implicit or undeclared. Would it be better to simply // fail silently so that app code can easily loop through sections // and declare all of them? if (force && BaseConfigurationRecord.IsImplicitSection(SectionName)) throw new ConfigurationErrorsException(SR.Format(SR.Cannot_declare_or_remove_implicit_section, SectionName)); if (force && _flags[FlagIsUndeclared]) { throw new ConfigurationErrorsException( SR.Config_cannot_edit_configurationsection_when_it_is_undeclared); } _flags[FlagDeclared] = force; } } // method to cause a section to be protected using the specified provider public void ProtectSection(string protectionProvider) { ProtectedConfigurationProvider protectedConfigurationProvider; VerifyIsEditable(); // Do not encrypt sections that will be read by a native reader. // These sections are be marked with allowLocation=false. // Also, the configProtectedData section cannot be encrypted! if (!AllowLocation || (ConfigKey == BaseConfigurationRecord.ReservedSectionProtectedConfiguration)) throw new InvalidOperationException(SR.Config_not_allowed_to_encrypt_this_section); if (_configRecord != null) { if (string.IsNullOrEmpty(protectionProvider)) protectionProvider = _configRecord.DefaultProviderName; protectedConfigurationProvider = _configRecord.GetProtectionProviderFromName(protectionProvider, true); } else throw new InvalidOperationException(SR.Must_add_to_config_before_protecting_it); ProtectionProviderName = protectionProvider; _protectionProvider = protectedConfigurationProvider; _flags[FlagProtectionProviderDetermined] = true; _modifiedFlags[FlagProtectionProviderModified] = true; } public void UnprotectSection() { VerifyIsEditable(); _protectionProvider = null; ProtectionProviderName = null; _flags[FlagProtectionProviderDetermined] = true; _modifiedFlags[FlagProtectionProviderModified] = true; } public ConfigurationSection GetParentSection() { VerifyDesigntime(); if (_flags[FlagIsParentSection]) throw new InvalidOperationException(SR.Config_getparentconfigurationsection_first_instance); // if a users create a configsection with : sectionType sec = new sectionType(); // the config record will be null. Return null for the parent in this case. ConfigurationSection ancestor = null; if (_configRecord != null) { ancestor = _configRecord.FindAndCloneImmediateParentSection(_configurationSection); if (ancestor != null) { ancestor.SectionInformation._flags[FlagIsParentSection] = true; ancestor.SetReadOnly(); } } return ancestor; } public string GetRawXml() { VerifyDesigntime(); VerifyNotParentSection(); return RawXml ?? _configRecord?.GetRawXml(ConfigKey); } public void SetRawXml(string rawXml) { VerifyIsEditable(); if (_configRecord != null) _configRecord.SetRawXml(_configurationSection, rawXml); else RawXml = string.IsNullOrEmpty(rawXml) ? null : rawXml; } public void RevertToParent() { VerifyIsEditable(); VerifyIsAttachedToConfigRecord(); _configRecord.RevertToParent(_configurationSection); } } }
39.475146
129
0.614866
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionInformation.cs
27,001
C#
using Entities.Concrete; using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bussines.ValidationRules.FluentValidation { public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(u => u.Code).NotEmpty(); RuleFor(u => u.Name).NotEmpty(); RuleFor(u => u.Pass).NotEmpty(); RuleFor(u => u.Filter).NotEmpty(); } } }
23.863636
56
0.638095
[ "MIT" ]
boole52/EnterpriseProject
Bussines/ValidationRules/FluentValidation/UserValidator.cs
527
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using koi_jabo.Models; using koi_jabo.Entity; using System.Web.Http; using System.Net.Http; using MongoDB.Driver; using koi_jabo_models.Models.Pagination; namespace koi_jabo.Lib.Repository.Restaurant { public class RestaurantRepository { RestaurantManager _manager; public RestaurantRepository() { _manager = new RestaurantManager(); } public async Task<RestaurantEntity> Create(RestaurantModel model) { return await _manager.Create(model); } public async Task<PageEnvelope<RestaurantSummaryEntity>> Search(HttpRequestMessage request, int page, int pageSize) { var searchResult = await _manager.Search(request, page, pageSize); var total = await _manager.CountToTal(request); var queryStringParameter = request.GetQueryNameValuePairs().ToDictionary(x => x.Key, y =>(object) y.Value); return new PageEnvelope<RestaurantSummaryEntity>(total, page, pageSize, "DefaultApi", searchResult, request, queryStringParameter); } public Task<RestaurantEntity> Get(string id) { return _manager.Get(id); } public async Task<ReplaceOneResult> Update(RestaurantEntity restaurant) { return await _manager.Update(restaurant); } public Task<DeleteResult> Delete(string id) { return _manager.Delete(id); } public async Task<RestaurantEntity> FormDataInput(List<RestaurantFormValue> value) { var form = new RestaurantFormValue(); var entity = form.ParseFormValueToModel(value); return await _manager.Create(entity); } internal async Task<ReplaceOneResult> UpdateFormValue(List<RestaurantFormValue> value) { var form = new RestaurantFormValue(); var entity = form.ParseFormValueToModel(value); return await _manager.Update(entity); } } }
32.666667
143
0.649351
[ "Apache-2.0" ]
KoiJabo/KoiJabo-WebApi
koi jabo/koi jabo/Lib/Repository/Restaurant/RestaurantRepository.cs
2,158
C#
#region Copyright /*Copyright (C) 2015 Wosad 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. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Wosad.Dynamo.UI.Views.Analysis.Beam.Flexure { /// <summary> /// Interaction logic for BeamForceCaseView.xaml /// </summary> public partial class BeamDeflectionCaseView : UserControl { public BeamDeflectionCaseView() { InitializeComponent(); } } }
28.695652
75
0.739394
[ "Apache-2.0" ]
Wosad/Wosad.Dynamo
Wosad.Dynamo.UI/Views/Analysis/Beam/Flexure/BeamDeflectionCaseView.xaml.cs
1,322
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace V5_DataPublishModule.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("V5_DataPublishModule.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.546875
186
0.591001
[ "Apache-2.0" ]
Haxine/V5_DataCollection
V5_DataPublishModule/Properties/Resources.Designer.cs
2,817
C#
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; namespace Potato.Database.Shared.Builders.Modifiers { /// <summary> /// A unique index /// </summary> [Serializable] public class Unique : IndexModifier { } }
31.653846
75
0.716889
[ "Apache-2.0" ]
phogue/Potato
src/Potato.Database.Shared/Builders/Modifiers/Unique.cs
823
C#
using System; using System.Collections.Generic; using System.Text; namespace Kanyon.Core { public class PrecompiledManifestObject : IManifestObject { public string ApiVersion => "github.com/kanyon-k8s/kanyon/v1alpha1"; public string Kind => nameof(PrecompiledManifestObject); public string ManifestOutput { get; set; } } }
22.6875
76
0.710744
[ "MIT" ]
ermontgo/kapitan
src/Kanyon.Core/PrecompiledManifestObject.cs
365
C#
/*---------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v.2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ using System.Reflection; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется посредством следующего // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("NUnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NUnitTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Задание значения false для атрибута ComVisible приведет к тому, что типы из этой сборки станут невидимыми // для COM-компонентов. Если к одному из типов этой сборки необходимо обращаться из // модели COM, задайте для атрибута ComVisible этого типа значение true. [assembly: ComVisible(false)] // Если данный проект доступен для модели COM, следующий GUID используется в качестве идентификатора библиотеки типов [assembly: Guid("93acc849-e7e1-4695-b59d-54b3737e48a6")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [сборка: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.904762
118
0.690899
[ "MPL-2.0" ]
240596448/OneScript
src/NUnitTests/Properties/AssemblyInfo.cs
2,438
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.ComponentModel; using System.Drawing; using System.Windows.Forms; using Gallio.Common; using Gallio.Runtime.ProgressMonitoring; using Gallio.Runtime.Security; namespace Gallio.UI.ControlPanel.Preferences { internal partial class PreferenceControlPanelTab : ControlPanelTab { public PreferenceControlPanelTab() { InitializeComponent(); } /// <summary> /// Adds a preference pane. /// </summary> /// <param name="path">The preference pane path consisting of slash-delimited name segments /// specifying tree nodes.</param> /// <param name="icon">The preference pane icon, or null if none.</param> /// <param name="scope">The preference pane scope, or null if none.</param> /// <param name="paneFactory">The preference pane factory.</param> public void AddPane(string path, Icon icon, PreferencePaneScope scope, GallioFunc<PreferencePane> paneFactory) { string[] pathSegments = path.Split('/'); if (pathSegments.Length == 0) throw new ArgumentException("Preference pane path must not be empty.", "path"); TreeNode treeNode = null; foreach (string pathSegment in pathSegments) { TreeNodeCollection treeNodeCollection = treeNode != null ? treeNode.Nodes : preferencePaneTree.Nodes; TreeNode childTreeNode = FindTreeNodeByName(treeNodeCollection, pathSegment); if (childTreeNode == null) { childTreeNode = new TreeNode(pathSegment); childTreeNode.Tag = new PaneInfo(CreatePlaceholderPreferencePane, pathSegment); treeNodeCollection.Add(childTreeNode); } treeNode = childTreeNode; } string title = pathSegments[pathSegments.Length - 1]; if (scope == PreferencePaneScope.Machine) title += " (machine setting)"; treeNode.Tag = new PaneInfo(paneFactory, title); if (icon != null) { int imageIndex = preferencePaneIconImageList.Images.Count; preferencePaneIconImageList.Images.Add(icon); treeNode.ImageIndex = imageIndex; treeNode.SelectedImageIndex = imageIndex; } } /// <inheritdoc /> public override void ApplyPendingSettingsChanges(IElevationContext elevationContext, IProgressMonitor progressMonitor) { using (progressMonitor.BeginTask("Saving preferences.", 1)) { var preferencePanes = new List<PreferencePane>(GetPreferencePanes()); if (preferencePanes.Count == 0) return; double workPerPreferencePane = 1.0 / preferencePanes.Count; foreach (PreferencePane preferencePane in preferencePanes) { if (progressMonitor.IsCanceled) return; if (preferencePane.PendingSettingsChanges) { preferencePane.ApplyPendingSettingsChanges( preferencePane.RequiresElevation ? elevationContext : null, progressMonitor.CreateSubProgressMonitor(workPerPreferencePane)); } else { progressMonitor.Worked(workPerPreferencePane); } } } } private IEnumerable<PreferencePane> GetPreferencePanes() { foreach (PreferencePaneContainer preferencePaneContainer in preferencePaneSplitContainer.Panel2.Controls) yield return preferencePaneContainer.PreferencePane; } private static PreferencePane CreatePlaceholderPreferencePane() { return new PlaceholderPreferencePane(); } private static TreeNode FindTreeNodeByName(TreeNodeCollection collection, string name) { foreach (TreeNode node in collection) if (node.Text == name) return node; return null; } private void EnsurePaneVisible() { TreeNode treeNode = preferencePaneTree.SelectedNode; if (treeNode != null) { bool found = false; foreach (PreferencePaneContainer preferencePaneContainer in preferencePaneSplitContainer.Panel2.Controls) { if (preferencePaneContainer.Tag == treeNode) { preferencePaneContainer.Visible = true; found = true; } else { preferencePaneContainer.Visible = false; } } if (!found) { PaneInfo paneInfo = (PaneInfo) treeNode.Tag; PreferencePane preferencePane = paneInfo.Factory(); preferencePane.Dock = DockStyle.Fill; preferencePane.Margin = new Padding(0, 0, 0, 0); preferencePane.AutoSize = true; preferencePane.AutoSizeMode = AutoSizeMode.GrowAndShrink; preferencePane.PendingSettingsChangesChanged += preferencePane_PendingSettingsChangesChanged; preferencePane.RequiresElevationChanged += preferencePane_ElevationRequiredChanged; PreferencePaneContainer preferencePaneContainer = new PreferencePaneContainer(); preferencePaneContainer.Dock = DockStyle.Fill; preferencePaneContainer.Margin = new Padding(0, 0, 0, 0); preferencePaneContainer.AutoSize = true; preferencePaneContainer.AutoSizeMode = AutoSizeMode.GrowAndShrink; preferencePaneContainer.Tag = treeNode; preferencePaneContainer.PreferencePane = preferencePane; preferencePaneContainer.Title = paneInfo.Title; preferencePaneSplitContainer.Panel2.Controls.Add(preferencePaneContainer); RefreshPendingSettingsChangesState(); RefreshElevationRequiredState(); } } } private void preferencePaneTree_AfterSelect(object sender, TreeViewEventArgs e) { EnsurePaneVisible(); } private void PreferenceControlPanelTab_Load(object sender, EventArgs e) { if (preferencePaneTree.SelectedNode == null && preferencePaneTree.Nodes.Count != 0) { preferencePaneTree.SelectedNode = preferencePaneTree.Nodes[0]; } preferencePaneTree.ExpandAll(); } private void preferencePane_PendingSettingsChangesChanged(object sender, EventArgs e) { RefreshPendingSettingsChangesState(); } private void preferencePane_ElevationRequiredChanged(object sender, EventArgs e) { RefreshElevationRequiredState(); } private void RefreshPendingSettingsChangesState() { foreach (PreferencePane preferencePane in GetPreferencePanes()) { if (preferencePane.PendingSettingsChanges) { PendingSettingsChanges = true; return; } } PendingSettingsChanges = false; } private void RefreshElevationRequiredState() { foreach (PreferencePane preferencePane in GetPreferencePanes()) { if (preferencePane.RequiresElevation) { RequiresElevation = true; return; } } RequiresElevation = false; } private sealed class PaneInfo { public readonly GallioFunc<PreferencePane> Factory; public readonly string Title; public PaneInfo(GallioFunc<PreferencePane> factory, string title) { Factory = factory; Title = title; } } } }
38.52439
127
0.562836
[ "ECL-2.0", "Apache-2.0" ]
soelske/mbunit-v3
src/Gallio/Gallio.UI/ControlPanel/Preferences/PreferenceControlPanelTab.cs
9,477
C#
namespace Reductech.Sequence.Core.Tests.Steps; public partial class ArrayConcatTests : StepTestBase<ArrayConcat<SCLInt>, Array<SCLInt>> { /// <inheritdoc /> protected override IEnumerable<StepCase> StepCases { get { yield break; } } }
24.636364
89
0.671587
[ "Apache-2.0" ]
reductech/Core
Core.Tests/Steps/ArrayConcatTests.cs
273
C#
using System; using System.Threading; using System.Threading.Tasks; using Quartz.Logging; using Quartz.Util; namespace Quartz.Impl.AdoJobStore { internal class ClusterManager { private static readonly ILog log = LogProvider.GetLogger(typeof(ClusterManager)); // keep constant lock requestor id for manager's lifetime private readonly Guid requestorId = Guid.NewGuid(); private readonly JobStoreSupport jobStoreSupport; private QueuedTaskScheduler taskScheduler = null!; private readonly CancellationTokenSource cancellationTokenSource; private Task task = null!; private int numFails; internal ClusterManager(JobStoreSupport jobStoreSupport) { this.jobStoreSupport = jobStoreSupport; cancellationTokenSource = new CancellationTokenSource(); } public async Task Initialize() { await Manage().ConfigureAwait(false); string threadName = $"QuartzScheduler_{jobStoreSupport.InstanceName}-{jobStoreSupport.InstanceId}_ClusterManager"; taskScheduler = new QueuedTaskScheduler(threadCount: 1, threadPriority: ThreadPriority.AboveNormal, threadName: threadName, useForegroundThreads: !jobStoreSupport.MakeThreadsDaemons); task = Task.Factory.StartNew(() => Run(cancellationTokenSource.Token), cancellationTokenSource.Token, TaskCreationOptions.HideScheduler, taskScheduler).Unwrap(); } public async Task Shutdown() { cancellationTokenSource.Cancel(); try { taskScheduler.Dispose(); await task.ConfigureAwait(false); } catch (OperationCanceledException) { } } private async Task<bool> Manage() { bool res = false; try { res = await jobStoreSupport.DoCheckin(requestorId).ConfigureAwait(false); numFails = 0; log.Debug($"[iModelBridgeService.Quartz: {Thread.CurrentThread.ManagedThreadId}] ClusterManager:Manage -- check-in complete"); } catch (Exception e) { log.ErrorException($"[iModelBridgeService.Quartz: {Thread.CurrentThread.ManagedThreadId}] ClusterManager:Manage -- Error managing cluster: " + e.Message, e); numFails++; } return res; } private async Task Run(CancellationToken token) { while (true) { token.ThrowIfCancellationRequested(); TimeSpan timeToSleep = jobStoreSupport.ClusterCheckinInterval; TimeSpan transpiredTime = SystemTime.UtcNow() - jobStoreSupport.LastCheckin; timeToSleep = timeToSleep - transpiredTime; if (timeToSleep <= TimeSpan.Zero) { log.Debug($"[iModelBridgeService.Quartz: {Thread.CurrentThread.ManagedThreadId}] ClusterManager:Run -- Setting timeToSleep to 100ms"); timeToSleep = TimeSpan.FromMilliseconds(100); } if (numFails > 0) { log.Debug($"[iModelBridgeService.Quartz: {Thread.CurrentThread.ManagedThreadId}] ClusterManager:Run -- In numFails if condition with numFails = {numFails}"); timeToSleep = jobStoreSupport.DbRetryInterval > timeToSleep ? jobStoreSupport.DbRetryInterval : timeToSleep; } log.Debug($"[iModelBridgeService.Quartz: {Thread.CurrentThread.ManagedThreadId}] ClusterManager:Run -- Sleeping for {timeToSleep.TotalSeconds} seconds"); await Task.Delay(timeToSleep, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (await Manage().ConfigureAwait(false)) { jobStoreSupport.SignalSchedulingChangeImmediately(SchedulerConstants.SchedulingSignalDateTime); } } // ReSharper disable once FunctionNeverReturns } } }
39.628571
195
0.620524
[ "Apache-2.0" ]
davidhjones/quartznet
src/Quartz/Impl/AdoJobStore/ClusterManager.cs
4,163
C#
using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Jal.Router.AzureServiceBus.Impl; using Jal.Router.Interface; using Jal.Router.Interface.Inbound; using Jal.Router.Interface.Management; namespace Jal.Router.AzureServiceBus.Installer { public class AzureServiceBusRouterInstaller : IWindsorInstaller { private readonly int _maxconcurrentcalls; private readonly TimeSpan? _autorenewtimeout; public AzureServiceBusRouterInstaller(int maxconcurrentcalls=0, TimeSpan? autorenewtimeout = null) { _autorenewtimeout = autorenewtimeout; _maxconcurrentcalls = maxconcurrentcalls; } public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component.For<IPointToPointChannel>().ImplementedBy<AzureServiceBusQueue>().Named(typeof(AzureServiceBusQueue).FullName).DependsOn(new { maxconcurrentcalls = _maxconcurrentcalls, autorenewtimeout = _autorenewtimeout }).LifestyleSingleton()); container.Register(Component.For<IPublishSubscribeChannel>().ImplementedBy<AzureServiceBusTopic>().Named(typeof(AzureServiceBusTopic).FullName).DependsOn(new { maxconcurrentcalls = _maxconcurrentcalls, autorenewtimeout = _autorenewtimeout }).LifestyleSingleton()); container.Register(Component.For<IRequestReplyChannel>().ImplementedBy<AzureServiceBusSession>().Named(typeof(AzureServiceBusSession).FullName).LifestyleSingleton()); container.Register(Component.For<IChannelManager>().ImplementedBy<AzureServiceBusManager>().Named(typeof(AzureServiceBusManager).FullName).LifestyleSingleton()); container.Register(Component.For<IMessageAdapter>().ImplementedBy<BrokeredMessageAdapter>().Named(typeof(BrokeredMessageAdapter).FullName).LifestyleSingleton()); container.Register(Component.For<IMessageSerializer>().ImplementedBy<JsonMessageSerializer>().Named(typeof(JsonMessageSerializer).FullName).LifestyleSingleton()); } } }
52.5
276
0.776667
[ "Apache-2.0" ]
bobhonores/Jal.Router
Jal.Router.AzureServiceBus.Installer/AzureServiceBusRouterInstaller.cs
2,102
C#
using System; using Grasshopper.Kernel; using ARDB = Autodesk.Revit.DB; namespace RhinoInside.Revit.GH.Parameters { public class AssemblyInstance : GraphicalElementT<Types.AssemblyInstance, ARDB.AssemblyInstance> { public override GH_Exposure Exposure => GH_Exposure.secondary; public override Guid ComponentGuid => new Guid("d7958ccf-9847-4e27-996b-b7fdc0eb1086"); public AssemblyInstance() : base ( name: "Assembly", nickname: "A", description: "Contains a collection of Revit assemblies", category: "Params", subcategory: "Revit" ) { } } }
28.409091
99
0.6816
[ "MIT" ]
ishanshah4343/rhino.inside-revit
src/RhinoInside.Revit.GH/Parameters/AssemblyInstance.cs
625
C#
using UnityEngine; public class SingletnoAutoMono<T> : MonoBehaviour where T : SingletnoAutoMono<T> { private static string MonoSingletionName = "MonoSingletionRoot"; private static GameObject MonoSingletionRoot; private static T instance; public static T Instance { get { if (MonoSingletionRoot == null)//如果是第一次调用单例类型就查找所有单例类的总结点 { MonoSingletionRoot = GameObject.Find(MonoSingletionName); if (MonoSingletionRoot == null)//如果没有找到则创建一个所有继承MonoBehaviour单例类的节点 { MonoSingletionRoot = new GameObject(); MonoSingletionRoot.name = MonoSingletionName; DontDestroyOnLoad(MonoSingletionRoot);//防止被销毁 } } if (instance == null)//为空表示第一次获取当前单例类 { instance = MonoSingletionRoot.GetComponent<T>(); if (instance == null)//如果当前要调用的单例类不存在则添加一个 { instance = MonoSingletionRoot.AddComponent<T>(); } } return instance; } } }
32.055556
83
0.558059
[ "MIT" ]
euphoriaer/Roguelike-fantasy
Project/ARMRP-unity/Assets/Scripts/ProjectBase/Base/SingletnoAutoMono.cs
1,322
C#
using Components.Data; var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseWebRoot("wwwroot"); builder.WebHost.UseStaticWebAssets(); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton<WeatherForecastService>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); app.Run();
26.785714
131
0.76
[ "MIT" ]
PotatoMaster101/BlazorServerInDepthSolutions
Components/Program.cs
750
C#
using System; using System.Collections.Generic; using System.Linq; using NHibernate.Extensions.Tests.Entities; using NHibernate.Linq; using NUnit.Framework; namespace NHibernate.Extensions.Tests { [TestFixture] public partial class DeepCloneTests : BaseIncludeTest { [Test] public void TestSimpleProperties() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .ForType<EQBPerson>(t => t.ForMember(m => m.Name, opts => opts.Ignore()) )); // Lazy load some relations after cloning var friend = petra.BestFriend; var card = petra.IdentityCard; } Assert.AreEqual(petra.Id, clone.Id); Assert.AreEqual(null, clone.Name); Assert.AreEqual(petra.LastName, clone.LastName); Assert.IsNotNull(petra.BestFriend); Assert.IsNotNull(petra.IdentityCard); Assert.IsNull(clone.MarriedWith); Assert.IsNull(clone.BestFriend); Assert.IsNull(clone.IdentityCard); Assert.AreEqual(0, clone.OwnedHouses.Count); Assert.AreEqual(0, clone.CurrentOwnedVehicles.Count); } [Test] public void TestCloneAsReferenceAndIgnoreIdentifiers() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.IdentityCard) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .ForType<EQBPerson>(t => t .ForMember(m => m.Name, opts => opts.Ignore()) .CloneIdentifier(false) ) .CloneIdentifier(true) .CanCloneAsReference(type => type == typeof(EQBIdentityCard)) ); } Assert.AreEqual(default(int), clone.Id); Assert.IsNull(clone.Name); Assert.AreEqual(petra.LastName, clone.LastName); Assert.AreEqual(petra.IdentityCard, clone.IdentityCard); } [Test] public void TestReferences() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.BestFriend.IdentityCard) .Include(o => o.BestFriend.BestFriend) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra); } Assert.AreEqual(petra.Id, clone.Id); Assert.IsNotNull(clone.BestFriend); Assert.IsNotNull(clone.BestFriend.IdentityCard); Assert.AreEqual(clone.BestFriend, clone.BestFriend.IdentityCard.Owner); Assert.IsNotNull(clone.BestFriend.BestFriend); Assert.IsNull(clone.BestFriend.BestFriend.BestFriend); Assert.IsNull(clone.IdentityCard); Assert.AreEqual(0, clone.OwnedHouses.Count); Assert.AreEqual(0, clone.CurrentOwnedVehicles.Count); } [Test] public void TestEntityResolver() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.BestFriend.IdentityCard) .Include(o => o.BestFriend.BestFriend) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .AddEntityResolver(t => true, (entity, persister) => persister.CreateProxy(persister.GetIdentifier(entity), null))); Assert.AreEqual(petra.Id, clone.Id); Assert.False(NHibernateUtil.IsInitialized(clone)); Assert.Throws<LazyInitializationException>(() => { var friend = clone.BestFriend; }); } } [Test] public void TestEntityResolverSkipRoot() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.BestFriend.IdentityCard) .Include(o => o.BestFriend.BestFriend) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .AddEntityResolver((t, e) => e != petra, (entity, persister) => persister.CreateProxy(persister.GetIdentifier(entity), null))); Assert.AreEqual(petra.Id, clone.Id); Assert.AreEqual(petra.Name, clone.Name); Assert.True(NHibernateUtil.IsInitialized(clone)); Assert.False(NHibernateUtil.IsInitialized(clone.BestFriend)); Assert.Throws<LazyInitializationException>(() => { var card = clone.BestFriend.IdentityCard; }); } } [Test] public void TestCollections() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.CurrentOwnedVehicles.First().Wheels) .Include(o => o.CurrentOwnedVehicles.First().RoadworthyTests) .Include(o => o.CurrentOwnedVehicles.First().MileageHistory) .Include(o => o.PreviouslyOwnedVehicles) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra); } Assert.IsNull(clone.BestFriend); Assert.IsNull(clone.IdentityCard); Assert.IsNull(clone.MarriedWith); Assert.AreEqual(1, clone.CurrentOwnedVehicles.Count); Assert.AreEqual(clone, clone.CurrentOwnedVehicles.First().CurrentOwner); Assert.AreEqual(4, clone.CurrentOwnedVehicles.First().Wheels.Count); Assert.AreEqual(clone.CurrentOwnedVehicles.First(), clone.CurrentOwnedVehicles.First().Wheels.First().Vehicle); Assert.AreEqual(2, clone.CurrentOwnedVehicles.First().RoadworthyTests.Count); Assert.AreEqual(clone.CurrentOwnedVehicles.First(), clone.CurrentOwnedVehicles.First().RoadworthyTests[new DateTime(2009, 2, 1)].Vehicle); Assert.AreEqual(2, clone.CurrentOwnedVehicles.First().MileageHistory.Count); Assert.AreEqual(5000, clone.CurrentOwnedVehicles.First().MileageHistory[new DateTime(2010, 1, 1)]); Assert.AreEqual(2, clone.PreviouslyOwnedVehicles.Count); Assert.AreEqual(clone, clone.CurrentOwnedVehicles.First().CurrentOwner); } [Test] public void TestFilter() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.PreviouslyOwnedVehicles) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .ForType<EQBPerson>(t => t .ForMember(m => m.Name, m => m.Filter(n => n + "2")) .ForMember(m => m.PreviouslyOwnedVehicles, m => m .Filter(col => new HashSet<EQBVehicle>(col.Take(1))) ) )); } Assert.AreEqual("Petra2", clone.Name); Assert.IsNull(clone.BestFriend); Assert.IsNull(clone.IdentityCard); Assert.IsNull(clone.MarriedWith); Assert.AreEqual(0, clone.CurrentOwnedVehicles.Count); Assert.AreEqual(1, clone.PreviouslyOwnedVehicles.Count); } [Test] public void TestSkipEntityTypes() { EQBPerson clone; EQBPerson petra; using (var session = NHConfig.OpenSession()) { petra = session.Query<EQBPerson>() .Include(o => o.IdentityCard) .Include(o => o.BestFriend.IdentityCard) .Include(o => o.CurrentOwnedVehicles.First().Wheels) .Include(o => o.CurrentOwnedVehicles.First().RoadworthyTests) .Include(o => o.CurrentOwnedVehicles.First().MileageHistory) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .SkipEntityTypes()); } Assert.IsNull(clone.IdentityCard); Assert.IsNull(clone.BestFriend); Assert.AreEqual(1, clone.CurrentOwnedVehicles.Count); Assert.IsNull(clone.CurrentOwnedVehicles.First().CurrentOwner); Assert.AreEqual(4, clone.CurrentOwnedVehicles.First().Wheels.Count); Assert.IsNull(clone.CurrentOwnedVehicles.First().Wheels.First().Vehicle); Assert.AreEqual(2, clone.CurrentOwnedVehicles.First().RoadworthyTests.Count); Assert.IsNull(clone.CurrentOwnedVehicles.First().RoadworthyTests.First().Value.Vehicle); Assert.AreEqual(2, clone.CurrentOwnedVehicles.First().MileageHistory.Count); Assert.IsNotNull(clone.CurrentOwnedVehicles.First().MileageHistory[new DateTime(2010, 1, 1)]); } [Test] public void TestWithoutIdentifiers() { EQBPerson clone; using (var session = NHConfig.OpenSession()) { var petra = session.Query<EQBPerson>() .Include(o => o.IdentityCard) .Include(o => o.BestFriend.IdentityCard) .Include(o => o.CurrentOwnedVehicles.First().Wheels) .Include(o => o.CurrentOwnedVehicles.First().RoadworthyTests) .Include(o => o.CurrentOwnedVehicles.First().MileageHistory) .First(o => o.Name == "Petra"); clone = session.DeepClone(petra, o => o .CloneIdentifier(false)); } Assert.AreEqual(0, clone.Id); Assert.AreEqual(0, clone.IdentityCard.Id); Assert.AreEqual(0, clone.IdentityCard.Owner.Id); Assert.AreEqual(0, clone.BestFriend.Id); Assert.AreEqual(0, clone.BestFriend.IdentityCard.Id); Assert.AreEqual(1, clone.CurrentOwnedVehicles.Count); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().Id); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().CurrentOwner.Id); Assert.AreEqual(4, clone.CurrentOwnedVehicles.First().Wheels.Count); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().Wheels.First().Id); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().Wheels.First().Vehicle.Id); Assert.AreEqual(2, clone.CurrentOwnedVehicles.First().RoadworthyTests.Count); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().RoadworthyTests.First().Value.Id); Assert.AreEqual(0, clone.CurrentOwnedVehicles.First().RoadworthyTests.First().Value.Vehicle.Id); } } }
41.469965
150
0.554192
[ "MIT" ]
maca88/NHibernate.Extensions
NHibernate.Extensions.Tests/DeepCloneTests.cs
11,738
C#
namespace Community.CsharpSqlite { using System; using u8 = System.Byte; /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. */ public class FKey { public Table pFrom; /* Table containing the REFERENCES clause (aka: Child) */ public FKey pNextFrom; /* Next foreign key in pFrom */ public string zTo; /* Name of table that the key points to (aka: Parent) */ public FKey pNextTo; /* Next foreign key on table named zTo */ public FKey pPrevTo; /* Previous foreign key on table named zTo */ public int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ public u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ public u8[] aAction = new u8[2]; /* ON DELETE and ON UPDATE actions, respectively */ public Trigger[] apTrigger = new Trigger[2]; /* Triggers for aAction[] actions */ public class sColMap { /* Mapping of columns in pFrom to columns in zTo */ public int iFrom; /* Index of column in pFrom */ public string zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ }; public sColMap[] aCol; /* One entry for each of nCol column s */ public FKey Copy() { if (this == null) return null; else { FKey cp = (FKey)MemberwiseClone(); return cp; } } } }
32.315068
77
0.567189
[ "MIT" ]
ArsenShnurkov/csharp-sqlite
Community.CsharpSqlite/src/engine_scheme/FKey.cs
2,361
C#
using System; using Newtonsoft.Json; namespace RimuTec.PiranhaNH.Entities { [Serializable] internal sealed class PostPermissionEntity { public Guid PostId { get; set; } public string Permission { get; set; } [JsonIgnore] public PostEntity Post { get; set; } } }
18.75
45
0.666667
[ "MIT" ]
RimuTec/RimuTec.Piranha
src/PiranhaNH/Entities/PostPermissionEntity.cs
300
C#
using CoinbaseExchange.NET.Core; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CoinbaseExchange.NET.Endpoints.OrderBook { public class RealtimeOrderBookClient : ExchangeClientBase { private const string Product = "BTC-USD"; private object _spreadLock = new object(); private object _askLock = new object(); private object _bidLock = new object(); private List<BidAskOrder> _sells { get; set; } private List<BidAskOrder> _buys { get; set; } public List<BidAskOrder> Sells { get; set; } public List<BidAskOrder> Buys { get; set; } public event EventHandler Updated; public decimal Spread { get { lock (_spreadLock) { if (!Buys.Any() || !Sells.Any()) return 0; var maxBuy = Buys.Select(x => x.Price).Max(); var minSell = Sells.Select(x => x.Price).Min(); return minSell - maxBuy; } } } public RealtimeOrderBookClient(CBAuthenticationContainer auth) : base(auth) { _sells = new List<BidAskOrder>(); _buys = new List<BidAskOrder>(); Sells = new List<BidAskOrder>(); Buys = new List<BidAskOrder>(); ResetStateWithFullOrderBook(); } private async void ResetStateWithFullOrderBook() { var response = await GetProductOrderBook(Product, 3); lock (_spreadLock) { lock (_askLock) { lock (_bidLock) { _buys = response.Buys.ToList(); _sells = response.Sells.ToList(); Buys = _buys.ToList(); Sells = _sells.ToList(); } } } OnUpdated(); Subscribe(Product, OnOrderBookEventReceived); } private void OnUpdated() { if (Updated != null) Updated(this, new EventArgs()); } public async Task<GetProductOrderBookResponse> GetProductOrderBook(string productId, int level = 1) { var request = new GetProductOrderBookRequest(productId, level); var response = await this.GetResponse(request); var orderBookResponse = new GetProductOrderBookResponse(response); return orderBookResponse; } private void OnOrderBookEventReceived(RealtimeMessage message) { if (message is RealtimeReceived) { var receivedMessage = message as RealtimeReceived; OnReceived(receivedMessage); } else if (message is RealtimeOpen) { } else if (message is RealtimeDone) { var doneMessage = message as RealtimeDone; OnDone(doneMessage); } else if (message is RealtimeMatch) { } else if (message is RealtimeChange) { } else if (message is RealtimeOpen) { } OnUpdated(); } private void OnReceived(RealtimeReceived receivedMessage) { var order = new BidAskOrder(); order.Id = receivedMessage.OrderId; order.Price = receivedMessage.Price; order.Size = receivedMessage.Size; lock (_spreadLock) { if (receivedMessage.Side == "buy") { lock (_bidLock) { _buys.Add(order); Buys = _buys.ToList(); } } else if (receivedMessage.Side == "sell") { lock (_askLock) { _sells.Add(order); Sells = _sells.ToList(); } } } } private void OnDone(RealtimeDone message) { lock (_spreadLock) { lock (_askLock) { lock (_bidLock) { _buys.RemoveAll(b => b.Id == message.OrderId); _sells.RemoveAll(a => a.Id == message.OrderId); Buys = _buys.ToList(); Sells = _sells.ToList(); } } } } private static async void Subscribe(string product, Action<RealtimeMessage> onMessageReceived) { if (String.IsNullOrWhiteSpace(product)) throw new ArgumentNullException("product"); if (onMessageReceived == null) throw new ArgumentNullException("onMessageReceived", "Message received callback must not be null."); var uri = new Uri("wss://ws-feed.exchange.coinbase.com"); var webSocketClient = new ClientWebSocket(); var cancellationToken = new CancellationToken(); var requestString = String.Format(@"{{""type"": ""subscribe"",""product_id"": ""{0}""}}", product); var requestBytes = UTF8Encoding.UTF8.GetBytes(requestString); await webSocketClient.ConnectAsync(uri, cancellationToken); if (webSocketClient.State == WebSocketState.Open) { var subscribeRequest = new ArraySegment<byte>(requestBytes); var sendCancellationToken = new CancellationToken(); await webSocketClient.SendAsync(subscribeRequest, WebSocketMessageType.Text, true, sendCancellationToken); while (webSocketClient.State == WebSocketState.Open) { var receiveCancellationToken = new CancellationToken(); var receiveBuffer = new ArraySegment<byte>(new byte[1024 * 1024 * 5]); // 5MB buffer var webSocketReceiveResult = await webSocketClient.ReceiveAsync(receiveBuffer, receiveCancellationToken); if (webSocketReceiveResult.Count == 0) continue; var jsonResponse = Encoding.UTF8.GetString(receiveBuffer.Array, 0, webSocketReceiveResult.Count); var jToken = JToken.Parse(jsonResponse); var typeToken = jToken["type"]; if (typeToken == null) continue; var type = typeToken.Value<string>(); RealtimeMessage realtimeMessage = null; switch (type) { case "received": realtimeMessage = new RealtimeReceived(jToken); break; case "open": realtimeMessage = new RealtimeOpen(jToken); break; case "done": realtimeMessage = new RealtimeDone(jToken); break; case "match": realtimeMessage = new RealtimeMatch(jToken); break; case "change": realtimeMessage = new RealtimeChange(jToken); break; default: break; } if (realtimeMessage == null) continue; onMessageReceived(realtimeMessage); } } } } }
32.45749
125
0.487215
[ "MIT" ]
sefbkn/CoinbaseExchange.NET
CoinbaseExchange.NET/Endpoints/OrderBook/RealtimeOrderBookClient.cs
8,019
C#
using System.Threading.Tasks; using CryptoArbitrageSharp.Calculator; using CryptoArbitrageSharp.Exchanges; using CryptoArbitrageSharp.Exchanges.Binance; using CryptoArbitrageSharp.Exchanges.Bitfinex; using CryptoArbitrageSharp.Exchanges.Bitstamp; using CryptoArbitrageSharp.Exchanges.Bittrex; using CryptoArbitrageSharp.Exchanges.CoinbasePro; using CryptoArbitrageSharp.Exchanges.CoinExchange; using CryptoArbitrageSharp.Exchanges.Kraken; using CryptoArbitrageSharp.Exchanges.Poloniex; namespace CryptoArbitrageSharp { public class ArbitrageClient { private readonly IArbitrageCalculator arbitrageCalculator; public ArbitrageClient(IArbitrageCalculator arbitrageCalculator) { this.arbitrageCalculator = arbitrageCalculator; } public async Task<(BestExchangeQuote bestBid, BestExchangeQuote bestAsk)> Get(CurrencyPair currencyPair) { var httpClient = new HttpClient(); var httpRequestMessageService = new HttpRequestMessageService(); var currencyPairService = new CurrencyPairService(); var bittrexExchange = new BittrexExchange(httpClient, httpRequestMessageService, currencyPairService); var coinbaseProExchange = new CoinbaseProExchange(httpClient, httpRequestMessageService, currencyPairService); var krakenExchange = new KrakenExchange(httpClient, httpRequestMessageService, currencyPairService); var poloniexExchange = new PoloniexExchange(httpClient, httpRequestMessageService, currencyPairService); var binanceExchange = new BinanceExchange(httpClient, httpRequestMessageService, currencyPairService); var bitfinexExchange= new BitfinexExchange(httpClient, httpRequestMessageService, currencyPairService); var bitstampExchange = new BitstampExchange(httpClient, httpRequestMessageService, currencyPairService); var exchangeResults = await Task.WhenAll( bittrexExchange.Get(currencyPair), coinbaseProExchange.Get(currencyPair), krakenExchange.Get(currencyPair), poloniexExchange.Get(currencyPair), binanceExchange.Get(currencyPair), bitfinexExchange.Get(currencyPair), bitstampExchange.Get(currencyPair)); var result = arbitrageCalculator.Calculate( exchangeResults[0], exchangeResults[1], exchangeResults[2], exchangeResults[3], exchangeResults[4], exchangeResults[5], exchangeResults[6]); return result; } } }
44.766667
122
0.712211
[ "MIT" ]
dougdellolio/Crypto.Arbitrage.CSharp
CryptoArbitrageSharp/ArbitrageClient.cs
2,688
C#
using Nuke.Common; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.SonarScanner; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.SonarScanner.SonarScannerTasks; using static Helpers; using static System.IO.Path; partial class Build { [Parameter] readonly string SonarToken; [Parameter] readonly string SonarServer = "https://sonarcloud.io"; Target SonarPr => _ => _ .Requires(() => GitHubRepository != null) .Requires(() => GitHubHeadRef != null) .Requires(() => GitHubBaseRef != null) .Requires(() => GitHubPRNumber != null) .Executes(() => { Logger.Info($"GitHubRepository: {GitHubRepository}"); Logger.Info($"GitHubHeadRef: {GitHubHeadRef}"); Logger.Info($"GitHubBaseRef: {GitHubBaseRef}"); Logger.Info($"GitHubPRNumber: {GitHubPRNumber}"); TryDelete(SonarSolutionFile); DotNetBuildSonarSolution(AllSolutionFile); DotNetBuildSonarSolution(SonarSolutionFile, include: IsRelevantForSonar); DotNetRestore(c => c .SetProjectFile(SonarSolutionFile) .SetProcessWorkingDirectory(RootDirectory)); SonarScannerBegin(SonarBeginPrSettings); DotNetBuild(SonarBuildAll); try { DotNetTest( c => CoverNoBuildSettingsOnlyNet60(c, CoverProjects), degreeOfParallelism: DegreeOfParallelism, completeOnFailure: true); } catch { } SonarScannerEnd(SonarEndSettings); }); Target Sonar => _ => _ .Executes(() => { TryDelete(SonarSolutionFile); DotNetBuildSonarSolution(AllSolutionFile); DotNetBuildSonarSolution(SonarSolutionFile, include: IsRelevantForSonar); DotNetRestore(c => c .SetProjectFile(SonarSolutionFile) .SetProcessWorkingDirectory(RootDirectory)); Logger.Info("Creating Sonar analysis for version: {0} ...", GitVersion.SemVer); SonarScannerBegin(SonarBeginFullSettings); DotNetBuild(SonarBuildAll); try { DotNetTest( c => CoverNoBuildSettingsOnlyNet60(c, CoverProjects), degreeOfParallelism: DegreeOfParallelism, completeOnFailure: true); } catch { } SonarScannerEnd(SonarEndSettings); }); SonarScannerBeginSettings SonarBeginPrSettings(SonarScannerBeginSettings settings) => SonarBeginBaseSettings(settings) .SetProcessArgumentConfigurator(t => t .Add("/o:{0}", "chillicream") .Add("/d:sonar.pullrequest.provider={0}", "github") .Add("/d:sonar.pullrequest.github.repository={0}", GitHubRepository) .Add("/d:sonar.pullrequest.key={0}", GitHubPRNumber) .Add("/d:sonar.pullrequest.branch={0}", GitHubHeadRef) .Add("/d:sonar.pullrequest.base={0}", GitHubBaseRef) .Add("/d:sonar.cs.roslyn.ignoreIssues={0}", "true")) .SetFramework(Net50); SonarScannerBeginSettings SonarBeginFullSettings(SonarScannerBeginSettings settings) => SonarBeginBaseSettings(settings) .SetVersion(GitVersion.SemVer) .SetFramework(Net50); SonarScannerBeginSettings SonarBeginBaseSettings(SonarScannerBeginSettings settings) => SonarBaseSettings(settings) .SetProjectKey("HotChocolate") .SetName("HotChocolate") .SetServer(SonarServer) .SetLogin(SonarToken) .AddOpenCoverPaths(TestResultDirectory / "*.xml") .SetVSTestReports(TestResultDirectory / "*.trx") .AddSourceExclusions("**/Generated/**/*.*,**/*.Designer.cs,**/*.generated.cs,**/*.js,**/*.html,**/*.css,**/Sample/**/*.*,**/Samples.*/**/*.*,**/*Tools.*/**/*.*,**/Program.Dev.cs, **/Program.cs,**/*.ts,**/*.tsx,**/*EventSource.cs,**/*EventSources.cs,**/*.Samples.cs,**/*Tests.*/**/*.*,**/*Test.*/**/*.*") .SetProcessArgumentConfigurator(t => t .Add("/o:{0}", "chillicream") .Add("/d:sonar.cs.roslyn.ignoreIssues={0}", "true")); SonarScannerBeginSettings SonarBaseSettings(SonarScannerBeginSettings settings) => settings .SetLogin(SonarToken) .SetProcessWorkingDirectory(RootDirectory); SonarScannerEndSettings SonarEndSettings(SonarScannerEndSettings settings) => settings .SetLogin(SonarToken) .SetProcessWorkingDirectory(RootDirectory) .SetFramework(Net50); DotNetBuildSettings SonarBuildAll(DotNetBuildSettings settings) => settings .SetProjectFile(SonarSolutionFile) .SetNoRestore(true) .SetConfiguration(Debug) .SetProcessWorkingDirectory(RootDirectory) .SetFramework(Net60); bool IsRelevantForSonar(string fileName) => !ExcludedCover.Contains(GetFileNameWithoutExtension(fileName)); }
41.444444
315
0.60992
[ "MIT" ]
AccountTechnologies/hotchocolate
.build/Build.Sonar.cs
5,222
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.Mongodbatlas.Outputs { [OutputType] public sealed class GetCloudBackupSchedulePolicyItemWeeklyResult { /// <summary> /// Desired frequency of the new backup policy item specified by `frequency_type`. /// </summary> public readonly int FrequencyInterval; /// <summary> /// Frequency associated with the backup policy item. /// </summary> public readonly string FrequencyType; /// <summary> /// Unique identifier of the backup policy item. /// </summary> public readonly string Id; /// <summary> /// Scope of the backup policy item: days, weeks, or months. /// </summary> public readonly string RetentionUnit; /// <summary> /// Value to associate with `retention_unit`. /// </summary> public readonly int RetentionValue; [OutputConstructor] private GetCloudBackupSchedulePolicyItemWeeklyResult( int frequencyInterval, string frequencyType, string id, string retentionUnit, int retentionValue) { FrequencyInterval = frequencyInterval; FrequencyType = frequencyType; Id = id; RetentionUnit = retentionUnit; RetentionValue = retentionValue; } } }
29.964912
90
0.617681
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-mongodbatlas
sdk/dotnet/Outputs/GetCloudBackupSchedulePolicyItemWeeklyResult.cs
1,708
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WebServices.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct WS_HTTP_SSL_POLICY_DESCRIPTION { public WS_CHANNEL_PROPERTIES channelProperties; public WS_SECURITY_PROPERTIES securityProperties; public WS_SSL_TRANSPORT_SECURITY_BINDING_POLICY_DESCRIPTION sslTransportSecurityBinding; } }
35.411765
145
0.782392
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/WebServices/WS_HTTP_SSL_POLICY_DESCRIPTION.cs
604
C#
using System.Threading.Tasks; namespace Augustus.CRM { public interface ICrmService { CrmContext GetContext(); Task<CrmContext> GetContextAsync(); } }
16.454545
43
0.662983
[ "MIT" ]
gothandy/Augustus
Augustus.CRM/ICrmService.cs
183
C#
 namespace Backtrace.Unity.Model { internal sealed class BacktraceDefaultClassifierTypes { internal const string MessageType = "Message"; internal const string ExceptionType = "Exception"; internal const string UnhandledExceptionType = "Unhandled exception"; internal const string OOMExceptionType = "OOMException"; internal const string AnrExceptionType = "Hang"; } }
30.214286
77
0.711584
[ "MIT" ]
Bruce-Szo/NotABugGameJam2021
Not A Bug Game Jam 2021/Packages/backtrace-unity-3.7.1/Runtime/Model/BacktraceDefaultClassifierTypes.cs
425
C#
using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Nop.Core.Configuration; using Nop.Core.Infrastructure; using Nop.Web.Areas.Admin.Controllers; using Nop.Web.Controllers; using Nop.Web.Framework; using Nop.Web.Framework.Infrastructure.Extensions; using System; using System.Net; using Walter.Web.FireWall; using Walter.Web.FireWall.Filters; namespace Nop.Web { /// <summary> /// if any other plugin uses the same routs as the firewall then you just change these /// constance values and the configuration will adapt ensuring the firewall will work /// as expected /// </summary> public static class Links { public const string SiteMapEndPoint = "api/SiteMapPageRequest"; public const string IsUserEndpoint = "api/UserDiscovery"; public const string BeaconPoint = "api/BeaconPageRequest"; public const string CSP = "api/CSP"; public const string UserEndpointJavaScript = "js/jquery.legasy.js"; } /// <summary> /// Represents startup class of application /// </summary> public class Startup { #region Fields private readonly IConfiguration _configuration; private readonly IWebHostEnvironment _webHostEnvironment; private IEngine _engine; private NopConfig _nopConfig; #endregion #region Ctor public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment) { _configuration = configuration; _webHostEnvironment = webHostEnvironment; DBHelper.CreateDatabases(false, _configuration, "fireWallStateNope"); } #endregion /// <summary> /// Add services to the application and configure service provider /// </summary> /// <param name="services">Collection of service descriptors</param> public void ConfigureServices(IServiceCollection services) { // update method and inject core firewall filter in the MVC project // change : // var mvcCoreBuilder = services.AddMvcCore(); // // To: // var mvcCoreBuilder = services.AddMvcCore(setupAction=> { // setupAction.Filters.Add<Walter.Web.FireWall.Filters.FireWallFilter>(0); // }); (_engine, _nopConfig) = services.ConfigureApplicationServices(_configuration, _webHostEnvironment); /* Use memory cashing to speed up the application * you can use plugins like Redis or SQL backed cashing if you are using fail-over servers * when using cashing the discovered ISP data of those that are attacking you will be re-used * and do not have to be re-discovered on each request. */ services.AddMemoryCache(); /*Inject the firewall with a given configuration in your application * You can use your own class and derive the firewall from that as a base class * then you can tune the configuration options to reflect your preferences * see online documentation for more information on the configuration options * at https://firewallapi.asp-waf.com/?topic=html/AllMembers.T-Walter.Web.FireWall.IFireWallConfig.htm * * The sample configuration can also be stored and loaded in json configuration, perhaps make the configuration * in code first and then save it as json to get started as the number of configuration options are abundant */ services.AddFireWall<MyFireWall>(license: FireWallTrial.License,domainLicense: FireWallTrial.DomainKey ,domainName: new Uri("https://www.mydomain.com", UriKind.Absolute), options => { //---Play with the administrative settings if you like to use the management desktop as demonstrated in https://www.asp-waf.com/abuse--- options.Administration.DisplayName = "My NopShop"; options.Administration.GenerateConnectFile = true; options.Administration.LogDashboardRequests = false; //set the location that you would allow guest access from, remove it if no guest access is allowed options.Administration.Users.GuestAccess(Walter.BOM.Geo.GeoLocation.EUROPE, Walter.BOM.Geo.GeoLocation.RussianFederation); //only allow access to authenticated users from the country where they are options.Administration.Users.Seed(userName:"admin",password: "pa$$word1234",access: Walter.Web.FireWall.Infrastructure.AdminAccess.Full, Walter.BOM.Geo.GeoLocation.Luxembourg); //by specifying an ip address a user can only access if from the IP address or address range options.Administration.WhiteList("123.123.123.1-123.123.123.255"); //-- end of admin samples, use intelisense or api documentation for use additional settings //set your public IP address when debugging so you can simulate IP based protection //your real public IP address is accessible at Walter.Net.Networking.RuntimeValues.PublicIpAddress options.PublicIpAddress = IPAddress.Parse("8.8.8.4"); options.Cypher.ApplicationPassword = "The password is 5 x 5, but I will not say in what order!" .AsShaHash(HashMethod.SHA1,8); //data is stored in memory cash and not in session, use session if you might run low on memory options.UseSession = false; options.Cashing.TemporaryUsers.SlidingExpiration = TimeSpan.FromMinutes(20); options.Cashing.TemporaryUsers.Priority = Microsoft.Extensions.Caching.Memory.CacheItemPriority.High; //set the default security rule engines to reflect that you have a website and API requests for JavaScripts and monitoring options.FireWallMode = FireWallProtectionModes.WebSiteWithApi; //tell the duration a malicious user is to be blocked options.Rules.BlockRequest.BlockDuration.Expires = TimeSpan.FromMinutes(5); options.Rules.BlockRequest.BlockDuration.SlideExpiration = true; options.ProtectedEndPointTypes.Add(typeof(BasePublicController)); options.ProtectedEndPointTypes.Add(typeof(BaseAdminController)); //you can set the log levels for incident detection as well as firewall guard actions //manually. The namespace for the logger is at Walter.Web.FireWall.Guard options.Rules.IncidentLogLevel = Microsoft.Extensions.Logging.LogLevel.Information; options.Rules.GuardActionLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning; //we make use of the build-in Java script to detect and validate user and user interactions options.WebServices.IsUserApiUrl = new Uri(Links.IsUserEndpoint, UriKind.Relative); options.WebServices.RegisterLinksApiUrl = new Uri(Links.SiteMapEndPoint, UriKind.Relative); options.WebServices.BeaconApiUrl = new Uri(Links.BeaconPoint, UriKind.Relative); options.WebServices.CSPReportUrl = new Uri(Links.CSP, UriKind.Relative); //set the rules for browser based protection, the firewall can do without them but the extra layer of defense does not hurt //having set the rules also helps the firewall understand your intend and help sniff-out bots that are violating the rules that //the browser would have detected and rejected. Header protection is "camouflage" as well as adds an active layer of protection options.Rules.Headers.AddDefaultSecurePolicy() .AddFrameOptionsDeny() .AddStrictTransportSecurityNoCache() .DoNotTrack() .SimulateDifferentServer(Walter.Web.FireWall.Headers.ServerSimulation.Apache249Unix) .SimulateDifferentTechnologyStack(Walter.Web.FireWall.Headers.StackSimulation.PHP) .AddXssProtectionBlockAndReport(Links.CSP) .AddContentSecurityPolicyTrustOnlySelf(); options.OnEndpointsCreated += Options_OnEndpointsCreated; })//store firewall state in a database making the firewall faster and allow it for the firewall to maintain large data volumes .UseDatabase(connectionString: _configuration.GetConnectionString("fireWallStateNope"), schema: "dbo", dataRetention: TimeSpan.FromDays(90)); } /// <summary> /// When Endpoints have been discovered /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Options_OnEndpointsCreated(object sender, Walter.Web.FireWall.EventArguments.EndpointsCreatedEventArgs e) { var data = e.Links.EndpointsInPath("*.zip", "*.pdf"); foreach (var item in data) { item.AddHock = null; //allow external sites to access documents as well as download links item.NoValidate |= FireWallGuardModules.RejectAddHockRequests | FireWallGuardModules.RejectCrossSiteRequests; } data = e.Links.EndpointsInPath("*.css", "*.png", "*.jpg", "*.js"); foreach (var item in data) { //disable the firewall on all items that match the above filter, item.NoValidate = FireWallGuardModules.ALL; item.FirewallDisabled = true; } } public void ConfigureContainer(ContainerBuilder builder) { _engine.RegisterDependencies(builder, _nopConfig); } /// <summary> /// Configure the application HTTP request pipeline /// </summary> /// <param name="application">Builder for configuring an application's request pipeline</param> public void Configure(IApplicationBuilder application) { application.ConfigureRequestPipeline(); application.StartEngine(); //integrate the firewall application.UseFireWall(); } } }
49.518519
192
0.645942
[ "MIT" ]
PeterPann23/FireWall
Samples/NopeCommerce/Presentation/Nop.Web/Startup.cs
10,698
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. namespace Stride.Rendering.Materials { public interface IMaterialClearCoatFeature : IMaterialFeature { } }
36.583333
81
0.749431
[ "MIT" ]
Ethereal77/stride
sources/engine/Stride.Rendering/Rendering/Materials/IMaterialClearCoatFeature.cs
441
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request to modify the system's default policy settings. /// The response is either SuccessResponse or ErrorResponse. /// The following elements are only used in AS data mode: /// GroupAdminDialableCallerIDAccess /// ServiceProviderAdminDialableCallerIDAccess /// GroupAdminCommunicationBarringUserProfileAccess (This element is only used for groups in an Enterprise) /// GroupAdminVerifyTranslationAndRoutingAccess /// ServiceProviderVerifyTranslationAndRoutingAccess /// groupUserAutoAttendantNameDialingAccess /// The following elements are only used in XS data mode: /// serviceProviderAdminCommunicationBarringAccess /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:14530""}]")] public class SystemPolicyModifyDefaultRequest22 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private BroadWorksConnector.Ocip.Models.GroupCallingPlanAccess _groupCallingPlanAccess; [XmlElement(ElementName = "groupCallingPlanAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupCallingPlanAccess GroupCallingPlanAccess { get => _groupCallingPlanAccess; set { GroupCallingPlanAccessSpecified = true; _groupCallingPlanAccess = value; } } [XmlIgnore] protected bool GroupCallingPlanAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupExtensionAccess _groupExtensionAccess; [XmlElement(ElementName = "groupExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupExtensionAccess GroupExtensionAccess { get => _groupExtensionAccess; set { GroupExtensionAccessSpecified = true; _groupExtensionAccess = value; } } [XmlIgnore] protected bool GroupExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupVoiceMessagingAccess _groupVoiceMessagingAccess; [XmlElement(ElementName = "groupVoiceMessagingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupVoiceMessagingAccess GroupVoiceMessagingAccess { get => _groupVoiceMessagingAccess; set { GroupVoiceMessagingAccessSpecified = true; _groupVoiceMessagingAccess = value; } } [XmlIgnore] protected bool GroupVoiceMessagingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminUserAccess _groupDepartmentAdminUserAccess; [XmlElement(ElementName = "groupDepartmentAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminUserAccess GroupDepartmentAdminUserAccess { get => _groupDepartmentAdminUserAccess; set { GroupDepartmentAdminUserAccessSpecified = true; _groupDepartmentAdminUserAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminTrunkGroupAccess _groupDepartmentAdminTrunkGroupAccess; [XmlElement(ElementName = "groupDepartmentAdminTrunkGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminTrunkGroupAccess GroupDepartmentAdminTrunkGroupAccess { get => _groupDepartmentAdminTrunkGroupAccess; set { GroupDepartmentAdminTrunkGroupAccessSpecified = true; _groupDepartmentAdminTrunkGroupAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminTrunkGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminPhoneNumberExtensionAccess _groupDepartmentAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "groupDepartmentAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminPhoneNumberExtensionAccess GroupDepartmentAdminPhoneNumberExtensionAccess { get => _groupDepartmentAdminPhoneNumberExtensionAccess; set { GroupDepartmentAdminPhoneNumberExtensionAccessSpecified = true; _groupDepartmentAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminCallingLineIdNumberAccess _groupDepartmentAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "groupDepartmentAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminCallingLineIdNumberAccess GroupDepartmentAdminCallingLineIdNumberAccess { get => _groupDepartmentAdminCallingLineIdNumberAccess; set { GroupDepartmentAdminCallingLineIdNumberAccessSpecified = true; _groupDepartmentAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserAuthenticationAccess _groupUserAuthenticationAccess; [XmlElement(ElementName = "groupUserAuthenticationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupUserAuthenticationAccess GroupUserAuthenticationAccess { get => _groupUserAuthenticationAccess; set { GroupUserAuthenticationAccessSpecified = true; _groupUserAuthenticationAccess = value; } } [XmlIgnore] protected bool GroupUserAuthenticationAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserGroupDirectoryAccess _groupUserGroupDirectoryAccess; [XmlElement(ElementName = "groupUserGroupDirectoryAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupUserGroupDirectoryAccess GroupUserGroupDirectoryAccess { get => _groupUserGroupDirectoryAccess; set { GroupUserGroupDirectoryAccessSpecified = true; _groupUserGroupDirectoryAccess = value; } } [XmlIgnore] protected bool GroupUserGroupDirectoryAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserProfileAccess _groupUserProfileAccess; [XmlElement(ElementName = "groupUserProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupUserProfileAccess GroupUserProfileAccess { get => _groupUserProfileAccess; set { GroupUserProfileAccessSpecified = true; _groupUserProfileAccess = value; } } [XmlIgnore] protected bool GroupUserProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserCallLogAccess _groupUserEnhancedCallLogsAccess; [XmlElement(ElementName = "groupUserEnhancedCallLogsAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupUserCallLogAccess GroupUserEnhancedCallLogsAccess { get => _groupUserEnhancedCallLogsAccess; set { GroupUserEnhancedCallLogsAccessSpecified = true; _groupUserEnhancedCallLogsAccess = value; } } [XmlIgnore] protected bool GroupUserEnhancedCallLogsAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserAutoAttendantNameDialingAccess _groupUserAutoAttendantNameDialingAccess; [XmlElement(ElementName = "groupUserAutoAttendantNameDialingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupUserAutoAttendantNameDialingAccess GroupUserAutoAttendantNameDialingAccess { get => _groupUserAutoAttendantNameDialingAccess; set { GroupUserAutoAttendantNameDialingAccessSpecified = true; _groupUserAutoAttendantNameDialingAccess = value; } } [XmlIgnore] protected bool GroupUserAutoAttendantNameDialingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminProfileAccess _groupAdminProfileAccess; [XmlElement(ElementName = "groupAdminProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminProfileAccess GroupAdminProfileAccess { get => _groupAdminProfileAccess; set { GroupAdminProfileAccessSpecified = true; _groupAdminProfileAccess = value; } } [XmlIgnore] protected bool GroupAdminProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminUserAccess _groupAdminUserAccess; [XmlElement(ElementName = "groupAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminUserAccess GroupAdminUserAccess { get => _groupAdminUserAccess; set { GroupAdminUserAccessSpecified = true; _groupAdminUserAccess = value; } } [XmlIgnore] protected bool GroupAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminAdminAccess _groupAdminAdminAccess; [XmlElement(ElementName = "groupAdminAdminAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminAdminAccess GroupAdminAdminAccess { get => _groupAdminAdminAccess; set { GroupAdminAdminAccessSpecified = true; _groupAdminAdminAccess = value; } } [XmlIgnore] protected bool GroupAdminAdminAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminDepartmentAccess _groupAdminDepartmentAccess; [XmlElement(ElementName = "groupAdminDepartmentAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminDepartmentAccess GroupAdminDepartmentAccess { get => _groupAdminDepartmentAccess; set { GroupAdminDepartmentAccessSpecified = true; _groupAdminDepartmentAccess = value; } } [XmlIgnore] protected bool GroupAdminDepartmentAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminAccessDeviceAccess _groupAdminAccessDeviceAccess; [XmlElement(ElementName = "groupAdminAccessDeviceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminAccessDeviceAccess GroupAdminAccessDeviceAccess { get => _groupAdminAccessDeviceAccess; set { GroupAdminAccessDeviceAccessSpecified = true; _groupAdminAccessDeviceAccess = value; } } [XmlIgnore] protected bool GroupAdminAccessDeviceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminEnhancedServiceInstanceAccess _groupAdminEnhancedServiceInstanceAccess; [XmlElement(ElementName = "groupAdminEnhancedServiceInstanceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminEnhancedServiceInstanceAccess GroupAdminEnhancedServiceInstanceAccess { get => _groupAdminEnhancedServiceInstanceAccess; set { GroupAdminEnhancedServiceInstanceAccessSpecified = true; _groupAdminEnhancedServiceInstanceAccess = value; } } [XmlIgnore] protected bool GroupAdminEnhancedServiceInstanceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminFeatureAccessCodeAccess _groupAdminFeatureAccessCodeAccess; [XmlElement(ElementName = "groupAdminFeatureAccessCodeAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminFeatureAccessCodeAccess GroupAdminFeatureAccessCodeAccess { get => _groupAdminFeatureAccessCodeAccess; set { GroupAdminFeatureAccessCodeAccessSpecified = true; _groupAdminFeatureAccessCodeAccess = value; } } [XmlIgnore] protected bool GroupAdminFeatureAccessCodeAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminPhoneNumberExtensionAccess _groupAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "groupAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminPhoneNumberExtensionAccess GroupAdminPhoneNumberExtensionAccess { get => _groupAdminPhoneNumberExtensionAccess; set { GroupAdminPhoneNumberExtensionAccessSpecified = true; _groupAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool GroupAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminCallingLineIdNumberAccess _groupAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "groupAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminCallingLineIdNumberAccess GroupAdminCallingLineIdNumberAccess { get => _groupAdminCallingLineIdNumberAccess; set { GroupAdminCallingLineIdNumberAccessSpecified = true; _groupAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool GroupAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminServiceAccess _groupAdminServiceAccess; [XmlElement(ElementName = "groupAdminServiceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminServiceAccess GroupAdminServiceAccess { get => _groupAdminServiceAccess; set { GroupAdminServiceAccessSpecified = true; _groupAdminServiceAccess = value; } } [XmlIgnore] protected bool GroupAdminServiceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminTrunkGroupAccess _groupAdminTrunkGroupAccess; [XmlElement(ElementName = "groupAdminTrunkGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminTrunkGroupAccess GroupAdminTrunkGroupAccess { get => _groupAdminTrunkGroupAccess; set { GroupAdminTrunkGroupAccessSpecified = true; _groupAdminTrunkGroupAccess = value; } } [XmlIgnore] protected bool GroupAdminTrunkGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminVerifyTranslationAndRoutingAccess _groupAdminVerifyTranslationAndRoutingAccess; [XmlElement(ElementName = "groupAdminVerifyTranslationAndRoutingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminVerifyTranslationAndRoutingAccess GroupAdminVerifyTranslationAndRoutingAccess { get => _groupAdminVerifyTranslationAndRoutingAccess; set { GroupAdminVerifyTranslationAndRoutingAccessSpecified = true; _groupAdminVerifyTranslationAndRoutingAccess = value; } } [XmlIgnore] protected bool GroupAdminVerifyTranslationAndRoutingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminSessionAdmissionControlAccess _groupAdminSessionAdmissionControlAccess; [XmlElement(ElementName = "groupAdminSessionAdmissionControlAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminSessionAdmissionControlAccess GroupAdminSessionAdmissionControlAccess { get => _groupAdminSessionAdmissionControlAccess; set { GroupAdminSessionAdmissionControlAccessSpecified = true; _groupAdminSessionAdmissionControlAccess = value; } } [XmlIgnore] protected bool GroupAdminSessionAdmissionControlAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminDialableCallerIDAccess _groupAdminDialableCallerIDAccess; [XmlElement(ElementName = "groupAdminDialableCallerIDAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminDialableCallerIDAccess GroupAdminDialableCallerIDAccess { get => _groupAdminDialableCallerIDAccess; set { GroupAdminDialableCallerIDAccessSpecified = true; _groupAdminDialableCallerIDAccess = value; } } [XmlIgnore] protected bool GroupAdminDialableCallerIDAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminOfficeZoneAccess _groupAdminOfficeZoneAccess; [XmlElement(ElementName = "groupAdminOfficeZoneAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminOfficeZoneAccess GroupAdminOfficeZoneAccess { get => _groupAdminOfficeZoneAccess; set { GroupAdminOfficeZoneAccessSpecified = true; _groupAdminOfficeZoneAccess = value; } } [XmlIgnore] protected bool GroupAdminOfficeZoneAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminNumberActivationAccess _groupAdminNumberActivationAccess; [XmlElement(ElementName = "groupAdminNumberActivationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminNumberActivationAccess GroupAdminNumberActivationAccess { get => _groupAdminNumberActivationAccess; set { GroupAdminNumberActivationAccessSpecified = true; _groupAdminNumberActivationAccess = value; } } [XmlIgnore] protected bool GroupAdminNumberActivationAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminCommunicationBarringUserProfileAccess _groupAdminCommunicationBarringUserProfileAccess; [XmlElement(ElementName = "groupAdminCommunicationBarringUserProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.GroupAdminCommunicationBarringUserProfileAccess GroupAdminCommunicationBarringUserProfileAccess { get => _groupAdminCommunicationBarringUserProfileAccess; set { GroupAdminCommunicationBarringUserProfileAccessSpecified = true; _groupAdminCommunicationBarringUserProfileAccess = value; } } [XmlIgnore] protected bool GroupAdminCommunicationBarringUserProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminProfileAccess _serviceProviderAdminProfileAccess; [XmlElement(ElementName = "serviceProviderAdminProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminProfileAccess ServiceProviderAdminProfileAccess { get => _serviceProviderAdminProfileAccess; set { ServiceProviderAdminProfileAccessSpecified = true; _serviceProviderAdminProfileAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminGroupAccess _serviceProviderAdminGroupAccess; [XmlElement(ElementName = "serviceProviderAdminGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminGroupAccess ServiceProviderAdminGroupAccess { get => _serviceProviderAdminGroupAccess; set { ServiceProviderAdminGroupAccessSpecified = true; _serviceProviderAdminGroupAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminUserAccess _serviceProviderAdminUserAccess; [XmlElement(ElementName = "serviceProviderAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminUserAccess ServiceProviderAdminUserAccess { get => _serviceProviderAdminUserAccess; set { ServiceProviderAdminUserAccessSpecified = true; _serviceProviderAdminUserAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminAdminAccess _serviceProviderAdminAdminAccess; [XmlElement(ElementName = "serviceProviderAdminAdminAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminAdminAccess ServiceProviderAdminAdminAccess { get => _serviceProviderAdminAdminAccess; set { ServiceProviderAdminAdminAccessSpecified = true; _serviceProviderAdminAdminAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminAdminAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminDepartmentAccess _serviceProviderAdminDepartmentAccess; [XmlElement(ElementName = "ServiceProviderAdminDepartmentAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminDepartmentAccess ServiceProviderAdminDepartmentAccess { get => _serviceProviderAdminDepartmentAccess; set { ServiceProviderAdminDepartmentAccessSpecified = true; _serviceProviderAdminDepartmentAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminDepartmentAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminAccessDeviceAccess _serviceProviderAdminAccessDeviceAccess; [XmlElement(ElementName = "serviceProviderAdminAccessDeviceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminAccessDeviceAccess ServiceProviderAdminAccessDeviceAccess { get => _serviceProviderAdminAccessDeviceAccess; set { ServiceProviderAdminAccessDeviceAccessSpecified = true; _serviceProviderAdminAccessDeviceAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminAccessDeviceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminPhoneNumberExtensionAccess _serviceProviderAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "serviceProviderAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminPhoneNumberExtensionAccess ServiceProviderAdminPhoneNumberExtensionAccess { get => _serviceProviderAdminPhoneNumberExtensionAccess; set { ServiceProviderAdminPhoneNumberExtensionAccessSpecified = true; _serviceProviderAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminCallingLineIdNumberAccess _serviceProviderAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "serviceProviderAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminCallingLineIdNumberAccess ServiceProviderAdminCallingLineIdNumberAccess { get => _serviceProviderAdminCallingLineIdNumberAccess; set { ServiceProviderAdminCallingLineIdNumberAccessSpecified = true; _serviceProviderAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminServiceAccess _serviceProviderAdminServiceAccess; [XmlElement(ElementName = "serviceProviderAdminServiceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminServiceAccess ServiceProviderAdminServiceAccess { get => _serviceProviderAdminServiceAccess; set { ServiceProviderAdminServiceAccessSpecified = true; _serviceProviderAdminServiceAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminServiceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminServicePackAccess _serviceProviderAdminServicePackAccess; [XmlElement(ElementName = "serviceProviderAdminServicePackAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminServicePackAccess ServiceProviderAdminServicePackAccess { get => _serviceProviderAdminServicePackAccess; set { ServiceProviderAdminServicePackAccessSpecified = true; _serviceProviderAdminServicePackAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminServicePackAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminSessionAdmissionControlAccess _serviceProviderAdminSessionAdmissionControlAccess; [XmlElement(ElementName = "serviceProviderAdminSessionAdmissionControlAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminSessionAdmissionControlAccess ServiceProviderAdminSessionAdmissionControlAccess { get => _serviceProviderAdminSessionAdmissionControlAccess; set { ServiceProviderAdminSessionAdmissionControlAccessSpecified = true; _serviceProviderAdminSessionAdmissionControlAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminSessionAdmissionControlAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminVerifyTranslationAndRoutingAccess _serviceProviderAdminVerifyTranslationAndRoutingAccess; [XmlElement(ElementName = "serviceProviderAdminVerifyTranslationAndRoutingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminVerifyTranslationAndRoutingAccess ServiceProviderAdminVerifyTranslationAndRoutingAccess { get => _serviceProviderAdminVerifyTranslationAndRoutingAccess; set { ServiceProviderAdminVerifyTranslationAndRoutingAccessSpecified = true; _serviceProviderAdminVerifyTranslationAndRoutingAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminVerifyTranslationAndRoutingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminWebBrandingAccess _serviceProviderAdminWebBrandingAccess; [XmlElement(ElementName = "serviceProviderAdminWebBrandingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminWebBrandingAccess ServiceProviderAdminWebBrandingAccess { get => _serviceProviderAdminWebBrandingAccess; set { ServiceProviderAdminWebBrandingAccessSpecified = true; _serviceProviderAdminWebBrandingAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminWebBrandingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminOfficeZoneAccess _serviceProviderAdminOfficeZoneAccess; [XmlElement(ElementName = "serviceProviderAdminOfficeZoneAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminOfficeZoneAccess ServiceProviderAdminOfficeZoneAccess { get => _serviceProviderAdminOfficeZoneAccess; set { ServiceProviderAdminOfficeZoneAccessSpecified = true; _serviceProviderAdminOfficeZoneAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminOfficeZoneAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminCommunicationBarringAccess _serviceProviderAdminCommunicationBarringAccess; [XmlElement(ElementName = "serviceProviderAdminCommunicationBarringAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminCommunicationBarringAccess ServiceProviderAdminCommunicationBarringAccess { get => _serviceProviderAdminCommunicationBarringAccess; set { ServiceProviderAdminCommunicationBarringAccessSpecified = true; _serviceProviderAdminCommunicationBarringAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminCommunicationBarringAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.EnterpriseAdminNetworkPolicyAccess _enterpriseAdminNetworkPolicyAccess; [XmlElement(ElementName = "enterpriseAdminNetworkPolicyAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.EnterpriseAdminNetworkPolicyAccess EnterpriseAdminNetworkPolicyAccess { get => _enterpriseAdminNetworkPolicyAccess; set { EnterpriseAdminNetworkPolicyAccessSpecified = true; _enterpriseAdminNetworkPolicyAccess = value; } } [XmlIgnore] protected bool EnterpriseAdminNetworkPolicyAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminDialableCallerIDAccess _serviceProviderAdminDialableCallerIDAccess; [XmlElement(ElementName = "serviceProviderAdminDialableCallerIDAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminDialableCallerIDAccess ServiceProviderAdminDialableCallerIDAccess { get => _serviceProviderAdminDialableCallerIDAccess; set { ServiceProviderAdminDialableCallerIDAccessSpecified = true; _serviceProviderAdminDialableCallerIDAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminDialableCallerIDAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.EnterpriseAdminNumberActivationAccess _enterpriseAdminNumberActivationAccess; [XmlElement(ElementName = "enterpriseAdminNumberActivationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14530")] public BroadWorksConnector.Ocip.Models.EnterpriseAdminNumberActivationAccess EnterpriseAdminNumberActivationAccess { get => _enterpriseAdminNumberActivationAccess; set { EnterpriseAdminNumberActivationAccessSpecified = true; _enterpriseAdminNumberActivationAccess = value; } } [XmlIgnore] protected bool EnterpriseAdminNumberActivationAccessSpecified { get; set; } } }
42.981797
157
0.691644
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemPolicyModifyDefaultRequest22.cs
37,781
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/codecapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CODECAPI_AVEncCommonMinBitRate" /> struct.</summary> public static unsafe partial class CODECAPI_AVEncCommonMinBitRateTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncCommonMinBitRate" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(CODECAPI_AVEncCommonMinBitRate).GUID, Is.EqualTo(IID_CODECAPI_AVEncCommonMinBitRate)); } /// <summary>Validates that the <see cref="CODECAPI_AVEncCommonMinBitRate" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CODECAPI_AVEncCommonMinBitRate>(), Is.EqualTo(sizeof(CODECAPI_AVEncCommonMinBitRate))); } /// <summary>Validates that the <see cref="CODECAPI_AVEncCommonMinBitRate" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CODECAPI_AVEncCommonMinBitRate).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CODECAPI_AVEncCommonMinBitRate" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CODECAPI_AVEncCommonMinBitRate), Is.EqualTo(1)); } } }
42.266667
145
0.694006
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/codecapi/CODECAPI_AVEncCommonMinBitRateTests.cs
1,904
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MikuMikuWorld.Network; namespace Exporter_MMW { public partial class CollisionSphere : UserControl, ICollisionShape { private NwCollisionSphere shape; public CollisionSphere(NwCollisionSphere shape) { InitializeComponent(); this.shape = shape; if (shape != null) { numericUpDown_radius.Value = (decimal)shape.Radius; numericUpDown_radius.ValueChanged += (s, e) => shape.Radius = (float)numericUpDown_radius.Value; } } } }
26.033333
112
0.659411
[ "BSD-3-Clause" ]
yoship1639/MikuMikuWorld
Exporter_MWO/CollisionSphere.cs
783
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("Barrage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Barrage")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("5e9c60b0-75a9-4c97-89bd-b34f7b4267c2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.486486
84
0.743331
[ "MIT" ]
Bigguy34/ScriptCs.Barrage
ScriptCs.Barrage/Barrage/Properties/AssemblyInfo.cs
1,390
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Array_Data { class Program { static void Main(string[] args) { List<int> inputNumbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); string command = Console.ReadLine(); double averageNumber = inputNumbers.Average(); List<int> newList = inputNumbers .Where(n => n >= averageNumber) .OrderBy(n => n) .ToList(); if (command == "Max") { Console.WriteLine(newList.Max()); } else if (command == "Min") { Console.WriteLine(newList.Min()); } else if (command == "All") { Console.WriteLine(string.Join(" ", newList)); } } } }
25
94
0.489474
[ "MIT" ]
alexdimitrov2000/SU-Initial-Tasks
4.0 Programming Fundamentals/Array Data/ArrayData.cs
952
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISolutionExtensions { public static async Task<IEnumerable<INamespaceSymbol>> GetGlobalNamespacesAsync( this Solution solution, CancellationToken cancellationToken) { var results = new List<INamespaceSymbol>(); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); results.Add(compilation.Assembly.GlobalNamespace); } return results; } public static IEnumerable<DocumentId> GetChangedDocuments(this Solution newSolution, Solution oldSolution) { if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var documentId in projectChanges.GetChangedDocuments()) { yield return documentId; } } } } public static TextDocument GetTextDocument(this Solution solution, DocumentId documentId) { return solution.GetDocument(documentId) ?? solution.GetAdditionalDocument(documentId); } public static Solution WithTextDocumentText(this Solution solution, DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveIdentity) { var document = solution.GetTextDocument(documentId); if (document is Document) { return solution.WithDocumentText(documentId, text, mode); } else { return solution.WithAdditionalDocumentText(documentId, text, mode); } } } }
36.530303
174
0.630859
[ "Apache-2.0" ]
0x53A/roslyn
src/Workspaces/Core/Portable/Shared/Extensions/ISolutionExtensions.cs
2,413
C#
using Imagin.Common; using Imagin.Common.Input; using Imagin.Common.Linq; using Imagin.Common.Media; using System; using System.Threading.Tasks; using System.Windows.Media; namespace Imagin.Colour.Controls.Models { /// <summary> /// /// </summary> public abstract class Component : ObjectBase { /// <summary> /// Occurs when the value of the component changes. /// </summary> public event EventHandler<EventArgs<double>> ValueChanged; /// <summary> /// /// </summary> protected internal bool ColorChangedHandled = false; /// <summary> /// /// </summary> protected internal bool TextChangedHandled = false; /// <summary> /// /// </summary> internal ColorModel ColorSpace { get; set; } = default(ColorModel); /// <summary> /// /// </summary> public Imagin.Colour.Conversion.ColorConverter Converter { get; set; } /// <summary> /// Gets a label that represents the component. /// </summary> public abstract string Label { get; } /// <summary> /// Gets the maximum value of the component. /// </summary> public abstract double Maximum { get; } /// <summary> /// Gets the minimum value of the component. /// </summary> public abstract double Minimum { get; } /// <summary> /// Gets whether or not the component can be selected. /// </summary> public virtual bool CanSelect => false; /// <summary> /// Gets the increment. /// </summary> public virtual double Increment => 1.0; /// <summary> /// Gets the unit of measurement. /// </summary> public virtual ComponentUnit Unit => ComponentUnit.None; double _value = 0; /// <summary> /// Gets or sets the value of the component. /// </summary> public double Value { get => _value; set { Property.Set(this, ref _value, value); OnValueChanged(value); } } /// <summary> /// Gets the hashcode of the component. /// </summary> /// <returns></returns> public override int GetHashCode() => GetType().ToString().GetHashCode(); /// <summary> /// Initializes a new instance of the <see cref="Component"/> class. /// </summary> public Component() : base() { OnPropertyChanged("Increment"); OnPropertyChanged("Maximum"); OnPropertyChanged("Minimum"); } /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public int Clean(double value) => value.Round().Coerce(Maximum, Minimum).ToInt32(); /// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public int Clean(int value) => value.Coerce(Maximum.ToInt32(), Minimum.ToInt32()); /// <summary> /// Gets the value of the component based on the given color. /// </summary> public abstract double GetValue(Color Color); /// <summary> /// Sets the value of the component based on the given color (asynchronously). /// </summary> /// <param name="Color"></param> public async Task SetAsync(Color Color) => Value = await Task.Run(() => GetValue(Color)); /// <summary> /// Sets the value of the component based on the given color. /// </summary> /// <param name="Color"></param> public void Set(Color Color) => Value = GetValue(Color); /// <summary> /// Occurs when the value of the component changes. /// </summary> /// <param name="value"></param> protected virtual void OnValueChanged(double value) => ValueChanged?.Invoke(this, new EventArgs<double>(value)); } }
29.755396
120
0.53264
[ "BSD-2-Clause" ]
OkumaScott/Imagin.NET
Imagin.Colour.WPF/Models/_Components/Component.cs
4,138
C#
public class Solution { public int Calculate(string s) { Stack<char> operStk = new Stack<char>(); Stack<int> numStk = new Stack<int>(); for (int i = 0; i < s.Length; i++) { var c = s[i]; if (char.IsDigit(c)) { long currentNumber = 0; while (i < s.Length && char.IsDigit(s[i])) { currentNumber = currentNumber * 10 + int.Parse(s[i].ToString()); i++; } numStk.Push((int)currentNumber); i--; } else if (c == '+' || c == '-') { while (operStk.Count > 0 && operStk.Peek() != '(') { ProcessOper(numStk, operStk.Pop()); } operStk.Push(c); } else if (c == '(') { operStk.Push(c); } else if (c == ')') { while (true) { var op = operStk.Pop(); if (op == '(') { break; } ProcessOper(numStk, op); } } } while (operStk.Count > 0) { ProcessOper(numStk, operStk.Pop()); } return numStk.Pop(); } private void ProcessOper(Stack<int> numStk, char oper) { int num2 = numStk.Pop(); int num1 = numStk.Pop(); switch (oper) { case '+': numStk.Push(num1 + num2); break; case '-': default: numStk.Push(num1 - num2); break; } } }
32.384615
85
0.364014
[ "MIT" ]
txchen/csharp-leet
solutions/Q224.cs
1,684
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #nullable enable using System.Linq; using Dolittle.Runtime.Events.Processing.EventHandlers; using Integration.Tests.Events.Processing.EventHandlers.given; namespace Integration.Tests.Events.Processing.EventHandlers.with_a_single.scoped.not_partitioned.fast_event_handler.with_implicit_filter.processing_all_event_types.given; class single_tenant_and_event_handlers : with_implicit_filter.given.single_tenant_and_event_handlers { protected static void expect_stream_definition(IEventHandler event_handler) => expect_stream_definition(event_handler, number_of_event_types); protected static void expect_stream_processor_state_without_failure(IEventHandler event_handler) => expect_stream_processor_state_without_failure(event_handler, scoped_committed_events[event_handler_scope].Count); protected static IEventHandler setup_event_handler() { with_event_handlers_filtering_number_of_event_types(new[] { number_of_event_types } .Select(_ => _) .ToArray()); return event_handlers_to_run.First(); } }
37.735294
170
0.772408
[ "MIT" ]
dolittle-runtime/Runtime
Integration/Tests/Events.Processing/EventHandlers/with_a_single/scoped/not_partitioned/fast_event_handler/with_implicit_filter/processing_all_event_types/given/single_tenant_and_event_handlers.cs
1,283
C#
using System; using System.Collections.Generic; using System.Linq; namespace Amg.Build { public enum InvocationState { Pending, InProgress, Done, Failed } public interface IInvocation { InvocationId Id { get; } InvocationState State { get; } DateTime? Begin { get; } DateTime? End { get; } object? ReturnValue { get; } Exception? Exception { get; } } public static class InvocationExtensions { public static TimeSpan? Duration(this IInvocation invocation) { return invocation.Begin is { } && invocation.End is { } ? invocation.End - invocation.Begin : null; } public static bool Failed(this IInvocation invocation) => invocation.Exception is { }; public static bool Failed(this IEnumerable<IInvocation> invocations) => invocations.Any(_ => _.Failed()); } }
24.073171
76
0.577508
[ "MIT" ]
sidiandi/Amg.Build
src/Amg.Build/IInvocation.cs
989
C#
namespace ThreeJs4Net.Geometries { public class TetrahedronGeometry { } }
12.428571
36
0.689655
[ "MIT" ]
threejs4net/threejs4net
ThreeJs4Net/Geometries/TetrahedronGeometry.cs
89
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; namespace Microsoft.PythonTools.Interpreter { public class PythonWorkspaceContextEventArgs : EventArgs { public PythonWorkspaceContextEventArgs(IPythonWorkspaceContext workspace) { Workspace = workspace; } public IPythonWorkspaceContext Workspace { get; } } }
37.214286
83
0.747601
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/PTVS
Python/Product/VSInterpreters/PythonWorkspaceContextEventArgs.cs
1,044
C#
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. using AttackSurfaceAnalyzer.Objects; using AttackSurfaceAnalyzer.Types; using Microsoft.Data.Sqlite; using Newtonsoft.Json; using Serilog; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Threading; namespace AttackSurfaceAnalyzer.Utils { public class DBSettings { public int BatchSize { get; set; } = 100; public int FlushCount { get; set; } = -1; public string JournalMode { get; set; } = "DELETE"; public string LockingMode { get; set; } = "NORMAL"; public bool LowMemoryUsage { get; set; } = false; public int PageSize { get; set; } = 4096; public int ShardingFactor { get; set; } = 7; public string Synchronous { get; set; } = "OFF"; } public class SqliteDatabaseManager : DatabaseManager { // Max number of elements to keep in Queue if LowMemoryUsage mode is enabled. public const int LOW_MEMORY_CUTOFF = 1000; public SqliteDatabaseManager(string filename, DBSettings? dbSettingsIn = null) { dbSettings = (dbSettingsIn == null) ? new DBSettings() : dbSettingsIn; if (filename != null) { if (Location != filename) { if (Path.IsPathRooted(filename)) { Location = filename; } else { Location = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{filename}"; } } } else { Location = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}asa.sqlite"; } } public List<SqlConnectionHolder> Connections { get; private set; } = new List<SqlConnectionHolder>(); public override bool HasElements { get { { return Connections.Any(x => x.WriteQueue.Count > 0 || x.IsWriting); } } } public SqlConnectionHolder? MainConnection { get { if (Connections.Any()) return Connections[0]; return null; } } public override int QueueSize { get { return Connections.Sum(x => x.WriteQueue.Count); } } public override void BeginTransaction() { Connections.AsParallel().ForAll(cxn => cxn.BeginTransaction()); } public override void CloseDatabase() { RollBack(); Connections.AsParallel().ForAll(cxn => { cxn.ShutDown(); }); Connections.RemoveAll(_ => true); } public override void Commit() { Connections.AsParallel().ForAll(x => x.Commit()); } public override void DeleteRun(string runid) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using var truncateRunsTable = new SqliteCommand(SQL_TRUNCATE_RUN, MainConnection.Connection, MainConnection.Transaction); truncateRunsTable.Parameters.AddWithValue("@run_id", runid); truncateRunsTable.ExecuteNonQuery(); Connections.AsParallel().ForAll(cxn => { using var truncateCollectTable = new SqliteCommand(SQL_DELETE_RUN, cxn.Connection, cxn.Transaction); truncateCollectTable.Parameters.AddWithValue("@run_id", runid); truncateCollectTable.ExecuteNonQuery(); }); } public override void Destroy() { Connections.AsParallel().ForAll(x => x.Destroy()); Connections.RemoveAll(x => true); } public bool EstablishMainConnection() { if (Connections.Count > 0) { return false; } else { Connections.Add(GenerateSqlConnection(0)); return true; } } public override IEnumerable<WriteObject> GetAllMissing(string firstRunId, string secondRunId) { var output = new ConcurrentQueue<WriteObject>(); Connections.AsParallel().ForAll(cxn => { using var cmd = new SqliteCommand(SQL_GET_UNIQUE_BETWEEN_RUNS, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); cmd.Parameters.AddWithValue("@second_run_id", secondRunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var runId = reader["run_id"].ToString(); var resultTypeString = reader["result_type"].ToString(); if (runId != null && resultTypeString != null) { var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId); if (wo is WriteObject WO) output.Enqueue(WO); } } } }); return output; } public IEnumerable<WriteObject> GetAllMissing2(string firstRunId, string secondRunId) { string SQL_GROUPED = "SELECT run_id, result_type, serialized FROM collect WHERE run_id = @first_run_id OR run_id = @second_run_id AND identity in (SELECT identity FROM collect WHERE run_id = @first_run_id OR run_id = @second_run_id GROUP BY identity HAVING COUNT(*) == 1);"; var output = new ConcurrentQueue<WriteObject>(); Connections.AsParallel().ForAll(cxn => { using var cmd = new SqliteCommand(SQL_GROUPED, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); cmd.Parameters.AddWithValue("@second_run_id", secondRunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var runId = reader["run_id"].ToString(); var resultTypeString = reader["result_type"].ToString(); if (runId != null && resultTypeString != null) { var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId); if (wo is WriteObject WO) output.Enqueue(WO); } } } }); return output; } public IEnumerable<WriteObject> GetAllMissingExplicit(string firstRunId, string secondRunId) { var output = new ConcurrentQueue<WriteObject>(); Connections.AsParallel().ForAll(cxn => { using var cmd = new SqliteCommand(SQL_GET_UNIQUE_BETWEEN_RUNS_EXPLICIT, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); cmd.Parameters.AddWithValue("@second_run_id", secondRunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var runId = reader["run_id"].ToString(); var resultTypeString = reader["result_type"].ToString(); if (runId != null && resultTypeString != null) { var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId); if (wo is WriteObject WO) output.Enqueue(WO); } } } }); return output; } public override bool GetComparisonCompleted(string? firstRunId, string secondRunId) { if (MainConnection != null) { using (var cmd = new SqliteCommand(SQL_CHECK_IF_COMPARISON_PREVIOUSLY_COMPLETED, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@base_run_id", firstRunId); cmd.Parameters.AddWithValue("@compare_run_id", secondRunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { return true; } } } } else { Log.Debug("Failed to GetComparisonCompleted because MainConnection is null."); } return false; } public override List<CompareResult> GetComparisonResults(string baseId, string compareId, RESULT_TYPE exportType) { List<CompareResult> records = new List<CompareResult>(); if (MainConnection != null) { using (var cmd = new SqliteCommand(GET_COMPARISON_RESULTS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@first_run_id", baseId); cmd.Parameters.AddWithValue("@second_run_id", compareId); cmd.Parameters.AddWithValue("@result_type", exportType); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["serialized"].ToString() is string serialized) records.Add(JsonConvert.DeserializeObject<CompareResult>(serialized)); } } } } return records; } public override List<CompareResult> GetComparisonResults(string baseId, string compareId, int resultType, int offset, int numResults) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); var results = new List<CompareResult>(); using (var cmd = new SqliteCommand(GET_COMPARISON_RESULTS_LIMIT, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@first_run_id", baseId); cmd.Parameters.AddWithValue("@second_run_id", compareId); cmd.Parameters.AddWithValue("@result_type", resultType); cmd.Parameters.AddWithValue("@offset", offset); cmd.Parameters.AddWithValue("@limit", numResults); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["meta_serialized"] is string meta_serialized) { CompareResult obj = JsonConvert.DeserializeObject<CompareResult>(meta_serialized); if (reader["first_serialized"] is string first_serialized) { obj.Base = JsonUtils.Hydrate(first_serialized, (RESULT_TYPE)resultType); } if (reader["second_serialized"] is string second_serialized) { obj.Compare = JsonUtils.Hydrate(second_serialized, (RESULT_TYPE)resultType); } results.Add(obj); } } } } return results; } public override int GetComparisonResultsCount(string baseId, string compareId, int resultType) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); var result_count = 0; using (var cmd = new SqliteCommand(GET_RESULT_COUNT, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@first_run_id", baseId); cmd.Parameters.AddWithValue("@second_run_id", compareId); cmd.Parameters.AddWithValue("@result_type", resultType); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["count(*)"].ToString() is string integer) result_count = int.Parse(integer, CultureInfo.InvariantCulture); } } } return result_count; } public override DBSettings GetCurrentSettings() { return dbSettings; } public override List<string> GetLatestRunIds(int numberOfIds, RUN_TYPE type) { List<string> output = new List<string>(); if (MainConnection != null) { using (var cmd = new SqliteCommand(SQL_SELECT_LATEST_N_RUNS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@type", type); cmd.Parameters.AddWithValue("@limit", numberOfIds); try { using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var str = reader["run_id"].ToString(); if (!string.IsNullOrEmpty(str)) output.Add(str); } } } catch (SqliteException) { Log.Debug("Couldn't determine latest {0} run ids.", numberOfIds); } } } else { Log.Debug("Failed to GetLatestRunIds because MainConnection is null."); } return output; } public override IEnumerable<WriteObject> GetMissingFromFirst(string firstRunId, string secondRunId) { var output = new ConcurrentQueue<WriteObject>(); Connections.AsParallel().ForAll(cxn => { using var cmd = new SqliteCommand(SQL_GET_COLLECT_MISSING_IN_B, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); cmd.Parameters.AddWithValue("@second_run_id", secondRunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var runId = reader["run_id"].ToString(); var resultTypeString = reader["result_type"].ToString(); if (runId != null && resultTypeString != null) { var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId); if (wo is WriteObject WO) output.Enqueue(WO); } } } }); return output; } public override IEnumerable<(WriteObject, WriteObject)> GetModified(string firstRunId, string secondRunId) { var output = new ConcurrentQueue<(WriteObject, WriteObject)>(); Connections.AsParallel().ForAll(cxn => { using var cmd = new SqliteCommand(SQL_GET_COLLECT_MODIFIED, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); cmd.Parameters.AddWithValue("@second_run_id", secondRunId); using var reader = cmd.ExecuteReader(); while (reader.Read()) { var aRunId = reader["a_run_id"].ToString(); var bRunId = reader["b_run_id"].ToString(); var aResultType = reader["a_result_type"].ToString(); var bResultType = reader["b_result_type"].ToString(); if (aRunId != null && bRunId != null && aResultType != null && bResultType != null) { if (reader["a_serialized"] is string a_serialized && reader["b_serialized"] is string b_serialized) { var val1 = WriteObject.FromString(a_serialized, (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), aResultType), aRunId); var val2 = WriteObject.FromString(b_serialized, (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), bResultType), bRunId); if (val1 is WriteObject V1 && val2 is WriteObject V2) { output.Enqueue((V1, V2)); } } } } }); return output; } public override List<FileMonitorObject> GetMonitorResults(string runId, int offset, int numResults) { var results = new List<FileMonitorObject>(); if (MainConnection != null) { using (var cmd = new SqliteCommand(GET_MONITOR_RESULTS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", runId); cmd.Parameters.AddWithValue("@offset", offset); cmd.Parameters.AddWithValue("@limit", numResults); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["serialized"] is string serialized) { var obj = JsonConvert.DeserializeObject<FileMonitorObject>(serialized); results.Add(obj); } } } } } else { Log.Debug("Failed to GetMonitorResults. MainConnection was null."); } return results; } public override int GetNumMonitorResults(string runId) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using (var cmd = new SqliteCommand(GET_RESULT_COUNT_MONITORED, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", runId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["count(*)"].ToString() is string integer) return int.Parse(integer, CultureInfo.InvariantCulture); } } } return 0; } public override int GetNumResults(RESULT_TYPE ResultType, string runId) { try { if (MainConnection != null) { using (var cmd = new SqliteCommand(SQL_GET_NUM_RESULTS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", runId); cmd.Parameters.AddWithValue("@result_type", ResultType.ToString()); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { return int.Parse(reader["the_count"].ToString() ?? "-1", CultureInfo.InvariantCulture); } } } } } catch (SqliteException) { Log.Error(Strings.Get("Err_Sql"), MethodBase.GetCurrentMethod()?.Name); } return -1; } public override List<DataRunModel> GetResultModels(RUN_STATUS runStatus) { var output = new List<DataRunModel>(); if (MainConnection != null) { using (var cmd = new SqliteCommand(SQL_QUERY_ANALYZED, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@status", runStatus); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { output.Add(new DataRunModel(KeyIn: reader["base_run_id"].ToString() + " vs. " + reader["compare_run_id"].ToString(), TextIn: reader["base_run_id"].ToString() + " vs. " + reader["compare_run_id"].ToString())); } } } } else { Log.Debug("Failed to GetResultModels, MainConnection is null"); } return output; } public override IEnumerable<WriteObject> GetResultsByRunid(string runid) { foreach (var cxn in Connections) { using var cmd = new SqliteCommand(SQL_GET_RESULTS_BY_RUN_ID, cxn.Connection, cxn.Transaction); cmd.Parameters.AddWithValue("@run_id", runid); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var runId = reader["run_id"].ToString(); var resultTypeString = reader["result_type"].ToString(); if (runId != null && resultTypeString != null) { var wo = WriteObject.FromString((string)reader["serialized"], (RESULT_TYPE)Enum.Parse(typeof(RESULT_TYPE), resultTypeString), runId); if (wo is WriteObject WO) { yield return WO; } } } } } } public override Dictionary<RESULT_TYPE, int> GetResultTypesAndCounts(string runId) { var outDict = new Dictionary<RESULT_TYPE, int>() { }; try { if (MainConnection != null) { using (var cmd = new SqliteCommand(SQL_GET_RESULT_TYPES_COUNTS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", runId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (Enum.TryParse(reader["result_type"].ToString(), out RESULT_TYPE result_type)) { outDict.TryAdd(result_type, int.Parse(reader["count"].ToString() ?? "-1", CultureInfo.InvariantCulture)); } } } } } } catch (SqliteException) { Log.Error(Strings.Get("Err_ResultTypesCounts")); } return outDict; } public override AsaRun? GetRun(string RunId) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using (var cmd = new SqliteCommand(SQL_GET_RUN, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", RunId); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { if (reader["serialized"].ToString() is string serialized) return JsonConvert.DeserializeObject<AsaRun>(serialized); } } } return null; } public override List<string> GetRuns(RUN_TYPE type) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); List<string> Runs = new List<string>(); using var cmd = new SqliteCommand(SQL_SELECT_RUNS, MainConnection.Connection, MainConnection.Transaction); cmd.Parameters.AddWithValue("@type", type); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Runs.Add((string)reader["run_id"]); } } return Runs; } public override List<FileMonitorEvent> GetSerializedMonitorResults(string runId) { List<FileMonitorEvent> records = new List<FileMonitorEvent>(); if (MainConnection != null) { using (var cmd = new SqliteCommand(GET_SERIALIZED_RESULTS, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@run_id", runId); using (var reader = cmd.ExecuteReader()) { FileMonitorEvent obj; while (reader.Read()) { if (reader["serialized"].ToString() is string serialized) { obj = JsonConvert.DeserializeObject<FileMonitorEvent>(serialized); obj.ChangeType = (CHANGE_TYPE)int.Parse(reader["change_type"].ToString() ?? "0", CultureInfo.InvariantCulture); records.Add(obj); } } } } } return records; } public override Settings? GetSettings() { try { using var getSettings = new SqliteCommand(SQL_GET_PERSISTED_SETTINGS, MainConnection?.Connection, MainConnection?.Transaction); getSettings.Parameters.AddWithValue("@id", "Persisted"); using var reader = getSettings.ExecuteReader(); // Settings exist, this isn't the first run if (reader.HasRows) { while (reader.Read()) { if (reader["serialized"].ToString() is string settings) { return JsonConvert.DeserializeObject<Settings>(settings); } } } } catch (Exception e) when (e is SqliteException || e is ArgumentNullException || e is NullReferenceException) { Log.Debug("Didn't find any settings in the database."); //Expected when the table doesn't exist (first run) } return null; } public override void InsertAnalyzed(CompareResult objIn) { if (objIn != null && MainConnection != null) { using (var cmd = new SqliteCommand(SQL_INSERT_FINDINGS_RESULT, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@first_run_id", objIn.BaseRunId); cmd.Parameters.AddWithValue("@second_run_id", objIn.CompareRunId); cmd.Parameters.AddWithValue("@result_type", objIn.ResultType); cmd.Parameters.AddWithValue("@level", objIn.Analysis); cmd.Parameters.AddWithValue("@identity", objIn.Identity); cmd.Parameters.AddWithValue("@first_serialized", JsonConvert.SerializeObject(objIn.Base)); cmd.Parameters.AddWithValue("@second_serialized", JsonConvert.SerializeObject(objIn.Compare)); // Remove these because they don't deserialize properly objIn.Base = null; objIn.Compare = null; cmd.Parameters.AddWithValue("@meta_serialized", JsonConvert.SerializeObject(objIn)); cmd.ExecuteNonQuery(); } } else { Log.Debug("Failed to InsertAnalyzed because MainConnection was null"); } } public override void InsertCompareRun(string? firstRunId, string secondRunId, RUN_STATUS runStatus) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using (var cmd = new SqliteCommand(INSERT_RUN_INTO_RESULT_TABLE_SQL, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@base_run_id", firstRunId); cmd.Parameters.AddWithValue("@compare_run_id", secondRunId); cmd.Parameters.AddWithValue("@status", runStatus); cmd.ExecuteNonQuery(); } } public override void InsertRun(AsaRun run) { if (run == null) { return; } if (MainConnection != null) { using var cmd = new SqliteCommand(SQL_INSERT_RUN, MainConnection.Connection, MainConnection.Transaction); cmd.Parameters.AddWithValue("@run_id", run.RunId); cmd.Parameters.AddWithValue("@type", run.Type); cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(run)); try { cmd.ExecuteNonQuery(); } catch (SqliteException e) { Log.Warning(e.StackTrace); Log.Warning(e.Message); AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e); } } else { Log.Debug("Failed to InsertRun because MainConnection is null."); } } public int PopulateConnections() { var connectionsCreated = 0; for (int i = Connections.Count; i < dbSettings.ShardingFactor; i++) { Connections.Add(GenerateSqlConnection(i)); connectionsCreated++; } return connectionsCreated; } public override void RollBack() { if (Connections != null) { Connections.AsParallel().ForAll(cxn => { try { cxn.Transaction?.Rollback(); } catch (Exception e) { Log.Verbose("Failed to roll back {0} ({1}:{2})", cxn.Source, e.GetType(), e.Message); } cxn.Transaction = null; }); } } public override PLATFORM RunIdToPlatform(string runid) { if (MainConnection != null) { var Run = GetRun(runid); if (Run != null) { return Run.Platform; } else { Log.Debug("Failed to get RunIdToPlatform. RunId was not found in database."); } } else { Log.Debug("Failed to get RunIdToPlatform. MainConnection was null."); } return PLATFORM.UNKNOWN; } public override void SetSettings(Settings settings) { if (MainConnection != null && MainConnection.Connection != null) { try { using var cmd = new SqliteCommand(SQL_UPSERT_PERSISTED_SETTINGS, MainConnection?.Connection, MainConnection?.Transaction); cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(settings)); cmd.Parameters.AddWithValue("@id", "Persisted"); cmd.ExecuteNonQuery(); } catch (SqliteException) { Log.Warning("Failed to save settings to database."); } } else { Log.Warning("Failed to save settings to database."); } } public override ASA_ERROR Setup() { // Clean up if we were already open. CloseDatabase(); if (!EstablishMainConnection()) { Log.Fatal(Strings.Get("FailedToEstablishMainConnection"), Location); return ASA_ERROR.FAILED_TO_ESTABLISH_MAIN_DB_CONNECTION; } var settingsFromDb = GetSettings(); if (settingsFromDb != null) { FirstRun = false; if (SCHEMA_VERSION != settingsFromDb.SchemaVersion) { Log.Fatal(Strings.Get("WrongSchema"), settingsFromDb.SchemaVersion, SCHEMA_VERSION); return ASA_ERROR.MATCHING_SCHEMA; } if (settingsFromDb.ShardingFactor != dbSettings.ShardingFactor) { Log.Information(Strings.Get("InvalidShardingRequest"), dbSettings.ShardingFactor, settingsFromDb.ShardingFactor); } dbSettings.ShardingFactor = settingsFromDb.ShardingFactor; AsaTelemetry.SetEnabled(settingsFromDb.TelemetryEnabled); } else { FirstRun = true; } PopulateConnections(); if (MainConnection == null) { Log.Fatal(Strings.Get("FailedToEstablishMainConnection"), Location); return ASA_ERROR.FAILED_TO_ESTABLISH_MAIN_DB_CONNECTION; } if (FirstRun) { try { BeginTransaction(); using var cmd2 = new SqliteCommand(SQL_CREATE_RUNS, MainConnection.Connection, MainConnection.Transaction); cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_RESULTS; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FINDINGS_RESULTS; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FINDINGS_LEVEL_INDEX; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FINDINGS_IDENTITY_INDEX; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_FILE_MONITORED; cmd2.ExecuteNonQuery(); cmd2.CommandText = SQL_CREATE_PERSISTED_SETTINGS; cmd2.ExecuteNonQuery(); SetSettings(new Settings() { SchemaVersion = SCHEMA_VERSION, ShardingFactor = dbSettings.ShardingFactor, TelemetryEnabled = true }); Connections.AsParallel().ForAll(cxn => { using (var innerCmd = new SqliteCommand(SQL_CREATE_COLLECT_RESULTS, cxn.Connection, cxn.Transaction)) { innerCmd.ExecuteNonQuery(); innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_INDEX; innerCmd.ExecuteNonQuery(); innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX; innerCmd.ExecuteNonQuery(); innerCmd.CommandText = SQL_CREATE_COLLECT_RUN_ID_IDENTITY_INDEX; innerCmd.ExecuteNonQuery(); } }); } catch (SqliteException e) { Log.Debug(e, "Failed to set up fresh database."); return ASA_ERROR.FAILED_TO_CREATE_DATABASE; } finally { Commit(); } } return ASA_ERROR.NONE; } public void StallIfHighMemoryUsageAndLowMemoryModeEnabled() { if (dbSettings.LowMemoryUsage) { int stallCount = 0; while (QueueSize > LOW_MEMORY_CUTOFF) { if (stallCount++ % 1000 == 0) { Log.Verbose("Stalling Collector with {0} results for Memory Usage", QueueSize); } Thread.Sleep(1); } } } public override void TrimToLatest() { if (MainConnection != null) { using var cmd = new SqliteCommand(GET_RUNS, MainConnection.Connection, MainConnection.Transaction); using (var reader = cmd.ExecuteReader()) { //Skip first row, that is the one we want to keep reader.Read(); while (reader.Read()) { DeleteRun((string)reader["run_id"]); } } } else { Log.Debug("Failed to trim. MainConnection is null."); } } public override void UpdateCompareRun(string? firstRunId, string secondRunId, RUN_STATUS runStatus) { _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using (var cmd = new SqliteCommand(UPDATE_RUN_IN_RESULT_TABLE, MainConnection.Connection, MainConnection.Transaction)) { cmd.Parameters.AddWithValue("@base_run_id", firstRunId); cmd.Parameters.AddWithValue("@compare_run_id", secondRunId); cmd.Parameters.AddWithValue("@status", runStatus); cmd.ExecuteNonQuery(); } } public override void Vacuum() { Connections.AsParallel().ForAll(cxn => { using var inner_cmd = new SqliteCommand(SQL_VACUUM, cxn.Connection, cxn.Transaction); inner_cmd.ExecuteNonQuery(); }); } public override void Write(CollectObject? colObj, string? runId) { if (colObj != null && runId != null) { var objIn = new WriteObject(colObj, runId); Connections[ModuloString(objIn.Identity, shardingFactor: dbSettings.ShardingFactor)].WriteQueue.Push(objIn); } } public override void WriteFileMonitor(FileMonitorObject fmo, string RunId) { if (fmo == null) { return; } _ = MainConnection ?? throw new NullReferenceException(Strings.Get("MainConnection")); using var cmd = new SqliteCommand(SQL_INSERT, MainConnection.Connection, MainConnection.Transaction); cmd.Parameters.AddWithValue("@run_id", RunId); cmd.Parameters.AddWithValue("@path", fmo.Path); cmd.Parameters.AddWithValue("@timestamp", fmo.Timestamp); cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(fmo)); cmd.ExecuteNonQuery(); } private const string GET_COMPARISON_RESULTS = "select * from findings where first_run_id = @first_run_id and second_run_id = @second_run_id and result_type=@result_type order by level desc;"; private const string GET_COMPARISON_RESULTS_LIMIT = "select * from findings where first_run_id = @first_run_id and second_run_id = @second_run_id and result_type=@result_type order by level desc limit @offset,@limit;"; private const string GET_MONITOR_RESULTS = "select * from file_system_monitored where run_id=@run_id order by timestamp limit @offset,@limit;"; private const string GET_RESULT_COUNT = "select count(*) from findings where first_run_id = @first_run_id and second_run_id = @second_run_id and result_type=@result_type"; private const string GET_RESULT_COUNT_MONITORED = "select count(*) from file_system_monitored where run_id=@run_id;"; private const string GET_RUNS = "select run_id from runs order by ROWID desc;"; private const string GET_SERIALIZED_RESULTS = "select change_type, Serialized from file_system_monitored where run_id = @run_id"; private const string INSERT_RUN_INTO_RESULT_TABLE_SQL = "insert into results (base_run_id, compare_run_id, status) values (@base_run_id, @compare_run_id, @status);"; private const int SCHEMA_VERSION = 10; private const string SQL_CHECK_IF_COMPARISON_PREVIOUSLY_COMPLETED = "select * from results where base_run_id=@base_run_id and compare_run_id=@compare_run_id"; private const string SQL_CREATE_COLLECT_RESULTS = "create table if not exists collect (run_id text, result_type text, identity text, row_key blob, serialized blob, UNIQUE(run_id, identity))"; private const string SQL_CREATE_COLLECT_RUN_ID_IDENTITY_INDEX = "create index if not exists i_collect_collect_run_id_identity on collect(run_id, identity)"; private const string SQL_CREATE_COLLECT_RUN_ID_INDEX = "create index if not exists i_collect_collect_run_id on collect(run_id)"; private const string SQL_CREATE_COLLECT_RUN_KEY_IDENTITY_COMBINED_INDEX = "create index if not exists i_collect_collect_runid_row_type on collect(run_id, identity, row_key, result_type)"; private const string SQL_CREATE_FILE_MONITORED = "create table if not exists file_system_monitored (run_id text, path text, timestamp text, serialized text)"; private const string SQL_CREATE_FINDINGS_IDENTITY_INDEX = "create index if not exists i_findings_identity on findings(identity)"; private const string SQL_CREATE_FINDINGS_LEVEL_INDEX = "create index if not exists i_findings_level on findings(level)"; private const string SQL_CREATE_FINDINGS_LEVEL_RESULT_TYPE_INDEX = "create index if not exists i_findings_level_result_type on findings(level, result_type)"; private const string SQL_CREATE_FINDINGS_RESULT_TYPE_INDEX = "create index if not exists i_findings_result_type on findings(result_type)"; private const string SQL_CREATE_FINDINGS_RESULTS = "create table if not exists findings (first_run_id text, second_run_id text, level int, result_type int, identity text, first_serialized text, second_serialized text, meta_serialized text)"; private const string SQL_CREATE_PERSISTED_SETTINGS = "create table if not exists persisted_settings (id text, serialized text, unique(id))"; private const string SQL_CREATE_RESULTS = "create table if not exists results (base_run_id text, compare_run_id text, status text);"; private const string SQL_CREATE_RUNS = "create table if not exists runs (run_id text, type string, serialized blob, unique(run_id))"; private const string SQL_DELETE_RUN = "delete from collect where run_id=@run_id"; private const string SQL_GET_COLLECT_MISSING_IN_B = "SELECT * FROM collect b WHERE b.run_id = @second_run_id AND b.identity NOT IN (SELECT identity FROM collect a WHERE a.run_id = @first_run_id);"; private const string SQL_GET_COLLECT_MODIFIED = "select a.serialized as 'a_serialized', a.result_type as 'a_result_type', a.run_id as 'a_run_id'," + "b.serialized as 'b_serialized', b.result_type as 'b_result_type', b.run_id as 'b_run_id'" + " from collect a indexed by i_collect_collect_runid_row_type," + " collect b indexed by i_collect_collect_runid_row_type" + " where a.run_id=@first_run_id and b.run_id=@second_run_id and a.identity = b.identity and " + "a.row_key != b.row_key and a.result_type = b.result_type and a.serialized != b.serialized;"; private const string SQL_GET_NUM_RESULTS = "select count(*) as the_count from collect where run_id = @run_id and result_type = @result_type"; private const string SQL_GET_PERSISTED_SETTINGS = "select serialized from persisted_settings where id=@id"; private const string SQL_GET_RESULT_TYPES_COUNTS = "select count(*) as count,result_type from collect where run_id = @run_id group by result_type"; private const string SQL_GET_RESULTS_BY_RUN_ID = "select * from collect where run_id = @run_id"; private const string SQL_GET_RUN = "select * from runs where run_id = @run_id"; private const string SQL_GET_UNIQUE_BETWEEN_RUNS = "SELECT run_id, result_type, serialized, COUNT (*) FROM collect WHERE run_id = @first_run_id or run_id = @second_run_id GROUP BY identity, result_type HAVING COUNT(*) == 1;"; private const string SQL_GET_UNIQUE_BETWEEN_RUNS_EXPLICIT = "SELECT run_id, result_type, serialized, COUNT (*) FROM collect indexed by i_collect_collect_runid_row_type WHERE run_id = @first_run_id or run_id = @second_run_id GROUP BY identity, result_type HAVING COUNT(*) == 1;"; private const string SQL_INSERT = "insert into file_system_monitored (run_id, path, timestamp, serialized) values (@run_id, @path, @timestamp, @serialized)"; private const string SQL_INSERT_FINDINGS_RESULT = "insert into findings (first_run_id, second_run_id, result_type, level, identity, first_serialized, second_serialized, meta_serialized) values (@first_run_id, @second_run_id, @result_type, @level, @identity, @first_serialized, @second_serialized, @meta_serialized)"; private const string SQL_INSERT_RUN = "insert into runs (run_id, type, serialized) values (@run_id, @type, @serialized)"; private const string SQL_QUERY_ANALYZED = "select * from results where status = @status"; private const string SQL_SELECT_LATEST_N_RUNS = "select run_id from runs where type = @type order by ROWID desc limit 0,@limit;"; private const string SQL_SELECT_RUNS = "select distinct run_id from runs where type=@type order by ROWID asc;"; private const string SQL_TRUNCATE_RUN = "delete from runs where run_id=@run_id"; private const string SQL_UPSERT_PERSISTED_SETTINGS = "insert or replace into persisted_settings (id, serialized) values (@id, @serialized)"; private const string SQL_VACUUM = "VACUUM"; private const string UPDATE_RUN_IN_RESULT_TABLE = "update results set status = @status where (base_run_id = @base_run_id and compare_run_id = @compare_run_id)"; private DBSettings dbSettings = new DBSettings(); private SqlConnectionHolder GenerateSqlConnection(int i) { if (i == 0) { return new SqlConnectionHolder(Location, dbSettings); } else { return new SqlConnectionHolder($"{Location}_{i}", dbSettings); } } } }
44.669708
324
0.534111
[ "MIT" ]
Bhaskers-Blu-Org2/AttackSurfaceAnalyzer
Lib/Utils/SqliteDatabaseManager.cs
48,960
C#
using AzureSearchToolkit.Mapping; using AzureSearchToolkit.Utilities; using Microsoft.Azure.Search.Models; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace AzureSearchToolkit.Request.Visitors { class MemberProjectionExpressionVisitor : AzureSearchFieldsExpressionVisitor { protected static readonly MethodInfo GetKeyedValueMethod = typeof(MemberProjectionExpressionVisitor).GetMethodInfo(m => m.Name == "GetKeyedValueOrDefault"); readonly HashSet<string> fieldNames = new HashSet<string>(); MemberProjectionExpressionVisitor(Type sourceType, ParameterExpression bindingParameter, IAzureSearchMapping mapping) : base(sourceType, bindingParameter, mapping) { } internal new static RebindCollectionResult<string> Rebind(Type sourceType, IAzureSearchMapping mapping, Expression selector) { var parameter = Expression.Parameter(typeof(Document), "h"); var visitor = new MemberProjectionExpressionVisitor(sourceType, parameter, mapping); Argument.EnsureNotNull(nameof(selector), selector); var materializer = visitor.Visit(selector); return new RebindCollectionResult<string>(materializer, visitor.fieldNames, parameter); } protected override Expression VisitMember(MemberExpression node) { if (node.Expression != null) { switch (node.Expression.NodeType) { case ExpressionType.Parameter: case ExpressionType.MemberAccess: return VisitFieldSelection(node); } } return base.VisitMember(node); } Expression VisitFieldSelection(MemberExpression m) { var member = base.VisitAzureSearchField(m); fieldNames.Add(m.Member.Name.ToLowerInvariant()); return member; } } }
34.066667
164
0.66683
[ "Apache-2.0" ]
nkovacic/AzureSearch.Toolkit
AzureSearchToolkit/Request/Visitors/MemberProjectionExpressionVisitor.cs
2,046
C#
using SevenTiny.Bantina; using System; namespace SevenTiny.Cloud.MultiTenantPlatform.DataApi.Models { public class QueryArgs { public string _interface { get; set; } public int _pageIndex { get; set; } public int _pageSize { get; set; } public void QueryArgsCheck() { if (string.IsNullOrEmpty(_interface)) { throw new Exception("interfaceCode can not be null!"); } } } }
23.142857
70
0.578189
[ "Apache-2.0" ]
sevenTiny/7Tiny.Cloud.MultiTenant
Code/SevenTiny.Cloud.MultiTenant.DataApi/Models/QueryArgs.cs
488
C#
using Microsoft.EntityFrameworkCore; using Skyline.Domain.ContactAggregate; using Skyline.Infrastructure.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Skyline.Infrastructure.Repositories { public class ContactRepository : Repository<Contact, Guid, ApplicationDbContext>, IContactRepository { ApplicationDbContext _dbContext; public ContactRepository(ApplicationDbContext dbContext) : base(dbContext) { _dbContext = dbContext; } public async Task<List<Contact>> GetAllContactsWithAuthorized() { var contacts = await _dbContext.Contacts.ToListAsync(); return contacts; } /// <summary> /// 获取通讯录 /// TODO:表达式树实现条件查询 /// </summary> /// <returns></returns> public async Task<List<Contact>> GetContactsWithOutAuthorized(string currentUserId) { var contacts = _dbContext.Contacts.Where(c => c.Status == ContactStatus.Approved || c.OwnerId == currentUserId); return await contacts.ToListAsync(); } } }
30.589744
104
0.65549
[ "MIT" ]
zhaobingwang/Skyline
MicroServicesArchitecture/src/Skyline.Infrastructure/Repositories/ContactRepository.cs
1,225
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:RequestMessageFactory.cs 文件功能描述:获取XDocument转换后的IRequestMessageBase实例 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20150327 修改描述:添加小视频类型 ----------------------------------------------------------------*/ using System; using System.IO; using System.Xml; using System.Xml.Linq; using Senparc.Weixin.Exceptions; using Senparc.Weixin.MP.Entities; using Senparc.Weixin.MP.Entities.Request; using Senparc.Weixin.MP.Helpers; namespace Senparc.Weixin.MP { /// <summary> /// RequestMessage 消息处理方法工厂类 /// </summary> public static class RequestMessageFactory { //<?xml version="1.0" encoding="utf-8"?> //<xml> // <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName> // <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName> // <CreateTime>1357986928</CreateTime> // <MsgType><![CDATA[text]]></MsgType> // <Content><![CDATA[中文]]></Content> // <MsgId>5832509444155992350</MsgId> //</xml> /// <summary> /// 获取XDocument转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null) { RequestMessageBase requestMessage = null; RequestMsgType msgType; try { msgType = MsgTypeHelper.GetRequestMsgType(doc); switch (msgType) { case RequestMsgType.Text: requestMessage = new RequestMessageText(); break; case RequestMsgType.Location: requestMessage = new RequestMessageLocation(); break; case RequestMsgType.Image: requestMessage = new RequestMessageImage(); break; case RequestMsgType.Voice: requestMessage = new RequestMessageVoice(); break; case RequestMsgType.Video: requestMessage = new RequestMessageVideo(); break; case RequestMsgType.Link: requestMessage = new RequestMessageLink(); break; case RequestMsgType.ShortVideo: requestMessage = new RequestMessageShortVideo(); break; case RequestMsgType.Event: //判断Event类型 switch (doc.Root.Element("Event").Value.ToUpper()) { case "ENTER"://进入会话 requestMessage = new RequestMessageEvent_Enter(); break; case "LOCATION"://地理位置 requestMessage = new RequestMessageEvent_Location(); break; case "SUBSCRIBE"://订阅(关注) requestMessage = new RequestMessageEvent_Subscribe(); break; case "UNSUBSCRIBE"://取消订阅(关注) requestMessage = new RequestMessageEvent_Unsubscribe(); break; case "CLICK"://菜单点击 requestMessage = new RequestMessageEvent_Click(); break; case "SCAN"://二维码扫描 requestMessage = new RequestMessageEvent_Scan(); break; case "VIEW"://URL跳转 requestMessage = new RequestMessageEvent_View(); break; case "MASSSENDJOBFINISH": requestMessage = new RequestMessageEvent_MassSendJobFinish(); break; case "TEMPLATESENDJOBFINISH"://模板信息 requestMessage = new RequestMessageEvent_TemplateSendJobFinish(); break; case "SCANCODE_PUSH"://扫码推事件(scancode_push) requestMessage = new RequestMessageEvent_Scancode_Push(); break; case "SCANCODE_WAITMSG"://扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg) requestMessage = new RequestMessageEvent_Scancode_Waitmsg(); break; case "PIC_SYSPHOTO"://弹出系统拍照发图(pic_sysphoto) requestMessage = new RequestMessageEvent_Pic_Sysphoto(); break; case "PIC_PHOTO_OR_ALBUM"://弹出拍照或者相册发图(pic_photo_or_album) requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album(); break; case "PIC_WEIXIN"://弹出微信相册发图器(pic_weixin) requestMessage = new RequestMessageEvent_Pic_Weixin(); break; case "LOCATION_SELECT"://弹出地理位置选择器(location_select) requestMessage = new RequestMessageEvent_Location_Select(); break; case "CARD_PASS_CHECK"://卡券通过审核 requestMessage = new RequestMessageEvent_Card_Pass_Check(); break; case "CARD_NOT_PASS_CHECK"://卡券未通过审核 requestMessage = new RequestMessageEvent_Card_Not_Pass_Check(); break; case "USER_GET_CARD"://领取卡券 requestMessage = new RequestMessageEvent_User_Get_Card(); break; case "USER_DEL_CARD"://删除卡券 requestMessage = new RequestMessageEvent_User_Del_Card(); break; case "KF_CREATE_SESSION"://多客服接入会话 requestMessage = new RequestMessageEvent_Kf_Create_Session(); break; case "KF_CLOSE_SESSION"://多客服关闭会话 requestMessage = new RequestMessageEvent_Kf_Close_Session(); break; case "KF_SWITCH_SESSION"://多客服转接会话 requestMessage = new RequestMessageEvent_Kf_Switch_Session(); break; case "POI_CHECK_NOTIFY"://审核结果事件推送 requestMessage = new RequestMessageEvent_Poi_Check_Notify(); break; case "WIFICONNECTED"://Wi-Fi连网成功事件 requestMessage = new RequestMessageEvent_WifiConnected(); break; case "USER_CONSUME_CARD"://卡券核销 requestMessage = new RequestMessageEvent_User_Consume_Card(); break; case "USER_ENTER_SESSION_FROM_CARD"://从卡券进入公众号会话 requestMessage = new RequestMessageEvent_User_Enter_Session_From_Card(); break; case "USER_VIEW_CARD"://进入会员卡 requestMessage = new RequestMessageEvent_User_View_Card(); break; case "MERCHANT_ORDER"://微小店订单付款通知 requestMessage = new RequestMessageEvent_Merchant_Order(); break; case "SUBMIT_MEMBERCARD_USER_INFO"://接收会员信息事件通知 requestMessage = new RequestMessageEvent_Submit_Membercard_User_Info(); break; case "SHAKEAROUNDUSERSHAKE"://摇一摇事件通知 requestMessage = new RequestMessageEvent_ShakearoundUserShake(); break; case "USER_GIFTING_CARD"://卡券转赠事件推送 requestMessage = new RequestMessageEvent_User_Gifting_Card(); break; case "USER_PAY_FROM_PAY_CELL":// 微信买单完成 requestMessage = new RequestMessageEvent_User_Pay_From_Pay_Cell(); break; case "UPDATE_MEMBER_CARD":// 会员卡内容更新事件:会员卡积分余额发生变动时 requestMessage = new RequestMessageEvent_Update_Member_Card(); break; case "CARD_SKU_REMIND"://卡券库存报警事件:当某个card_id的初始库存数大于200且当前库存小于等于100时 requestMessage = new RequestMessageEvent_Card_Sku_Remind(); break; case "CARD_PAY_ORDER"://券点流水详情事件:当商户朋友的券券点发生变动时 requestMessage = new RequestMessageEvent_Card_Pay_Order(); break; default://其他意外类型(也可以选择抛出异常) requestMessage = new RequestMessageEventBase(); break; } break; default: throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常 } EntityHelper.FillEntityWithXml(requestMessage, doc); } catch (ArgumentException ex) { throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex); } return requestMessage; } /// <summary> /// 获取XML转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(string xml) { return GetRequestEntity(XDocument.Parse(xml)); } /// <summary> /// 获取内容为XML的Stream转换后的IRequestMessageBase实例。 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常 /// </summary> /// <param name="stream">如Request.InputStream</param> /// <returns></returns> public static IRequestMessageBase GetRequestEntity(Stream stream) { using (XmlReader xr = XmlReader.Create(stream)) { var doc = XDocument.Load(xr); // return GetRequestEntity(doc); } } } }
48.046512
245
0.487899
[ "Apache-2.0" ]
AjuPrince/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/RequestMessageFactory.cs
13,438
C#
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.PublisherApi.Enums { /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> [SupportByVersion("Publisher", 14,15,16)] [EntityType(EntityType.IsEnum)] public enum PbMailMergeDataSource { /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>5</remarks> [SupportByVersion("Publisher", 14,15,16)] pbMergeInfoFromODSO = 5, /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> /// <remarks>6</remarks> [SupportByVersion("Publisher", 14,15,16)] pbMergeInfoSubODSO = 6 } }
24.333333
44
0.666667
[ "MIT" ]
DominikPalo/NetOffice
Source/Publisher/Enums/PbMailMergeDataSource.cs
659
C#
using CompanyName.MyMeetings.Modules.UserAccess.Application.Configuration.Queries; using Dapper; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace CompanyName.MyMeetings.Modules.UserAccess.Application.Authorization.GetUserPermissions { internal class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQuery, List<UserPermissionDto>> { private readonly ISqlConnectionFactory _sqlConnectionFactory; public GetUserPermissionsQueryHandler(ISqlConnectionFactory sqlConnectionFactory) { _sqlConnectionFactory = sqlConnectionFactory; } public async Task<List<UserPermissionDto>> Handle(GetUserPermissionsQuery request, CancellationToken cancellationToken) { var connection = _sqlConnectionFactory.GetOpenConnection(); const string sql = "SELECT " + "[UserPermission].[PermissionCode] AS [Code] " + "FROM [users].[v_UserPermissions] AS [UserPermission] " + "WHERE [UserPermission].UserId = @UserId"; var permissions = await connection.QueryAsync<UserPermissionDto>(sql, new { request.UserId }); return permissions.AsList(); } } }
39.787879
127
0.689261
[ "MIT" ]
GamilYassin/modular-monolith-with-ddd
src/Modules/UserAccess/Application/Authorization/GetUserPermissions/GetUserPermissionsQueryHandler.cs
1,315
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using OptimizationRepeater.Models; namespace OptimizationRepeater.ViewModels { public class OptimizationFunctionViewModel : BindableBaseWithErrorsContainer { public ObservableCollection<OptimizationFunction> OptimizationFunctions { get; set; } = new ObservableCollection<OptimizationFunction>(); public OptimizationFunctionViewModel() { //OptimizationFunctions.Add(new OptimizationFunction { FunctionType = "MaxEud", RoiName = "Rectum", DoseLevel = 2500, EudParameterA = 1, Weight = 1, PlanLabel = "1-1-1" }); //OptimizationFunctions.Add(new OptimizationFunction { FunctionType = "MaxEud", RoiName = "Bladder", DoseLevel = 2000, EudParameterA = 1, Weight = 1, PlanLabel = "Combined dose" }); //OptimizationFunctions.Add(new OptimizationFunction { FunctionType = "UniformDose", RoiName = "PTV", DoseLevel = 7600, Weight = 100, PlanLabel = "1-1-2" }); } public OptimizationFunctionViewModel(List<OptimizationFunction> optimizationFunctions) { OptimizationFunctions = new ObservableCollection<OptimizationFunction>(optimizationFunctions); } } }
51.458333
193
0.721457
[ "MIT" ]
s2atoru/RayStationScripts
OptimizationRepeater/ViewModels/OptimizationFunctionViewModel.cs
1,237
C#
public class OffCollisionCommand : ToolActionCommandBase // TypeDefIndex: 6280 { // Methods // RVA: 0x1D8EA70 Offset: 0x1D8EB71 VA: 0x1D8EA70 public void .ctor(ActionCommandDataTable actionCommandData, AS_ToolController controller) { } // RVA: 0x1D8EAD0 Offset: 0x1D8EBD1 VA: 0x1D8EAD0 Slot: 8 public override void DoAction() { } }
28.333333
94
0.767647
[ "MIT" ]
SinsofSloth/RF5-global-metadata
_no_namespace/OffCollisionCommand.cs
340
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LinqToLdap.Visitors { /// <summary> /// Pulled from http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx /// </summary> internal static class Evaluator { /// <summary> /// Performs evaluation and replacement of independent sub-trees /// </summary> /// <param name="expression">The root of the expression tree.</param> /// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param> /// <returns>A new tree with sub-trees evaluated and replaced.</returns> private static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated) { expression = new BooleanRewriter().Rewrite(expression); expression = new BooleanReducer().Reduce(expression); return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression); } /// <summary> /// Performs evaluation and replacement of independent sub-trees /// </summary> /// <param name="expression">The root of the expression tree.</param> /// <returns>A new tree with sub-trees evaluated and replaced.</returns> public static Expression PartialEval(Expression expression) { return PartialEval(expression, CanBeEvaluatedLocally); } private static bool CanBeEvaluatedLocally(Expression expression) { if (expression.NodeType == ExpressionType.Constant) { return !(((ConstantExpression)expression).Value is IQueryable); } return expression.NodeType != ExpressionType.Parameter; } #region Nested type: SubtreeEvaluator /// <summary> /// Evaluates and replaces sub-trees when first candidate is reached (top-down) /// </summary> private class SubtreeEvaluator : ExpressionVisitor { private readonly HashSet<Expression> _candidates; public SubtreeEvaluator(HashSet<Expression> candidates) { _candidates = candidates; } public Expression Eval(Expression exp) { return Visit(exp); } protected override Expression Visit(Expression exp) { if (exp == null) { return null; } if (_candidates.Contains(exp)) { return Evaluate(exp); } return base.Visit(exp); } private static Expression Evaluate(Expression e) { if (e.NodeType == ExpressionType.Constant) return e; if (e.NodeType == ExpressionType.Lambda) return e; LambdaExpression lambda = Expression.Lambda(e); Delegate fn = lambda.Compile(); return Expression.Constant(fn.DynamicInvoke(null), e.Type); } } #endregion Nested type: SubtreeEvaluator } }
34.852632
141
0.579583
[ "MIT" ]
madhatter22/LinqToLdap
LinqToLdap/Visitors/Evaluator.cs
3,313
C#
using System.Collections.Generic; using UnityEngine; namespace Hydra.HydraCommon.Utils.Comparers { /// <summary> /// ClockwiseComparer provides functionality for sorting a collection of Vector2s such /// that they are ordered clockwise about a given origin. /// </summary> public class ClockwiseComparer : IComparer<Vector2> { private Vector2 m_Origin; #region Properties /// <summary> /// Gets or sets the origin. /// </summary> /// <value>The origin.</value> public Vector2 origin { get { return m_Origin; } set { m_Origin = value; } } #endregion /// <summary> /// Initializes a new instance of the ClockwiseComparer class. /// </summary> /// <param name="origin">Origin.</param> public ClockwiseComparer(Vector2 origin) { m_Origin = origin; } #region IComparer Methods /// <summary> /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> public int Compare(Vector2 first, Vector2 second) { return IsClockwise(first, second, m_Origin); } #endregion /// <summary> /// Returns 1 if first comes before second in clockwise order. /// Returns -1 if second comes before first. /// Returns 0 if the points are identical. /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="origin">Origin.</param> public static int IsClockwise(Vector2 first, Vector2 second, Vector2 origin) { if (first == second) return 0; Vector2 firstOffset = first - origin; Vector2 secondOffset = second - origin; float angle1 = Mathf.Atan2(firstOffset.x, firstOffset.y); float angle2 = Mathf.Atan2(secondOffset.x, secondOffset.y); if (angle1 < angle2) return -1; if (angle1 > angle2) return 1; // Check to see which point is closest return (firstOffset.sqrMagnitude > secondOffset.sqrMagnitude) ? -1 : 1; } } }
31.776316
127
0.570186
[ "MIT" ]
jotaate/Crowds
Assets/Scripts/Utils/ClockwiseComparer.cs
2,417
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the docdb-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DocDB.Model { /// <summary> /// Container for the parameters to the DescribeDBClusterParameterGroups operation. /// Returns a list of <code>DBClusterParameterGroup</code> descriptions. If a <code>DBClusterParameterGroupName</code> /// parameter is specified, the list contains only the description of the specified cluster /// parameter group. /// </summary> public partial class DescribeDBClusterParameterGroupsRequest : AmazonDocDBRequest { private string _dbClusterParameterGroupName; private List<Filter> _filters = new List<Filter>(); private string _marker; private int? _maxRecords; /// <summary> /// Gets and sets the property DBClusterParameterGroupName. /// <para> /// The name of a specific cluster parameter group to return details for. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// If provided, must match the name of an existing <code>DBClusterParameterGroup</code>. /// </para> /// </li> </ul> /// </summary> public string DBClusterParameterGroupName { get { return this._dbClusterParameterGroupName; } set { this._dbClusterParameterGroupName = value; } } // Check to see if DBClusterParameterGroupName property is set internal bool IsSetDBClusterParameterGroupName() { return this._dbClusterParameterGroupName != null; } /// <summary> /// Gets and sets the property Filters. /// <para> /// This parameter is not currently supported. /// </para> /// </summary> public List<Filter> Filters { get { return this._filters; } set { this._filters = value; } } // Check to see if Filters property is set internal bool IsSetFilters() { return this._filters != null && this._filters.Count > 0; } /// <summary> /// Gets and sets the property Marker. /// <para> /// An optional pagination token provided by a previous request. If this parameter is /// specified, the response includes only records beyond the marker, up to the value specified /// by <code>MaxRecords</code>. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } /// <summary> /// Gets and sets the property MaxRecords. /// <para> /// The maximum number of records to include in the response. If more records exist than /// the specified <code>MaxRecords</code> value, a pagination token (marker) is included /// in the response so that the remaining results can be retrieved. /// </para> /// /// <para> /// Default: 100 /// </para> /// /// <para> /// Constraints: Minimum 20, maximum 100. /// </para> /// </summary> public int MaxRecords { get { return this._maxRecords.GetValueOrDefault(); } set { this._maxRecords = value; } } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this._maxRecords.HasValue; } } }
33.043796
122
0.594213
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/DocDB/Generated/Model/DescribeDBClusterParameterGroupsRequest.cs
4,527
C#
// Copyright (c) Microsoft Corporation. All rights reserved. using SmartDisplay.Bluetooth; using SmartDisplay.Contracts; using SmartDisplay.Utils; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Foundation.Diagnostics; using Windows.Networking.Sockets; using Windows.Storage; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; namespace SmartDisplay.ViewModels.Settings { public class BluetoothSettingsVM : BaseViewModel { #region UI properties and commands public bool BluetoothWatcherEnabled { get { return GetStoredProperty<bool>(); } set { SetStoredProperty(value); } } public bool BluetoothToggleIsOn { get { return GetStoredProperty<bool>(); } set { if (_isBluetoothDiscoverable && SetStoredProperty(value)) { if (value) { StartWatcherWithConfirmationAsync(); } else { StopWatcherWithConfirmationAsync(); } }; } } public string ConfirmationMessageText { get { return GetStoredProperty<string>() ?? string.Empty; } private set { SetStoredProperty(value); } } public double PanelWidth { get; } = Constants.SettingsWidth; public ObservableCollection<BluetoothDeviceInfo> BluetoothDeviceCollection { get; } = new ObservableCollection<BluetoothDeviceInfo>(); private enum MessageType { YesNoMessage, OKMessage, InformationalMessage }; // Device watcher private DeviceWatcher _deviceWatcher = null; private TypedEventHandler<DeviceWatcher, DeviceInformation> _handlerAdded = null; private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> _handlerUpdated = null; private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> _handlerRemoved = null; // Pairing controls and notifications private Button _inProgressPairButton = null; private FlyoutBase _savedPairButtonFlyout = null; private BluetoothDeviceInfo _deviceInfo = null; private DevicePairingRequestedEventArgs _pairingRequestedArgs = null; private Deferral _deferral = null; private RfcommServiceProvider _provider = null; private static bool _isBluetoothDiscoverable = false; private bool _isPairing = false; #endregion #region Localized UI strings private string BluetoothAttemptingToPairFormat { get; } = Common.GetLocalizedText("BluetoothAttemptingToPairFormat"); private string BluetoothConfirmOnlyText { get; } = Common.GetLocalizedText("BluetoothConfirmOnlyFormat"); private string BluetoothConfirmPINMatchText { get; } = Common.GetLocalizedText("BluetoothConfirmPinMatchFormat"); private string BluetoothDeviceNameUnknownText { get; } = Common.GetLocalizedText("BluetoothDeviceNameUnknownText"); private string BluetoothDisplayPINText { get; } = Common.GetLocalizedText("BluetoothDisplayPinFormat"); private string BluetoothInboundRegistrationFailed { get; } = Common.GetLocalizedText("BluetoothInboundRegistrationFailed"); private string BluetoothInboundRegistrationSucceededFormat { get; } = Common.GetLocalizedText("BluetoothInboundRegistrationSucceededFormat"); private string BluetoothIncorrectEnteredPIN { get; } = Common.GetLocalizedText("BluetoothIncorrectEnteredPIN"); private string BluetoothNoDeviceAvailableFormat { get; } = Common.GetLocalizedText("BluetoothNoDeviceAvailableFormat"); private string BluetoothPairingFailureFormat { get; } = Common.GetLocalizedText("BluetoothPairingFailureFormat"); private string BluetoothPairingSuccessFormat { get; } = Common.GetLocalizedText("BluetoothPairingSuccessFormat"); private string BluetoothPreferencesText { get; } = Common.GetLocalizedText("BluetoothPreferences/Text"); private string BluetoothStartedWatching { get; } = Common.GetLocalizedText("BluetoothStartedWatching"); private string BluetoothStoppedWatching { get; } = Common.GetLocalizedText("BluetoothStoppedWatching"); private string BluetoothUnpairingFailureFormat { get; } = Common.GetLocalizedText("BluetoothUnpairingFailureFormat"); private string BluetoothUnpairingSuccessFormat { get; } = Common.GetLocalizedText("BluetoothUnpairingSuccessFormat"); private string NoButtonText { get; } = Common.GetLocalizedText("NoButtonText"); private string OkButtonText { get; } = Common.GetLocalizedText("OkButtonText"); private string YesButtonText { get; } = Common.GetLocalizedText("YesButtonText"); #endregion #region Data containers, dispatcher, and services private ApplicationDataContainer LocalSettings => ApplicationData.Current?.LocalSettings; private ILogService LogService => AppService?.LogService; private ITelemetryService TelemetryService => AppService?.TelemetryService; #endregion public BluetoothSettingsVM() : base() { BluetoothToggleIsOn = false; } public void SetUpVM() { // Handle inbound pairing requests App.InboundPairingRequested += App_InboundPairingRequestedAsync; if (BluetoothWatcherEnabled) { if (_deviceWatcher == null || (_deviceWatcher.Status == DeviceWatcherStatus.Stopped)) { StartWatcherAsync(); } } } public void TearDownVM() { App.InboundPairingRequested -= App_InboundPairingRequestedAsync; if (_deviceWatcher != null && _deviceWatcher.Status != DeviceWatcherStatus.Stopped) { StopWatcher(); } } public void SetUpBluetooth() { _inProgressPairButton = new Button(); _savedPairButtonFlyout = _inProgressPairButton.Flyout; RegisterForInboundPairingRequests(); } /// <summary> /// Make this device discoverable to other Bluetooth devices within range /// </summary> /// <returns></returns> private async Task<bool> MakeDiscoverable() { // Make the system discoverable. Don't repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists." if (!_isBluetoothDiscoverable) { try { Guid BluetoothServiceUuid = new Guid(Constants.BluetoothServiceUuid); _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid)); StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.PlainSocket); // No need to set SPD attributes _provider.StartAdvertising(listener, true); _isBluetoothDiscoverable = true; } catch (Exception ex) { string confirmationMessage = string.Format(BluetoothNoDeviceAvailableFormat, ex.Message); await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); } } return _isBluetoothDiscoverable; } /// <summary> /// Register the device for inbound pairing requests /// </summary> private async void RegisterForInboundPairingRequests() { // Make the system discoverable for Bluetooth. await MakeDiscoverable(); string confirmationMessage = string.Empty; // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present, // so leave the diagnostic message put up by the call to MakeDiscoverable(). if (_isBluetoothDiscoverable) { // Get state of ceremony checkboxes DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); int iCurrentSelectedCeremonies = (int)ceremoniesSelected; int iSavedSelectedCeremonies = -1; // Deliberate impossible value // Find out if we changed the ceremonies we originally registered with. // If we have registered before, these will be saved. object supportedPairingKinds = LocalSettings.Values["supportedPairingKinds"]; if (supportedPairingKinds != null) { iSavedSelectedCeremonies = (int)supportedPairingKinds; } if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected)) { confirmationMessage = string.Format(BluetoothInboundRegistrationFailed, ceremoniesSelected.ToString()); } else { // Save off the ceremonies we registered with LocalSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies; confirmationMessage = string.Format(BluetoothInboundRegistrationSucceededFormat, ceremoniesSelected.ToString()); } BluetoothWatcherEnabled = true; } else { BluetoothWatcherEnabled = false; } await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); } /// <summary> /// Called when an inbound Bluetooth connection is requested /// </summary> /// <param name="sender"></param> /// <param name="inboundArgs"></param> private async void App_InboundPairingRequestedAsync(object sender, InboundPairingEventArgs inboundArgs) { LogService.Write("Bluetooth inbound pairing requested", LoggingLevel.Information); BluetoothServerHelper.Instance.Disconnect(); // Ignore the inbound if pairing is already in progress if (_inProgressPairButton == null && !_isPairing) { try { _isPairing = true; // Restore the ceremonies we registered with LogService.Write("Restoring supported ceremonies...", LoggingLevel.Information); Object supportedPairingKinds = LocalSettings.Values["supportedPairingKinds"]; int iSelectedCeremonies = (int)DevicePairingKinds.ConfirmOnly; if (supportedPairingKinds != null) { iSelectedCeremonies = (int)supportedPairingKinds; } // Clear any previous devices LogService.Write("Refreshing Bluetooth devices...", LoggingLevel.Information); BluetoothDeviceCollection.Clear(); // Add the latest information to display BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(inboundArgs.DeviceInfo); BluetoothDeviceCollection.Add(currentDevice); // Display a message about the inbound request string confirmationMessage = string.Format(BluetoothAttemptingToPairFormat, currentDevice.Name, currentDevice.Id); // Get the ceremony type and protection level selections DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); // Get the protection level DevicePairingProtectionLevel protectionLevel = currentDevice.DeviceInformation.Pairing.ProtectionLevel; // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication DeviceInformationCustomPairing customPairing = currentDevice.DeviceInformation.Pairing.Custom; customPairing.PairingRequested += PairingRequestedHandlerAsync; DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel); if (result.Status == DevicePairingResultStatus.Paired) { confirmationMessage = string.Format(BluetoothPairingSuccessFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } else { confirmationMessage = string.Format(BluetoothPairingFailureFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } // Display the result of the pairing attempt await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); } catch (Exception ex) { LogService.Write(ex.ToString(), LoggingLevel.Error); } _isPairing = false; } else { LogService.Write("Pairing already in progress", LoggingLevel.Information); } } /// <summary> /// Clear listed devices, start a Bluetooth watcher, and display a notification message /// </summary> public async void StartWatcherWithConfirmationAsync() { BluetoothDeviceCollection.Clear(); StartWatcherAsync(); await DisplayMessagePanel(BluetoothStartedWatching, MessageType.InformationalMessage); } /// <summary> /// Clear listed devices, stop a Bluetooth watcher, and display a notification message /// </summary> public async void StopWatcherWithConfirmationAsync() { BluetoothDeviceCollection.Clear(); StopWatcher(); await DisplayMessagePanel(BluetoothStoppedWatching, MessageType.InformationalMessage); } /// <summary> /// Method to start the Bluetooth watcher /// </summary> /// <returns></returns> private async void StartWatcherAsync() { await Task.Run(() => { // Bluetooth + BluetoothLE string aqsFilter = "System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\" OR " + "System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\""; // Request the IsPaired property so we can display the paired status in the UI string[] requestedProperties = { "System.Devices.Aep.IsPaired" }; // Get the device selector chosen by the UI, then 'AND' it with the 'CanPair' property _deviceWatcher = DeviceInformation.CreateWatcher( aqsFilter, requestedProperties, DeviceInformationKind.AssociationEndpoint); // Hook up handlers for the watcher events before starting the watcher. // An EnumerationCompleted and Stopped handler are not shown here, but also available to use. _handlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>((watcher, currentDevice) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { if (currentDevice.Pairing.CanPair || currentDevice.Pairing.IsPaired) { BluetoothDeviceCollection.Add(new BluetoothDeviceInfo(currentDevice)); } }); }); _deviceWatcher.Added += _handlerAdded; _handlerUpdated = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { // Find the corresponding updated DeviceInformation in the collection and pass the update object // to the Update method of the existing DeviceInformation. This automatically updates the object // for us. foreach (BluetoothDeviceInfo currentDevice in BluetoothDeviceCollection) { if (currentDevice.Id == deviceInfoUpdate.Id) { currentDevice.Update(deviceInfoUpdate); break; } } }); }); _deviceWatcher.Updated += _handlerUpdated; _handlerRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { // Find the corresponding DeviceInformation in the collection and remove it foreach (BluetoothDeviceInfo currentDevice in BluetoothDeviceCollection) { if (currentDevice.Id == deviceInfoUpdate.Id) { BluetoothDeviceCollection.Remove(currentDevice); break; } } }); }); _deviceWatcher.Removed += _handlerRemoved; // Start the Device Watcher _deviceWatcher.Start(); }); } /// <summary> /// Method to stop the Bluetooth watcher /// </summary> private void StopWatcher() { if (null != _deviceWatcher) { // First unhook all event handlers except the stopped handler. This ensures our // event handlers don't get called after stop, as stop won't block for any "in flight" // event handler calls. We leave the stopped handler as it's guaranteed to only be called // once and we'll use it to know when the query is completely stopped. _deviceWatcher.Added -= _handlerAdded; _deviceWatcher.Updated -= _handlerUpdated; _deviceWatcher.Removed -= _handlerRemoved; if (_deviceWatcher.Status != DeviceWatcherStatus.Stopped) { _deviceWatcher.Stop(); } } } /// <summary> /// Accept the current pairing after confirming the user entered the correct device PIN /// </summary> /// <param name="inputPIN"></param> public void AcceptPairingUsingInputPIN(string inputPIN) { // If the PIN the user enters does not match the device PIN, return if (inputPIN != _pairingRequestedArgs.Pin) { ConfirmationMessageText = BluetoothIncorrectEnteredPIN; return; } // Close the flyout _inProgressPairButton.Flyout.Hide(); _inProgressPairButton.Flyout = null; // Use the PIN to accept the pairing AcceptPairingWithPIN(inputPIN); } /// <summary> /// Accept the current pairing using the PIN parameter and complete the deferral /// </summary> /// <param name="PIN"></param> private void AcceptPairingWithPIN(string PIN) { if (_pairingRequestedArgs != null) { _pairingRequestedArgs.Accept(PIN); _pairingRequestedArgs = null; } CompleteDeferral(); } /// <summary> /// Called when a custom pairing is initiated so that we can handle its custom ceremony /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public async void PairingRequestedHandlerAsync(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args) { LogService.Write((Enum.GetName(typeof(DevicePairingKinds), args.PairingKind)), LoggingLevel.Information); BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(args.DeviceInformation); // Save the args for use in ProvidePin case _pairingRequestedArgs = args; // Save the deferral away and complete it where necessary. if (args.PairingKind != DevicePairingKinds.DisplayPin) { _deferral = args.GetDeferral(); } switch (args.PairingKind) { // Windows itself will pop the confirmation dialog as part of "consent" depending on which operating OS is running case DevicePairingKinds.ConfirmOnly: { var confirmationMessage = string.Format(BluetoothConfirmOnlyText, args.DeviceInformation.Name, args.DeviceInformation.Id); if (await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage)) { AcceptPairing(); } } break; // We only show the PIN on this side. The ceremony is actually completed when the user enters the PIN on the target device. case DevicePairingKinds.DisplayPin: { var confirmationMessage = string.Format(BluetoothDisplayPINText, args.Pin); await DisplayMessagePanel(confirmationMessage, MessageType.OKMessage); } break; // A PIN may be shown on the target device and the user needs to enter the matching PIN on the originating device. case DevicePairingKinds.ProvidePin: { _inProgressPairButton.Flyout = _savedPairButtonFlyout; _inProgressPairButton.Flyout.ShowAt(_inProgressPairButton); } break; // We show the PIN here and the user responds with whether the PIN matches what is displayed on the target device. case DevicePairingKinds.ConfirmPinMatch: { var confirmationMessage = string.Format(BluetoothConfirmPINMatchText, args.Pin); if (await DisplayMessagePanel(confirmationMessage, MessageType.YesNoMessage)) { AcceptPairing(); } } break; } } /// <summary> /// Accept the pairing and complete the deferral /// </summary> public void AcceptPairing() { LogService.Write("Bluetooth Pairing Accepted", LoggingLevel.Information); TelemetryService.WriteEvent("BluetoothDevicePaired"); if (_pairingRequestedArgs != null) { _pairingRequestedArgs.Accept(); _pairingRequestedArgs = null; } CompleteDeferral(); } /// <summary> /// Complete the deferral /// </summary> public void CompleteDeferral() { _deferral?.Complete(); _deferral = null; } /// <summary> /// Called to pair a targeted device /// </summary> /// <param name="pairButton">Pair button</param> /// <param name="currentDevice">Displayable information for the targeted device</param> public async Task PairingRequestedAsync(Button pairButton, BluetoothDeviceInfo currentDevice) { try { _deviceInfo = currentDevice; _inProgressPairButton = pairButton; // Display confirmation message panel string deviceIdentifier = _deviceInfo.Name != BluetoothDeviceNameUnknownText ? _deviceInfo.Name : _deviceInfo.IdWithoutProtocolPrefix; string confirmationMessage = string.Format(BluetoothAttemptingToPairFormat, _deviceInfo.Name, _deviceInfo.IdWithoutProtocolPrefix); await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); // Save the flyout and set to null so it doesn't appear without explicitly being called _savedPairButtonFlyout = pairButton.Flyout; _inProgressPairButton.Flyout = null; pairButton.IsEnabled = false; // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default; // Setup a custom pairing and handler, then get the results of the request DeviceInformationCustomPairing customPairing = _deviceInfo.DeviceInformation.Pairing.Custom; customPairing.PairingRequested += PairingRequestedHandlerAsync; DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel); if (result.Status == DevicePairingResultStatus.Paired) { confirmationMessage = string.Format(BluetoothPairingSuccessFormat, deviceIdentifier, result.Status.ToString()); } else { confirmationMessage = string.Format(BluetoothPairingFailureFormat, deviceIdentifier, result.Status.ToString()); } // Display the result of the pairing attempt await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure their current state is reflected if (BluetoothWatcherEnabled) { BluetoothDeviceCollection.Clear(); StopWatcher(); StartWatcherAsync(); } else { // If the watcher is off, this is an inbound request so we only need to clear the list BluetoothDeviceCollection.Clear(); } _inProgressPairButton = null; pairButton.IsEnabled = true; } catch (Exception ex) { LogService.Write(ex.ToString(), LoggingLevel.Error); } } /// <summary> /// Called to unpair a targeted device /// </summary> /// <param name="unpairButton">Unpair button</param> /// <param name="currentDevice">Displayable information for the targeted device</param> public async Task UnpairDeviceAsync(Button unpairButton, BluetoothDeviceInfo currentDevice) { try { string confirmationMessage = string.Empty; // Disable the unpair button until we are done unpairButton.IsEnabled = false; DeviceUnpairingResult unpairingResult = await currentDevice.DeviceInformation.Pairing.UnpairAsync(); if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired) { // Device is unpaired confirmationMessage = string.Format(BluetoothUnpairingSuccessFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } else { confirmationMessage = string.Format(BluetoothUnpairingFailureFormat, unpairingResult.Status.ToString(), currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } // Display the result of the unpairing attempt await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure state is reflected in list if (BluetoothWatcherEnabled) { BluetoothDeviceCollection.Clear(); StopWatcher(); StartWatcherAsync(); } else { // If the watcher is off this is an inbound request so just clear the list BluetoothDeviceCollection.Clear(); } // Enable the unpair button unpairButton.IsEnabled = true; } catch (Exception ex) { LogService.Write(ex.ToString(), LoggingLevel.Error); } } /// <summary> /// Get the set of acceptable ceremonies from the check boxes /// </summary> /// <returns>Types of I/O Bluetooth connections supported by the device</returns> private DevicePairingKinds GetSelectedCeremonies() { DevicePairingKinds ceremonySelection = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch; return ceremonySelection; } /// <summary> /// Used to display different types of notification dialogs based on the message /// </summary> /// <param name="confirmationMessage">The message to display as a string</param> /// <param name="messageType">MessageType of the message</param> private async Task<bool> DisplayMessagePanel(string confirmationMessage, MessageType messageType) { ConfirmationMessageText = confirmationMessage; switch (messageType) { // For notification messages that don't require user interaction case MessageType.InformationalMessage: return true; // For confirmation messages that only require user acknowledgement case MessageType.OKMessage: return await AppService.YesNoAsync(BluetoothPreferencesText, confirmationMessage, OkButtonText); // For confirmation messages that prompt the user to make a yes or no selection case MessageType.YesNoMessage: return await AppService.YesNoAsync(BluetoothPreferencesText, confirmationMessage, YesButtonText, NoButtonText); default: return false; } } /// <summary> /// We have to have a callback handler to handle "ConnectionReceived" but we don't do anything because /// the StartAdvertising is just a way to turn on Bluetooth discoverability /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { return; } } }
45.257302
158
0.590934
[ "MIT" ]
ATM006/Windows-iotcore-samples
Samples/IoTCoreDefaultApp/CS/SmartDisplay/Views/Settings/BluetoothSettingsVM.cs
32,542
C#
using System; using System.Collections.Generic; using Timesheet.Domain.Common; namespace Timesheet.Domain.Entities { public class Task : Entity { public int Id { get; set; } public string Code { get; set; } public string Name { get; set; } public Status CurrentStatus { get; set; } public DateTime Created { get; set; } public DateTime Updated { get; set; } public float HoursEstimated { get; set; } public float HoursRemaining { get; set; } public int ProjectId { get; set; } public virtual Project Project { get; set; } public int EmployeeCreatorId { get; set; } public virtual Employee EmployeeCreator { get; set; } public virtual ICollection<TimeLog> TimeLogs { get; set; } public Task() { Created = DateTime.UtcNow; Updated = Created; } public enum Status { New = 0, InProgress = 1, Paused = 2, Cancelled = 3, Completed = 4 } } }
26.928571
67
0.535809
[ "MIT" ]
aert/Timesheet
Timesheet.Domain/Entities/Task.cs
1,133
C#
using System; using System.Linq.Expressions; using ConsoleToolkit.Exceptions; using ConsoleToolkit.Utilities; namespace ConsoleToolkit.CommandLineInterpretation { internal static class SetterBuilder { public static object Build(Type target, Expression body) { if (!(body is MemberExpression inputMemberExpression)) throw new MemberReferenceExpected(); var staticMember = inputMemberExpression.Member.IsStatic(); var commandTypeInstance = Expression.Parameter(target); var convertedParameterValue = Expression.Parameter(inputMemberExpression.Type); var parent = staticMember ? null : commandTypeInstance; var memberAccess = Expression.MakeMemberAccess(parent, inputMemberExpression.Member); var expression = Expression.Assign(memberAccess, convertedParameterValue); Type delegateType; ParameterExpression[] parameters; if (staticMember) { delegateType = typeof(Action<>).MakeGenericType(convertedParameterValue.Type); parameters = new[] { convertedParameterValue }; } else { delegateType = typeof(Action<,>).MakeGenericType(commandTypeInstance.Type, convertedParameterValue.Type); parameters = new []{commandTypeInstance, convertedParameterValue}; } var lambdaExpression = Expression.Lambda(delegateType, expression, parameters); return lambdaExpression.Compile(); } } }
40.825
122
0.643601
[ "MIT" ]
jamie-davis/ConsoleTools
ConsoleToolkit/CommandLineInterpretation/SetterBuilder.cs
1,633
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was automatically generated. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FoxKit.Modules.DataSet.Fox.TppGameKit { using System; using System.Collections.Generic; using FoxKit.Modules.DataSet.Fox.FoxCore; using FoxKit.Modules.Lua; using FoxLib; using static KopiLua.Lua; using OdinSerializer; using UnityEngine; using DataSetFile2 = DataSetFile2; using TppGameKit = FoxKit.Modules.DataSet.Fox.TppGameKit; [SerializableAttribute, ExposeClassToLuaAttribute] public partial class TppTrapCheckIsPlayerAndLocalCallbackDataElement : GeoTrapModuleCallbackDataElement { public override short ClassId => 0; public override ushort Version => 0; public override string Category => ""; } }
33.46875
107
0.601307
[ "MIT" ]
Joey35233/FoxKit
FoxKit/Assets/FoxKit/Modules/DataSet/Fox/TppGameKit/TppTrapCheckIsPlayerAndLocalCallbackDataElement.Generated.cs
1,071
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Console : MonoBehaviour { private Text ConsoleObject; //Reference to the main console object // Start is called before the first frame update void Awake() { ConsoleObject = GetComponentInChildren<Text>(); } // Update is called once per frame void Update() { } /* Allows external scripts to access console and dipslay a message Main functionality is to test gameplay, and to be adopted to print to specific UI elements */ public void PrintToConsole(string message) { if(ConsoleObject != null) { ConsoleObject.text = message; } } /* Update Log manages the updating of the text box which displays all console logs. A user has requested this function is not based on a timer but on user interaction. Potentially the logs can also be stored in a seperate variable. */ }
21.893617
94
0.677357
[ "CC0-1.0" ]
Espresshock/RoC
Assets/Scripts/Console.cs
1,029
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace P._01._2015._05.V2_Calculation_Problem_2 { class Program { static void Main(string[] args) { //1. read input //2. convert every number to decimal value ---> mia to 6532 //3. sum all the numbers (sum in decimal) ----> (sum) //4. convert the sum to meow numeral system //5. print the result //var catNumbers = Console.ReadLine().Split(); //with symbols (chars) //Console.WriteLine(string.Join("\r\n", catNumbers)); //to check if it reads properly //Console.WriteLine(MeowToDec(catNumbers[0])); //var catNumbers = Console.ReadLine().Split(' ').Select(MeowToDec).ToArray(); //selects all chars and converts them to int decimal //Console.WriteLine(catNumbers[0]); var sum = Console.ReadLine().Split(' ').Select(MeowToDec).Sum(); //selects all chars and converts them to int decimal and then sums(concatenates) them all Console.WriteLine(sum); var anwser = DecimalToMeow(sum) + " = " + sum; Console.WriteLine(anwser); } static int MeowToDec(string meow) //получаваме от mea ----> 6532 (concatenated decimal digits) { int result = 0; foreach (char digit in meow) { result = (digit - 'a') + result * 23; //a is 97 in ACII (от десетична 97 към символче 'а') ( като ги сумираме) } return result; } static string DecimalToMeow(int decValue) //sums the input numbers in meow lenguage (mia ----> mia) (grrrr miao miao ---> htksw) { // better performance could be achieved by using indexing instead of concatanation string result = string.Empty; do { char digit = (char)('a' + (decValue % 23)); //от символче до десетична result = digit + result;//получаваме цифрите в обратен ред (by concatenation) decValue /= 23; } while (decValue > 0); return result; } } }
38.101695
167
0.568505
[ "MIT" ]
jsdelivrbot/Telerik_Academy
CSharp/CSharp Part 2/Exam-Preparation/P.01.2015.05.V2-Calculation-Problem-2/Program.cs
2,348
C#
namespace SourceControlSystem.Api.Tests.ControllerTests { using Microsoft.VisualStudio.TestTools.UnitTesting; using Controllers; using MyWebApi; using Models.Projects; using System.Web.Http.Cors; using System.Collections.Generic; using System; [TestClass] public class ProjectsControllerTests { [TestMethod] public void GetShouldHaveCorsEnabled() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Get()) .ShouldHave() .ActionAttributes(attr => attr.ContainingAttributeOfType<EnableCorsAttribute>()); } [TestMethod] public void GetShouldReturnOkWithProperResponse() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Get()) .ShouldReturn() .Ok() .WithResponseModelOfType<List<SoftwareProjectDetailsResponseModel>>() .Passing(pr => pr.Count == 1); } [TestMethod] public void GetShouldHaveAuthorizedAttribute() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Get(string.Empty)) .ShouldHave() .ActionAttributes(attr => attr.RestrictingForAuthorizedRequests()); } [TestMethod] public void GetShouldReturnNotFoundWhenProjectIsNull() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .WithAuthenticatedUser() .Calling(c => c.Get("Invalid")) .ShouldReturn() .NotFound(); } [TestMethod] public void GetShouldReturnOkWhenProjectIsNotNull() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .WithAuthenticatedUser() .Calling(c => c.Get("Valid")) .ShouldReturn() .Ok() .WithResponseModelOfType<SoftwareProjectDetailsResponseModel>() .Passing(pr => { Assert.AreEqual(new DateTime(2015, 11, 5, 23, 47, 12), pr.CreatedOn); Assert.AreEqual("Test", pr.Name); Assert.AreEqual(0, pr.TotalUsers); }); } [TestMethod] public void GetByIdShouldReturnBadRequestWithNullId() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Get(null)) .ShouldReturn() .BadRequest() .WithErrorMessage("Project name cannot be null or empty."); } [TestMethod] public void PostShouldValidateModelState() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Post(TestObjectFactory.GetInvalidModel())) .ShouldHave() .InvalidModelState(); } [TestMethod] public void PostShouldReturnBadRequestWithInvalidModel() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Post(TestObjectFactory.GetInvalidModel())) .ShouldReturn() .BadRequest() .WithModelStateFor<SaveProjectRequestModel>() .ContainingModelStateErrorFor(m => m.Name); } [TestMethod] public void AllShouldReturnOk() { MyWebApi .Controller<ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .Calling(c => c.Get(1, 10)) .ShouldReturn() .Ok() .WithResponseModelOfType<List<SoftwareProjectDetailsResponseModel>>() .Passing(pr => pr.Count == 1); } } }
35.6
97
0.55229
[ "MIT" ]
EmilMitev/Telerik-Academy
Web Services and Cloud/Slides and demos/03. ASP.NET-Web-API-Architecture/LiveDemo-2015-SourceControlSystem/Tests/SourceControlSystem.Api.Tests/ControllerTests/ProjectsControllerTests.cs
4,630
C#
using System; namespace CheatSheetConsoleApp { class Ex17_1_Exception { internal static void Run() { try { ThrowException(); } catch (Ex17_1_Exception_MyException ex) when (ex.Value >= 1) { Console.WriteLine("Catch MyException"); } catch (Exception ex) { Console.WriteLine("Catch Exception: " + ex.Message); throw; // 再スロー } } static void ThrowException() { throw new Ex17_1_Exception_MyException() {Value = 1}; } } public class Ex17_1_Exception_MyException : Exception { public int Value { get; set; } } //C# 7.0より例外を式としてスローできるようになった箇所 public class Ex17_1_Exception_MyClass { public string Name { get; } //ラムダ式や式形式メンバの=>の後 public Ex17_1_Exception_MyClass() => throw new Exception(); //null合算演算子の第2オペランド public Ex17_1_Exception_MyClass(string name) => Name = name ?? throw new Exception(); //三項演算子の第2,第3オペランド public Ex17_1_Exception_MyClass(int i) => Name = i > 0 ? GetNameById(i) : throw new Exception(); private string GetNameById(int i) => $"name-{i}"; } }
23.895833
100
0.624237
[ "MIT" ]
tanaka-takayoshi/CSharpCheatSheet
CheatSheetConsoleApp/Ex17_1_Exception.cs
1,279
C#
using System; using Newtonsoft.Json; using Basket.API.Entities; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; namespace Basket.API.Repositories { public class BasketRepository : IBasketRepository { private readonly IDistributedCache _redisCache; public BasketRepository(IDistributedCache redisCache) { _redisCache = redisCache ?? throw new ArgumentNullException(nameof(redisCache)); } public async Task<ShoppingCart> GetBasket(string userName) { var basket = await _redisCache.GetStringAsync(userName); if (String.IsNullOrEmpty(basket)) return null; return JsonConvert.DeserializeObject<ShoppingCart>(basket); } public async Task<ShoppingCart> UpdateBasket(ShoppingCart basket) { await _redisCache.SetStringAsync(basket.UserName, JsonConvert.SerializeObject(basket)); return await GetBasket(basket.UserName); } public async Task DeleteBasket(string userName) { await _redisCache.RemoveAsync(userName); } } }
25.780488
93
0.737938
[ "MIT" ]
FernandoDevBh/MicroServicesAspnet
src/Services/Basket/Basket.API/Repositories/BasketRepository.cs
1,059
C#
using Microsoft.AspNetCore.Identity; namespace HeroClub.Domain { public class UserRole : IdentityUserRole<int> { public User User { get; set; } public Role Role { get; set; } } }
20.7
49
0.642512
[ "MIT" ]
vsandrade/HeroClub
HeroClub.Domain/UserRole.cs
207
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 cloudformation-2010-05-15.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.CloudFormation.Model { /// <summary> /// The output for the <a>CreateChangeSet</a> action. /// </summary> public partial class CreateChangeSetResponse : AmazonWebServiceResponse { private string _id; private string _stackId; /// <summary> /// Gets and sets the property Id. /// <para> /// The Amazon Resource Name (ARN) of the change set. /// </para> /// </summary> [AWSProperty(Min=1)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property StackId. /// <para> /// The unique ID of the stack. /// </para> /// </summary> public string StackId { get { return this._stackId; } set { this._stackId = value; } } // Check to see if StackId property is set internal bool IsSetStackId() { return this._stackId != null; } } }
27.402597
112
0.600948
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudFormation/Generated/Model/CreateChangeSetResponse.cs
2,110
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from d3dx12.h in the microsoft/DirectX-Graphics-Samples tag v10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. Licensed under the MIT License (MIT). using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="D3DX12_MESH_SHADER_PIPELINE_STATE_DESC" /> struct.</summary> public static unsafe class D3DX12_MESH_SHADER_PIPELINE_STATE_DESCTests { /// <summary>Validates that the <see cref="D3DX12_MESH_SHADER_PIPELINE_STATE_DESC" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<D3DX12_MESH_SHADER_PIPELINE_STATE_DESC>(), Is.EqualTo(sizeof(D3DX12_MESH_SHADER_PIPELINE_STATE_DESC))); } /// <summary>Validates that the <see cref="D3DX12_MESH_SHADER_PIPELINE_STATE_DESC" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(D3DX12_MESH_SHADER_PIPELINE_STATE_DESC).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="D3DX12_MESH_SHADER_PIPELINE_STATE_DESC" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(D3DX12_MESH_SHADER_PIPELINE_STATE_DESC), Is.EqualTo(568)); } else { Assert.That(sizeof(D3DX12_MESH_SHADER_PIPELINE_STATE_DESC), Is.EqualTo(524)); } } } }
42.227273
151
0.684069
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/other/d3dx12/D3DX12_MESH_SHADER_PIPELINE_STATE_DESCTests.cs
1,860
C#
/* Copyright (c) 2006 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 Google.GData.Extensions; namespace Google.GData.ContentForShopping.Elements { public class CustomGroup : SimpleContainer { /// <summary> /// CustomAttribute collection /// </summary> private ExtensionCollection<CustomAttribute> customAttributes; /// <summary> /// default constructor for sc:group /// </summary> public CustomGroup() : base(ContentForShoppingNameTable.Group, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { } /// <summary> /// constructor for sc:group with name /// </summary> /// <param name="name">The group's name.</param> public CustomGroup(string name) : base(ContentForShoppingNameTable.Group, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { this.Name = name; } /// <summary> /// default constructor for sc:group with attributes /// </summary> /// <param name="customAttributes">The list of attributes for the group.</param> public CustomGroup(ExtensionCollection<CustomAttribute> customAttributes) : base(ContentForShoppingNameTable.Group, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { this.customAttributes = customAttributes; } /// <summary> /// constructor for sc:group with name and attributes /// </summary> /// <param name="name">The group's name.</param> /// <param name="customAttributes">The list of attributes for the group.</param> public CustomGroup(string name, ExtensionCollection<CustomAttribute> customAttributes) : base(ContentForShoppingNameTable.Group, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { this.Name = name; this.customAttributes = customAttributes; } /// <summary> /// Name property accessor /// </summary> public string Name { get { return Convert.ToString(Attributes[ContentForShoppingNameTable.Name]); } set { Attributes[ContentForShoppingNameTable.Name] = value; } } /// <summary> /// Attributes property accessor /// </summary> public ExtensionCollection<CustomAttribute> CustomAttributes { get { if (this.customAttributes == null) { this.customAttributes = new ExtensionCollection<CustomAttribute>(this); } return this.customAttributes; } } } }
35.77451
95
0.590299
[ "Apache-2.0" ]
michael-jia-sage/libgoogle
src/contentforshopping/elements/customgroup.cs
3,651
C#
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System.Collections; using System.Collections.Generic; namespace Newtonsoft.Json.Bson { internal abstract class BsonToken { public abstract BsonType Type { get; } public BsonToken Parent { get; set; } public int CalculatedSize { get; set; } } internal class BsonObject : BsonToken, IEnumerable<BsonProperty> { private readonly List<BsonProperty> _children = new List<BsonProperty>(); public void Add(string name, BsonToken token) { _children.Add(new BsonProperty { Name = new BsonString(name, false), Value = token }); token.Parent = this; } public override BsonType Type { get { return BsonType.Object; } } public IEnumerator<BsonProperty> GetEnumerator() { return _children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class BsonArray : BsonToken, IEnumerable<BsonToken> { private readonly List<BsonToken> _children = new List<BsonToken>(); public void Add(BsonToken token) { _children.Add(token); token.Parent = this; } public override BsonType Type { get { return BsonType.Array; } } public IEnumerator<BsonToken> GetEnumerator() { return _children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class BsonValue : BsonToken { private readonly object _value; private readonly BsonType _type; public BsonValue(object value, BsonType type) { _value = value; _type = type; } public object Value { get { return _value; } } public override BsonType Type { get { return _type; } } } internal class BsonString : BsonValue { public int ByteCount { get; set; } public bool IncludeLength { get; set; } public BsonString(object value, bool includeLength) : base(value, BsonType.String) { IncludeLength = includeLength; } } internal class BsonBinary : BsonValue { public BsonBinaryType BinaryType { get; set; } public BsonBinary(byte[] value, BsonBinaryType binaryType) : base(value, BsonType.Binary) { BinaryType = binaryType; } } internal class BsonRegex : BsonToken { public BsonString Pattern { get; set; } public BsonString Options { get; set; } public BsonRegex(string pattern, string options) { Pattern = new BsonString(pattern, false); Options = new BsonString(options, false); } public override BsonType Type { get { return BsonType.Regex; } } } internal class BsonProperty { public BsonString Name { get; set; } public BsonToken Value { get; set; } } } #endif
26.27044
93
0.6531
[ "Unlicense" ]
madparker/LumarcaUnity
LumarcaUnity2/Assets/Scripts/JsonDotNet/Source/WinRT/Bson/RT_BsonToken.cs
4,177
C#
namespace GetRichOrDieTrying.Data.Migrations { using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), EmailConfirmed = table.Column<bool>(nullable: false), Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "Questions", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Text = table.Column<string>(maxLength: 100, nullable: false), QuestionDifficuly = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Questions", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Games", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: true), FinalSum = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Games", x => x.Id); table.ForeignKey( name: "FK_Games_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Answers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Text = table.Column<string>(maxLength: 100, nullable: false), QuestionId = table.Column<int>(nullable: false), IsCorrectAnswer = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Answers", x => x.Id); table.ForeignKey( name: "FK_Answers_Questions_QuestionId", column: x => x.QuestionId, principalTable: "Questions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "QuestionGames", columns: table => new { QuestionId = table.Column<int>(nullable: false), GameId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_QuestionGames", x => new { x.QuestionId, x.GameId }); table.ForeignKey( name: "FK_QuestionGames_Games_GameId", column: x => x.GameId, principalTable: "Games", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_QuestionGames_Questions_QuestionId", column: x => x.QuestionId, principalTable: "Questions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Answers_QuestionId", table: "Answers", column: "QuestionId"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_Games_UserId", table: "Games", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_QuestionGames_GameId", table: "QuestionGames", column: "GameId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Answers"); migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "QuestionGames"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "Games"); migrationBuilder.DropTable( name: "Questions"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
42.529052
122
0.486158
[ "MIT" ]
l3kov9/Who-wants-to-be-a-millionaire-
GetRichOrDieTrying/GetRichOrDieTrying.Data/Migrations/20180609093012_InitialCreate.cs
13,909
C#
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; namespace TiltBrush { public class FreePaintTool : BaseTool { [SerializeField] private float m_AdjustSizeScalar; [SerializeField] private float m_HapticInterval = .1f; [SerializeField] private float m_HapticSizeUp; [SerializeField] private float m_HapticSizeDown; private bool m_PaintingActive; override public void Init() { base.Init(); m_PaintingActive = false; } public override bool ShouldShowPointer() { return !PanelManager.m_Instance.IntroSketchbookMode; } override public void EnableTool(bool bEnable) { base.EnableTool(bEnable); if (!bEnable) { PointerManager.m_Instance.EnableLine(false); WidgetManager.m_Instance.ResetActiveStencil(); } m_PaintingActive = false; } override public bool ShouldShowTouch() { return false; } static Quaternion sm_OrientationAdjust = Quaternion.Euler(new Vector3(0, 180, 0)); override public void UpdateTool() { // Don't call base.UpdateTool() because we have a different 'stop eating input' check // for FreePaintTool. float brushTriggerRatio = InputManager.Brush.GetTriggerRatio(); if (m_EatInput) { if (brushTriggerRatio <= 0.0f) { m_EatInput = false; } } if (m_ExitOnAbortCommand && InputManager.m_Instance.GetCommandDown(InputManager.SketchCommands.Abort)) { m_RequestExit = true; } PositionPointer(); m_PaintingActive = !m_EatInput && !m_ToolHidden && brushTriggerRatio > 0; PointerManager.m_Instance.EnableLine(m_PaintingActive); PointerManager.m_Instance.PointerPressure = InputManager.Brush.GetTriggerRatio(); } override public void LateUpdateTool() { // When the pointer manager is processing our line, don't stomp its position. if (!PointerManager.m_Instance.IsMainPointerProcessingLine()) { PositionPointer(); } } override public void AssignControllerMaterials(InputManager.ControllerName controller) { if (controller == InputManager.ControllerName.Brush) { if (App.Instance.IsInStateThatAllowsPainting()) { if (m_PaintingActive) { // TODO: Make snap work with non-line shapes. if (PointerManager.m_Instance.StraightEdgeModeEnabled && PointerManager.m_Instance.StraightEdgeGuideIsLine) { InputManager.Brush.Geometry.TogglePadSnapHint( PointerManager.m_Instance.StraightEdgeGuide.SnapEnabled, enabled: true); } } else { InputManager.Brush.Geometry.ShowBrushSizer(); } } } } void PositionPointer() { // Angle the pointer according to the user-defined pointer angle. Transform rAttachPoint = InputManager.m_Instance.GetBrushControllerAttachPoint(); Vector3 pos = rAttachPoint.position; Quaternion rot = rAttachPoint.rotation * sm_OrientationAdjust; // Modify pointer position and rotation with stencils. WidgetManager.m_Instance.MagnetizeToStencils(ref pos, ref rot); PointerManager.m_Instance.SetPointerTransform(InputManager.ControllerName.Brush, pos, rot); } override public void UpdateSize(float fAdjustAmount) { float fPrevRatio = GetSize01(); PointerManager.m_Instance.AdjustAllPointersBrushSize01(m_AdjustSizeScalar * fAdjustAmount); PointerManager.m_Instance.MarkAllBrushSizeUsed(); float fCurrentRatio = GetSize01(); float fHalfInterval = m_HapticInterval * 0.5f; int iPrevInterval = (int)((fPrevRatio + fHalfInterval) / m_HapticInterval); int iCurrentInterval = (int)((fCurrentRatio + fHalfInterval) / m_HapticInterval); if (!App.VrSdk.AnalogIsStick(InputManager.ControllerName.Brush)) { if (iCurrentInterval > iPrevInterval) { InputManager.m_Instance.TriggerHaptics( InputManager.ControllerName.Brush, m_HapticSizeUp); } else if (iCurrentInterval < iPrevInterval) { InputManager.m_Instance.TriggerHaptics( InputManager.ControllerName.Brush, m_HapticSizeDown); } } } override public float GetSize01() { return PointerManager.m_Instance.GetPointerBrushSize01(InputManager.ControllerName.Brush); } override public bool CanAdjustSize() { return App.Instance.IsInStateThatAllowsPainting(); } } } // namespace TiltBrush
36.475904
103
0.582164
[ "Apache-2.0" ]
Baflee/crypto-art-gallery-redo
Assets/Scripts/Tools/FreePaintTool.cs
6,057
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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; // Windows Runtime Component does not support extension methods and method overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP namespace UnitsNet.Extensions.NumberToElectricField { public static class NumberToElectricFieldExtensions { #region VoltPerMeter /// <inheritdoc cref="ElectricField.FromVoltsPerMeter(UnitsNet.QuantityValue)" /> public static ElectricField VoltsPerMeter<T>(this T value) => ElectricField.FromVoltsPerMeter(Convert.ToDouble(value)); #endregion } } #endif
46.280702
140
0.706596
[ "MIT" ]
Melina-Aero/MelinaAero-UnitsNet
UnitsNet/GeneratedCode/Extensions/Number/NumberToElectricFieldExtensions.g.cs
2,640
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; namespace DozensAPI { internal class JavaScriptSerializer : System.Web.Script.Serialization.JavaScriptSerializer { } }
19.846154
94
0.782946
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
jsakamoto/DozensApiClient-for-DotNet
Dozens/Internal/JavaScriptSerializer.cs
260
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.Vpc.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class EnableCcnRoutesResponse : 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.659091
116
0.66906
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Vpc/V20170312/Models/EnableCcnRoutesResponse.cs
1,393
C#
namespace EnvironmentAssessment.Common.VimApi { public class Description : DynamicData { protected string _label; protected string _summary; public string Label { get { return this._label; } set { this._label = value; } } public string Summary { get { return this._summary; } set { this._summary = value; } } } }
12.387097
45
0.606771
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/D/Description.cs
384
C#
using Epi.Web.Enter.Common.Message; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Epi.Web; using Epi.Web.Enter.Common.ObjectMapping; using Epi.Web.Enter.Common; using Epi.Web.Enter.Common.DTO; using Epi.Web.Enter.Common.Exception; using System.ServiceModel; using System.Configuration; namespace Epi.Web.WCF.SurveyService { public class EWEManagerServiceV2 : EWEManagerService , IEWEManagerServiceV2 { public bool ValidateOrganization(OrganizationRequest Request) { bool IsValid; try { Enter.Interfaces.DataInterfaces.ISurveyInfoDao ISurveyInfoDao = new EF.EntitySurveyInfoDao(); Epi.Web.BLL.SurveyInfo Implementation = new Epi.Web.BLL.SurveyInfo(ISurveyInfoDao); IsValid = Implementation.ValidateOrganization(Request); } catch (Exception ex) { throw ex; } return IsValid; } public SurveyInfoResponse GetAllSurveysByOrgKey(string OrgKey) { SurveyInfoResponse SurveyInfoResponse = new SurveyInfoResponse(); try { Enter.Interfaces.DataInterfaces.ISurveyInfoDao ISurveyInfoDao = new EF.EntitySurveyInfoDao(); Epi.Web.BLL.SurveyInfo Implementation = new Epi.Web.BLL.SurveyInfo(ISurveyInfoDao); SurveyInfoResponse.SurveyInfoList = Mapper.ToDataTransferObject(Implementation.GetAllSurveysByOrgKey(OrgKey)); } catch (Exception ex) { throw ex; } return SurveyInfoResponse; } // public string SetJsonColumn(List<string> SurveyIds, string OrgId) // { // return ""; // } // public string SetJsonColumnAll(string AdminKey) // { // string Key = EIWSConfig.AdminKey.ToString(); // if (AdminKey == Key) // { // } // return " Done"; // } // public UserResponse GetLoginToken(UserRequest UserInfo) // { // UserResponse UserResponse = new UserResponse(); // UserRequest UserRequest = new UserRequest(); // try // { // Enter.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // bool UserExist = Implementation.GetExistingUser(Mapper.ToUserBO(UserRequest.User)); // if (UserExist) // { // UserResponse.Message = ConfigurationManager.AppSettings[""]; // } // } // catch (Exception ex) // { // throw ex; // } // return UserResponse; // } // public bool UpdateUserInfo(UserRequest UserInfo) // { // Enter.Interfaces.DataInterfaces.IDaoFactory entityDaoFactory = new EF.EntityDaoFactory(); // Enter.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // var UserBO = Mapper.ToUserBO(UserInfo.User); // OrganizationBO OrgBO = new OrganizationBO(); // OrgBO = Mapper.ToBusinessObject(UserInfo.Organization); // return Implementation.UpdateUser(UserBO, OrgBO); // } // public bool DeleteUser(UserRequest UserInfo) // { // UserRequest UserRequest = new UserRequest(); // return true; // } // public UserResponse GetUserListByOrganization(UserRequest UserInfo) // { // UserResponse UserResponse = new UserResponse(); // UserRequest UserRequest = new UserRequest(); // Epi.Web.Enter.Interfaces.DataInterfaces.IOrganizationDao IOrganizationDao = new EF.EntityOrganizationDao(); // Epi.Web.BLL.Organization OrgImplementation = new Epi.Web.BLL.Organization(IOrganizationDao); // OrganizationBO OrganizationBO = OrgImplementation.GetOrganizationByKey(UserInfo.Organization.OrganizationKey); // Epi.Web.Enter.Interfaces.DataInterfaces.IDaoFactory entityDaoFactory = new EF.EntityDaoFactory(); // Epi.Web.Enter.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // UserResponse.User = Mapper.ToUserDTO(Implementation.GetUsersByOrgId(OrganizationBO.OrganizationId)); // return UserResponse; // } // public bool SetUserInfo(UserRequest UserInfo) // { // OrganizationRequest OrganizationRequest = new OrganizationRequest(); // OrganizationRequest.Organization.OrganizationKey = UserInfo.Organization.OrganizationKey; // bool IsSet = false; // try // { // Epi.Web.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // Epi.Web.Interfaces.DataInterfaces.IOrganizationDao IOrganizationDao = new EF.EntityOrganizationDao(); // Epi.Web.BLL.Organization OrgImplementation = new Epi.Web.BLL.Organization(IOrganizationDao); // OrganizationBO OrganizationBO = OrgImplementation.GetOrganizationByKey(UserInfo.Organization.OrganizationKey); // IsSet = Implementation.SetUserInfo(Mapper.ToUserBO(UserInfo.User), OrganizationBO); // } // catch (Exception ex) // { // throw ex; // } // return IsSet; // } // public bool GetExistingUser(UserRequest UserInfo) // { // UserRequest UserRequest = new UserRequest(); // bool UserExist = false; // try // { // Epi.Web.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // UserExist = Implementation.GetExistingUser(Mapper.ToUserBO(UserRequest.User)); // } // catch (Exception ex) // { // throw ex; // } // return UserExist; // } // public UserResponse GetUserByUserId(UserRequest UserInfo) // { // UserResponse UserResponse = new UserResponse(); // Epi.Web.Enter.Interfaces.DataInterfaces.IUserDao IUserDao = new EF.EntityUserDao(); // Epi.Web.BLL.User Implementation = new Epi.Web.BLL.User(IUserDao); // var CurrentUser = Implementation.GetUserByUserId(Mapper.ToUserBO(UserInfo.User), Mapper.ToBusinessObject(UserInfo.Organization)); // UserResponse.User = new List<UserDTO>(); // UserResponse.User.Add(Mapper.ToUserDTO(CurrentUser)); // return UserResponse; // } public string GetJsonResponseAll(string SurveyId, string OrganizationId, string PublisherKey) { return Enter.Common.Helper.SqlHelper.GetJsonResponseAll(SurveyId); } public PublishReportResponse PublishReport(PublishReportRequest Request) { try { PublishReportResponse result = new PublishReportResponse(); Epi.Web.Enter.Interfaces.DataInterfaces.IReportDao IReportDao = new EF.EntityReportDao(); Epi.Web.BLL.Report Implementation = new Epi.Web.BLL.Report(IReportDao); Epi.Web.Enter.Common.BusinessObject.ReportInfoBO ReportInfoBO = Mapper.ToReportInfoBO(Request.ReportInfo); Implementation.PublishReport(ReportInfoBO); result.Message = "The report was successfully published"; var ReportInfo = new ReportInfoDTO(); ReportInfo.ReportURL = ConfigurationManager.AppSettings["ReportURL"] + Request.ReportInfo.ReportId; result.Reports = new List<ReportInfoDTO>(); result.Reports.Add(ReportInfo); return result; } catch (Exception ex) { CustomFaultException customFaultException = new CustomFaultException(); customFaultException.CustomMessage = ex.Message; customFaultException.Source = ex.Source; customFaultException.StackTrace = ex.StackTrace; customFaultException.HelpLink = ex.HelpLink; throw new FaultException<CustomFaultException>(customFaultException); } } public PublishReportResponse DeleteReport(PublishReportRequest Request) { try { PublishReportResponse result = new PublishReportResponse(); Epi.Web.Enter.Interfaces.DataInterfaces.IReportDao IReportDao = new EF.EntityReportDao(); Epi.Web.BLL.Report Implementation = new Epi.Web.BLL.Report(IReportDao); Epi.Web.Enter.Common.BusinessObject.ReportInfoBO ReportInfoBO = Mapper.ToReportInfoBO(Request.ReportInfo); Implementation.DeleteReport(ReportInfoBO); result.Message = "The report was successfully Deleted"; return result; } catch (Exception ex) { CustomFaultException customFaultException = new CustomFaultException(); customFaultException.CustomMessage = ex.Message; customFaultException.Source = ex.Source; customFaultException.StackTrace = ex.StackTrace; customFaultException.HelpLink = ex.HelpLink; throw new FaultException<CustomFaultException>(customFaultException); } } } }
34.298361
147
0.58178
[ "Apache-2.0" ]
Epi-Info/Epi-Info-Cloud-Data-Capture
SurveyManagerInterface/EWEManagerServiceV2.cs
10,463
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using VRM; public class VRMFaceInitialize : MonoBehaviour { //[SerializeField] VRMFaceTracker VRMFace; public void FaceInitialize(GameObject root) { var anim = root.GetComponent<Animator>(); var proxy = root.GetComponent<VRMBlendShapeProxy>(); //VRMFace.head = anim.GetBoneTransform (HumanBodyBones.Head); //VRMFace.proxy = proxy; } }
26.777778
70
0.680498
[ "Apache-2.0" ]
MeBuDA/VRMSelfieApp
Assets/Scripts/VRMModel/VRMFaceInitialize.cs
484
C#
// This file contains auto-generated code. namespace System { namespace Linq { // Generated from `System.Linq.Enumerable` in `System.Linq, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public static class Enumerable { public static TResult Aggregate<TSource, TAccumulate, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, System.Func<TAccumulate, TSource, TAccumulate> func, System.Func<TAccumulate, TResult> resultSelector) => throw null; public static TAccumulate Aggregate<TSource, TAccumulate>(this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, System.Func<TAccumulate, TSource, TAccumulate> func) => throw null; public static TSource Aggregate<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TSource, TSource> func) => throw null; public static bool All<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static bool Any<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static bool Any<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Append<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, TSource element) => throw null; public static System.Collections.Generic.IEnumerable<TSource> AsEnumerable<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Decimal Average(this System.Collections.Generic.IEnumerable<System.Decimal> source) => throw null; public static System.Decimal? Average(this System.Collections.Generic.IEnumerable<System.Decimal?> source) => throw null; public static double Average(this System.Collections.Generic.IEnumerable<double> source) => throw null; public static double? Average(this System.Collections.Generic.IEnumerable<double?> source) => throw null; public static float Average(this System.Collections.Generic.IEnumerable<float> source) => throw null; public static float? Average(this System.Collections.Generic.IEnumerable<float?> source) => throw null; public static double Average(this System.Collections.Generic.IEnumerable<int> source) => throw null; public static double? Average(this System.Collections.Generic.IEnumerable<int?> source) => throw null; public static double Average(this System.Collections.Generic.IEnumerable<System.Int64> source) => throw null; public static double? Average(this System.Collections.Generic.IEnumerable<System.Int64?> source) => throw null; public static System.Decimal Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal> selector) => throw null; public static System.Decimal? Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal?> selector) => throw null; public static double Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double> selector) => throw null; public static double? Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double?> selector) => throw null; public static float Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float> selector) => throw null; public static float? Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float?> selector) => throw null; public static double Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int> selector) => throw null; public static double? Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int?> selector) => throw null; public static double Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64> selector) => throw null; public static double? Average<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64?> selector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Cast<TResult>(this System.Collections.IEnumerable source) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) => throw null; public static bool Contains<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, TSource value) => throw null; public static bool Contains<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, TSource value, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static int Count<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static int Count<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> DefaultIfEmpty<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Collections.Generic.IEnumerable<TSource> DefaultIfEmpty<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, TSource defaultValue) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static TSource ElementAt<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int index) => throw null; public static TSource ElementAtOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int index) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Empty<TResult>() => throw null; public static System.Collections.Generic.IEnumerable<TSource> Except<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Except<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static TSource First<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource First<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static TSource FirstOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource FirstOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector, System.Func<TKey, System.Collections.Generic.IEnumerable<TElement>, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector, System.Func<TKey, System.Collections.Generic.IEnumerable<TElement>, TResult> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector) => throw null; public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TKey, System.Collections.Generic.IEnumerable<TSource>, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TKey, System.Collections.Generic.IEnumerable<TSource>, TResult> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this System.Collections.Generic.IEnumerable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this System.Collections.Generic.IEnumerable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Intersect<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Intersect<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this System.Collections.Generic.IEnumerable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this System.Collections.Generic.IEnumerable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static TSource Last<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource Last<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static TSource LastOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource LastOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Int64 LongCount<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Int64 LongCount<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Decimal Max(this System.Collections.Generic.IEnumerable<System.Decimal> source) => throw null; public static System.Decimal? Max(this System.Collections.Generic.IEnumerable<System.Decimal?> source) => throw null; public static double Max(this System.Collections.Generic.IEnumerable<double> source) => throw null; public static double? Max(this System.Collections.Generic.IEnumerable<double?> source) => throw null; public static float Max(this System.Collections.Generic.IEnumerable<float> source) => throw null; public static float? Max(this System.Collections.Generic.IEnumerable<float?> source) => throw null; public static int Max(this System.Collections.Generic.IEnumerable<int> source) => throw null; public static int? Max(this System.Collections.Generic.IEnumerable<int?> source) => throw null; public static System.Int64 Max(this System.Collections.Generic.IEnumerable<System.Int64> source) => throw null; public static System.Int64? Max(this System.Collections.Generic.IEnumerable<System.Int64?> source) => throw null; public static TResult Max<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TResult> selector) => throw null; public static TSource Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Decimal Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal> selector) => throw null; public static System.Decimal? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal?> selector) => throw null; public static double Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double> selector) => throw null; public static double? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double?> selector) => throw null; public static float Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float> selector) => throw null; public static float? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float?> selector) => throw null; public static int Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int> selector) => throw null; public static int? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int?> selector) => throw null; public static System.Int64 Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64> selector) => throw null; public static System.Int64? Max<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64?> selector) => throw null; public static System.Decimal Min(this System.Collections.Generic.IEnumerable<System.Decimal> source) => throw null; public static System.Decimal? Min(this System.Collections.Generic.IEnumerable<System.Decimal?> source) => throw null; public static double Min(this System.Collections.Generic.IEnumerable<double> source) => throw null; public static double? Min(this System.Collections.Generic.IEnumerable<double?> source) => throw null; public static float Min(this System.Collections.Generic.IEnumerable<float> source) => throw null; public static float? Min(this System.Collections.Generic.IEnumerable<float?> source) => throw null; public static int Min(this System.Collections.Generic.IEnumerable<int> source) => throw null; public static int? Min(this System.Collections.Generic.IEnumerable<int?> source) => throw null; public static System.Int64 Min(this System.Collections.Generic.IEnumerable<System.Int64> source) => throw null; public static System.Int64? Min(this System.Collections.Generic.IEnumerable<System.Int64?> source) => throw null; public static TResult Min<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TResult> selector) => throw null; public static TSource Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Decimal Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal> selector) => throw null; public static System.Decimal? Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal?> selector) => throw null; public static double Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double> selector) => throw null; public static double? Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double?> selector) => throw null; public static float Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float> selector) => throw null; public static float? Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float?> selector) => throw null; public static int Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int> selector) => throw null; public static int? Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int?> selector) => throw null; public static System.Int64 Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64> selector) => throw null; public static System.Int64? Min<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64?> selector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult>(this System.Collections.IEnumerable source) => throw null; public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null; public static System.Linq.IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Linq.IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Prepend<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, TSource element) => throw null; public static System.Collections.Generic.IEnumerable<int> Range(int start, int count) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Repeat<TResult>(TResult element, int count) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Reverse<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Select<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TResult> selector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Select<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, TResult> selector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Collections.Generic.IEnumerable<TCollection>> collectionSelector, System.Func<TSource, TCollection, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, System.Collections.Generic.IEnumerable<TCollection>> collectionSelector, System.Func<TSource, TCollection, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Collections.Generic.IEnumerable<TResult>> selector) => throw null; public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource, TResult>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>> selector) => throw null; public static bool SequenceEqual<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) => throw null; public static bool SequenceEqual<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static TSource Single<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource Single<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static TSource SingleOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static TSource SingleOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Skip<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int count) => throw null; public static System.Collections.Generic.IEnumerable<TSource> SkipLast<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int count) => throw null; public static System.Collections.Generic.IEnumerable<TSource> SkipWhile<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> SkipWhile<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, bool> predicate) => throw null; public static System.Decimal Sum(this System.Collections.Generic.IEnumerable<System.Decimal> source) => throw null; public static System.Decimal? Sum(this System.Collections.Generic.IEnumerable<System.Decimal?> source) => throw null; public static double Sum(this System.Collections.Generic.IEnumerable<double> source) => throw null; public static double? Sum(this System.Collections.Generic.IEnumerable<double?> source) => throw null; public static float Sum(this System.Collections.Generic.IEnumerable<float> source) => throw null; public static float? Sum(this System.Collections.Generic.IEnumerable<float?> source) => throw null; public static int Sum(this System.Collections.Generic.IEnumerable<int> source) => throw null; public static int? Sum(this System.Collections.Generic.IEnumerable<int?> source) => throw null; public static System.Int64 Sum(this System.Collections.Generic.IEnumerable<System.Int64> source) => throw null; public static System.Int64? Sum(this System.Collections.Generic.IEnumerable<System.Int64?> source) => throw null; public static System.Decimal Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal> selector) => throw null; public static System.Decimal? Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Decimal?> selector) => throw null; public static double Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double> selector) => throw null; public static double? Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, double?> selector) => throw null; public static float Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float> selector) => throw null; public static float? Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, float?> selector) => throw null; public static int Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int> selector) => throw null; public static int? Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int?> selector) => throw null; public static System.Int64 Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64> selector) => throw null; public static System.Int64? Sum<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, System.Int64?> selector) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Take<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int count) => throw null; public static System.Collections.Generic.IEnumerable<TSource> TakeLast<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int count) => throw null; public static System.Collections.Generic.IEnumerable<TSource> TakeWhile<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> TakeWhile<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, bool> predicate) => throw null; public static System.Linq.IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this System.Linq.IOrderedEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Linq.IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this System.Linq.IOrderedEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null; public static System.Linq.IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this System.Linq.IOrderedEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Linq.IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this System.Linq.IOrderedEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null; public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Collections.Generic.Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector) => throw null; public static System.Collections.Generic.Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Collections.Generic.Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.HashSet<TSource> ToHashSet<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Collections.Generic.HashSet<TSource> ToHashSet<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static System.Collections.Generic.List<TSource> ToList<TSource>(this System.Collections.Generic.IEnumerable<TSource> source) => throw null; public static System.Linq.ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector) => throw null; public static System.Linq.ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Func<TSource, TElement> elementSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Linq.ILookup<TKey, TSource> ToLookup<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector) => throw null; public static System.Linq.ILookup<TKey, TSource> ToLookup<TSource, TKey>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, TKey> keySelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Union<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Union<TSource>(this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Where<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TSource> Where<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource, int, bool> predicate) => throw null; public static System.Collections.Generic.IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this System.Collections.Generic.IEnumerable<TFirst> first, System.Collections.Generic.IEnumerable<TSecond> second, System.Func<TFirst, TSecond, TResult> resultSelector) => throw null; public static System.Collections.Generic.IEnumerable<(TFirst, TSecond)> Zip<TFirst, TSecond>(this System.Collections.Generic.IEnumerable<TFirst> first, System.Collections.Generic.IEnumerable<TSecond> second) => throw null; } // Generated from `System.Linq.IGrouping<,>` in `System.Linq, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public interface IGrouping<TKey, TElement> : System.Collections.Generic.IEnumerable<TElement>, System.Collections.IEnumerable { TKey Key { get; } } // Generated from `System.Linq.ILookup<,>` in `System.Linq, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public interface ILookup<TKey, TElement> : System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TElement>>, System.Collections.IEnumerable { bool Contains(TKey key); int Count { get; } System.Collections.Generic.IEnumerable<TElement> this[TKey key] { get; } } // Generated from `System.Linq.IOrderedEnumerable<>` in `System.Linq, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public interface IOrderedEnumerable<TElement> : System.Collections.Generic.IEnumerable<TElement>, System.Collections.IEnumerable { System.Linq.IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(System.Func<TElement, TKey> keySelector, System.Collections.Generic.IComparer<TKey> comparer, bool descending); } // Generated from `System.Linq.Lookup<,>` in `System.Linq, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a` public class Lookup<TKey, TElement> : System.Collections.Generic.IEnumerable<System.Linq.IGrouping<TKey, TElement>>, System.Collections.IEnumerable, System.Linq.ILookup<TKey, TElement> { public System.Collections.Generic.IEnumerable<TResult> ApplyResultSelector<TResult>(System.Func<TKey, System.Collections.Generic.IEnumerable<TElement>, TResult> resultSelector) => throw null; public bool Contains(TKey key) => throw null; public int Count { get => throw null; } public System.Collections.Generic.IEnumerator<System.Linq.IGrouping<TKey, TElement>> GetEnumerator() => throw null; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null; public System.Collections.Generic.IEnumerable<TElement> this[TKey key] { get => throw null; } } } }
159.647577
484
0.760017
[ "MIT" ]
01SMD/codeql
csharp/ql/test/resources/stubs/_frameworks/Microsoft.NETCore.App/System.Linq.cs
36,240
C#
namespace Mafia2Tool { partial class PrefabEditor { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrefabEditor)); this.Grid_Prefabs = new System.Windows.Forms.PropertyGrid(); this.TreeView_Prefabs = new Mafia2Tool.Controls.MTreeView(); this.Context_Menu = new System.Windows.Forms.ContextMenuStrip(this.components); this.Context_Delete = new System.Windows.Forms.ToolStripMenuItem(); this.Browser_ImportPRB = new System.Windows.Forms.OpenFileDialog(); this.ToolStrip_Main = new System.Windows.Forms.ToolStrip(); this.Button_File = new System.Windows.Forms.ToolStripDropDownButton(); this.Button_Save = new System.Windows.Forms.ToolStripMenuItem(); this.Button_Reload = new System.Windows.Forms.ToolStripMenuItem(); this.Button_Exit = new System.Windows.Forms.ToolStripMenuItem(); this.Button_Tools = new System.Windows.Forms.ToolStripDropDownButton(); this.Button_Import = new System.Windows.Forms.ToolStripMenuItem(); this.Button_Export = new System.Windows.Forms.ToolStripMenuItem(); this.Button_Delete = new System.Windows.Forms.ToolStripMenuItem(); this.Browser_ExportPRB = new System.Windows.Forms.SaveFileDialog(); this.Context_ImportXML = new System.Windows.Forms.ToolStripMenuItem(); this.Context_ExportXML = new System.Windows.Forms.ToolStripMenuItem(); this.Context_Menu.SuspendLayout(); this.ToolStrip_Main.SuspendLayout(); this.SuspendLayout(); // // Grid_Prefabs // this.Grid_Prefabs.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.Grid_Prefabs.Location = new System.Drawing.Point(469, 32); this.Grid_Prefabs.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.Grid_Prefabs.Name = "Grid_Prefabs"; this.Grid_Prefabs.PropertySort = System.Windows.Forms.PropertySort.Categorized; this.Grid_Prefabs.Size = new System.Drawing.Size(450, 473); this.Grid_Prefabs.TabIndex = 10; // // TreeView_Prefabs // this.TreeView_Prefabs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.TreeView_Prefabs.ContextMenuStrip = this.Context_Menu; this.TreeView_Prefabs.Location = new System.Drawing.Point(14, 32); this.TreeView_Prefabs.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.TreeView_Prefabs.Name = "TreeView_Prefabs"; this.TreeView_Prefabs.Size = new System.Drawing.Size(429, 472); this.TreeView_Prefabs.TabIndex = 11; this.TreeView_Prefabs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.OnNodeSelectSelect); // // Context_Menu // this.Context_Menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Context_ImportXML, this.Context_ExportXML, this.Context_Delete}); this.Context_Menu.Name = "Context_Menu"; this.Context_Menu.Size = new System.Drawing.Size(181, 92); this.Context_Menu.Opening += new System.ComponentModel.CancelEventHandler(this.Context_Menu_OnOpening); // // Context_Delete // this.Context_Delete.Name = "Context_Delete"; this.Context_Delete.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Delete))); this.Context_Delete.Size = new System.Drawing.Size(180, 22); this.Context_Delete.Text = "$DELETE"; this.Context_Delete.Click += new System.EventHandler(this.Context_Delete_Click); // // Browser_ImportPRB // this.Browser_ImportPRB.FileName = "Select Singular Prefab file"; this.Browser_ImportPRB.Filter = "Prefab File|*.prb|All Files|*.*"; this.Browser_ImportPRB.Tag = ""; // // ToolStrip_Main // this.ToolStrip_Main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Button_File, this.Button_Tools}); this.ToolStrip_Main.Location = new System.Drawing.Point(0, 0); this.ToolStrip_Main.Name = "ToolStrip_Main"; this.ToolStrip_Main.Size = new System.Drawing.Size(933, 25); this.ToolStrip_Main.TabIndex = 15; this.ToolStrip_Main.Text = "toolStrip1"; // // Button_File // this.Button_File.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.Button_File.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Button_Save, this.Button_Reload, this.Button_Exit}); this.Button_File.Image = ((System.Drawing.Image)(resources.GetObject("Button_File.Image"))); this.Button_File.ImageTransparentColor = System.Drawing.Color.Magenta; this.Button_File.Name = "Button_File"; this.Button_File.Size = new System.Drawing.Size(47, 22); this.Button_File.Text = "$FILE"; // // Button_Save // this.Button_Save.Name = "Button_Save"; this.Button_Save.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.Button_Save.Size = new System.Drawing.Size(180, 22); this.Button_Save.Text = "$SAVE"; this.Button_Save.Click += new System.EventHandler(this.Button_Save_Click); // // Button_Reload // this.Button_Reload.Name = "Button_Reload"; this.Button_Reload.Size = new System.Drawing.Size(180, 22); this.Button_Reload.Text = "$RELOAD"; // // Button_Exit // this.Button_Exit.Name = "Button_Exit"; this.Button_Exit.Size = new System.Drawing.Size(180, 22); this.Button_Exit.Text = "$EXIT"; // // Button_Tools // this.Button_Tools.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.Button_Tools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Button_Import, this.Button_Export, this.Button_Delete}); this.Button_Tools.Image = ((System.Drawing.Image)(resources.GetObject("Button_Tools.Image"))); this.Button_Tools.ImageTransparentColor = System.Drawing.Color.Magenta; this.Button_Tools.Name = "Button_Tools"; this.Button_Tools.Size = new System.Drawing.Size(61, 22); this.Button_Tools.Text = "$TOOLS"; // // Button_Import // this.Button_Import.Name = "Button_Import"; this.Button_Import.Size = new System.Drawing.Size(214, 22); this.Button_Import.Text = "$IMPORT_PREFAB"; this.Button_Import.Click += new System.EventHandler(this.Button_Import_Click); // // Button_Export // this.Button_Export.Name = "Button_Export"; this.Button_Export.Size = new System.Drawing.Size(214, 22); this.Button_Export.Text = "$EXPORT_PREFAB"; this.Button_Export.Click += new System.EventHandler(this.Button_Export_Click); // // Button_Delete // this.Button_Delete.Name = "Button_Delete"; this.Button_Delete.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Delete))); this.Button_Delete.Size = new System.Drawing.Size(214, 22); this.Button_Delete.Text = "$DELETE_PREFAB"; this.Button_Delete.Click += new System.EventHandler(this.Button_Delete_Click); // // Browser_ExportPRB // this.Browser_ExportPRB.FileName = "Save Singular Prefab file"; this.Browser_ExportPRB.Filter = "Prefab File|*.prb|All Files|*.*"; // // Context_ImportXML // this.Context_ImportXML.Name = "Context_ImportXML"; this.Context_ImportXML.Size = new System.Drawing.Size(180, 22); this.Context_ImportXML.Text = "$IMPORT_XML"; this.Context_ImportXML.Click += new System.EventHandler(this.Context_ImportAsXML_Clicked); // // Context_ExportXML // this.Context_ExportXML.Name = "Context_ExportXML"; this.Context_ExportXML.Size = new System.Drawing.Size(180, 22); this.Context_ExportXML.Text = "$EXPORT_XML"; this.Context_ExportXML.Click += new System.EventHandler(this.Context_ExportAsXML_Clicked); // // PrefabEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(933, 519); this.Controls.Add(this.ToolStrip_Main); this.Controls.Add(this.Grid_Prefabs); this.Controls.Add(this.TreeView_Prefabs); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.Name = "PrefabEditor"; this.Text = "$PREFAB_EDITOR_TITLE"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.PrefabEditor_Closing); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.PrefabEditor_OnKeyUp); this.Context_Menu.ResumeLayout(false); this.ToolStrip_Main.ResumeLayout(false); this.ToolStrip_Main.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PropertyGrid Grid_Prefabs; private System.Windows.Forms.OpenFileDialog Browser_ImportPRB; private System.Windows.Forms.ToolStrip ToolStrip_Main; private System.Windows.Forms.ToolStripDropDownButton Button_File; private System.Windows.Forms.ToolStripMenuItem Button_Save; private System.Windows.Forms.ToolStripMenuItem Button_Reload; private System.Windows.Forms.ToolStripMenuItem Button_Exit; private System.Windows.Forms.ToolStripDropDownButton Button_Tools; private System.Windows.Forms.ToolStripMenuItem Button_Import; private System.Windows.Forms.ToolStripMenuItem Button_Export; private System.Windows.Forms.ToolStripMenuItem Button_Delete; private System.Windows.Forms.SaveFileDialog Browser_ExportPRB; private System.Windows.Forms.ContextMenuStrip Context_Menu; private System.Windows.Forms.ToolStripMenuItem Context_Delete; private Controls.MTreeView TreeView_Prefabs; private System.Windows.Forms.ToolStripMenuItem Context_ImportXML; private System.Windows.Forms.ToolStripMenuItem Context_ExportXML; } }
52.502058
164
0.629723
[ "MIT" ]
farivarfarsiann/MafiaToolkit
Mafia2Libs/Forms/PrefabEditor.Designer.cs
12,760
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Authorization.IdentityServer.Data.ApplicationDb { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
42.304545
108
0.48845
[ "Apache-2.0" ]
Calabonga/Authorization-Exercises
Exercises/Authorization.IdentityServer/Data/ApplicationDb/20200613075727_Initial.cs
9,309
C#
using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ClaimApplication.Models { public class EditUserViewModel { public string Id { get; set; } public string Name { get; set; } public string Email { get; set; } [Display(Name = "User Claims")] public List<SelectListItem> UserClaims { get; set; } } }
26.315789
60
0.682
[ "MIT" ]
rafysanchez/ASP.NET-MVC--Angular-UIGrid-Paging
AuthenticationClaimBasedauthorizationwithIdentity/C#/src/ClaimApplication/Models/EditUserViewModel.cs
502
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("ConsoleApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("c3f74541-c4ec-40e2-a09d-ca91a08a5e8d")] // 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")]
38.621622
85
0.725682
[ "MIT" ]
agilitix/SameAssemblySeveralVersions
ConsoleApp/Properties/AssemblyInfo.cs
1,432
C#
using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; using SFA.DAS.Payments.DataLocks.Domain.Models; using SFA.DAS.Payments.DataLocks.Domain.Services.CourseValidation; using SFA.DAS.Payments.Model.Core; using SFA.DAS.Payments.Model.Core.Entities; namespace SFA.DAS.Payments.DataLocks.Domain.UnitTests.Services.CourseValidation { [TestFixture] public class FrameworkCodeValidatorTests { private const string PriceEpisodeIdentifier = "pe-1"; private EarningPeriod period; [OneTimeSetUp] public void Setup() { period = new EarningPeriod { Period = 1, }; } [Test] public void WhenFrameworkCodeMatches_ThenNoDatalock() { var validation = new DataLockValidationModel { PriceEpisode = new PriceEpisode { Identifier = PriceEpisodeIdentifier }, EarningPeriod = period, Apprenticeship = new ApprenticeshipModel { Id = 1, ApprenticeshipPriceEpisodes = new List<ApprenticeshipPriceEpisodeModel> { new ApprenticeshipPriceEpisodeModel { Id = 100 } }, FrameworkCode = 123, }, Aim = new LearningAim { FrameworkCode = 123, }, }; var validator = new FrameworkCodeValidator(); var result = validator.Validate(validation); result.DataLockErrorCode.Should().BeNull(); result.ApprenticeshipPriceEpisodes.Should().HaveCount(1); result.ApprenticeshipPriceEpisodes[0].Id.Should().Be(100); } [Test] public void WhenFrameworkCodeDoesNotMatch_ThenDLOCK_04() { var validation = new DataLockValidationModel { PriceEpisode = new PriceEpisode { Identifier = PriceEpisodeIdentifier }, EarningPeriod = period, Apprenticeship = new ApprenticeshipModel { Id = 1, ApprenticeshipPriceEpisodes = new List<ApprenticeshipPriceEpisodeModel> { new ApprenticeshipPriceEpisodeModel { Id = 100 } }, FrameworkCode = 123, }, Aim = new LearningAim { FrameworkCode = 124, }, }; var validator = new FrameworkCodeValidator(); var result = validator.Validate(validation); result.DataLockErrorCode.Should().Be(DataLockErrorCode.DLOCK_04); result.ApprenticeshipPriceEpisodes.Should().HaveCount(0); } } }
33.777778
91
0.521382
[ "MIT" ]
PJChamley/das-payments-V2
src/SFA.DAS.Payments.DataLocks.Domain.UnitTests/Services/CourseValidation/FrameworkCodeValidatorTests.cs
3,042
C#
using System; using System.Security.Cryptography; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Numerics; namespace LibOrbisPkg.Util { public static class Crypto { /// <summary> /// From FPKG code: /// a common function to generate a final key for PFS /// </summary> public static byte[] PfsGenCryptoKey(byte[] ekpfs, byte[] seed, uint index) { byte[] d = new byte[4 + seed.Length]; Array.Copy(BitConverter.GetBytes(index), d, 4); Array.Copy(seed, 0, d, 4, seed.Length); using (var hmac = new HMACSHA256(ekpfs)) { return hmac.ComputeHash(d); } } /// <summary> /// Generates a (tweak, data) key pair for XTS /// </summary> public static Tuple<byte[], byte[]> PfsGenEncKey(byte[] ekpfs, byte[] seed, bool newCrypt = false) { var encKey = PfsGenCryptoKey(newCrypt ? new HMACSHA256(ekpfs).ComputeHash(seed) : ekpfs, seed, 1); var dataKey = new byte[16]; var tweakKey = new byte[16]; Buffer.BlockCopy(encKey, 0, tweakKey, 0, 16); Buffer.BlockCopy(encKey, 16, dataKey, 0, 16); return Tuple.Create(tweakKey, dataKey); } /// <summary> /// From FPKG code: /// asigning key generator based on EKPFS and PFS header seed /// </summary> public static byte[] PfsGenSignKey(byte[] ekpfs, byte[] seed) { return PfsGenCryptoKey(ekpfs, seed, 2); } /// <summary> /// From FPKG Code (sceSblPfsSetKeys): Turns the EEKPfs to an EKPfs /// </summary> public static byte[] DecryptEEKPfs(byte[] eekpfs, RSAKeyset keyset) { var @params = new RSAParameters { D = keyset.PrivateExponent, DP = keyset.Exponent1, DQ = keyset.Exponent2, Exponent = keyset.PublicExponent, InverseQ = keyset.Coefficient, Modulus = keyset.Modulus, P = keyset.Prime1, Q = keyset.Prime2 }; using(var rsa = RSA.Create()) { rsa.KeySize = 2048; rsa.ImportParameters(@params); return rsa.DecryptValue(eekpfs); } } /// <summary> /// Encrypts the given hash with the given public key (modulus) /// </summary> /// <param name="modulus"></param> /// <param name="hash"></param> /// <param name="extra"></param> /// <returns></returns> public static byte[] RSA2048EncryptKey(byte[] modulus, byte[] hash) { // 1. Seed MT PRNG with hash of key and input hash var buffer = new byte[256 + 32]; Buffer.BlockCopy(modulus, 0, buffer, 0, 256); Buffer.BlockCopy(hash, 0, buffer, 256, 32); var final_hash = Sha256(Sha256(buffer)); var final_hash_ints = new uint[8]; for (int i = 0; i < 32; i += 4) { final_hash_ints[i / 4] = ((uint)final_hash[0 + i] << 24) | ((uint)final_hash[1 + i] << 16) | ((uint)final_hash[2 + i] << 8) | ((uint)final_hash[3 + i] << 0); } var mt = new MersenneTwister(final_hash_ints); // 2. Pad the RSA input (header hash) using the Mersenne Twister PRNG var sha_source = new MemoryStream(48); var padded_input = new byte[256]; padded_input[0] = 0; padded_input[1] = 2; padded_input[223] = 0; Buffer.BlockCopy(hash, 0, padded_input, 224, 32); for (int k = 2; k < 223;) { sha_source.Position = 0; for (int i = 0; i < 12; i++) { sha_source.WriteUInt32BE(mt.Int32()); } var random = Sha256(sha_source); foreach (var r in random) { if (k >= 223) break; if (r != 0) padded_input[k++] = r; } } // 3. Encrypt the padded input with RSA 2048 (modular exponentiation) return RSA2048Encrypt(padded_input, modulus); } /// <summary> /// Sign the given SHA-256 hash with PKCS1 padding /// </summary> /// <param name="sha256Hash">Hash</param> /// <param name="keyset">Keys to use</param> /// <returns>RSA 2048 signature of the hash</returns> public static byte[] RSA2048SignSha256(byte[] sha256Hash, RSAKeyset keyset) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(new RSAParameters { P = keyset.Prime1, Q = keyset.Prime2, Exponent = keyset.PublicExponent, Modulus = keyset.Modulus, DP = keyset.Exponent1, DQ = keyset.Exponent2, InverseQ = keyset.Coefficient, D = keyset.PrivateExponent }); return rsa.SignHash(sha256Hash, CryptoConfig.MapNameToOID("SHA256")); } public static bool RSA2048VerifySha256(byte[] sha256Hash, byte[] signature, RSAKeyset keyset) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(new RSAParameters { P = keyset.Prime1, Q = keyset.Prime2, Exponent = keyset.PublicExponent, Modulus = keyset.Modulus, DP = keyset.Exponent1, DQ = keyset.Exponent2, InverseQ = keyset.Coefficient, D = keyset.PrivateExponent }); return rsa.VerifyHash(sha256Hash, CryptoConfig.MapNameToOID("SHA256"), signature); } /// <summary> /// Encrypts the value with 2048 bit RSA. /// Accepts and returns Big-Endian values /// </summary> /// <param name="value"></param> /// <param name="mod"></param> /// <returns></returns> public static byte[] RSA2048Encrypt(byte[] value, byte[] mod, int exp = 65537) { var message = new BigInteger(value.Reverse().ToArray()); var modulus = new BigInteger(mod.Reverse().Concat(new byte[] { 0 }).ToArray()); var exponent = new BigInteger(exp); var leResult = BigInteger.ModPow(message, exponent, modulus).ToByteArray().Take(256); return leResult .Concat(Enumerable.Range(0, 256 - leResult.Count()).Select(x => (byte)0)) .Reverse() .ToArray(); } public static byte[] RSA2048Decrypt(byte[] ciphertext, RSAKeyset keyset) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(new RSAParameters { P = keyset.Prime1, Q = keyset.Prime2, Exponent = keyset.PublicExponent, Modulus = keyset.Modulus, DP = keyset.Exponent1, DQ = keyset.Exponent2, InverseQ = keyset.Coefficient, D = keyset.PrivateExponent }); return rsa.Decrypt(ciphertext, false); } // TODO public static int AesCbcCfb128Encrypt(byte[] @out, byte[] @in, int size, byte[] key, byte[] iv) { var cipher = new AesManaged { Mode = CipherMode.CBC, KeySize = 128, Key = key, IV = iv, Padding = PaddingMode.None, BlockSize = 128, }; var tmp = new byte[size]; using (var pt_stream = new MemoryStream(@in)) using (var ct_stream = new MemoryStream(tmp)) using (var dec = cipher.CreateEncryptor(key, iv)) using (var s = new CryptoStream(ct_stream, dec, CryptoStreamMode.Write)) { pt_stream.CopyTo(s); } Buffer.BlockCopy(tmp, 0, @out, 0, tmp.Length); return 0; } public static int AesCbcCfb128Decrypt(byte[] @out, byte[] @in, int size, byte[] key, byte[] iv) { var cipher = new AesManaged { Mode = CipherMode.CBC, KeySize = 128, Key = key, IV = iv, Padding = PaddingMode.None, BlockSize = 128, }; var tmp = new byte[size]; using (var ct_stream = new MemoryStream(@in)) using (var pt_stream = new MemoryStream(tmp)) using (var dec = cipher.CreateDecryptor(key, iv)) using (var s = new CryptoStream(ct_stream, dec, CryptoStreamMode.Read)) { s.CopyTo(pt_stream); } Buffer.BlockCopy(tmp, 0, @out, 0, tmp.Length); return 0; } /// <summary> /// Computes the SHA256 hash of the given data. /// </summary> public static byte[] Sha256(byte[] data) => SHA256.Create().ComputeHash(data); public static byte[] Sha256(Stream data) { data.Position = 0; return SHA256.Create().ComputeHash(data); } /// <summary> /// Computes the SHA256 hash of the data in the stream between (start) and (start+length) /// </summary> public static byte[] Sha256(Stream data, long start, long length) { using (var s = new SubStream(data, start, length)) { return Sha256(s); } } public static byte[] HmacSha256(byte[] key, byte[] data) => new HMACSHA256(key).ComputeHash(data); public static byte[] HmacSha256(byte[] key, Stream data) { data.Position = 0; return new HMACSHA256(key).ComputeHash(data); } public static byte[] HmacSha256(byte[] key, Stream data, long start, long length) { using (var s = new SubStream(data, start, length)) { return HmacSha256(key, s); } } /// <summary> /// Computes keys for the package. /// The key is the result of a SHA256 hash of the concatenation of: /// - The SHA256 hash of the index (4 bytes big-endian) /// - The SHA256 hash of the Contend ID (36 bytes padded to 48 with nulls) /// - The passcode /// The EKPFS is Index 1. /// </summary> public static byte[] ComputeKeys(string ContentId, string Passcode, uint Index) { if (ContentId.Length != 36) throw new Exception("Content ID must be 36 characters long"); if (Passcode.Length != 32) throw new Exception("Passcode must be 32 characters long"); byte[] data = new byte[96]; Buffer.BlockCopy(Sha256(BitConverter.GetBytes(Index).Reverse().ToArray()), 0, data, 0, 32); Buffer.BlockCopy(Sha256(Encoding.ASCII.GetBytes(ContentId.PadRight(48, '\0'))), 0, data, 32, 32); Buffer.BlockCopy(Encoding.ASCII.GetBytes(Passcode), 0, data, 64, 32); return Sha256(data); } public static byte[] CreateKeystone(string passcode) { var keystoneHeader = "6b657973746f6e65020001000000000000000000000000000000000000000000".FromHexCompact(); var fingerprint = HmacSha256(Keys.keystone_hmac_key, Encoding.ASCII.GetBytes(passcode)); var final = HmacSha256(Keys.keystone_mac_data, keystoneHeader.Concat(fingerprint).ToArray()); return keystoneHeader.Concat(fingerprint).Concat(final).ToArray(); } /// <summary> /// XORs a with b and stores the result in a /// </summary> public static byte[] Xor(this byte[] a, byte[] b) { for(var i = 0; i < a.Length; i++) { a[i] ^= b[i]; } return a; } public static string AsHexCompact(this byte[] k) { StringBuilder sb = new StringBuilder(k.Length * 2); foreach(var b in k) { sb.AppendFormat("{0:X2}", b); } return sb.ToString(); } public static byte[] FromHexCompact(this string k) { var b = new List<byte>(); var key = k.Replace(" ", ""); for (var x = 0; x < key.Length - 1;) { byte result = 0; int sub; for(var i = 0; i < 2; i++, x++) { result <<= 4; if (key[x] >= '0' && key[x] <= '9') sub = '0'; else if (key[x] >= 'a' && key[x] <= 'f') sub = 'a' - 10; else if (key[x] >= 'A' && key[x] <= 'F') sub = 'A' - 10; else continue; result |= (byte)(key[x] - sub); } b.Add(result); } return b.ToArray(); } // System.String.GetHashCode(): http://referencesource.microsoft.com/#mscorlib/system/string.cs,0a17bbac4851d0d4 // System.Web.Util.StringUtil.GetStringHashCode(System.String): http://referencesource.microsoft.com/#System.Web/Util/StringUtil.cs,c97063570b4e791a public static int CombineHashCodes(params int[] hashCodes) { int hash1 = (5381 << 16) + 5381; int hash2 = hash1; int i = 0; foreach (var hashCode in hashCodes) { if (i % 2 == 0) hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ hashCode; else hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ hashCode; ++i; } return hash1 + (hash2 * 1566083941); } } }
32.506527
152
0.580884
[ "Unlicense" ]
Mohamadaoda/DirectPackageInstaller
LibOrbisPkg/Util/Crypto.cs
12,452
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.RuleEngine { #region Namespaces using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml.Linq; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Helper class having factory method to create various ICheck validation processors /// </summary> internal static class VerifierFactory { /// <summary> /// Factory method to create various IVerifier objects /// </summary> /// <param name="xml">The xml element representing the validating action</param> /// <returns>IVerifer derived object for validating action</returns> [SuppressMessage("DataWeb.Usage", "AC0014:DoNotHandleProhibitedExceptionsRule", Justification = "Taken care of by similar mechanism")] public static IVerifier Create(XElement xml) { var attrProcessor = xml.Attribute("processor"); if (attrProcessor == null) { return null; } IVerifier verifier = null; try { switch (attrProcessor.Value) { case "rng": verifier = VerifierFactory.CreateRngVerifier(xml.Elements().Single()); break; case "regex": verifier = VerifierFactory.CreateRegexVerifier(xml.Element("regex")); break; case "headerregex": verifier = VerifierFactory.CreateHeaderRegexVerifier(xml.Elements().Single()); break; case "xslt+rng": verifier = VerifierFactory.CreateXsltRngVerifier(xml.Elements().Single()); break; case "jsonschema": verifier = VerifierFactory.CreateJsonSchemaVerifier(xml.Element("jsonschema")); break; case "xslt+jsonschema": verifier = VerifierFactory.CreateXstJsonSchemaVerifier(xml.Elements().Single()); break; default: // not supported processor types break; } } catch (Exception e) { if (!ExceptionHelper.IsCatchableExceptionType(e)) { throw; } verifier = null; } return verifier; } /// <summary> /// Creates ReleaxNG verifier object from xml element node /// </summary> /// <param name="xmlRngSchema">the xml element node containing the relaxNG schema</param> /// <returns>IVerifier interface of the newly created ReleaxNG verifier object</returns> private static IVerifier CreateRngVerifier(XElement xmlRngSchema) { if (xmlRngSchema == null) { throw new ArgumentNullException("xmlRngSchema"); } if (!xmlRngSchema.Name.LocalName.Equals("grammar", StringComparison.Ordinal)) { throw new ArgumentException(Resource.RelaxNGRootNode); } return new RngVerifier(xmlRngSchema.ToString()); } /// <summary> /// Creates regular expression verifier from xml element node /// </summary> /// <param name="xmlRegex">xml node containing the pattern of regular expression</param> /// <returns>IVerifier interface of the newly created regular expression pattern verifier object</returns> private static IVerifier CreateRegexVerifier(XElement xmlRegex) { if (xmlRegex != null && !string.IsNullOrEmpty(xmlRegex.UnescapeElementValue())) { return new RegexVerifier(xmlRegex.UnescapeElementValue()); } return null; } /// <summary> /// Creates Http header pattern verifier object from xml element node /// </summary> /// <param name="xmlHeader">the xml element node containing the header field name and repected regular expression value </param> /// <returns>IVerifier interface of the newly created Http Header pattern verifier object</returns> private static IVerifier CreateHeaderRegexVerifier(XElement xmlHeader) { if (xmlHeader != null && xmlHeader.Attribute("field") != null && xmlHeader.Element("regex") != null) { return new HttpHeaderRegexVerifier(xmlHeader.GetAttributeValue("field"), xmlHeader.GetFirstSubElementValue("regex")); } return null; } /// <summary> /// Creates XSLT-ReleaxNG composite verifier from xml element node /// </summary> /// <param name="xmlSxlt">the xml node containing XSLT instuctions</param> /// <returns>IVerifier interface of the newly created XSLT-ReleaxNG composite verifier object</returns> private static IVerifier CreateXsltRngVerifier(XElement xmlSxlt) { if (xmlSxlt == null) { throw new ArgumentNullException("xmlSxlt"); } return new XsltRngVerifier(xmlSxlt.ToString()); } /// <summary> /// Creates Json schema verifer object from xml element node /// </summary> /// <param name="xmlJsonSchema">the xml node contining Json schema</param> /// <returns>IVerifier interface of the newly created Json schema verifer object</returns> private static IVerifier CreateJsonSchemaVerifier(XElement xmlJsonSchema) { if (xmlJsonSchema == null) { throw new ArgumentNullException("xmlJsonSchema"); } string jsonSchema = xmlJsonSchema.UnescapeElementValue(); return new JsonSchemaVerifier(jsonSchema); } /// <summary> /// Creates composite dynamic(xslt-processed) Jscon schema verifier from xml node /// </summary> /// <param name="xmlSxlt">the xml node containing xslt instructions</param> /// <returns>IVerifier interface of the newly created composite XSLT-Jscon schema verifier object</returns> private static IVerifier CreateXstJsonSchemaVerifier(XElement xmlSxlt) { if (xmlSxlt == null) { throw new ArgumentNullException("xmlSxlt"); } return new XsltJsonSchemaVerifier(xmlSxlt.ToString()); } } }
40.422857
143
0.565027
[ "MIT" ]
OData/ValidationTool
src/RuleEngine/VerifierFactory.cs
7,074
C#
using Microsoft.Azure.ServiceBus; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Pds.Contracts.ContractEventProcessor.Services.Interfaces; using System; using System.Threading.Tasks; namespace Pds.Contracts.ContractEventProcessor.Func { /// <summary> /// Example ServiceBus queue triggered Azure Function. /// </summary> public class ContractEventProcessorFunction { private readonly IContractEventSessionManager _contractEventSessionManager; /// <summary> /// Initializes a new instance of the <see cref="ContractEventProcessorFunction" /> class. /// </summary> /// <param name="contractEventSessionManager">The contract event session manager.</param> public ContractEventProcessorFunction(IContractEventSessionManager contractEventSessionManager) { _contractEventSessionManager = contractEventSessionManager; } /// <summary> /// Entry point to the Azure Function. /// </summary> /// <param name="contractEvent">The queue item that triggered this function to run.</param> /// <param name="messageSession">The message session.</param> /// <param name="log">The logger.</param> /// <returns> /// Async Task. /// </returns> [FunctionName(nameof(ContractEventProcessorFunction))] public async Task Run( [ServiceBusTrigger("%ContractEventsSessionQueue%", Connection = "ServiceBusConnection", IsSessionsEnabled = true)] Message contractEvent, IMessageSession messageSession, ILogger log) { var runId = Guid.NewGuid(); using (log?.BeginScope($"[{nameof(ContractEventProcessorFunction)}] - RunId: [{runId}], message: [{contractEvent.MessageId}], and session: [{messageSession.SessionId}] attempt: [{contractEvent.SystemProperties.DeliveryCount}]")) { log?.LogInformation($"Start: Processing message: {contractEvent.MessageId} from session: {messageSession.SessionId}."); contractEvent.UserProperties.Add("ContractEventProcessorRunId", runId); var state = await _contractEventSessionManager.ProcessSessionMessageAsync(messageSession, contractEvent); if (state.IsFaulted) { log?.LogWarning($"[{nameof(ContractEventProcessorFunction)}] - End: Message: {contractEvent.MessageId} moved to DLQ from session: {messageSession.SessionId}."); } else { log?.LogInformation($"[{nameof(ContractEventProcessorFunction)}] - End: Successfully processed message: {contractEvent.MessageId} from session: {messageSession.SessionId}."); } } } } }
47.066667
241
0.655453
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.pds-contracts-func-contract-processor
Pds.Contracts.ContractEventProcessor/Pds.Contracts.ContractEventProcessor.Func/ContractEventProcessorFunction.cs
2,826
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using ClearCanvas.Enterprise.Common; using System.Runtime.Serialization; namespace ClearCanvas.Ris.Application.Common.Admin.LocationAdmin { [DataContract] public class DeleteLocationRequest : DataContractBase { public DeleteLocationRequest(EntityRef locationRef) { this.LocationRef = locationRef; } [DataMember] public EntityRef LocationRef; } }
41.755102
87
0.742424
[ "Apache-2.0" ]
econmed/ImageServer20
Ris/Application/Common/Admin/LocationAdmin/DeleteLocationRequest.cs
2,048
C#
namespace Microsoft.Maui { /// <summary> /// Represents a View that reacts to touch events. /// </summary> public interface IButton : IView, IText, IPadding { /// <summary> /// Allows you to display a bitmap image on the Button. /// </summary> IImageSource? ImageSource { get; } void ImageSourceLoaded(); /// <summary> /// Occurs when the Button is pressed. /// </summary> void Pressed(); /// <summary> /// Occurs when the Button is released. /// </summary> void Released(); /// <summary> /// Occurs when the Button is clicked. /// </summary> void Clicked(); } }
19.580645
57
0.621087
[ "MIT" ]
Abdesol/maui
src/Core/src/Core/IButton.cs
607
C#
using System; using Dapper; using Npgsql; namespace EventStoreBasics { public class EventStore: IDisposable, IEventStore { private readonly NpgsqlConnection databaseConnection; public EventStore(NpgsqlConnection databaseConnection) { this.databaseConnection = databaseConnection; } public void Init() { // See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/ CreateStreamsTable(); CreateEventsTable(); } private void CreateStreamsTable() { const string CreateStreamsTableSQL = @"CREATE TABLE IF NOT EXISTS streams( id UUID NOT NULL PRIMARY KEY, type TEXT NOT NULL, version BIGINT NOT NULL );"; databaseConnection.Execute(CreateStreamsTableSQL); } private void CreateEventsTable() { const string CreateEventsTableSql = @"create table if not exists events( id UUID not null primary key, data jsonb not null, stream_id UUID not null, type TEXT not null, version BIGINT not null, created timestamp with time zone not null );"; databaseConnection.Execute(CreateEventsTableSql); } public void Dispose() { databaseConnection.Dispose(); } } }
27.54386
136
0.563057
[ "MIT" ]
tstuttard/EventSourcing.NetCore
Workshop/01-EventStoreBasics/02-CreateEventsTable/EventStore.cs
1,570
C#