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
// <copyright file="Friend.Generated.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> //------------------------------------------------------------------------------ // <auto-generated> // This source code was auto-generated by a roslyn code generator. // </auto-generated> //------------------------------------------------------------------------------ // ReSharper disable All namespace MUnique.OpenMU.Persistence.EntityFramework.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using MUnique.OpenMU.Persistence; /// <summary> /// The Entity Framework Core implementation of <see cref="MUnique.OpenMU.Interfaces.Friend"/>. /// </summary> [Table(nameof(Friend), Schema = "data")] internal partial class Friend : MUnique.OpenMU.Interfaces.Friend, IIdentifiable { /// <inheritdoc/> public override bool Equals(object obj) { var baseObject = obj as IIdentifiable; if (baseObject != null) { return baseObject.Id == this.Id; } return base.Equals(obj); } /// <inheritdoc/> public override int GetHashCode() { return this.Id.GetHashCode(); } } }
28.8
101
0.538889
[ "MIT" ]
RuriRyan/OpenMU
src/Persistence/EntityFramework/Model/Friend.Generated.cs
1,440
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace flappybird { [RequireComponent(typeof(PipeSpawnerScript))] [RequireComponent(typeof(AudioSource))] public class FlappyGameController : MonoBehaviour { private PlayerMovementScript playerObj; private PipeSpawnerScript pipeSpawner; [SerializeField] private Transform SpawnContainer; public GameObject playerPrefab; public Transform playerSpawnPoint; public ScoreScript scorer; public BgScrollscript bg1; public BgScrollscript bg2; public bool inProgress = false; [SerializeField] private UIHandler uiHandler; public AudioClip failAudio; public AudioClip gameoverAudio; public AudioSource audSrc; public int Score; public int highScore = 0; public int Lives = 2; public void ScoreAdd() { Score++; uiHandler.AddScore(); } private void Awake() { highScore = PlayerPrefs.GetInt("highscore", 0); gameoverAudio = Resources.Load<AudioClip>("gameover"); failAudio = Resources.Load<AudioClip>("fail"); audSrc = GetComponent<AudioSource>(); pipeSpawner = GetComponent<PipeSpawnerScript>(); } public void SpawnPlayer() { playerObj = Instantiate(playerPrefab, playerSpawnPoint.position, Quaternion.identity).GetComponent<PlayerMovementScript>(); } private void Start() { SpawnPlayer(); playerObj.StartPlayer(this); scorer.initGameObj(this); } private void ResetStage() { pipeSpawner.initPipeSpawning(playerObj.gameObject.transform); playerObj.transform.position = playerSpawnPoint.position; playerObj.enableMovement(false); } public void PlayerReady(bool status) { if (status) { pipeSpawner.spawn = true; bg1.scroll = true; bg2.scroll = true; } else { pipeSpawner.spawn = false; bg1.scroll = false; bg2.scroll = false; } } public void StartGame() { Lives = 3; uiHandler.RemoveStartScreen(); Score = 0; ResetStage(); PlayerReady(false); inProgress = true; playerObj.haultcounter = 0; } private void ContainerDestroyer() { foreach (Transform child in SpawnContainer) { Destroy(child.gameObject); } } public void CheckScore() { if (Score != 0 && Score > highScore) { highScore = Score; uiHandler.SetHighScore(highScore); PlayerPrefs.SetInt("highscore", highScore); PlayerPrefs.Save(); } } public void EndGame() { if (Lives == 0) { audSrc.PlayOneShot(gameoverAudio); CheckScore(); pipeSpawner.spawn = false; inProgress = false; ContainerDestroyer(); uiHandler.DisplayEndScreen(); ResetStage(); PlayerReady(false); playerObj.transform.position = playerSpawnPoint.position; } else { audSrc.PlayOneShot(failAudio); Lives--; uiHandler.AddLives(-1); PlayerReady(false); playerObj.haultcounter = 0; ContainerDestroyer(); ResetStage(); } } } }
27.809859
135
0.524943
[ "MIT" ]
raqdrox/flappy-bird
Assets/Scripts/FlappyGameController.cs
3,951
C#
using Nethereum.BlockchainStore.Repositories; using Nethereum.Contracts; using Nethereum.RPC.Eth.DTOs; using System; using System.Threading.Tasks; namespace Nethereum.BlockchainProcessing.Processing.Logs { public class TransactionLogProcessor<TEventDto> : ILogProcessor where TEventDto : class, new() { public TransactionLogProcessor(ITransactionLogRepository repository, Predicate<EventLog<TEventDto>> predicate = null) { Repository = repository; Predicate = predicate ?? new Predicate<EventLog<TEventDto>>(l => true); } public ITransactionLogRepository Repository { get; } public Predicate<EventLog<TEventDto>> Predicate { get; } public virtual bool IsLogForEvent(FilterLog log) => log.IsLogForEvent<TEventDto>(); public virtual async Task ProcessLogsAsync(params FilterLog[] eventLogs) { var decoded = eventLogs.DecodeAllEventsIgnoringIndexMisMatches<TEventDto>(); foreach (var log in decoded) { if (Predicate(log)) { await Repository.UpsertAsync(log.Log); } } } } }
33.333333
125
0.65
[ "MIT" ]
ConsenSys/Nethereum.BlockchainProcessing
Storage/Nethereum.BlockchainStore/Processing/Processors/TransactionLogProcessor.cs
1,202
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using System.Text; public class TextingTopPanel : MonoBehaviour { [SerializeField] private TextMeshProUGUI m_name = null; [SerializeField] private Image m_image = null; public void Init(ContactModel model) { m_name.text = model.Name; m_image.sprite = model.ProfilePic; } }
19.772727
44
0.712644
[ "Apache-2.0" ]
ttanatb/in-bed-cant-sleep
Assets/Scripts/TextingTopPanel.cs
437
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class PerformFastTravelRequest : gameScriptableSystemRequest { [Ordinal(0)] [RED("player")] public wCHandle<gameObject> Player { get; set; } [Ordinal(1)] [RED("pointData")] public CHandle<gameFastTravelPointData> PointData { get; set; } public PerformFastTravelRequest(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
30.823529
111
0.725191
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/PerformFastTravelRequest.cs
508
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; namespace DotNext { /// <summary> /// Provides strongly typed way to reflect enum type. /// </summary> /// <typeparam name="TEnum">Enum type to reflect.</typeparam> /// <seealso href="https://github.com/dotnet/corefx/issues/34077">EnumMember API</seealso> [SuppressMessage("Design", "CA1036")] [Serializable] public readonly struct Enum<TEnum> : IEquatable<TEnum>, IComparable<TEnum>, IFormattable, IEquatable<Enum<TEnum>>, ISerializable, IConvertible<TEnum> where TEnum : struct, Enum { private readonly struct Tuple : IEquatable<Tuple> { internal readonly string? Name; internal readonly TEnum Value; private Tuple(string name) { Name = name; Value = default; } private Tuple(TEnum value) { Value = value; Name = default; } public static implicit operator Tuple(string name) => new Tuple(name); public static implicit operator Tuple(TEnum value) => new Tuple(value); public bool Equals(Tuple other) => Name is null ? other.Name is null && EqualityComparer<TEnum>.Default.Equals(Value, other.Value) : Name == other.Name; public override bool Equals(object? other) => other is Tuple t && Equals(t); public override int GetHashCode() => Name is null ? Value.GetHashCode() : Name.GetHashCode(StringComparison.Ordinal); } private sealed class Mapping : Dictionary<Tuple, long> { internal readonly Enum<TEnum>[] Members; internal Mapping(out Enum<TEnum> min, out Enum<TEnum> max) { var names = Enum.GetNames(typeof(TEnum)); var values = (TEnum[])Enum.GetValues(typeof(TEnum)); Members = new Enum<TEnum>[names.LongLength]; min = max = default; for (var index = 0L; index < names.LongLength; index++) { var entry = Members[index] = new Enum<TEnum>(values[index], names[index]); Add(entry.Name, index); this[entry.Value] = index; // detect min and max min = entry.Value.CompareTo(min.Value) < 0 ? entry : min; max = entry.Value.CompareTo(max.Value) > 0 ? entry : max; } } internal Enum<TEnum> this[string name] => Members[base[name]]; internal bool TryGetValue(TEnum value, out Enum<TEnum> member) { if (base.TryGetValue(value, out var index)) { member = Members[index]; return true; } else { member = default; return false; } } } private static readonly Mapping EnumMapping = new Mapping(out MinValue, out MaxValue); /// <summary> /// Maximum enum value. /// </summary> public static readonly Enum<TEnum> MaxValue; /// <summary> /// Minimum enum value. /// </summary> public static readonly Enum<TEnum> MinValue; /// <summary> /// Returns an indication whether a constant with a specified value exists in a enumeration of type <typeparamref name="TEnum"/>. /// </summary> /// <param name="value">The value of a constant in <typeparamref name="TEnum"/>.</param> /// <returns><see langword="true"/> if a constant in <typeparamref name="TEnum"/> has a value equal to <paramref name="value"/>; otherwise, <see langword="false"/>.</returns> public static bool IsDefined(TEnum value) => EnumMapping.ContainsKey(value); /// <summary> /// Returns an indication whether a constant with a specified name exists in a enumeration of type <typeparamref name="TEnum"/>. /// </summary> /// <param name="name">The name of a constant in <typeparamref name="TEnum"/>.</param> /// <returns><see langword="true"/> if a constant in <typeparamref name="TEnum"/> has a name equal to <paramref name="name"/>; otherwise, <see langword="false"/>.</returns> public static bool IsDefined(string name) => EnumMapping.ContainsKey(name); /// <summary> /// Gets enum member by its value. /// </summary> /// <param name="value">The enum value.</param> /// <returns>The enum member.</returns> public static Enum<TEnum> GetMember(TEnum value) => EnumMapping.TryGetValue(value, out var result) ? result : new Enum<TEnum>(value, null); /// <summary> /// Attempts to retrieve enum member which constant value is equal to the given value. /// </summary> /// <param name="value">Enum value.</param> /// <param name="member">Enum member which constant value is equal to <paramref name="value"/>.</param> /// <returns><see langword="true"/>, if there are member declared the given constant value exist; otherwise, <see langword="false"/>.</returns> public static bool TryGetMember(TEnum value, out Enum<TEnum> member) => EnumMapping.TryGetValue(value, out member); /// <summary> /// Attempts to retrieve enum member which name is equal to the given value. /// </summary> /// <param name="name">The name of a constant.</param> /// <param name="member">Enum member which name is equal to <paramref name="name"/>.</param> /// <returns><see langword="true"/>, if there are member declared the given constant value exist; otherwise, <see langword="false"/>.</returns> public static bool TryGetMember(string name, out Enum<TEnum> member) { if (Enum.TryParse<TEnum>(name, out var value)) { member = new Enum<TEnum>(value, name); return true; } else { member = default; return false; } } /// <summary> /// Gets enum member by its case-sensitive name. /// </summary> /// <param name="name">The name of the enum value.</param> /// <returns>The enum member.</returns> /// <exception cref="KeyNotFoundException">Enum member with the requested name doesn't exist in enum.</exception> public static Enum<TEnum> GetMember(string name) => EnumMapping[name]; /// <summary> /// Gets declared enum members. /// </summary> public static IReadOnlyList<Enum<TEnum>> Members => EnumMapping.Members; /// <summary> /// Gets the underlying type of the specified enumeration. /// </summary> public static Type UnderlyingType => Enum.GetUnderlyingType(typeof(TEnum)); /// <summary> /// Gets code of the underlying primitive type. /// </summary> public static TypeCode UnderlyingTypeCode => Type.GetTypeCode(typeof(TEnum)); private const string NameSerData = "Name"; private const string ValueSerData = "Value"; private readonly string? name; private Enum(TEnum value, string? name) { Value = value; this.name = name; } [SuppressMessage("Usage", "CA1801", Justification = "context is required by .NET serialization framework")] private Enum(SerializationInfo info, StreamingContext context) { name = info.GetString(NameSerData); Value = (TEnum)info.GetValue(ValueSerData, typeof(TEnum)); } /// <summary> /// Determines whether one or more bit fields associated /// with the current instance are set in the given value. /// </summary> /// <param name="flags">An enumeration value.</param> /// <returns><see langword="true"/>, if <see cref="Value"/> bits are set in <paramref name="flags"/>.</returns> public bool IsFlag(TEnum flags) => Runtime.Intrinsics.HasFlag(flags, Value); /// <summary> /// Represents value of the enum member. /// </summary> public TEnum Value { get; } /// <inheritdoc/> TEnum IConvertible<TEnum>.Convert() => Value; /// <summary> /// Represents name of the enum member. /// </summary> public string Name => name ?? ValueTypeExtensions.ToString(Value); /// <summary> /// Converts typed enum wrapper into actual enum value. /// </summary> /// <param name="en">Enum wrapper to convert.</param> public static implicit operator TEnum(in Enum<TEnum> en) => en.Value; /// <summary> /// Compares this enum value with other. /// </summary> /// <param name="other">Other value to compare.</param> /// <returns>Comparison result.</returns> public int CompareTo(TEnum other) => Comparer<TEnum>.Default.Compare(Value, other); /// <summary> /// Determines whether this value equals to the other enum value. /// </summary> /// <param name="other">Other value to compare.</param> /// <returns>Equality check result.</returns> public bool Equals(TEnum other) => EqualityComparer<TEnum>.Default.Equals(Value, other); /// <summary> /// Determines whether two enum members are equal. /// </summary> /// <param name="other">Other member to compare.</param> /// <returns><see langword="true"/> if this enum member is the same as other; otherwise, <see langword="false"/>.</returns> public bool Equals(Enum<TEnum> other) => Equals(other.Value) && Equals(Name, other.Name); /// <summary> /// Determines whether this value equals to the other enum value. /// </summary> /// <param name="other">Other value to compare.</param> /// <returns>Equality check result.</returns> public override bool Equals(object? other) => other switch { Enum<TEnum> en => Equals(en), TEnum en => Equals(en), _ => false, }; /// <summary> /// Gets hash code of the enum member. /// </summary> /// <returns>The hash code of the enum member.</returns> public override int GetHashCode() => HashCode.Combine(Value, Name); /// <summary> /// Returns textual representation of the enum value. /// </summary> /// <returns>The textual representation of the enum value.</returns> public override string ToString() => ValueTypeExtensions.ToString(Value); /// <inheritdoc/> string IFormattable.ToString(string format, IFormatProvider provider) => ValueTypeExtensions.ToString(Value, format, provider); /// <summary> /// Determines whether two enum members are equal. /// </summary> /// <param name="first">The first member to compare.</param> /// <param name="second">The second member to compare.</param> /// <returns><see langword="true"/> if this enum member is the same as other; otherwise, <see langword="false"/>.</returns> public static bool operator ==(Enum<TEnum> first, Enum<TEnum> second) => first.Equals(second); /// <summary> /// Determines whether two enum members are not equal. /// </summary> /// <param name="first">The first member to compare.</param> /// <param name="second">The second member to compare.</param> /// <returns><see langword="true"/> if this enum member is not the same as other; otherwise, <see langword="false"/>.</returns> public static bool operator !=(Enum<TEnum> first, Enum<TEnum> second) => !first.Equals(second); /// <inheritdoc/> void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(NameSerData, name, typeof(string)); info.AddValue(ValueSerData, Value); } } }
43.101754
182
0.58393
[ "MIT" ]
GerardSmit/dotNext
src/DotNext/Enum.cs
12,286
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.Sms { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum SmsFilterActionType { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ AcceptImmediately, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ Drop, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ Peek, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ Accept, #endif } #endif }
26.192308
62
0.688693
[ "Apache-2.0" ]
AlexTrepanier/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Sms/SmsFilterActionType.cs
681
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TcoDrivesBeckhoffTestsConnector.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Localizations { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Localizations() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TcoDrivesBeckhoffTestsConnector.Properties.Localizations", typeof(Localizations).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.3125
205
0.62024
[ "MIT" ]
Barteling/TcOpen
src/TcoDrivesBeckhoff/tests/TcoDrivesBeckhoffTestsConnector/Properties/Localizations.Designer.cs
2,838
C#
using LozyeFramework.Lua.LuaHeaders; using LozyeFramework.Lua.LuaProxys; using System; namespace LozyeFramework.Lua { static class LuaStaticVisitor { public static T Get<T>(IntPtr _luaState, LuaRef luaPtr, string path) { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy<T>.Instance; var children = string.IsNullOrEmpty(path) ? new string[0] : path.Split('.'); var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); for (int i = 0; i < children.Length; i++) LuaJIT.lua_getfield(_luaState, -1, children[i]); return proxy.peek(_luaState, -1); } finally { LuaJIT.lua_settop(_luaState, top); } } public static void Set<T>(IntPtr _luaState, LuaRef luaPtr, string path, T value) { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy<T>.Instance; var children = path.Split('.'); var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); for (int i = 0; i < children.Length - 1; i++) LuaJIT.lua_getfield(_luaState, -1, children[i]); proxy.push(_luaState, value); LuaJIT.lua_setfield(_luaState, -2, children[children.Length - 1]); } finally { LuaJIT.lua_settop(_luaState, top); } } public static T GetFunction<T>(IntPtr _luaState, LuaRef luaPtr, string path) where T : Delegate { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy.Instance.Function; var children = string.IsNullOrEmpty(path) ? new string[0] : path.Split('.'); var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); for (int i = 0; i < children.Length; i++) LuaJIT.lua_getfield(_luaState, -1, children[i]); if (!LuaJIT.lua_isfunction(_luaState, -1)) throw new Exception("not function"); var idx = LuaJIT.luaL_ref(_luaState, LuaJIT.LUA_REGISTRYINDEX); return proxy.peek<T>(_luaState, idx); } finally { LuaJIT.lua_settop(_luaState, top); } } public static void SetFunction<T>(IntPtr _luaState, LuaRef luaPtr, string path, T value) where T : Delegate { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy.Instance.Function; var children = string.IsNullOrEmpty(path) ? null : path.Split('.'); var top = LuaJIT.lua_gettop(_luaState); try { if (children == null) { proxy.push(_luaState, value); LuaJIT.lua_replace(_luaState, -2); } else { LuaJIT.lua_pushref(_luaState, (int)luaPtr); for (int i = 0; i < children.Length - 1; i++) LuaJIT.lua_getfield(_luaState, -1, children[i]); proxy.push<T>(_luaState, value); LuaJIT.lua_setfield(_luaState, -2, children[children.Length - 1]); } } finally { LuaJIT.lua_settop(_luaState, top); } } public static T Get<T>(IntPtr _luaState, LuaRef luaPtr, int path) { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy<T>.Instance; var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); LuaJIT.lua_pushinteger(_luaState, path); LuaJIT.lua_gettable(_luaState, -2); return proxy.peek(_luaState, -1); } finally { LuaJIT.lua_settop(_luaState, top); } } public static void Set<T>(IntPtr _luaState, LuaRef luaPtr, int path, T value) { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var proxy = LuaProxy<T>.Instance; var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); LuaJIT.lua_pushinteger(_luaState, path); proxy.push(_luaState, value); LuaJIT.lua_settable(_luaState, -3); } finally { LuaJIT.lua_settop(_luaState, top); } } public static int Length(IntPtr _luaState, LuaRef luaPtr) { if (luaPtr == LuaRef.Zero) throw new NullReferenceException(); var top = LuaJIT.lua_gettop(_luaState); try { LuaJIT.lua_pushref(_luaState, (int)luaPtr); return (int)LuaJIT.lua_objlen(_luaState, -1); } finally { LuaJIT.lua_settop(_luaState, top); } } } }
28.459459
109
0.664767
[ "MIT" ]
lozye/LozyeFramework.Lua
LozyeFramework.Lua/Core/LuaStaticVisitor.cs
4,214
C#
// Jeebs Unit Tests // Copyright (c) bfren - licensed under https://mit.bfren.dev/2013 using System.Collections.Generic; using System.Linq; using Xunit; namespace Jeebs.EnumeratedList_Tests; public class Constructor_Tests { [Fact] public void Create_Empty_List() { // Arrange var list = new EnumeratedList<Foo>(); // Act // Assert Assert.Empty(list); } [Theory] [InlineData(null)] public void Create_Empty_List_From_Null_Strings(List<string> input) { // Arrange // Act var result = new EnumeratedList<Foo>(input); // Assert Assert.Empty(result); } [Fact] public void Create_List_From_Strings() { // Arrange var values = new[] { nameof(Foo.A), nameof(Foo.B) }.ToList(); // Act var result = new EnumeratedList<Foo>(values); // Assert Assert.Equal(Foo.A.ToString(), result[0].ToString()); Assert.Equal(Foo.B.ToString(), result[1].ToString()); } public record class Foo : Enumerated { public Foo(string name) : base(name) { } public static readonly Foo A = new("A"); public static readonly Foo B = new("B"); } }
17.966667
68
0.67718
[ "MIT" ]
bfren/jeebs
tests/Tests.Jeebs/Collections/EnumeratedList/Constructor_Tests.cs
1,078
C#
using L2dotNET.DataContracts; using L2dotNET.Models; using L2dotNET.Models.zones; namespace L2dotNET.Utility.Geometry { public class Cube : Square { // cube origin coordinates private readonly int _z; public Cube(int x, int y, int z, int a) : base(x, y, a) { _z = z; } public override double GetArea() { return 6 * A * A; } public override double GetVolume() { return A * A * A; } public override bool IsInside(int x, int y, int z) { int d; d = z - _z; if ((d < 0) || (d > A)) return false; d = x - X; if ((d < 0) || (d > A)) return false; d = y - Y; if ((d < 0) || (d > A)) return false; return true; } public override Location GetRandomLocation() { return new Location(X + Rnd.Get(A), Y + Rnd.Get(A), _z + Rnd.Get(A)); } } }
21.117647
81
0.433612
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SamerMoustafa/L2Ninja
src/L2dotNET/Utility/Geometry/Cube.cs
1,079
C#
using Polly; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Threading.Tasks; namespace RetryTaskWithPolly { class Program { static async Task Main(string[] args) { var policy = Policy.Handle<Exception>() //.RetryAsync(3, (exception, context) => Console.WriteLine($"{exception.Message}")); //.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1)); .WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(1)); List<Task<string>> tasks = new List<Task<string>>(); foreach (var itm in new int[3] {1,2,3}) { var tsk = policy.ExecuteAsync(() => DoSomething(itm)); tasks.Add(tsk); } while (tasks.Any()) { Task<string> completedTask = await Task.WhenAny(tasks); if (completedTask.IsCompleted) { try { Console.WriteLine(completedTask.Result); tasks.Remove(completedTask); } catch (Exception ex){} } } Console.WriteLine("All Done..!"); Console.ReadLine(); } public static async Task<string> DoSomething(int taskno) { if (taskno == 2) await Task.Delay(1000); Ping ping = new Ping(); PingReply pingStatus = ping.Send(IPAddress.Parse("8.8.8.8")); if (pingStatus.Status != IPStatus.Success) { Console.WriteLine($"Task {taskno} is failed..!"); throw new Exception($"Task {taskno} is failed..!"); } return await Task.FromResult($"Task {taskno} is done..!"); } } }
33.271186
115
0.501783
[ "MIT" ]
Khairultaher/RetryTaskWithPolly
RetryTaskWithPolly/Program.cs
1,965
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement2D : MonoBehaviour { private Vector2 _dir = Vector2.zero; private Vector3 AimDirection = Vector3.zero; private Vector3 Target = Vector3.zero; [SerializeField] private GameObject _player; [SerializeField] private GameObject projectile; [SerializeField] private Rigidbody _rgbd; [SerializeField] private Rigidbody Projectile; [SerializeField] private float speed; private Vector3 CursorPos; private Vector3 ObjectPos; private float angle; private Transform target; // Start is called before the first frame update void Start() { _dir = transform.up; Projectile = GetComponent<Rigidbody>(); if (!_rgbd) { _rgbd = GetComponent<Rigidbody>(); } } // Update is called once per frame void Update() { _dir.x = 0; _dir.y = 0; CursorPos = Input.mousePosition; ObjectPos = Camera.main.ScreenToWorldPoint(CursorPos); ObjectPos.z = 0; Vector3 dir = ObjectPos - transform.position; transform.up = dir.normalized; AimDirection = Vector3.zero; Target = Input.mousePosition; if (Input.GetKey(KeyCode.W)) _dir.y += 80; if (Input.GetKey(KeyCode.S)) _dir.y -= 80; if (Input.GetKey(KeyCode.A)) _dir.x -= 80; if (Input.GetKey(KeyCode.D)) _dir.x += 80; if (Input.GetKey(KeyCode.Mouse0)) { Vector3 ShootDirection; ShootDirection = Input.mousePosition; ShootDirection.z = 0.0f; ShootDirection = Camera.main.ScreenToWorldPoint(ShootDirection); ShootDirection.z = 0.0f; ShootDirection = (ShootDirection - transform.position).normalized; ShootDirection.z = 0.0f; GameObject curProjectile = Instantiate(projectile, transform.position, Quaternion.Euler(0, 0, Mathf.Atan2(ShootDirection.y, ShootDirection.x) * Mathf.Rad2Deg - 90)); curProjectile.GetComponent<Shot>().ProjectileDirection = new Vector2(ShootDirection.x + Random.Range(0, 11) / 20f - 0.25f, ShootDirection.y + Random.Range(0, 11) / 20f - 0.5f).normalized; } _dir.Normalize(); _rgbd.velocity = _dir * speed * Time.deltaTime; } }
31.379747
199
0.61073
[ "MIT" ]
schaumbu/Morphfox
Assets/Scripts/PlayerMovement2D.cs
2,481
C#
using System.Reflection; [assembly: AssemblyTitle("SIPSorcery.SIP.Net")] [assembly: AssemblyDescription("Helper classes for SIP related protocols.")] [assembly: AssemblyCompany("SIP Sorcery PTY LTD")] [assembly: AssemblyCopyright("Aaron Clauson")] [assembly: AssemblyVersion("1.5.6.*")]
36
76
0.770833
[ "BSD-3-Clause" ]
Rehan-Mirza/sipsorcery
sipsorcery-core/SIPSorcery.Net/AssemblyInfo.cs
288
C#
using System.Reflection; 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("ToDo_list.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ToDo_list.iOS")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("4e00ccf2-5d4e-415f-ae06-291965e1822e")] // 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.777778
84
0.740441
[ "MIT" ]
namarakM/ToDo-list
ToDo-list/ToDo-list.iOS/Properties/AssemblyInfo.cs
1,363
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("04. TextFilter")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("04. TextFilter")] [assembly: System.Reflection.AssemblyTitleAttribute("04. TextFilter")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.333333
80
0.645161
[ "MIT" ]
georgivv7/C-Sharp-Fundamentals-SoftUni
TextProcessing-Lab/04. TextFilter/obj/Debug/netcoreapp3.1/04. TextFilter.AssemblyInfo.cs
992
C#
using System; using System.Collections.Generic; using System.Text; 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.Shapes; using System.Collections.ObjectModel; using StoreDatabase; namespace DataBinding { /// <summary> /// Interaction logic for DataTemplateList.xaml /// </summary> public partial class VariedTemplates : System.Windows.Window { public VariedTemplates() { InitializeComponent(); } private ICollection<Product> products; private void cmdGetProducts_Click(object sender, RoutedEventArgs e) { products = App.StoreDb.GetProducts(); lstProducts.ItemsSource = products; } private void cmdApplyChange_Click(object sender, RoutedEventArgs e) { ((ObservableCollection<Product>)products)[1].CategoryName = "Travel"; DataTemplateSelector selector = lstProducts.ItemTemplateSelector; lstProducts.ItemTemplateSelector = null; lstProducts.ItemTemplateSelector = selector; } } }
27.8
81
0.688249
[ "MIT" ]
DiogoBarbosaSilvaSousa/apress
pro-wpf-4.5-in-csharp/Pro WPF 4.5 in C#/Chapter20/DataBinding/VariedTemplates.xaml.cs
1,251
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.Diagnostics.Tracing.Session; namespace JitBench { public class TestRun { public TestRun() { Benchmarks = new List<Benchmark>(); Configurations = new List<BenchmarkConfiguration>(); BenchmarkRunResults = new List<BenchmarkRunResult>(); MetricNames = new List<string>(); } public bool UseExistingSetup { get; set; } public string DotnetFrameworkVersion { get; set; } public string DotnetSdkVersion { get; set; } public string PrivateCoreCLRBinDir { get; set; } public Architecture Architecture { get; set; } public string OutputDir { get; set; } public int Iterations { get; set; } public List<Benchmark> Benchmarks { get; } public List<BenchmarkConfiguration> Configurations { get; private set; } public List<string> MetricNames { get; private set; } public string BenchviewRunId { get; set; } public DotNetInstallation DotNetInstallation { get; private set; } public List<BenchmarkRunResult> BenchmarkRunResults { get; private set; } public void Run(ITestOutputHelper output) { CheckConfiguration(); SetupBenchmarks(output).Wait(); RunBenchmarks(output); WriteBenchmarkResults(output); } public void CheckConfiguration() { ValidateOutputDir(); ValidateMetrics(); } private void ValidateMetrics() { var validCollectionOptions = new[] { "default", "gcapi", "stopwatch", "BranchMispredictions", "CacheMisses", "InstructionRetired", }; var reducedList = MetricNames.Distinct(StringComparer.OrdinalIgnoreCase); var isSubset = !reducedList.Except(validCollectionOptions, StringComparer.OrdinalIgnoreCase).Any(); if (!isSubset) { var errorMessage = $"Valid collection metrics are: {string.Join("|", validCollectionOptions)}"; throw new InvalidOperationException(errorMessage); } MetricNames = reducedList.Count() > 0 ? new List<string>(reducedList) : new List<string> { "stopwatch" }; if (MetricNames.Any(n => !n.Equals("stopwatch"))) { if (TraceEventSession.IsElevated() != true) { throw new UnauthorizedAccessException("The application is required to run as Administrator in order to capture kernel data"); } } } private void ValidateOutputDir() { if (string.IsNullOrWhiteSpace(OutputDir)) throw new InvalidOperationException("The output directory name cannot be null, empty or white space."); if (OutputDir.Any(c => Path.GetInvalidPathChars().Contains(c))) throw new InvalidOperationException($"Specified output directory {OutputDir} contains invalid path characters."); OutputDir = Path.IsPathRooted(OutputDir) ? OutputDir : Path.GetFullPath(OutputDir); if (OutputDir.Length > 80) { throw new InvalidOperationException($"The output directory path {OutputDir} is too long (>80 characters). Tests writing here may trigger errors because of path length limits"); } try { Directory.CreateDirectory(OutputDir); } catch (IOException e) { throw new Exception($"Unable to create output directory {OutputDir}: {e.Message}", e); } } public void WriteConfiguration(ITestOutputHelper output) { output.WriteLine(""); output.WriteLine(" === CONFIGURATION ==="); output.WriteLine(""); output.WriteLine("DotnetFrameworkVersion: " + DotnetFrameworkVersion); output.WriteLine("DotnetSdkVersion: " + DotnetSdkVersion); output.WriteLine("PrivateCoreCLRBinDir: " + PrivateCoreCLRBinDir); output.WriteLine("Architecture: " + Architecture); output.WriteLine("OutputDir: " + OutputDir); output.WriteLine("Iterations: " + Iterations); output.WriteLine("UseExistingSetup: " + UseExistingSetup); output.WriteLine("Configurations: " + string.Join(",", Configurations.Select(c => c.Name))); } async Task SetupBenchmarks(ITestOutputHelper output) { output.WriteLine(""); output.WriteLine(" === SETUP ==="); output.WriteLine(""); if(UseExistingSetup) { output.WriteLine("UseExistingSetup is TRUE. Setup will be skipped."); } await PrepareDotNet(output); foreach (Benchmark benchmark in Benchmarks) { await benchmark.Setup(DotNetInstallation, OutputDir, UseExistingSetup, output); } } async Task PrepareDotNet(ITestOutputHelper output) { if (!UseExistingSetup) { DotNetSetup setup = new DotNetSetup(Path.Combine(OutputDir, ".dotnet")) .WithSdkVersion(DotnetSdkVersion) .WithArchitecture(Architecture); if(DotnetFrameworkVersion != "use-sdk") { setup.WithFrameworkVersion(DotnetFrameworkVersion); } if (PrivateCoreCLRBinDir != null) { setup.WithPrivateRuntimeBinaryOverlay(PrivateCoreCLRBinDir); } DotNetInstallation = await setup.Run(output); } else { DotNetInstallation = new DotNetInstallation(Path.Combine(OutputDir, ".dotnet"), DotnetFrameworkVersion, DotnetSdkVersion, Architecture); } } void RunBenchmarks(ITestOutputHelper output) { output.WriteLine(""); output.WriteLine(" === EXECUTION ==="); output.WriteLine(""); foreach (Benchmark benchmark in Benchmarks) { BenchmarkRunResults.AddRange(benchmark.Run(this, output)); } } public void WriteBenchmarkResults(ITestOutputHelper output) { output.WriteLine(""); output.WriteLine(" === RESULTS ==="); output.WriteLine(""); WriteBenchmarkResultsTable((b, m) => b.GetDefaultDisplayMetrics().Any(metric => metric.Equals(m)), output); } void WriteBenchmarkResultsTable(Func<Benchmark,Metric, bool> primaryMetricSelector, ITestOutputHelper output) { List<ResultTableRowModel> rows = BuildRowModels(primaryMetricSelector); List<ResultTableColumn> columns = BuildColumns(); List<List<string>> formattedCells = new List<List<string>>(); List<string> headerCells = new List<string>(); foreach(var column in columns) { headerCells.Add(column.Heading); } formattedCells.Add(headerCells); foreach(var row in rows) { List<string> rowFormattedCells = new List<string>(); foreach(var column in columns) { rowFormattedCells.Add(column.CellFormatter(row)); } formattedCells.Add(rowFormattedCells); } StringBuilder headerRow = new StringBuilder(); StringBuilder headerRowUnderline = new StringBuilder(); StringBuilder rowFormat = new StringBuilder(); for (int j = 0; j < columns.Count; j++) { int columnWidth = Enumerable.Range(0, formattedCells.Count).Select(i => formattedCells[i][j].Length).Max(); int hw = headerCells[j].Length; headerRow.Append(headerCells[j].PadLeft(hw + (columnWidth - hw) / 2).PadRight(columnWidth + 2)); headerRowUnderline.Append(new string('-', columnWidth) + " "); rowFormat.Append("{" + j + "," + columnWidth + "} "); } output.WriteLine(headerRow.ToString()); output.WriteLine(headerRowUnderline.ToString()); for(int i = 1; i < formattedCells.Count; i++) { output.WriteLine(string.Format(rowFormat.ToString(), formattedCells[i].ToArray())); } } List<ResultTableRowModel> BuildRowModels(Func<Benchmark, Metric, bool> primaryMetricSelector) { List<ResultTableRowModel> rows = new List<ResultTableRowModel>(); foreach (Benchmark benchmark in Benchmarks) { BenchmarkRunResult canonResult = BenchmarkRunResults.Where(r => r.Benchmark == benchmark).FirstOrDefault(); if (canonResult == null || canonResult.IterationResults == null || canonResult.IterationResults.Count == 0) { continue; } IterationResult canonIteration = canonResult.IterationResults[0]; foreach (Metric metric in canonIteration.Measurements.Keys) { if (primaryMetricSelector(benchmark, metric)) { rows.Add(new ResultTableRowModel() { Benchmark = benchmark, Metric = metric }); } } } return rows; } List<ResultTableColumn> BuildColumns() { List<ResultTableColumn> columns = new List<ResultTableColumn>(); ResultTableColumn benchmarkColumn = new ResultTableColumn(); benchmarkColumn.Heading = "Benchmark"; benchmarkColumn.CellFormatter = row => row.Benchmark.Name; columns.Add(benchmarkColumn); ResultTableColumn metricNameColumn = new ResultTableColumn(); metricNameColumn.Heading = "Metric"; metricNameColumn.CellFormatter = row => $"{row.Metric.Name} ({row.Metric.Unit})"; columns.Add(metricNameColumn); foreach(BenchmarkConfiguration config in Configurations) { ResultTableColumn column = new ResultTableColumn(); column.Heading = config.Name; column.CellFormatter = row => { var runResult = BenchmarkRunResults.Where(r => r.Benchmark == row.Benchmark && r.Configuration == config).Single(); var measurements = runResult.IterationResults.Skip(1).Select(r => r.Measurements.Where(kv => kv.Key.Equals(row.Metric)).Single()).Select(kv => kv.Value); double median = measurements.Median(); double q1 = measurements.Quartile1(); double q3 = measurements.Quartile3(); int digits = Math.Min(Math.Max(0, (int)Math.Ceiling(-Math.Log10(q3-q1) + 1)), 15); return $"{Math.Round(median, digits)} ({Math.Round(q1, digits)}-{Math.Round(q3, digits)})"; }; columns.Add(column); } return columns; } class ResultTableRowModel { public Benchmark Benchmark; public Metric Metric; } class ResultTableColumn { public string Heading; public Func<ResultTableRowModel, string> CellFormatter; } } }
42.421986
192
0.564491
[ "MIT" ]
Alecu100/coreclr
tests/src/performance/Scenario/JitBench/Runner/TestRun.cs
11,965
C#
namespace SitecoreCognitiveServices.Feature.IntelligentMedia.Areas.SitecoreCognitiveServices.Models { public interface IImageSearchJsonResult { string Url { get; set; } string Alt { get; set; } string Id { get; set; } string Title { get; set; } } }
29.3
100
0.651877
[ "MIT" ]
markstiles/SitecoreCognitiveServices.IntelligentMedia
code/Areas/SitecoreCognitiveServices/Models/IImageSearchJsonResult.cs
295
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; namespace Formula.SimpleAuthServerUI { public class ConsentInputModel { public string Button { get; set; } public IEnumerable<string> ScopesConsented { get; set; } public bool RememberConsent { get; set; } public string ReturnUrl { get; set; } } }
31.5625
107
0.69703
[ "Apache-2.0" ]
NephosIntegration/Formula.SimpleAuthServerUI
Controllers/Consent/ConsentInputModel.cs
507
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Iam { public static class GetPolicyDocument { /// <summary> /// Generates an IAM policy document in JSON format for use with resources that expect policy documents such as `aws.iam.Policy`. /// /// Using this data source to generate policy documents is *optional*. It is also valid to use literal JSON strings in your configuration or to use the `file` interpolation function to read a raw JSON policy document from a file. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// ### Basic Example /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var examplePolicyDocument = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "1", /// Actions = /// { /// "s3:ListAllMyBuckets", /// "s3:GetBucketLocation", /// }, /// Resources = /// { /// "arn:aws:s3:::*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "s3:ListBucket", /// }, /// Resources = /// { /// $"arn:aws:s3:::{@var.S3_bucket_name}", /// }, /// Conditions = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementConditionArgs /// { /// Test = "StringLike", /// Variable = "s3:prefix", /// Values = /// { /// "", /// "home/", /// "home/&amp;{aws:username}/", /// }, /// }, /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// $"arn:aws:s3:::{@var.S3_bucket_name}/home/&amp;{{aws:username}}", /// $"arn:aws:s3:::{@var.S3_bucket_name}/home/&amp;{{aws:username}}/*", /// }, /// }, /// }, /// })); /// var examplePolicy = new Aws.Iam.Policy("examplePolicy", new Aws.Iam.PolicyArgs /// { /// Path = "/", /// Policy = examplePolicyDocument.Apply(examplePolicyDocument =&gt; examplePolicyDocument.Json), /// }); /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Assume-Role Policy with Multiple Principals /// /// You can specify multiple principal blocks with different types. You can also use this data source to generate an assume-role policy. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var eventStreamBucketRoleAssumeRolePolicy = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "sts:AssumeRole", /// }, /// Principals = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "Service", /// Identifiers = /// { /// "firehose.amazonaws.com", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "AWS", /// Identifiers = /// { /// @var.Trusted_role_arn, /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "Federated", /// Identifiers = /// { /// $"arn:aws:iam::{@var.Account_id}:saml-provider/{@var.Provider_name}", /// "cognito-identity.amazonaws.com", /// }, /// }, /// }, /// }, /// }, /// })); /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Using A Source Document /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var source = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var sourceJsonExample = source.Apply(source =&gt; Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourceJson = source.Json, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "arn:aws:s3:::somebucket", /// "arn:aws:s3:::somebucket/*", /// }, /// }, /// }, /// }))); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.source_json_example.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Using An Override Document /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var @override = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var overrideJsonExample = @override.Apply(@override =&gt; Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// OverrideJson = @override.Json, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "arn:aws:s3:::somebucket", /// "arn:aws:s3:::somebucket/*", /// }, /// }, /// }, /// }))); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.override_json_example.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example with Both Source and Override Documents /// /// You can also combine `source_json` and `override_json` in the same document. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var source = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceholder", /// Actions = /// { /// "ec2:DescribeAccountAttributes", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var @override = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceholder", /// Actions = /// { /// "s3:GetObject", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var politik = Output.Tuple(source, @override).Apply(values =&gt; /// { /// var source = values.Item1; /// var @override = values.Item2; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourceJson = source.Json, /// OverrideJson = @override.Json, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.politik.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example of Merging Source Documents /// /// Multiple documents can be combined using the `source_policy_documents` or `override_policy_documents` attributes. `source_policy_documents` requires that all documents have unique Sids, while `override_policy_documents` will iteratively override matching Sids. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var sourceOne = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "UniqueSidOne", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var sourceTwo = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "UniqueSidTwo", /// Actions = /// { /// "iam:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "lambda:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var combined = Output.Tuple(sourceOne, sourceTwo).Apply(values =&gt; /// { /// var sourceOne = values.Item1; /// var sourceTwo = values.Item2; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourcePolicyDocuments = /// { /// sourceOne.Json, /// sourceTwo.Json, /// }, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.combined.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example of Merging Override Documents /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var policyOne = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderOne", /// Effect = "Allow", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var policyTwo = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Effect = "Allow", /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderTwo", /// Effect = "Allow", /// Actions = /// { /// "iam:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var policyThree = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderOne", /// Effect = "Deny", /// Actions = /// { /// "logs:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var combined = Output.Tuple(policyOne, policyTwo, policyThree).Apply(values =&gt; /// { /// var policyOne = values.Item1; /// var policyTwo = values.Item2; /// var policyThree = values.Item3; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// OverridePolicyDocuments = /// { /// policyOne.Json, /// policyTwo.Json, /// policyThree.Json, /// }, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderTwo", /// Effect = "Deny", /// Actions = /// { /// "*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.combined.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Task<GetPolicyDocumentResult> InvokeAsync(GetPolicyDocumentArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPolicyDocumentResult>("aws:iam/getPolicyDocument:getPolicyDocument", args ?? new GetPolicyDocumentArgs(), options.WithDefaults()); /// <summary> /// Generates an IAM policy document in JSON format for use with resources that expect policy documents such as `aws.iam.Policy`. /// /// Using this data source to generate policy documents is *optional*. It is also valid to use literal JSON strings in your configuration or to use the `file` interpolation function to read a raw JSON policy document from a file. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// ### Basic Example /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var examplePolicyDocument = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "1", /// Actions = /// { /// "s3:ListAllMyBuckets", /// "s3:GetBucketLocation", /// }, /// Resources = /// { /// "arn:aws:s3:::*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "s3:ListBucket", /// }, /// Resources = /// { /// $"arn:aws:s3:::{@var.S3_bucket_name}", /// }, /// Conditions = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementConditionArgs /// { /// Test = "StringLike", /// Variable = "s3:prefix", /// Values = /// { /// "", /// "home/", /// "home/&amp;{aws:username}/", /// }, /// }, /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// $"arn:aws:s3:::{@var.S3_bucket_name}/home/&amp;{{aws:username}}", /// $"arn:aws:s3:::{@var.S3_bucket_name}/home/&amp;{{aws:username}}/*", /// }, /// }, /// }, /// })); /// var examplePolicy = new Aws.Iam.Policy("examplePolicy", new Aws.Iam.PolicyArgs /// { /// Path = "/", /// Policy = examplePolicyDocument.Apply(examplePolicyDocument =&gt; examplePolicyDocument.Json), /// }); /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Assume-Role Policy with Multiple Principals /// /// You can specify multiple principal blocks with different types. You can also use this data source to generate an assume-role policy. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var eventStreamBucketRoleAssumeRolePolicy = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "sts:AssumeRole", /// }, /// Principals = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "Service", /// Identifiers = /// { /// "firehose.amazonaws.com", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "AWS", /// Identifiers = /// { /// @var.Trusted_role_arn, /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalArgs /// { /// Type = "Federated", /// Identifiers = /// { /// $"arn:aws:iam::{@var.Account_id}:saml-provider/{@var.Provider_name}", /// "cognito-identity.amazonaws.com", /// }, /// }, /// }, /// }, /// }, /// })); /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Using A Source Document /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var source = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var sourceJsonExample = source.Apply(source =&gt; Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourceJson = source.Json, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "arn:aws:s3:::somebucket", /// "arn:aws:s3:::somebucket/*", /// }, /// }, /// }, /// }))); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.source_json_example.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example Using An Override Document /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var @override = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var overrideJsonExample = @override.Apply(@override =&gt; Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// OverrideJson = @override.Json, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "SidToOverride", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "arn:aws:s3:::somebucket", /// "arn:aws:s3:::somebucket/*", /// }, /// }, /// }, /// }))); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.override_json_example.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example with Both Source and Override Documents /// /// You can also combine `source_json` and `override_json` in the same document. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var source = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceholder", /// Actions = /// { /// "ec2:DescribeAccountAttributes", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var @override = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceholder", /// Actions = /// { /// "s3:GetObject", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var politik = Output.Tuple(source, @override).Apply(values =&gt; /// { /// var source = values.Item1; /// var @override = values.Item2; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourceJson = source.Json, /// OverrideJson = @override.Json, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.politik.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example of Merging Source Documents /// /// Multiple documents can be combined using the `source_policy_documents` or `override_policy_documents` attributes. `source_policy_documents` requires that all documents have unique Sids, while `override_policy_documents` will iteratively override matching Sids. /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var sourceOne = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "UniqueSidOne", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var sourceTwo = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "UniqueSidTwo", /// Actions = /// { /// "iam:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Actions = /// { /// "lambda:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var combined = Output.Tuple(sourceOne, sourceTwo).Apply(values =&gt; /// { /// var sourceOne = values.Item1; /// var sourceTwo = values.Item2; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// SourcePolicyDocuments = /// { /// sourceOne.Json, /// sourceTwo.Json, /// }, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.combined.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% example %}} /// ### Example of Merging Override Documents /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var policyOne = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderOne", /// Effect = "Allow", /// Actions = /// { /// "s3:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var policyTwo = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Effect = "Allow", /// Actions = /// { /// "ec2:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderTwo", /// Effect = "Allow", /// Actions = /// { /// "iam:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var policyThree = Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderOne", /// Effect = "Deny", /// Actions = /// { /// "logs:*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// var combined = Output.Tuple(policyOne, policyTwo, policyThree).Apply(values =&gt; /// { /// var policyOne = values.Item1; /// var policyTwo = values.Item2; /// var policyThree = values.Item3; /// return Output.Create(Aws.Iam.GetPolicyDocument.InvokeAsync(new Aws.Iam.GetPolicyDocumentArgs /// { /// OverridePolicyDocuments = /// { /// policyOne.Json, /// policyTwo.Json, /// policyThree.Json, /// }, /// Statements = /// { /// new Aws.Iam.Inputs.GetPolicyDocumentStatementArgs /// { /// Sid = "OverridePlaceHolderTwo", /// Effect = "Deny", /// Actions = /// { /// "*", /// }, /// Resources = /// { /// "*", /// }, /// }, /// }, /// })); /// }); /// } /// /// } /// ``` /// /// `data.aws_iam_policy_document.combined.json` will evaluate to: /// /// ```csharp /// using Pulumi; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Output<GetPolicyDocumentResult> Invoke(GetPolicyDocumentInvokeArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.Invoke<GetPolicyDocumentResult>("aws:iam/getPolicyDocument:getPolicyDocument", args ?? new GetPolicyDocumentInvokeArgs(), options.WithDefaults()); } public sealed class GetPolicyDocumentArgs : Pulumi.InvokeArgs { /// <summary> /// IAM policy document whose statements with non-blank `sid`s will override statements with the same `sid` from documents assigned to the `source_json`, `source_policy_documents`, and `override_policy_documents` arguments. Non-overriding statements will be added to the exported document. /// </summary> [Input("overrideJson")] public string? OverrideJson { get; set; } [Input("overridePolicyDocuments")] private List<string>? _overridePolicyDocuments; /// <summary> /// List of IAM policy documents that are merged together into the exported document. In merging, statements with non-blank `sid`s will override statements with the same `sid` from earlier documents in the list. Statements with non-blank `sid`s will also override statements with the same `sid` from documents provided in the `source_json` and `source_policy_documents` arguments. Non-overriding statements will be added to the exported document. /// </summary> public List<string> OverridePolicyDocuments { get => _overridePolicyDocuments ?? (_overridePolicyDocuments = new List<string>()); set => _overridePolicyDocuments = value; } /// <summary> /// ID for the policy document. /// </summary> [Input("policyId")] public string? PolicyId { get; set; } /// <summary> /// IAM policy document used as a base for the exported policy document. Statements with the same `sid` from documents assigned to the `override_json` and `override_policy_documents` arguments will override source statements. /// </summary> [Input("sourceJson")] public string? SourceJson { get; set; } [Input("sourcePolicyDocuments")] private List<string>? _sourcePolicyDocuments; /// <summary> /// List of IAM policy documents that are merged together into the exported document. Statements defined in `source_policy_documents` or `source_json` must have unique `sid`s. Statements with the same `sid` from documents assigned to the `override_json` and `override_policy_documents` arguments will override source statements. /// </summary> public List<string> SourcePolicyDocuments { get => _sourcePolicyDocuments ?? (_sourcePolicyDocuments = new List<string>()); set => _sourcePolicyDocuments = value; } [Input("statements")] private List<Inputs.GetPolicyDocumentStatementArgs>? _statements; /// <summary> /// Configuration block for a policy statement. Detailed below. /// </summary> public List<Inputs.GetPolicyDocumentStatementArgs> Statements { get => _statements ?? (_statements = new List<Inputs.GetPolicyDocumentStatementArgs>()); set => _statements = value; } /// <summary> /// IAM policy document version. Valid values are `2008-10-17` and `2012-10-17`. Defaults to `2012-10-17`. For more information, see the [AWS IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html). /// </summary> [Input("version")] public string? Version { get; set; } public GetPolicyDocumentArgs() { } } public sealed class GetPolicyDocumentInvokeArgs : Pulumi.InvokeArgs { /// <summary> /// IAM policy document whose statements with non-blank `sid`s will override statements with the same `sid` from documents assigned to the `source_json`, `source_policy_documents`, and `override_policy_documents` arguments. Non-overriding statements will be added to the exported document. /// </summary> [Input("overrideJson")] public Input<string>? OverrideJson { get; set; } [Input("overridePolicyDocuments")] private InputList<string>? _overridePolicyDocuments; /// <summary> /// List of IAM policy documents that are merged together into the exported document. In merging, statements with non-blank `sid`s will override statements with the same `sid` from earlier documents in the list. Statements with non-blank `sid`s will also override statements with the same `sid` from documents provided in the `source_json` and `source_policy_documents` arguments. Non-overriding statements will be added to the exported document. /// </summary> public InputList<string> OverridePolicyDocuments { get => _overridePolicyDocuments ?? (_overridePolicyDocuments = new InputList<string>()); set => _overridePolicyDocuments = value; } /// <summary> /// ID for the policy document. /// </summary> [Input("policyId")] public Input<string>? PolicyId { get; set; } /// <summary> /// IAM policy document used as a base for the exported policy document. Statements with the same `sid` from documents assigned to the `override_json` and `override_policy_documents` arguments will override source statements. /// </summary> [Input("sourceJson")] public Input<string>? SourceJson { get; set; } [Input("sourcePolicyDocuments")] private InputList<string>? _sourcePolicyDocuments; /// <summary> /// List of IAM policy documents that are merged together into the exported document. Statements defined in `source_policy_documents` or `source_json` must have unique `sid`s. Statements with the same `sid` from documents assigned to the `override_json` and `override_policy_documents` arguments will override source statements. /// </summary> public InputList<string> SourcePolicyDocuments { get => _sourcePolicyDocuments ?? (_sourcePolicyDocuments = new InputList<string>()); set => _sourcePolicyDocuments = value; } [Input("statements")] private InputList<Inputs.GetPolicyDocumentStatementInputArgs>? _statements; /// <summary> /// Configuration block for a policy statement. Detailed below. /// </summary> public InputList<Inputs.GetPolicyDocumentStatementInputArgs> Statements { get => _statements ?? (_statements = new InputList<Inputs.GetPolicyDocumentStatementInputArgs>()); set => _statements = value; } /// <summary> /// IAM policy document version. Valid values are `2008-10-17` and `2012-10-17`. Defaults to `2012-10-17`. For more information, see the [AWS IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html). /// </summary> [Input("version")] public Input<string>? Version { get; set; } public GetPolicyDocumentInvokeArgs() { } } [OutputType] public sealed class GetPolicyDocumentResult { /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; /// <summary> /// Standard JSON policy document rendered based on the arguments above. /// </summary> public readonly string Json; public readonly string? OverrideJson; public readonly ImmutableArray<string> OverridePolicyDocuments; public readonly string? PolicyId; public readonly string? SourceJson; public readonly ImmutableArray<string> SourcePolicyDocuments; public readonly ImmutableArray<Outputs.GetPolicyDocumentStatementResult> Statements; public readonly string? Version; [OutputConstructor] private GetPolicyDocumentResult( string id, string json, string? overrideJson, ImmutableArray<string> overridePolicyDocuments, string? policyId, string? sourceJson, ImmutableArray<string> sourcePolicyDocuments, ImmutableArray<Outputs.GetPolicyDocumentStatementResult> statements, string? version) { Id = id; Json = json; OverrideJson = overrideJson; OverridePolicyDocuments = overridePolicyDocuments; PolicyId = policyId; SourceJson = sourceJson; SourcePolicyDocuments = sourcePolicyDocuments; Statements = statements; Version = version; } } }
40.681058
455
0.338629
[ "ECL-2.0", "Apache-2.0" ]
dmelo/pulumi-aws
sdk/dotnet/Iam/GetPolicyDocument.cs
58,418
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CharacterNameSpace.Stats { //determines speed and hit/miss chances public class SkillStat : Stat { [Tooltip("max is the miss chance at max skill")] public Vector3 missChanceRanges = new Vector2(.1f,0.5f); // Use this for initialization public override float MissOutCome() { float t = Mathf.InverseLerp((float)minValue,(float)maxValue,(float)value); return missChanceRanges.y - Mathf.Lerp(missChanceRanges.x, missChanceRanges.y, t); } } }
29.428571
94
0.668285
[ "MIT" ]
Therdre/LD41
Assets/Characters/Scripts/Stats/SkillStat.cs
620
C#
using System; using NUnit.Framework; using System.IO; using System.Linq; using Elektronik.Protobuf.Data; using Google.Protobuf; namespace Protobuf.Tests { public class TrackedObjsTests : TestsBase { private readonly TrackedObjPb[] _objects; private readonly string _filename = $"{nameof(TrackedObjsTests)}.dat"; private static int _timestamp = 0; private static readonly Random Rand = new Random(); public TrackedObjsTests() { _objects = Enumerable.Range(0, 3).Select(id => new TrackedObjPb() { Id = id, Rotation = new Vector4Pb() {W = 1,}, Translation = new Vector3Pb(), }).ToArray(); } [Test, Order(1)] public void Create() { var packet = new PacketPb() { Action = PacketPb.Types.ActionType.Add, TrackedObjs = new PacketPb.Types.TrackedObjs(), Timestamp = ++_timestamp, Special = true, }; _objects[0].Translation = new Vector3Pb(); _objects[1].Translation = new Vector3Pb() {X = 0.5,}; _objects[2].Translation = new Vector3Pb() {X = -0.5,}; _objects[0].TrackColor = new ColorPb() {R = 255,}; _objects[1].TrackColor = new ColorPb() {G = 255,}; _objects[2].TrackColor = new ColorPb() {B = 255,}; packet.TrackedObjs.Data.Add(_objects); using var file = File.Open(_filename, FileMode.Create); packet.WriteDelimitedTo(file); var response = MapClient.Handle(packet); Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message); } [Test, Order(2)] public void Update() { var packet = new PacketPb() { Action = PacketPb.Types.ActionType.Update, TrackedObjs = new PacketPb.Types.TrackedObjs(), Timestamp = ++_timestamp, Special = true, }; _objects[0].Translation = new Vector3Pb() {X = 0.0, Z = 0.5}; _objects[1].Translation = new Vector3Pb() {X = 0.5, Z = 0.5}; _objects[2].Translation = new Vector3Pb() {X = -0.5, Z = 0.5}; packet.TrackedObjs.Data.Clear(); packet.TrackedObjs.Data.Add(_objects); var response = MapClient.Handle(packet); using var file = File.Open(_filename, FileMode.Append); packet.WriteDelimitedTo(file); Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message); } [Test, Order(3), Repeat(5)] public void UpdateRandom() { var packet = new PacketPb() { Action = PacketPb.Types.ActionType.Update, TrackedObjs = new PacketPb.Types.TrackedObjs(), Timestamp = ++_timestamp, }; _objects[0].Translation = new Vector3Pb() {X = Rand.NextDouble(), Y = Rand.NextDouble(), Z = Rand.NextDouble()}; _objects[1].Translation = new Vector3Pb() {X = Rand.NextDouble(), Y = Rand.NextDouble(), Z = Rand.NextDouble()}; _objects[2].Translation = new Vector3Pb() {X = Rand.NextDouble(), Y = Rand.NextDouble(), Z = Rand.NextDouble()}; packet.TrackedObjs.Data.Clear(); packet.TrackedObjs.Data.Add(_objects); var response = MapClient.Handle(packet); using var file = File.Open(_filename, FileMode.Append); packet.WriteDelimitedTo(file); Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message); } [Test, Order(4)] public void Remove() { var packet = new PacketPb() { Action = PacketPb.Types.ActionType.Remove, TrackedObjs = new PacketPb.Types.TrackedObjs(), Timestamp = ++_timestamp, Special = true, }; packet.TrackedObjs.Data.Add(new[] {_objects[1]}); var response = MapClient.Handle(packet); using var file = File.Open(_filename, FileMode.Append); packet.WriteDelimitedTo(file); Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message); } [Test, Order(5)] public void Clear() { var packet = new PacketPb() { Action = PacketPb.Types.ActionType.Clear, TrackedObjs = new PacketPb.Types.TrackedObjs(), Timestamp = ++_timestamp, Special = true, }; var response = MapClient.Handle(packet); using var file = File.Open(_filename, FileMode.Append); packet.WriteDelimitedTo(file); Assert.True(response.ErrType == ErrorStatusPb.Types.ErrorStatusEnum.Succeeded, response.Message); } } }
39.360902
109
0.540974
[ "MIT" ]
KrasnovPavel/Elektronik-Tools-2.0
plugins/Protobuf.Tests/TrackedObjsTests.cs
5,237
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Ordering.Domain.Entities; namespace Ordering.Infrastructure.Persistence { public class OrderContextSeed { public static async Task SeedAsync(OrderContext context, ILogger<OrderContextSeed> logger) { if (!context.Orders.Any()) { context.Orders.AddRange(GetPreconfiguredOrders()); await context.SaveChangesAsync(); logger.LogInformation("Seed database associated with context {DbContextName}", typeof(OrderContext).Name); } } private static IEnumerable<Order> GetPreconfiguredOrders() { return new List<Order> { new Order{UserName = "swn", FirstName = "Burak", LastName = "Neiş", EmailAddress = "vexildar@gmail.com", AddressLine = "Karşıyaka", TotalPrice = 450 } }; } } }
33.933333
166
0.636542
[ "MIT" ]
neisburak/aspnet-microservices
src/services/Ordering/Ordering.Infrastructure/Persistence/OrderContextSeed.cs
1,021
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; using Titan.Blog.Infrastructure.Utility; namespace Titan.Blog.WebAPP.Auth.JWT { public class JwtHelper { /// <summary> /// 颁发JWT字符串 /// </summary> /// <param name="tokenModel"></param> /// <returns></returns> public static string IssueJWT(TokenModelJWT tokenModel) { var dateTime = DateTime.UtcNow; string iss = Appsettings.app(new string[] { "Audience", "Issuer" }); string aud = Appsettings.app(new string[] { "Audience", "Audience" }); string secret = Appsettings.app(new string[] { "Audience", "Secret" }); //var claims = new Claim[] //old var claims = new List<Claim> { //下边为Claim的默认配置 new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()), new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") , //这个就是过期时间,目前是过期100秒,可自定义,注意JWT有自己的缓冲过期时间 new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(100)).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Iss,iss), new Claim(JwtRegisteredClaimNames.Aud,aud), //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法 }; // 可以将一个用户的多个角色全部赋予; // 作者:DX 提供技术支持; claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //秘钥 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwt = new JwtSecurityToken( issuer: iss, claims: claims, signingCredentials: creds); var jwtHandler = new JwtSecurityTokenHandler(); var encodedJwt = jwtHandler.WriteToken(jwt); return encodedJwt; } /// <summary> /// 解析 /// </summary> /// <param name="jwtStr"></param> /// <returns></returns> public static TokenModelJWT SerializeJWT(string jwtStr) { var jwtHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr); object role = new object(); ; try { jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role); } catch (Exception e) { Console.WriteLine(e); throw; } var tm = new TokenModelJWT { Uid = (jwtToken.Id).ObjToInt(), Role = role != null ? role.ObjToString() : "", }; return tm; } } /// <summary> /// 令牌 /// </summary> public class TokenModelJWT { /// <summary> /// Id /// </summary> public long Uid { get; set; } /// <summary> /// 角色 /// </summary> public string Role { get; set; } /// <summary> /// 职能 /// </summary> public string Work { get; set; } } }
32.294643
130
0.539121
[ "Apache-2.0" ]
HanJunJun/Titan.Blog.WebAPP
Titan.Blog.WebAPP/Titan.Blog.WebAPP/Auth/JWT/JwtHelper.cs
3,829
C#
/*<FILE_LICENSE> * NFX (.NET Framework Extension) Unistack Library * Copyright 2003-2014 IT Adapter Inc / 2015 Aum Code LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. </FILE_LICENSE>*/ 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("NFX.NUnit.Integration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IT Adapter Corp. Inc.")] [assembly: AssemblyProduct("NFX.NUnit.Integration")] [assembly: AssemblyCopyright("Copyright © 2003-2015 IT Adapter Corp. Inc.")] [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("3751e4c9-e5a4-468c-9210-e8076baa114c")] // 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("2.0.0.1")] [assembly: AssemblyFileVersion("2.0.0.1")]
41.471698
85
0.733849
[ "Apache-2.0" ]
PavelTorgashov/nfx
Source/Testing/NUnit/NFX.NUnit.Integration/Properties/AssemblyInfo.cs
2,199
C#
namespace ModManagerUlt { internal class XmlWriter { } }
17
31
0.647059
[ "BSD-3-Clause" ]
diehard3303/ModManagerUlt
XmlWriter.cs
70
C#
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.Data.Entity; namespace SmartLMS.Models { public enum UserRoles { Administrator = 1, Manager = 2, Lecturer = 4, User = 8, } public class ApplicationUser : IdentityUser { public bool ConfirmedEmail { get; set; } public ICollection<StudentAssignment> Assignments { get; set; } public virtual ICollection<StudentCourse> Courses { get; set; } public ICollection<StudentQuiz> Quiz { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return userIdentity; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public DbSet<Course> Courses { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Question> Questions { get; set; } public DbSet<AnswerChoice> Answerchoices { get; set; } public DbSet<Quiz> Quiz { get; set; } public DbSet<Assignment> Assignment { get; set; } public DbSet<Certificate> Certificates { get; set; } public DbSet<Contact> Contact { get; set; } public DbSet<Lecture> Lectures { get; set; } public DbSet<Subscribe> Subscribe { get; set; } public DbSet<StudentCourse> StudentCourses { get; set; } public DbSet<StudentQuiz> StudentQuiz { get; set; } public DbSet<ADLog> ADLogs { get; set; } public DbSet<Rating> Ratings { get; set; } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<StudentCourse>() .HasKey(t => new { t.StudentId, t.CourseId }); modelBuilder.Entity<StudentCourse>() .HasRequired(pt => pt.Student) .WithMany(p => p.Courses) .HasForeignKey(pt => pt.StudentId); modelBuilder.Entity<StudentCourse>() .HasRequired(pt => pt.Course) .WithMany(t => t.Enrollments) .HasForeignKey(pt => pt.CourseId); modelBuilder.Entity<StudentQuiz>() .HasKey(t => new { t.StudentId, t.QuizId }); modelBuilder.Entity<StudentQuiz>() .HasRequired(pt => pt.Student) .WithMany(p => p.Quiz) .HasForeignKey(pt => pt.StudentId); modelBuilder.Entity<StudentQuiz>() .HasRequired(pt => pt.Quiz) .WithMany(t => t.Students) .HasForeignKey(pt => pt.QuizId); modelBuilder.Entity<StudentAssignment>() .HasKey(t => new { t.StudentId, t.AssignmentId }); modelBuilder.Entity<StudentAssignment>() .HasRequired(pt => pt.Student) .WithMany(p => p.Assignments) .HasForeignKey(pt => pt.StudentId); modelBuilder.Entity<StudentAssignment>() .HasRequired(pt => pt.Assignment) .WithMany(t => t.Students) .HasForeignKey(pt => pt.AssignmentId); } } }
38.608696
132
0.591441
[ "MIT" ]
arifgit12/SmartLMS
SmartLMS/Models/IdentityModels.cs
4,442
C#
using System; using System.Linq; namespace _2._Knights_of_Honor { class Program { static void Main(string[] args) { Action<string> honor = (name) => { Console.WriteLine($"Sir " + name); }; Console.ReadLine() .Split(' ', StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(honor); } } }
21.047619
66
0.470588
[ "MIT" ]
dimitarkolev00/SoftUni-Advanced
04.Functional Programming/P02.Knights of Honor/Program.cs
444
C#
namespace TeisterMask.Data.Models { using System.ComponentModel.DataAnnotations.Schema; public class EmployeeTask { [ForeignKey(nameof(Employee))] public int EmployeeId { get; set; } public virtual Employee Employee { get; set; } [ForeignKey(nameof(Task))] public int TaskId { get; set; } public virtual Task Task { get; set; } } }
22.277778
55
0.625935
[ "MIT" ]
A-Manev/SoftUni-CSharp-Advanced-january-2020
CSharp Databases - MS SQL Server/Databases Advanced/00. Exams/02. CSharp DB Advanced Exam - 07 Dec 2019/TeisterMask/Data/Models/EmployeeTask.cs
403
C#
using LifeCycleWorkflowBackend.Settings.OperationSettings.OperationType; using LifeCycleWorkflowBackend.Settings.OperationSettings.OperationType.OperationTypeComponents; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LifeCycleWorkflowBackend.Settings.DefaultSettings { public class DataSourceTypeOperationBuilder { private DataSourceTypeOperation _typeOperation; private WipSheetWithDataSettings _wipSheet; private DataSourceSheetSettings _dataSource; private FinalSheetSettings _finalSheet; public DataSourceTypeOperationBuilder BuildReportSheetSetting(string sheetName, int headerRow, int writingRow, int formulaRow, int referenceRow, string readingAddress) { _wipSheet = new WipSheetWithDataSettings( worksheetName: sheetName, headerRow: headerRow, formulaRow: formulaRow, referenceRow: referenceRow, writingRow: writingRow, readingAddress: readingAddress ); return this; } public DataSourceTypeOperationBuilder BuildWipSheetSetting(string sheetName, int headerRow, int writingRow, int formulaRow, int referenceRow, string readingAddress) { _wipSheet = new WipSheetWithDataSettings( worksheetName: sheetName, headerRow: headerRow, formulaRow: formulaRow, referenceRow: referenceRow, writingRow: writingRow, readingAddress: readingAddress ); return this; } public DataSourceTypeOperationBuilder BuildFinalSheetSettings(string sheetName, string writingAddress) { _finalSheet = new FinalSheetSettings( worksheetName: sheetName, writingAddress: writingAddress ); return this; } public DataSourceTypeOperationBuilder BuildDataSheetSetting(string sheetName, int headerRow, int writingRow) { _dataSource = new DataSourceSheetSettings ( writingRow: writingRow, headerRow: headerRow, sheetname: sheetName ); return this; } public DataSourceTypeOperation Build() { if (_wipSheet != null && _finalSheet != null && _dataSource != null) { _typeOperation = new DataSourceTypeOperation( wipSettings: _wipSheet, finalSettings: _finalSheet, dataSourceSettings: _dataSource ); return _typeOperation; } else { throw new ArgumentException("Failed to build default Settings with DataSourceTypeBuilder"); } } } }
33.978022
107
0.594114
[ "MIT", "Unlicense" ]
alwaysmiddle/LifeCycleWorkflowTool
LifeCycleWorkflowBackend/Settings/DefaultSettings/Builders/DataSourceOperationTypeBuilder.cs
3,094
C#
using System; namespace ProjectServices.Application.Responses.Audit { public class AuditResponse { public int Id { get; set; } public string UserId { get; set; } public string Type { get; set; } public string TableName { get; set; } public DateTime DateTime { get; set; } public string OldValues { get; set; } public string NewValues { get; set; } public string AffectedColumns { get; set; } public string PrimaryKey { get; set; } } }
30.588235
53
0.609615
[ "MIT" ]
NguyenDuyCuong/projectservices
src/Application/Responses/Audit/AuditResponse.cs
522
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using neobooru.Models; namespace neobooru.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private string[] _subsectionPages = { "Home" }; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { ViewBag.SubsectionPages = _subsectionPages; ViewBag.ActiveSubpage = _subsectionPages[0]; return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
27.263158
113
0.633205
[ "MIT" ]
TheSlipper/neobooru
neobooru/Controllers/HomeController.cs
1,038
C#
using Kotocorn.Core.Services.Database.Models; namespace Kotocorn.Modules.Xp.Common { public class FullUserStats { public DiscordUser User { get; } public UserXpStats FullGuildStats { get; } public LevelStats Global { get; } public LevelStats Guild { get; } public int GlobalRanking { get; } public int GuildRanking { get; } public FullUserStats(DiscordUser usr, UserXpStats fullGuildStats, LevelStats global, LevelStats guild, int globalRanking, int guildRanking) { this.User = usr; this.Global = global; this.Guild = guild; this.GlobalRanking = globalRanking; this.GuildRanking = guildRanking; this.FullGuildStats = fullGuildStats; } } }
30.444444
66
0.610706
[ "MIT" ]
Erencorn/Kotocorn
NadekoBot.Core/Modules/Xp/Common/FullUserStats.cs
824
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace UiPath.Web.Client20204 { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Environments. /// </summary> public static partial class EnvironmentsExtensions { /// <summary> /// Gets Environments. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='filter'> /// Filters the results, based on a Boolean condition. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='orderby'> /// Sorts the results. /// </param> /// <param name='top'> /// Returns only the first n results. /// </param> /// <param name='skip'> /// Skips the first n results. /// </param> /// <param name='count'> /// Includes a count of the matching results in the response. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static ODataValueIEnumerableEnvironmentDto Get(this IEnvironments operations, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?)) { return operations.GetAsync(expand, filter, select, orderby, top, skip, count, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Gets Environments. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='filter'> /// Filters the results, based on a Boolean condition. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='orderby'> /// Sorts the results. /// </param> /// <param name='top'> /// Returns only the first n results. /// </param> /// <param name='skip'> /// Skips the first n results. /// </param> /// <param name='count'> /// Includes a count of the matching results in the response. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ODataValueIEnumerableEnvironmentDto> GetAsync(this IEnvironments operations, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(expand, filter, select, orderby, top, skip, count, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Post new environment /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Create. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='environmentDto'> /// The entity to post /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static EnvironmentDto Post(this IEnvironments operations, EnvironmentDto environmentDto, long? xUIPATHOrganizationUnitId = default(long?)) { return operations.PostAsync(environmentDto, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Post new environment /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Create. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='environmentDto'> /// The entity to post /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EnvironmentDto> PostAsync(this IEnvironments operations, EnvironmentDto environmentDto, long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostWithHttpMessagesAsync(environmentDto, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a single environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static EnvironmentDto GetById(this IEnvironments operations, long id, string expand = default(string), string select = default(string), long? xUIPATHOrganizationUnitId = default(long?)) { return operations.GetByIdAsync(id, expand, select, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Gets a single environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EnvironmentDto> GetByIdAsync(this IEnvironments operations, long id, string expand = default(string), string select = default(string), long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetByIdWithHttpMessagesAsync(id, expand, select, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='environmentDto'> /// The entity to put /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static void PutById(this IEnvironments operations, long id, EnvironmentDto environmentDto, long? xUIPATHOrganizationUnitId = default(long?)) { operations.PutByIdAsync(id, environmentDto, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Updates an environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='environmentDto'> /// The entity to put /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutByIdAsync(this IEnvironments operations, long id, EnvironmentDto environmentDto, long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.PutByIdWithHttpMessagesAsync(id, environmentDto, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Deletes an environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Delete. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='ifMatch'> /// If-Match header /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static void DeleteById(this IEnvironments operations, long id, string ifMatch = default(string), long? xUIPATHOrganizationUnitId = default(long?)) { operations.DeleteByIdAsync(id, ifMatch, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Deletes an environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Delete. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='ifMatch'> /// If-Match header /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteByIdAsync(this IEnvironments operations, long id, string ifMatch = default(string), long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.DeleteByIdWithHttpMessagesAsync(id, ifMatch, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns a collection of all robots and, if no other sorting is provided, /// will place first those belonging to the environment. Allows odata query /// options. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View and Robots.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// The Id of the environment for which the associated robots are placed first. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='filter'> /// Filters the results, based on a Boolean condition. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='orderby'> /// Sorts the results. /// </param> /// <param name='top'> /// Returns only the first n results. /// </param> /// <param name='skip'> /// Skips the first n results. /// </param> /// <param name='count'> /// Includes a count of the matching results in the odata-count header. /// </param> public static ODataValueIEnumerableRobotDto GetRobotsForEnvironmentByKey(this IEnvironments operations, long key, long? xUIPATHOrganizationUnitId = default(long?), string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?)) { return operations.GetRobotsForEnvironmentByKeyAsync(key, xUIPATHOrganizationUnitId, expand, filter, select, orderby, top, skip, count).GetAwaiter().GetResult(); } /// <summary> /// Returns a collection of all robots and, if no other sorting is provided, /// will place first those belonging to the environment. Allows odata query /// options. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View and Robots.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// The Id of the environment for which the associated robots are placed first. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='expand'> /// Expands related entities inline. /// </param> /// <param name='filter'> /// Filters the results, based on a Boolean condition. /// </param> /// <param name='select'> /// Selects which properties to include in the response. /// </param> /// <param name='orderby'> /// Sorts the results. /// </param> /// <param name='top'> /// Returns only the first n results. /// </param> /// <param name='skip'> /// Skips the first n results. /// </param> /// <param name='count'> /// Includes a count of the matching results in the odata-count header. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ODataValueIEnumerableRobotDto> GetRobotsForEnvironmentByKeyAsync(this IEnvironments operations, long key, long? xUIPATHOrganizationUnitId = default(long?), string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetRobotsForEnvironmentByKeyWithHttpMessagesAsync(key, xUIPATHOrganizationUnitId, expand, filter, select, orderby, top, skip, count, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns a collection of all the ids of the robots associated to an /// environment based on environment Id. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View and Robots.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// The Id of the environment for which the robot ids are fetched. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static ODataValueIEnumerableInt64 GetRobotIdsForEnvironmentByKey(this IEnvironments operations, long key, long? xUIPATHOrganizationUnitId = default(long?)) { return operations.GetRobotIdsForEnvironmentByKeyAsync(key, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Returns a collection of all the ids of the robots associated to an /// environment based on environment Id. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Read. /// /// Required permissions: Environments.View and Robots.View. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// The Id of the environment for which the robot ids are fetched. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ODataValueIEnumerableInt64> GetRobotIdsForEnvironmentByKeyAsync(this IEnvironments operations, long key, long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetRobotIdsForEnvironmentByKeyWithHttpMessagesAsync(key, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Associates a robot with the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='addRobotParameters'> /// RobotId - The associated robot Id. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static void AddRobotById(this IEnvironments operations, long id, AddRobotParameters addRobotParameters = default(AddRobotParameters), long? xUIPATHOrganizationUnitId = default(long?)) { operations.AddRobotByIdAsync(id, addRobotParameters, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Associates a robot with the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='addRobotParameters'> /// RobotId - The associated robot Id. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddRobotByIdAsync(this IEnvironments operations, long id, AddRobotParameters addRobotParameters = default(AddRobotParameters), long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.AddRobotByIdWithHttpMessagesAsync(id, addRobotParameters, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Dissociates a robot from the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='removeRobotParameters'> /// RobotId - The dissociated robot Id. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static void RemoveRobotById(this IEnvironments operations, long id, RemoveRobotParameters removeRobotParameters = default(RemoveRobotParameters), long? xUIPATHOrganizationUnitId = default(long?)) { operations.RemoveRobotByIdAsync(id, removeRobotParameters, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Dissociates a robot from the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='removeRobotParameters'> /// RobotId - The dissociated robot Id. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RemoveRobotByIdAsync(this IEnvironments operations, long id, RemoveRobotParameters removeRobotParameters = default(RemoveRobotParameters), long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.RemoveRobotByIdWithHttpMessagesAsync(id, removeRobotParameters, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Associates a group of robots with and dissociates another group of robots /// from the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='setRobotsParameters'> /// &lt;para /&gt;addedRobotIds - The id of the robots to be associated with /// the environment. /// &lt;para /&gt;removedRobotIds - The id of the robots to be dissociated from /// the environment. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> public static void SetRobotsById(this IEnvironments operations, long id, SetRobotsParameters setRobotsParameters, long? xUIPATHOrganizationUnitId = default(long?)) { operations.SetRobotsByIdAsync(id, setRobotsParameters, xUIPATHOrganizationUnitId).GetAwaiter().GetResult(); } /// <summary> /// Associates a group of robots with and dissociates another group of robots /// from the given environment. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Robots or Robots.Write. /// /// Required permissions: Environments.Edit. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='setRobotsParameters'> /// &lt;para /&gt;addedRobotIds - The id of the robots to be associated with /// the environment. /// &lt;para /&gt;removedRobotIds - The id of the robots to be dissociated from /// the environment. /// </param> /// <param name='xUIPATHOrganizationUnitId'> /// Folder/OrganizationUnit Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetRobotsByIdAsync(this IEnvironments operations, long id, SetRobotsParameters setRobotsParameters, long? xUIPATHOrganizationUnitId = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.SetRobotsByIdWithHttpMessagesAsync(id, setRobotsParameters, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
47.701095
508
0.549588
[ "MIT" ]
AFWberlin/orchestrator-powershell
UiPath.Web.Client/generated20204/EnvironmentsExtensions.cs
30,481
C#
using Windows.UI.Xaml.Controls; namespace UWPSample.Polar.Coordinates { public sealed partial class View : UserControl { public View() { InitializeComponent(); } } }
16.615385
50
0.592593
[ "MIT" ]
Live-Charts/LiveCharts2
samples/UWPSample/Polar/Coordinates/View.xaml.cs
218
C#
/* * OEML - REST API * * This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) * * The version of the OpenAPI document: v1 * Contact: support@coinapi.io * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = CoinAPI.OMS.API.SDK.Client.OpenAPIDateConverter; namespace CoinAPI.OMS.API.SDK.Model { /// <summary> /// The order execution report message. /// </summary> [DataContract(Name = "OrderExecutionReport_allOf")] public partial class OrderExecutionReportAllOf : IEquatable<OrderExecutionReportAllOf>, IValidatableObject { /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name = "status", IsRequired = true, EmitDefaultValue = false)] public OrdStatus Status { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OrderExecutionReportAllOf" /> class. /// </summary> [JsonConstructorAttribute] protected OrderExecutionReportAllOf() { } /// <summary> /// Initializes a new instance of the <see cref="OrderExecutionReportAllOf" /> class. /// </summary> /// <param name="clientOrderIdFormatExchange">The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. (required).</param> /// <param name="exchangeOrderId">Unique identifier of the order assigned by the exchange or executing system..</param> /// <param name="amountOpen">Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60; (required).</param> /// <param name="amountFilled">Total quantity filled. (required).</param> /// <param name="avgPx">Calculated average price of all fills on this order..</param> /// <param name="status">status (required).</param> /// <param name="statusHistory">Timestamped history of order status changes..</param> /// <param name="errorMessage">Error message..</param> /// <param name="fills">Relay fill information on working orders..</param> public OrderExecutionReportAllOf(string clientOrderIdFormatExchange = default(string), string exchangeOrderId = default(string), decimal amountOpen = default(decimal), decimal amountFilled = default(decimal), decimal avgPx = default(decimal), OrdStatus status = default(OrdStatus), List<List<string>> statusHistory = default(List<List<string>>), string errorMessage = default(string), List<Fills> fills = default(List<Fills>)) { // to ensure "clientOrderIdFormatExchange" is required (not null) this.ClientOrderIdFormatExchange = clientOrderIdFormatExchange ?? throw new ArgumentNullException("clientOrderIdFormatExchange is a required property for OrderExecutionReportAllOf and cannot be null"); this.AmountOpen = amountOpen; this.AmountFilled = amountFilled; this.Status = status; this.ExchangeOrderId = exchangeOrderId; this.AvgPx = avgPx; this.StatusHistory = statusHistory; this.ErrorMessage = errorMessage; this.Fills = fills; } /// <summary> /// The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. /// </summary> /// <value>The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it.</value> [DataMember(Name = "client_order_id_format_exchange", IsRequired = true, EmitDefaultValue = false)] public string ClientOrderIdFormatExchange { get; set; } /// <summary> /// Unique identifier of the order assigned by the exchange or executing system. /// </summary> /// <value>Unique identifier of the order assigned by the exchange or executing system.</value> [DataMember(Name = "exchange_order_id", EmitDefaultValue = false)] public string ExchangeOrderId { get; set; } /// <summary> /// Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60; /// </summary> /// <value>Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60;</value> [DataMember(Name = "amount_open", IsRequired = true, EmitDefaultValue = false)] public decimal AmountOpen { get; set; } /// <summary> /// Total quantity filled. /// </summary> /// <value>Total quantity filled.</value> [DataMember(Name = "amount_filled", IsRequired = true, EmitDefaultValue = false)] public decimal AmountFilled { get; set; } /// <summary> /// Calculated average price of all fills on this order. /// </summary> /// <value>Calculated average price of all fills on this order.</value> [DataMember(Name = "avg_px", EmitDefaultValue = false)] public decimal AvgPx { get; set; } /// <summary> /// Timestamped history of order status changes. /// </summary> /// <value>Timestamped history of order status changes.</value> [DataMember(Name = "status_history", EmitDefaultValue = false)] public List<List<string>> StatusHistory { get; set; } /// <summary> /// Error message. /// </summary> /// <value>Error message.</value> [DataMember(Name = "error_message", EmitDefaultValue = false)] public string ErrorMessage { get; set; } /// <summary> /// Relay fill information on working orders. /// </summary> /// <value>Relay fill information on working orders.</value> [DataMember(Name = "fills", EmitDefaultValue = false)] public List<Fills> Fills { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderExecutionReportAllOf {\n"); sb.Append(" ClientOrderIdFormatExchange: ").Append(ClientOrderIdFormatExchange).Append("\n"); sb.Append(" ExchangeOrderId: ").Append(ExchangeOrderId).Append("\n"); sb.Append(" AmountOpen: ").Append(AmountOpen).Append("\n"); sb.Append(" AmountFilled: ").Append(AmountFilled).Append("\n"); sb.Append(" AvgPx: ").Append(AvgPx).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" StatusHistory: ").Append(StatusHistory).Append("\n"); sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); sb.Append(" Fills: ").Append(Fills).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderExecutionReportAllOf); } /// <summary> /// Returns true if OrderExecutionReportAllOf instances are equal /// </summary> /// <param name="input">Instance of OrderExecutionReportAllOf to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderExecutionReportAllOf input) { if (input == null) return false; return ( this.ClientOrderIdFormatExchange == input.ClientOrderIdFormatExchange || (this.ClientOrderIdFormatExchange != null && this.ClientOrderIdFormatExchange.Equals(input.ClientOrderIdFormatExchange)) ) && ( this.ExchangeOrderId == input.ExchangeOrderId || (this.ExchangeOrderId != null && this.ExchangeOrderId.Equals(input.ExchangeOrderId)) ) && ( this.AmountOpen == input.AmountOpen || this.AmountOpen.Equals(input.AmountOpen) ) && ( this.AmountFilled == input.AmountFilled || this.AmountFilled.Equals(input.AmountFilled) ) && ( this.AvgPx == input.AvgPx || this.AvgPx.Equals(input.AvgPx) ) && ( this.Status == input.Status || this.Status.Equals(input.Status) ) && ( this.StatusHistory == input.StatusHistory || this.StatusHistory != null && input.StatusHistory != null && this.StatusHistory.SequenceEqual(input.StatusHistory) ) && ( this.ErrorMessage == input.ErrorMessage || (this.ErrorMessage != null && this.ErrorMessage.Equals(input.ErrorMessage)) ) && ( this.Fills == input.Fills || this.Fills != null && input.Fills != null && this.Fills.SequenceEqual(input.Fills) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ClientOrderIdFormatExchange != null) hashCode = hashCode * 59 + this.ClientOrderIdFormatExchange.GetHashCode(); if (this.ExchangeOrderId != null) hashCode = hashCode * 59 + this.ExchangeOrderId.GetHashCode(); hashCode = hashCode * 59 + this.AmountOpen.GetHashCode(); hashCode = hashCode * 59 + this.AmountFilled.GetHashCode(); hashCode = hashCode * 59 + this.AvgPx.GetHashCode(); hashCode = hashCode * 59 + this.Status.GetHashCode(); if (this.StatusHistory != null) hashCode = hashCode * 59 + this.StatusHistory.GetHashCode(); if (this.ErrorMessage != null) hashCode = hashCode * 59 + this.ErrorMessage.GetHashCode(); if (this.Fills != null) hashCode = hashCode * 59 + this.Fills.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
47.558935
467
0.596418
[ "MIT" ]
AllSafeCybercurity/coinapi-sdk
oeml-sdk/csharp-netcore/src/CoinAPI.OMS.API.SDK/Model/OrderExecutionReportAllOf.cs
12,508
C#
namespace InvoiceManagementSystem.Application.Helpers { public class PagingParams { private const int MAX_PAGE_SIZE = 50; public int PageNumber { get; set; } = 1; private int _pageSize = 10; public int PageSize { get => _pageSize; set => _pageSize = (value > MAX_PAGE_SIZE) ? MAX_PAGE_SIZE : value; } } }
24.4375
79
0.580563
[ "MIT" ]
andrija-mitrovic/InvoiceManagementSystem
src/InvoiceManagementSystem.Application/Helpers/PagingParams.cs
393
C#
using System; namespace PnP.Core.Model.SharePoint { /// <summary> /// Options to setup on the <see cref="RenderListDataOptions"/> RenderOptions property /// See https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest#sprenderlistdataoptions-options /// </summary> [Flags] public enum RenderListDataOptionsFlags { /// <summary> /// Return default output /// </summary> None = 0, /// <summary> /// Return list context information /// </summary> ContextInfo = 1, /// <summary> /// Return list data (same as None) /// </summary> ListData = 2, /// <summary> /// Return list schema /// </summary> ListSchema = 4, /// <summary> /// Return HTML for the list menu /// </summary> MenuView = 8, /// <summary> /// Returns information about list content types. Must be combined with the ContextInfo flag /// </summary> ListContentType = 16, /// <summary> /// The returned list will have a FileSystemItemId field on each item if possible. Must be combined with the ListData flag /// </summary> FileSystemItemId = 32, /// <summary> /// Returns the client form schema to add and edit items /// </summary> ClientFormSchema = 64, /// <summary> /// Returns QuickLaunch navigation nodes /// </summary> QuickLaunch = 128, /// <summary> /// Returns Spotlight rendering information /// </summary> Spotlight = 256, /// <summary> /// Returns Visualization rendering information /// </summary> Visualization = 512, /// <summary> /// Returns view XML and other information about the current view /// </summary> ViewMetadata = 1024, /// <summary> /// Prevents AutoHyperlink from being run on text fields in this query /// </summary> DisableAutoHyperlink = 2048, /// <summary> /// Enables URLs pointing to Media TA service, such as .thumbnailUrl, .videoManifestUrl, .pdfConversionUrls /// </summary> EnableMediaTAUrls = 4096, /// <summary> /// Returns parent folder information /// </summary> ParentInfo = 8192, /// <summary> /// Returns page context info for the current list being rendered /// </summary> PageContextInfo = 16384, /// <summary> /// Return client-side component manifest information associated with the list (reserved for future use) /// </summary> ClientSideComponentManifest = 32768, /// <summary> /// Return all content-types available on the list /// </summary> ListAvailableContentTypes = 65536, /// <summary> /// Return the order of items in the new-item menu /// </summary> FolderContentTypeOrder = 131072, /// <summary> /// Return information to initialize Grid for quick edit /// </summary> GridInitInfo = 262144, /// <summary> /// Indicator if the vroom API of the SPItemUrl returned in MediaTAUrlGenerator should use site url as host /// </summary> SiteUrlAsMediaTASPItemHost = 524288, /// <summary> /// Return the files representing mount points in the list /// </summary> AddToOneDrive = 1048576, /// <summary> /// Return SPFX CustomAction /// </summary> SPFXCustomActions = 2097152, /// <summary> /// Do not return non-SPFX CustomAction /// </summary> CustomActions = 4194304, } }
28.984962
146
0.560052
[ "MIT" ]
DonKirkham/pnpcore
src/sdk/PnP.Core/Model/SharePoint/Core/Public/Enums/RenderListDataOptionsFlags.cs
3,857
C#
using System; using System.Collections.Generic; namespace Careful.Module.Core.Modularity { /// <summary> /// Defines the interface for the service that will retrieve and initialize the application's modules. /// </summary> public interface IModuleManager { /// <summary> /// Gets all the <see cref="IModuleInfo"/> classes that are in the <see cref="IModuleCatalog"/>. /// </summary> IEnumerable<IModuleInfo> Modules { get; } /// <summary> /// Initializes the modules marked as <see cref="InitializationMode.WhenAvailable"/> on the <see cref="IModuleCatalog"/>. /// </summary> void Run(); /// <summary> /// Loads and initializes the module on the <see cref="IModuleCatalog"/> with the name <paramref name="moduleName"/>. /// </summary> /// <param name="moduleName">Name of the module requested for initialization.</param> void LoadModule(string moduleName); /// <summary> /// Raised repeatedly to provide progress as modules are downloaded. /// </summary> event EventHandler<ModuleDownloadProgressChangedEventArgs> ModuleDownloadProgressChanged; /// <summary> /// Raised when a module is loaded or fails to load. /// </summary> event EventHandler<LoadModuleCompletedEventArgs> LoadModuleCompleted; } }
36.789474
129
0.6402
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
daixin10310/CarefulDemo
MVVMCareful/Careful.Module.Core/Modularity/IModuleManager.cs
1,398
C#
using System; using Axoom.Extensions.Prometheus.Standalone; using JetBrains.Annotations; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MyVendor.ServiceBroker.Broker; using MyVendor.ServiceBroker.Infrastructure; namespace MyVendor.ServiceBroker { [UsedImplicitly] public class Startup : IStartup { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; } // Register services for DI public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddPrometheusServer(_configuration.GetSection("Metrics")) .AddSecurity(_configuration.GetSection("Authentication")) .AddRestApi(); string dbConnectionString = _configuration.GetConnectionString("Database"); services.AddDbContext<DbContext>(options => { if (dbConnectionString.Contains("Host=")) options.UseNpgsql(dbConnectionString); else options.UseSqlite(dbConnectionString); }); services.AddHealthChecks() .AddDbContextCheck<DbContext>(); services.AddBroker(_configuration.GetSection("Broker")); return services.BuildServiceProvider(); } // Configure HTTP request pipeline public void Configure(IApplicationBuilder app) => app.UseHealthChecks("/health") .UseRestApi(); // Tasks that need to run before serving HTTP requests public static void Init(IServiceProvider provider) { // TODO: Replace .EnsureCreated() with .Migrate() once you start using EF Migrations provider.GetRequiredService<DbContext>().Database.EnsureCreated(); } } }
35.288136
97
0.648895
[ "MIT" ]
AXOOM/Templates.ServiceBroker
content/src/ServiceBroker/Startup.cs
2,082
C#
using System.Runtime.CompilerServices; using ComputeSharp.__Internals; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Interop; using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES; using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; using static TerraFX.Interop.DirectX.D3D12_UAV_DIMENSION; using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; #pragma warning disable CS0618 namespace ComputeSharp.Resources; /// <summary> /// A <see langword="class"/> representing a typed 3D texture stored on GPU memory. /// </summary> /// <typeparam name="T">The type of items stored on the texture.</typeparam> public unsafe abstract class Texture3D<T> : NativeObject, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { /// <summary> /// The <see cref="D3D12MA_Allocation"/> instance used to retrieve <see cref="d3D12Resource"/>. /// </summary> private ComPtr<D3D12MA_Allocation> allocation; /// <summary> /// The <see cref="ID3D12Resource"/> instance currently mapped. /// </summary> private ComPtr<ID3D12Resource> d3D12Resource; /// <summary> /// The <see cref="D3D12_CPU_DESCRIPTOR_HANDLE"/> instance for the current resource. /// </summary> private readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; /// <summary> /// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instance for the current resource. /// </summary> internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; /// <summary> /// The default <see cref="D3D12_RESOURCE_STATES"/> value for the current resource. /// </summary> private readonly D3D12_RESOURCE_STATES d3D12ResourceState; /// <summary> /// The <see cref="D3D12_COMMAND_LIST_TYPE"/> value to use for copy operations. /// </summary> private readonly D3D12_COMMAND_LIST_TYPE d3D12CommandListType; /// <summary> /// The <see cref="D3D12_PLACED_SUBRESOURCE_FOOTPRINT"/> description for the current resource. /// </summary> private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint; /// <summary> /// Creates a new <see cref="Texture3D{T}"/> instance with the specified parameters. /// </summary> /// <param name="device">The <see cref="ComputeSharp.GraphicsDevice"/> associated with the current instance.</param> /// <param name="height">The height of the texture.</param> /// <param name="width">The width of the texture.</param> /// <param name="depth">The depth of the texture.</param> /// <param name="resourceType">The resource type for the current texture.</param> /// <param name="allocationMode">The allocation mode to use for the new resource.</param> /// <param name="d3D12FormatSupport">The format support for the current texture type.</param> private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, D3D12.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(depth)); if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType<T>(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture3D<T>(); } GraphicsDevice = device; this.allocation = device.Allocator->CreateResource( device.Pool, resourceType, allocationMode, DXGIFormatHelper.GetForType<T>(), (uint)width, (uint)height, (ushort)depth, out this.d3D12ResourceState); this.d3D12Resource = new ComPtr<ID3D12Resource>(this.allocation.Get()->GetResource()); this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON ? D3D12_COMMAND_LIST_TYPE_COPY : D3D12_COMMAND_LIST_TYPE_COMPUTE; device.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType<T>(), (uint)width, (uint)height, (ushort)depth, out this.d3D12PlacedSubresourceFootprint, out _, out _); device.RegisterAllocatedResource(); device.RentShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); switch (resourceType) { case ResourceType.ReadOnly: device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType<T>(), D3D12_SRV_DIMENSION_TEXTURE3D, D3D12CpuDescriptorHandle); break; case ResourceType.ReadWrite: device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType<T>(), D3D12_UAV_DIMENSION_TEXTURE3D, D3D12CpuDescriptorHandle); break; } this.d3D12Resource.Get()->SetName(this); } /// <summary> /// Gets the <see cref="ComputeSharp.GraphicsDevice"/> associated with the current instance. /// </summary> public GraphicsDevice GraphicsDevice { get; } /// <summary> /// Gets the width of the current texture. /// </summary> public int Width => (int)this.d3D12PlacedSubresourceFootprint.Footprint.Width; /// <summary> /// Gets the height of the current texture. /// </summary> public int Height => (int)this.d3D12PlacedSubresourceFootprint.Footprint.Height; /// <summary> /// Gets the depth of the current texture. /// </summary> public int Depth => (int)this.d3D12PlacedSubresourceFootprint.Footprint.Depth; /// <summary> /// Gets the <see cref="ID3D12Resource"/> instance currently mapped. /// </summary> internal ID3D12Resource* D3D12Resource => this.d3D12Resource; /// <summary> /// Reads the contents of the specified range from the current <see cref="Texture3D{T}"/> instance and writes them into a target memory area. /// </summary> /// <param name="destination">The target memory area to write data to.</param> /// <param name="size">The size of the memory area to write data to.</param> /// <param name="sourceOffsetX">The horizontal offset in the source texture.</param> /// <param name="sourceOffsetY">The vertical offset in the source texture.</param> /// <param name="sourceOffsetZ">The depthwise offset in the source texture.</param> /// <param name="width">The width of the memory area to copy.</param> /// <param name="height">The height of the memory area to copy.</param> /// <param name="depth">The depth of the memory area to copy.</param> internal void CopyTo(ref T destination, int size, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); ThrowIfDisposed(); Guard.IsInRange(sourceOffsetX, 0, Width, nameof(sourceOffsetX)); Guard.IsInRange(sourceOffsetY, 0, Height, nameof(sourceOffsetY)); Guard.IsInRange(sourceOffsetZ, 0, Depth, nameof(sourceOffsetZ)); Guard.IsBetweenOrEqualTo(width, 1, Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, Depth, nameof(depth)); Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth, nameof(size)); GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType<T>(), (uint)width, (uint)height, (ushort)depth, out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, out ulong rowSizeInBytes, out ulong totalSizeInBytes); using ComPtr<D3D12MA_Allocation> allocation = GraphicsDevice.Allocator->CreateResource( GraphicsDevice.Pool, ResourceType.ReadBack, AllocationMode.Default, totalSizeInBytes); using ComPtr<ID3D12Resource> d3D12Resource = new(allocation.Get()->GetResource()); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( d3D12ResourceDestination: d3D12Resource.Get(), &d3D12PlacedSubresourceFootprintDestination, destinationX: 0, destinationY: 0, destinationZ: 0, d3D12ResourceSource: D3D12Resource, sourceX: (uint)sourceOffsetX, sourceY: (uint)sourceOffsetY, sourceZ: (ushort)sourceOffsetZ, (uint)width, (uint)height, (ushort)depth); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); } using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); fixed (void* destinationPointer = &destination) { MemoryHelper.Copy( resource.Pointer, (uint)height, (uint)depth, rowSizeInBytes, d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch, d3D12PlacedSubresourceFootprintDestination.Footprint.RowPitch * (uint)height, destinationPointer); } } /// <summary> /// Reads the contents of the specified range from the current <see cref="Texture3D{T}"/> instance and writes them into a <see cref="Texture3D{T}"/> instance. /// </summary> /// <param name="destination">The target <see cref="Texture3D{T}"/> instance to write data to.</param> /// <param name="sourceOffsetX">The horizontal offset in the source texture.</param> /// <param name="sourceOffsetY">The vertical offset in the source texture.</param> /// <param name="sourceOffsetZ">The depthwise offset in the source texture.</param> /// <param name="destinationOffsetX">The horizontal offset within <paramref name="destination"/>.</param> /// <param name="destinationOffsetY">The vertical offset within <paramref name="destination"/>.</param> /// <param name="destinationOffsetZ">The depthwise offset within <paramref name="destination"/>.</param> /// <param name="width">The width of the memory area to copy.</param> /// <param name="height">The height of the memory area to copy.</param> /// <param name="depth">The depth of the memory area to copy.</param> internal void CopyTo(Texture3D<T> destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); ThrowIfDisposed(); destination.ThrowIfDeviceMismatch(GraphicsDevice); destination.ThrowIfDisposed(); Guard.IsInRange(sourceOffsetX, 0, Width, nameof(sourceOffsetX)); Guard.IsInRange(sourceOffsetY, 0, Height, nameof(sourceOffsetY)); Guard.IsInRange(sourceOffsetZ, 0, Depth, nameof(sourceOffsetZ)); Guard.IsInRange(destinationOffsetX, 0, destination.Width, nameof(destinationOffsetX)); Guard.IsInRange(destinationOffsetY, 0, destination.Height, nameof(destinationOffsetY)); Guard.IsInRange(destinationOffsetZ, 0, destination.Depth, nameof(destinationOffsetZ)); Guard.IsBetweenOrEqualTo(width, 1, Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, Depth, nameof(depth)); Guard.IsBetweenOrEqualTo(width, 1, destination.Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, destination.Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth, nameof(depth)); Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); D3D12_COMMAND_LIST_TYPE d3D12CommandListType = this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_COPY; using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( d3D12ResourceDestination: destination.D3D12Resource, (uint)destinationOffsetX, (uint)destinationOffsetY, (ushort)destinationOffsetZ, d3D12ResourceSource: D3D12Resource, (uint)sourceOffsetX, (uint)sourceOffsetY, (ushort)sourceOffsetZ, (uint)width, (uint)height, (ushort)depth); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); } /// <summary> /// Reads the contents of the specified range from the current <see cref="Texture3D{T}"/> instance and writes them into a <see cref="ReadBackTexture3D{T}"/> instance. /// </summary> /// <param name="destination">The target <see cref="ReadBackTexture3D{T}"/> instance to write data to.</param> /// <param name="sourceOffsetX">The horizontal offset in the source texture.</param> /// <param name="sourceOffsetY">The vertical offset in the source texture.</param> /// <param name="sourceOffsetZ">The depthwise offset in the source texture.</param> /// <param name="destinationOffsetX">The horizontal offset within <paramref name="destination"/>.</param> /// <param name="destinationOffsetY">The vertical offset within <paramref name="destination"/>.</param> /// <param name="destinationOffsetZ">The depthwise offset within <paramref name="destination"/>.</param> /// <param name="width">The width of the memory area to copy.</param> /// <param name="height">The height of the memory area to copy.</param> /// <param name="depth">The depth of the memory area to copy.</param> internal void CopyTo(ReadBackTexture3D<T> destination, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); ThrowIfDisposed(); destination.ThrowIfDeviceMismatch(GraphicsDevice); destination.ThrowIfDisposed(); Guard.IsInRange(sourceOffsetX, 0, Width, nameof(sourceOffsetX)); Guard.IsInRange(sourceOffsetY, 0, Height, nameof(sourceOffsetY)); Guard.IsInRange(sourceOffsetZ, 0, Depth, nameof(sourceOffsetZ)); Guard.IsInRange(destinationOffsetX, 0, destination.Width, nameof(destinationOffsetX)); Guard.IsInRange(destinationOffsetY, 0, destination.Height, nameof(destinationOffsetY)); Guard.IsInRange(destinationOffsetZ, 0, destination.Depth, nameof(destinationOffsetZ)); Guard.IsBetweenOrEqualTo(width, 1, Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, Depth, nameof(depth)); Guard.IsBetweenOrEqualTo(width, 1, destination.Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, destination.Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, destination.Depth, nameof(depth)); Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); Guard.IsBetweenOrEqualTo(destinationOffsetY + height, 1, destination.Height, nameof(destinationOffsetY)); Guard.IsBetweenOrEqualTo(destinationOffsetZ + depth, 1, destination.Depth, nameof(destinationOffsetZ)); Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, Depth, nameof(sourceOffsetZ)); using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) { copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( d3D12ResourceDestination: destination.D3D12Resource, d3D12PlacedSubresourceFootprintDestination, (uint)destinationOffsetX, (uint)destinationOffsetY, (ushort)destinationOffsetZ, d3D12ResourceSource: D3D12Resource, (uint)sourceOffsetX, (uint)sourceOffsetY, (ushort)sourceOffsetZ, (uint)width, (uint)height, (ushort)depth); } if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); } /// <summary> /// Writes the contents of a given memory area to a specified area of the current <see cref="Texture3D{T}"/> instance. /// </summary> /// <param name="source">The input memory area to read data from.</param> /// <param name="size">The size of the memory area to read data from.</param> /// <param name="destinationOffsetX">The horizontal offset in the destination texture.</param> /// <param name="destinationOffsetY">The vertical offset in the destination texture.</param> /// <param name="destinationOffsetZ">The depthwise offset in the destination texture.</param> /// <param name="width">The width of the memory area to write to.</param> /// <param name="height">The height of the memory area to write to.</param> /// <param name="depth">The depth of the memory area to write to.</param> internal void CopyFrom(ref T source, int size, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); ThrowIfDisposed(); Guard.IsInRange(destinationOffsetX, 0, Width, nameof(destinationOffsetX)); Guard.IsInRange(destinationOffsetY, 0, Height, nameof(destinationOffsetY)); Guard.IsInRange(destinationOffsetZ, 0, Depth, nameof(destinationOffsetZ)); Guard.IsBetweenOrEqualTo(width, 1, Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, Depth, nameof(depth)); Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); Guard.IsGreaterThanOrEqualTo(size, (nint)width * height * depth, nameof(size)); GraphicsDevice.D3D12Device->GetCopyableFootprint( DXGIFormatHelper.GetForType<T>(), (uint)width, (uint)height, (ushort)depth, out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, out ulong rowSizeInBytes, out ulong totalSizeInBytes); using ComPtr<D3D12MA_Allocation> allocation = GraphicsDevice.Allocator->CreateResource( GraphicsDevice.Pool, ResourceType.Upload, AllocationMode.Default, totalSizeInBytes); using ComPtr<ID3D12Resource> d3D12Resource = new(allocation.Get()->GetResource()); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) fixed (void* sourcePointer = &source) { MemoryHelper.Copy( sourcePointer, resource.Pointer, (uint)height, (uint)depth, rowSizeInBytes, d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch, d3D12PlacedSubresourceFootprintSource.Footprint.RowPitch * (uint)height); } using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( d3D12ResourceDestination: D3D12Resource, destinationX: (uint)destinationOffsetX, destinationY: (uint)destinationOffsetY, destinationZ: (ushort)destinationOffsetZ, d3D12ResourceSource: d3D12Resource.Get(), &d3D12PlacedSubresourceFootprintSource, sourceX: 0, sourceY: 0, sourceZ: 0, (uint)width, (uint)height, (ushort)depth); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); } /// <summary> /// Writes the contents of a given <see cref="UploadTexture3D{T}"/> instance to a specified area of the current <see cref="Texture3D{T}"/> instance. /// </summary> /// <param name="source">The input <see cref="UploadTexture3D{T}"/> instance to read data from.</param> /// <param name="sourceOffsetX">The horizontal offset within <paramref name="source"/>.</param> /// <param name="sourceOffsetY">The vertical offset within <paramref name="source"/>.</param> /// <param name="sourceOffsetZ">The depthwise offset within <paramref name="source"/>.</param> /// <param name="destinationOffsetX">The horizontal offset in the destination texture.</param> /// <param name="destinationOffsetY">The vertical offset in the destination texture.</param> /// <param name="destinationOffsetZ">The depthwise offset in the destination texture.</param> /// <param name="width">The width of the memory area to write to.</param> /// <param name="height">The height of the memory area to write to.</param> /// <param name="depth">The depth of the memory area to write to.</param> internal void CopyFrom(UploadTexture3D<T> source, int sourceOffsetX, int sourceOffsetY, int sourceOffsetZ, int destinationOffsetX, int destinationOffsetY, int destinationOffsetZ, int width, int height, int depth) { GraphicsDevice.ThrowIfDisposed(); ThrowIfDisposed(); source.ThrowIfDeviceMismatch(GraphicsDevice); source.ThrowIfDisposed(); Guard.IsInRange(sourceOffsetX, 0, source.Width, nameof(sourceOffsetX)); Guard.IsInRange(sourceOffsetY, 0, source.Height, nameof(sourceOffsetY)); Guard.IsInRange(sourceOffsetZ, 0, source.Depth, nameof(sourceOffsetZ)); Guard.IsInRange(destinationOffsetX, 0, Width, nameof(destinationOffsetX)); Guard.IsInRange(destinationOffsetY, 0, Height, nameof(destinationOffsetY)); Guard.IsInRange(destinationOffsetZ, 0, Depth, nameof(destinationOffsetZ)); Guard.IsBetweenOrEqualTo(width, 1, Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, Depth, nameof(depth)); Guard.IsBetweenOrEqualTo(width, 1, source.Width, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, source.Height, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, source.Depth, nameof(depth)); Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); Guard.IsLessThanOrEqualTo(sourceOffsetY + height, source.Height, nameof(sourceOffsetY)); Guard.IsLessThanOrEqualTo(sourceOffsetZ + depth, source.Depth, nameof(sourceOffsetZ)); Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); Guard.IsLessThanOrEqualTo(destinationOffsetY + height, Height, nameof(destinationOffsetY)); Guard.IsLessThanOrEqualTo(destinationOffsetZ + depth, Depth, nameof(destinationOffsetZ)); using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) { copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( d3D12ResourceDestination: D3D12Resource, (uint)destinationOffsetX, (uint)destinationOffsetY, (ushort)destinationOffsetZ, d3D12ResourceSource: source.D3D12Resource, d3D12PlacedSubresourceFootprintSource, (uint)sourceOffsetX, (uint)sourceOffsetY, (ushort)sourceOffsetZ, (uint)width, (uint)height, (ushort)depth); } if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); } /// <inheritdoc/> protected override void OnDispose() { this.d3D12Resource.Dispose(); this.allocation.Dispose(); if (GraphicsDevice is GraphicsDevice device) { device.UnregisterAllocatedResource(); device.ReturnShaderResourceViewDescriptorHandles(D3D12CpuDescriptorHandle, D3D12GpuDescriptorHandle); } } /// <summary> /// Throws a <see cref="GraphicsDeviceMismatchException"/> if the target device doesn't match the current one. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ThrowIfDeviceMismatch(GraphicsDevice device) { if (GraphicsDevice != device) { GraphicsDeviceMismatchException.Throw(this, device); } } /// <inheritdoc/> D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { ThrowIfDisposed(); ThrowIfDeviceMismatch(device); return D3D12GpuDescriptorHandle; } }
50.627551
221
0.695321
[ "MIT" ]
arcadiogarcia/ComputeSharp
src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs
29,771
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; namespace Microsoft.Extensions.CompilationAbstractions { public interface ISourceReference { string Name { get; } } }
26.916667
111
0.73065
[ "Apache-2.0" ]
aspnet/DNX
src/Microsoft.Extensions.CompilationAbstractions/ISourceReference.cs
323
C#
using System; using System.ComponentModel.DataAnnotations; using WEBCON.FormsGenerator.BusinessLogic.Domain.Exceptions; namespace WEBCON.FormsGenerator.BusinessLogic.Domain.Model { public class Form : Entity { public Form() { } public Form(string name, string content, BpsFormType formType, BpsStepPath stepPath) { Validate(name, formType, stepPath); Guid = Guid.NewGuid(); Created = DateTime.Now; Name = name; Content = content; BpsStepPath = stepPath; BpsFormType = formType; } public DateTime Created { get; private set; } public DateTime Modified { get; private set; } [StringLength(50)] public string Name { get; private set; } public string Content { get; private set; } public BpsStepPath BpsStepPath { get; private set; } public BpsFormType BpsFormType { get; private set; } public string Style { get; private set; } public bool? IsCaptchaRequired { get; private set; } public string FrameAncestors { get; private set; } [StringLength(50)] public string ClientId { get; private set; } [StringLength(500)] public string ClientSecret { get; private set; } public bool UseStandardBootstrapStyle { get; private set; } public string CustomCssLink { get; private set; } public string ContentTitle { get; private set; } public string ContentDescription { get; private set; } public string ContentSubmitText { get; private set; } public string ContentSubmitProcessingText { get; private set; } public string ContentSubmitSuccessMessage { get; private set; } public bool IsActive { get; private set; } public Guid BusinessEntityGuid { get; set; } public void Update(string name, string content, BpsFormType formType, BpsStepPath stepPath) { Validate(name, formType, stepPath); Name = name; SetContent(content); BpsFormType = formType; BpsStepPath = stepPath; Modified = DateTime.Now; } public void SetBusinessEntity(Guid businessEntityGuid) { this.BusinessEntityGuid = businessEntityGuid; } public void SetIsActive(bool isActive) { IsActive = isActive; } public void SetCustomStyleLink(string customCssLink) { CustomCssLink = customCssLink; } public void SetCustomStyle(string style) { Style = style; } public void SetFrameAncestors(string frameAncestors) { FrameAncestors = frameAncestors; } public void SetCaptchaRequired(bool isRequired) { IsCaptchaRequired = isRequired; } public void SetUseStandardBootstrapStyle(bool useStandardStyle) { UseStandardBootstrapStyle = useStandardStyle; } public void SetCustomCredentials(string clientId, string clientSecret) { ClientId = clientId; ClientSecret = clientSecret; } public void SetContentTexts(string contentTitle, string contentDescription, string contentSubmitText, string contentSubmitProcessingMessage, string contentSubmitSuccessMessage) { ContentTitle = contentTitle; ContentDescription = contentDescription; ContentSubmitText = contentSubmitText; ContentSubmitProcessingText = contentSubmitProcessingMessage; ContentSubmitSuccessMessage = contentSubmitSuccessMessage; } public void SetContent(string content) { if (string.IsNullOrEmpty(content)) throw new ApplicationArgumentException("Content cannot be empty"); Content = content; } private void Validate(string name, BpsFormType formtype, BpsStepPath stepPath) { if (formtype == null) throw new ApplicationArgumentException("Form type has to be selected"); if (stepPath == null) throw new ApplicationArgumentException("Step path has to be selected"); if (string.IsNullOrEmpty(name)) throw new ApplicationArgumentException("Name cannot be empty"); } } }
39.353982
184
0.621992
[ "MIT" ]
WEBCON-BPS/public-forms
WEBCON.FormsGenerator.BuisnessLogic/Domain/Model/Form.cs
4,449
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using GridDesktop.Examples.WorkingWithGrid; using GridDesktop.Examples.Articles; using GridDesktop.Examples.WorkingWithWorksheet; using GridDesktop.Examples.WorkingWithRowsandColumns; using GridDesktop.Examples.WorkingWithCells; namespace GridDesktop.Examples { public partial class RunExamples : Form { public RunExamples() { InitializeComponent(); } private void closeAllToolStripMenuItem_Click(object sender, EventArgs e) { foreach (Form frm in this.MdiChildren) { if (frm != this) { frm.Close(); } } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void copyAndPasteRowsToolStripMenuItem_Click(object sender, EventArgs e) { CopyAndPasteRows frmCopyPasteRows = new CopyAndPasteRows(); frmCopyPasteRows.MdiParent = this; frmCopyPasteRows.Show(); } private void dataBindingFeaturesInWorksheetsToolStripMenuItem_Click(object sender, EventArgs e) { DataBindingFeature frmDataBindingFeatures = new DataBindingFeature(); frmDataBindingFeatures.MdiParent = this; frmDataBindingFeatures.Show(); } private void managingContextMenuToolStripMenuItem_Click(object sender, EventArgs e) { ManagingContextMenu frmManagingContextMenu = new ManagingContextMenu(); frmManagingContextMenu.MdiParent = this; frmManagingContextMenu.Show(); } private void openingExcelFileToolStripMenuItem_Click(object sender, EventArgs e) { OpeningExcelFile frmOpeningExcelFile = new OpeningExcelFile(); frmOpeningExcelFile.MdiParent = this; frmOpeningExcelFile.Show(); } private void savingExcelFileToolStripMenuItem_Click(object sender, EventArgs e) { SavingExcelFile frmSavingExcelFile = new SavingExcelFile(); frmSavingExcelFile.MdiParent = this; frmSavingExcelFile.Show(); } private void gridDesktopEventsToolStripMenuItem_Click(object sender, EventArgs e) { GridDesktopEvents frmGridDesktopEvents = new GridDesktopEvents(); frmGridDesktopEvents.MdiParent = this; frmGridDesktopEvents.Show(); } private void accessingWorksheetsToolStripMenuItem_Click(object sender, EventArgs e) { AccessingWorksheets frmAccessingWorksheets = new AccessingWorksheets(); frmAccessingWorksheets.MdiParent = this; frmAccessingWorksheets.Show(); } private void addORInsertWorksheetsToolStripMenuItem_Click(object sender, EventArgs e) { AddInsertWorksheet frmAddInsertWorksheet = new AddInsertWorksheet(); frmAddInsertWorksheet.MdiParent = this; frmAddInsertWorksheet.Show(); } private void removeAWorksheetToolStripMenuItem_Click(object sender, EventArgs e) { RemoveWorksheet frmRemoveWorksheet = new RemoveWorksheet(); frmRemoveWorksheet.MdiParent = this; frmRemoveWorksheet.Show(); } private void renameAWorksheetToolStripMenuItem_Click(object sender, EventArgs e) { RenameWorksheet frmRenameWorksheet = new RenameWorksheet(); frmRenameWorksheet.MdiParent = this; frmRenameWorksheet.Show(); } private void importDataFromDataTableToolStripMenuItem_Click(object sender, EventArgs e) { ImportDataFromDataTable frmImportData = new ImportDataFromDataTable(); frmImportData.MdiParent = this; frmImportData.Show(); } private void exportDataToDataTableToolStripMenuItem_Click(object sender, EventArgs e) { ExportDataToDataTable frmExportData = new ExportDataToDataTable(); frmExportData.MdiParent = this; frmExportData.Show(); } private void workingWithValidationsToolStripMenuItem_Click(object sender, EventArgs e) { ValidationInWorksheets frmValidations = new ValidationInWorksheets(); frmValidations.MdiParent = this; frmValidations.Show(); } private void sortDataToolStripMenuItem_Click(object sender, EventArgs e) { SortData frmSortData = new SortData(); frmSortData.MdiParent = this; frmSortData.Show(); } private void managingHyperlinksToolStripMenuItem_Click(object sender, EventArgs e) { ManagingHyperlinks frmHyperlinks = new ManagingHyperlinks(); frmHyperlinks.MdiParent = this; frmHyperlinks.Show(); } private void managingPicturesToolStripMenuItem_Click(object sender, EventArgs e) { ManagingPictures frmManagingPictures = new ManagingPictures(); frmManagingPictures.MdiParent = this; frmManagingPictures.Show(); } private void managingCommentsToolStripMenuItem_Click(object sender, EventArgs e) { ManagingComments frmManagingComments = new ManagingComments(); frmManagingComments.MdiParent = this; frmManagingComments.Show(); } private void addingCellControlsToolStripMenuItem_Click(object sender, EventArgs e) { AddingCellControls frmAddingCellControls = new AddingCellControls(); frmAddingCellControls.MdiParent = this; frmAddingCellControls.Show(); } private void managingCellControlsToolStripMenuItem_Click(object sender, EventArgs e) { ManagingCellControls frmManagingCellControls = new ManagingCellControls(); frmManagingCellControls.MdiParent = this; frmManagingCellControls.Show(); } private void showHideScrolBarsToolStripMenuItem_Click(object sender, EventArgs e) { DisplayHideScrolBars frmDisplayHideScrols = new DisplayHideScrolBars(); frmDisplayHideScrols.MdiParent = this; frmDisplayHideScrols.Show(); } private void movingWorksheetsToolStripMenuItem_Click(object sender, EventArgs e) { MovingWorksheets frmMovingWorksheets = new MovingWorksheets(); frmMovingWorksheets.MdiParent = this; frmMovingWorksheets.Show(); } private void readingDataValidationsToolStripMenuItem_Click(object sender, EventArgs e) { ReadingDataValidations frmDataValidations = new ReadingDataValidations(); frmDataValidations.MdiParent = this; frmDataValidations.Show(); } private void zoomingInOrOutToolStripMenuItem_Click(object sender, EventArgs e) { ZoomingInOut frmZoomingInOut = new ZoomingInOut(); frmZoomingInOut.MdiParent = this; frmZoomingInOut.Show(); } private void addInsertColumnToolStripMenuItem_Click(object sender, EventArgs e) { AddInsertColumn frmAddInsertColumn = new AddInsertColumn(); frmAddInsertColumn.MdiParent = this; frmAddInsertColumn.Show(); } private void removingAColmnToolStripMenuItem_Click(object sender, EventArgs e) { RemovingColumn frmRemovingColumn = new RemovingColumn(); frmRemovingColumn.MdiParent = this; frmRemovingColumn.Show(); } private void addInsertRowToolStripMenuItem_Click(object sender, EventArgs e) { AddInsertRow frmAddInsertRow = new AddInsertRow(); frmAddInsertRow.MdiParent = this; frmAddInsertRow.Show(); } private void removingARowToolStripMenuItem_Click(object sender, EventArgs e) { RemovingRow frmRemovingRow = new RemovingRow(); frmRemovingRow.MdiParent = this; frmRemovingRow.Show(); } private void applyingStyleOnRowColumnToolStripMenuItem_Click(object sender, EventArgs e) { ApplyingStyleOnRowColumn frmApplyStyle = new ApplyingStyleOnRowColumn(); frmApplyStyle.MdiParent = this; frmApplyStyle.Show(); } private void settingColumnWidhtRowHeightToolStripMenuItem_Click(object sender, EventArgs e) { SettingColumnWidthAndRowHeight frmSettingHeightWidth = new SettingColumnWidthAndRowHeight(); frmSettingHeightWidth.MdiParent = this; frmSettingHeightWidth.Show(); } private void freezeUnfreezeRowsColumnsToolStripMenuItem_Click(object sender, EventArgs e) { FreezeUnfreezeRowsColumns frmFreezeUnfreeze = new FreezeUnfreezeRowsColumns(); frmFreezeUnfreeze.MdiParent = this; frmFreezeUnfreeze.Show(); } private void addingCellControlsInColumnsToolStripMenuItem_Click(object sender, EventArgs e) { AddingCellControlsInColumns frmAddControl = new AddingCellControlsInColumns(); frmAddControl.MdiParent = this; frmAddControl.Show(); } private void workingWithColumnValidationsToolStripMenuItem_Click(object sender, EventArgs e) { WorkingWithColumnValidations frmColValidations = new WorkingWithColumnValidations(); frmColValidations.MdiParent = this; frmColValidations.Show(); } private void managingControlsInColumnsToolStripMenuItem_Click(object sender, EventArgs e) { ManagingControlsInColumns frmManageControls = new ManagingControlsInColumns(); frmManageControls.MdiParent = this; frmManageControls.Show(); } private void changeFontColorOfRowColumnToolStripMenuItem_Click(object sender, EventArgs e) { ChangeFontColorRowColumn frmChangeFontColor = new ChangeFontColorRowColumn(); frmChangeFontColor.MdiParent = this; frmChangeFontColor.Show(); } private void accessAndModifyCellsToolStripMenuItem_Click(object sender, EventArgs e) { AccessAndModifyCells frmAccessAndModify = new AccessAndModifyCells(); frmAccessAndModify.MdiParent = this; frmAccessAndModify.Show(); } private void accessingCellsToolStripMenuItem_Click(object sender, EventArgs e) { AccessingCells frmAccessCells = new AccessingCells(); frmAccessCells.MdiParent = this; frmAccessCells.Show(); } private void addCellProtectionToolStripMenuItem_Click(object sender, EventArgs e) { AddCellProtection frmAddCellProtection = new AddCellProtection(); frmAddCellProtection.MdiParent = this; frmAddCellProtection.Show(); } private void addingCellFormulasToolStripMenuItem_Click(object sender, EventArgs e) { AddingCellFormulas frmAddFormula = new AddingCellFormulas(); frmAddFormula.MdiParent = this; frmAddFormula.Show(); } private void applyingStyleOnCellsToolStripMenuItem_Click(object sender, EventArgs e) { ApplyStyleOnCells frmApplyStyle = new ApplyStyleOnCells(); frmApplyStyle.MdiParent = this; frmApplyStyle.Show(); } private void changeFontColorOfCellToolStripMenuItem_Click(object sender, EventArgs e) { ChangeFontColorOfCell frmChangeFontColor = new ChangeFontColorOfCell(); frmChangeFontColor.MdiParent = this; frmChangeFontColor.Show(); } private void filteringDataToolStripMenuItem_Click(object sender, EventArgs e) { FilteringData frmFilterData = new FilteringData(); frmFilterData.MdiParent = this; frmFilterData.Show(); } private void formattingCellRangeToolStripMenuItem_Click(object sender, EventArgs e) { FormattingCellRange frmFormattinCellRange = new FormattingCellRange(); frmFormattinCellRange.MdiParent = this; frmFormattinCellRange.Show(); } private void mergingAndUnmergingCellsToolStripMenuItem_Click(object sender, EventArgs e) { MergingAndUnMergingCells frmMergeUnmerge = new MergingAndUnMergingCells(); frmMergeUnmerge.MdiParent = this; frmMergeUnmerge.Show(); } private void undoAndRedoFeatureToolStripMenuItem_Click(object sender, EventArgs e) { UndoRedoFeature frmUndoRedo = new UndoRedoFeature(); frmUndoRedo.MdiParent = this; frmUndoRedo.Show(); } private void usingFormatPainterToolStripMenuItem_Click(object sender, EventArgs e) { UsingFormatPainter frmFormatPainter = new UsingFormatPainter(); frmFormatPainter.MdiParent = this; frmFormatPainter.Show(); } private void usingNamedRangesToolStripMenuItem_Click(object sender, EventArgs e) { UsingNamedRanges frmUsingNamedRanges = new UsingNamedRanges(); frmUsingNamedRanges.MdiParent = this; frmUsingNamedRanges.Show(); } } }
37.958564
104
0.658904
[ "MIT" ]
Aspose/Aspose.Cells-for-.NET
Examples.GridDesktop/CSharp/GridDesktop.Examples/RunExamples.cs
13,743
C#
using Org.BouncyCastle.Asn1.Pkcs; namespace Org.BouncyCastle.Asn1.Cms { public abstract class CmsObjectIdentifiers { public static readonly DerObjectIdentifier Data = PkcsObjectIdentifiers.Data; public static readonly DerObjectIdentifier SignedData = PkcsObjectIdentifiers.SignedData; public static readonly DerObjectIdentifier EnvelopedData = PkcsObjectIdentifiers.EnvelopedData; public static readonly DerObjectIdentifier SignedAndEnvelopedData = PkcsObjectIdentifiers.SignedAndEnvelopedData; public static readonly DerObjectIdentifier DigestedData = PkcsObjectIdentifiers.DigestedData; public static readonly DerObjectIdentifier EncryptedData = PkcsObjectIdentifiers.EncryptedData; public static readonly DerObjectIdentifier AuthenticatedData = PkcsObjectIdentifiers.IdCTAuthData; public static readonly DerObjectIdentifier CompressedData = PkcsObjectIdentifiers.IdCTCompressedData; public static readonly DerObjectIdentifier AuthEnvelopedData = PkcsObjectIdentifiers.IdCTAuthEnvelopedData; public static readonly DerObjectIdentifier timestampedData = PkcsObjectIdentifiers.IdCTTimestampedData; /** * The other Revocation Info arc * id-ri OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) * dod(6) internet(1) security(5) mechanisms(5) pkix(7) ri(16) } */ public static readonly DerObjectIdentifier id_ri = new DerObjectIdentifier("1.3.6.1.5.5.7.16"); public static readonly DerObjectIdentifier id_ri_ocsp_response = id_ri.Branch("2"); public static readonly DerObjectIdentifier id_ri_scvp = id_ri.Branch("4"); } }
60.37931
122
0.741862
[ "Apache-2.0", "MIT" ]
flobecker/trudi-koala
src/IVU.BouncyCastle.Crypto/src/asn1/cms/CMSObjectIdentifiers.cs
1,751
C#
using System; using Org.BouncyCastle.Bcpg.OpenPgp; using System.IO; using Org.BouncyCastle.Bcpg; using System.Collections; #pragma warning disable 1591 namespace FRENDS.Community.PgpSignature { public class PgpSignatureTask { /// <summary> /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath} /// </summary> public static Result PGPSignFile(Input input) { HashAlgorithmTag digest = input.HashFunction.ConvertEnum<HashAlgorithmTag>(); using (var privateKeyStream = File.OpenRead(input.PrivateKeyFile)) { PgpSecretKey pgpSecKey = ReadSecretKey(privateKeyStream); PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray()); PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest); PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator(); signatureGenerator.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, pgpPrivKey); IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (enumerator.MoveNext()) { signatureSubpacketGenerator.SetSignerUserId(false, (string)enumerator.Current); signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate()); } using (var outputStream = File.Create(input.OutputFile)) { ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream); BcpgOutputStream bcbgOutputStream = new BcpgOutputStream(armoredOutputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(bcbgOutputStream); FileInfo file = new FileInfo(input.InputFile); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); Stream literalDataOut = literalDataGenerator.Open(bcbgOutputStream, PgpLiteralData.Binary, file); using (var fileIn = file.OpenRead()) { int ch; while ((ch = fileIn.ReadByte()) >= 0) { literalDataOut.WriteByte((byte)ch); signatureGenerator.Update((byte)ch); } fileIn.Close(); literalDataGenerator.Close(); signatureGenerator.Generate().Encode(bcbgOutputStream); armoredOutputStream.Close(); outputStream.Close(); Result ret = new Result { FilePath = input.OutputFile }; return ret; } } } } internal static PgpSecretKey ReadSecretKey(Stream input) { PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle( PgpUtilities.GetDecoderStream(input)); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // foreach (PgpSecretKeyRing keyRing in pgpSec.GetKeyRings()) { foreach (PgpSecretKey key in keyRing.GetSecretKeys()) { if (key.IsSigningKey) { return key; } } } throw new ArgumentException("Can't find signing key in key ring."); } } }
41.645833
160
0.567034
[ "MIT" ]
CommunityHiQ/Frends.Community.PgpSignature
Frends.Community.PgpSignature/PgpSignatureTask.cs
4,000
C#
using System; using System.IO; using System.Net.Sockets; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Samples.Caching.Server; using static System.Console; namespace Samples.Caching.Client { public class ServiceChecker { public string SamplesDir { get; set; } public string ServerBinDir { get; set; } public DbSettings DbSettings { get; set; } public ClientSettings ClientSettings { get; set; } public ServiceChecker(DbSettings dbSettings, ClientSettings clientSettings) { DbSettings = dbSettings; ClientSettings = clientSettings; var baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ""; var binCfgPart = Regex.Match(baseDir, @"[\\/]bin[\\/]\w+[\\/]").Value; var cachingSampleDir = Path.GetFullPath(Path.Combine(baseDir, "../../../..")); SamplesDir = Path.GetFullPath(Path.Combine(cachingSampleDir, "../..")); ServerBinDir = Path.GetFullPath(Path.Combine(cachingSampleDir, $"Server/{binCfgPart}/net5.0/")); } public async Task WaitForServices(CancellationToken cancellationToken) { await WaitForService("SQL Server", DbSettings.ServerHost, DbSettings.ServerPort, "docker-compose up -d db", cancellationToken); await WaitForService("Samples.Caching.Server", ClientSettings.ServerHost, ClientSettings.ServerPort, "", cancellationToken); } private async Task WaitForService(string name, string ipAddress, int port, string command, CancellationToken cancellationToken) { var helpDisplayed = false; while (!IsPortOpen(ipAddress, port)) { if (!helpDisplayed) { helpDisplayed = true; if (string.IsNullOrEmpty(command)) WriteLine($"Start {name}."); else { WriteLine($"Start {name} by running:"); WriteLine($" {command}"); } } WriteLine($"Waiting for {name} to open {ipAddress}:{port}..."); await Task.Delay(1000, cancellationToken); } } private static bool IsPortOpen(string url, int port) { try { using var client = new TcpClient(url, port); return true; } catch (SocketException) { return false; } } } }
38.217391
135
0.579446
[ "MIT" ]
MessiDaGod/Stl.Fusion.Samples
src/Caching/Client/ServiceChecker.cs
2,637
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Recognizers.DataTypes.DateTime { public static class TimexConstraintsHelper { public static IEnumerable<TimeRange> Collapse(IEnumerable<TimeRange> ranges) { var r = ranges.ToList(); while (InnerCollapse(r)) { } r.Sort((a, b) => a.Start.GetTime() - b.Start.GetTime()); return r; } public static IEnumerable<DateRange> Collapse(IEnumerable<DateRange> ranges) { var r = ranges.ToList(); while (InnerCollapse(r)) { } r.Sort((a, b) => System.DateTime.Compare(a.Start, b.Start)); return r; } private static bool IsOverlapping(TimeRange r1, TimeRange r2) { return r1.End.GetTime() > r2.Start.GetTime() && r1.Start.GetTime() <= r2.Start.GetTime() || r1.Start.GetTime() < r2.End.GetTime() && r1.Start.GetTime() >= r2.Start.GetTime(); } private static TimeRange CollapseOverlapping(TimeRange r1, TimeRange r2) { return new TimeRange { Start = new Time(Math.Max(r1.Start.GetTime(), r2.Start.GetTime())), End = new Time(Math.Min(r1.End.GetTime(), r2.End.GetTime())) }; } private static bool InnerCollapse(List<TimeRange> ranges) { if (ranges.Count == 1) { return false; } for (int i = 0; i < ranges.Count; i++) { var r1 = ranges[i]; for (int j = i + 1; j < ranges.Count; j++) { var r2 = ranges[j]; if (IsOverlapping(r1, r2)) { ranges.RemoveRange(i, 1); ranges.RemoveRange(j - 1, 1); ranges.Add(CollapseOverlapping(r1, r2)); return true; } } } return false; } private static bool IsOverlapping(DateRange r1, DateRange r2) { return r1.End > r2.Start && r1.Start <= r2.Start || r1.Start < r2.End && r1.Start >= r2.Start; } private static DateRange CollapseOverlapping(DateRange r1, DateRange r2) { return new DateRange { Start = r1.Start > r2.Start ? r1.Start : r2.Start, End = r1.End < r2.End ? r1.End : r2.End }; } private static bool InnerCollapse(List<DateRange> ranges) { if (ranges.Count == 1) { return false; } for (int i = 0; i < ranges.Count; i++) { var r1 = ranges[i]; for (int j = i + 1; j < ranges.Count; j++) { var r2 = ranges[j]; if (IsOverlapping(r1, r2)) { ranges.RemoveRange(i, 1); ranges.RemoveRange(j - 1, 1); ranges.Add(CollapseOverlapping(r1, r2)); return true; } } } return false; } } }
30.482456
104
0.456978
[ "MIT" ]
stevengum97/Recognizers-Text
.NET/Microsoft.Recognizers.DataTypes.DateTime/TimexConstraintsHelper.cs
3,477
C#
using System; public class Exercises { static void Main() { var exercises = new Exercises(); Console.WriteLine(exercises.helloWorld()); Console.WriteLine(exercises.alternate("Hlo ol!", "el,Wrd")); Console.WriteLine(new String(exercises.swapEncrypt("Hello World".ToCharArray(), 11))); Console.WriteLine(new String(exercises.swapEncrypt("eHll ooWlrd".ToCharArray(), 11))); Console.WriteLine(exercises.isPalindrome("Hello, World!")); Console.WriteLine(exercises.isPalindrome("A Santa dog lived as a devil God at NASA.")); for (var i = 0; i < 10; i ++) Console.WriteLine(exercises.fibonacci(i)); } public string helloWorld() => "Hello, World!"; public string alternate(string first, string second) { var result = string.Empty; int i; for (i = 0; i < first.Length && i < second.Length; i++) result += first[i].ToString() + second[i]; result += first.Substring(i) + second.Substring(i); return result; } public char[] swapEncrypt(char[] toSwap, int length) { for (var i = 0; i + 1 < length; i += 2) { var tmp = toSwap[i]; toSwap[i] = toSwap[i + 1]; toSwap[i + 1] = tmp; } return toSwap; } public bool isPalindrome(string palindrome) { var clear = System.Text.RegularExpressions.Regex.Replace(palindrome, "[^A-Za-z]", "").ToLower(); for (int i = 0, j = clear.Length - 1; i < j; i++, j--) if (clear[i] != clear[j]) return false; return true; } public int fibonacci(int num) { if (num < 1) return 0; if (num == 1) return 1; return fibonacci(num - 2) + fibonacci(num - 1); } }
30.392157
98
0.652258
[ "MIT" ]
Progressor/ProgressorDefaultExercises
csharp/exercises.cs
1,552
C#
using PartyBook.ViewModels.Identity; using System.Threading.Tasks; namespace PartyBook.Client.Services { public interface IAuthService { Task<UserOutputModel> Login(LoginInputModel loginModel); Task Logout(); Task<UserOutputModel> Register(RegisterInputModel registerModel); } }
21.266667
73
0.730408
[ "MIT" ]
mishogv/PartyBook
src/PartyBook/Client/Services/IAuthService.cs
321
C#
using System; using Centaurus.Xdr; namespace Centaurus.Models { [XdrContract] [XdrUnion((int)MessageTypes.HandshakeInit, typeof(HandshakeInit))] [XdrUnion((int)MessageTypes.HandshakeResult, typeof(HandshakeResult))] [XdrUnion((int)MessageTypes.Heartbeat, typeof(Heartbeat))] [XdrUnion((int)MessageTypes.WithdrawalRequest, typeof(WithdrawalRequest))] [XdrUnion((int)MessageTypes.AccountDataRequest, typeof(AccountDataRequest))] [XdrUnion((int)MessageTypes.AccountDataResponse, typeof(AccountDataResponse))] [XdrUnion((int)MessageTypes.ITransactionResultMessage, typeof(ITransactionResultMessage))] [XdrUnion((int)MessageTypes.EffectsNotification, typeof(EffectsNotification))] [XdrUnion((int)MessageTypes.PaymentRequest, typeof(PaymentRequest))] [XdrUnion((int)MessageTypes.OrderRequest, typeof(OrderRequest))] [XdrUnion((int)MessageTypes.OrderCancellationRequest, typeof(OrderCancellationRequest))] [XdrUnion((int)MessageTypes.RequestQuantum, typeof(RequestQuantum))] [XdrUnion((int)MessageTypes.TxCommitQuantum, typeof(TxCommitQuantum))] [XdrUnion((int)MessageTypes.ResultMessage, typeof(ResultMessage))] [XdrUnion((int)MessageTypes.TxNotification, typeof(TxNotification))] [XdrUnion((int)MessageTypes.AuditorState, typeof(AuditorState))] [XdrUnion((int)MessageTypes.SetApexCursor, typeof(SetApexCursor))] [XdrUnion((int)MessageTypes.AlphaState, typeof(AlphaState))] [XdrUnion((int)MessageTypes.AuditorStateRequest, typeof(AuditorStateRequest))] [XdrUnion((int)MessageTypes.AuditorResultsBatch, typeof(AuditorResultsBatch))] [XdrUnion((int)MessageTypes.ConstellationInitQuantum, typeof(ConstellationInitQuantum))] [XdrUnion((int)MessageTypes.ConstellationUpgradeQuantum, typeof(ConstellationUpgradeQuantum))] [XdrUnion((int)MessageTypes.QuantaBatch, typeof(QuantaBatch))] [XdrUnion((int)MessageTypes.EffectsRequest, typeof(EffectsRequest))] [XdrUnion((int)MessageTypes.EffectsResponse, typeof(EffectsResponse))] [XdrUnion((int)MessageTypes.WithrawalsCleanup, typeof(WithrawalsCleanupQuantum))] public abstract class Message { public abstract MessageTypes MessageType { get; } public virtual long MessageId { get { return 0; } } } }
56.825
98
0.778707
[ "MIT" ]
amissine/centaurus
Centaurus.Models/Messages/Message.cs
2,275
C#
using System; using System.IO; using System.Windows.Forms; using Common; using DAL; using Models; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; namespace SolidWorksHelper { public class SSPFLATAutoDrawing : IAutoDrawing { readonly SSPFLATService objSSPFLATService = new SSPFLATService(); public void AutoDrawing(SldWorks swApp, ModuleTree tree, string projectPath) { //创建项目模型存放地址 string itemPath = projectPath + @"\" + tree.Module + "-" + tree.CategoryName; if (!Directory.Exists(itemPath)) { Directory.CreateDirectory(itemPath); } else { ShowMsg show = new ShowMsg(); DialogResult result = show.ShowMessageBoxTimeout("模型文件夹" + itemPath + "存在,如果之前pack已经执行过,将不执行pack过程而是直接修改模型,如果要中断作图点击YES,继续作图请点击No或者3s后窗口会自动消失", "提示信息", MessageBoxButtons.YesNo, 3000); if (result == DialogResult.Yes) return; } //Pack的后缀 string suffix = tree.Module + "-" + tree.ODPNo.Substring(tree.ODPNo.Length - 6); //判断文件是否存在,如果存在将不执行pack,如果不存在则执行pack //packango后需要接收打包完成的地址,参数为后缀 string packedAssyPath = itemPath + @"\" + tree.CategoryName.ToLower() + "_" + suffix + ".sldasm"; if (!File.Exists(packedAssyPath)) packedAssyPath = CommonFunc.PackAndGoFunc(suffix, swApp, tree.ModelPath, itemPath); //查询参数 SSPFLAT item = (SSPFLAT)objSSPFLATService.GetModelByModuleTreeId(tree.ModuleTreeId.ToString()); swApp.CommandInProgress = true; //告诉SolidWorks,现在是用外部程序调用命令 int warnings = 0; int errors = 0; suffix = "_" + suffix;//后缀 ModelDoc2 swModel = default(ModelDoc2); ModelDoc2 swPart = default(ModelDoc2); AssemblyDoc swAssy = default(AssemblyDoc); Component2 swComp; Feature swFeat = default(Feature); object configNames = null; ModelDocExtension swModelDocExt = default(ModelDocExtension); bool status = false; string compReName = string.Empty; //打开Pack后的模型 swModel = swApp.OpenDoc6(packedAssyPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2; swAssy = swModel as AssemblyDoc;//装配体 string assyName = swModel.GetTitle().Substring(0, swModel.GetTitle().Length - 7);//获取装配体名称 swModelDocExt = (ModelDocExtension)swModel.Extension; //打开装配体后必须重建,使Pack后的零件名都更新到带后缀的状态,否则程序出错 swModel.ForceRebuild3(true); //TopOnly参数设置成true,只重建顶层,不重建零件内部 /*注意SolidWorks单位是m,计算是应当/1000m * 整形与整形运算得出的结果仍然时整形,1640 / 1000m结果为0,因此必须将其中一个转化成decimal型,使用后缀m就可以了 * (int)不进行四舍五入,Convert.ToInt32会四舍五入 */ //-----------计算中间值,---------- try { //----------Top Level---------- //----------边缘Z板---------- swModel.Parameter("D1@Distance3").SystemValue = (item.MPanelNo * 2m - 1m) * 500m / 1000m; //左边 if (item.LeftType == "Z") { //重命名装配体内部 compReName = "FNCM0006[SSPFZ-" + tree.Module + ".L]{" + (int)(item.Length - 10m) + "}(" + (int)item.LeftLength + ")"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0006-L[SSPFZ-]{}()-4") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-4" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-4"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = item.LeftLength / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } //重命名装配体内部 compReName = "FNCM0004[SSPFW-" + tree.Module + ".L]{" + (int)(item.Length - 10m) + "}(500)"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0004-L[SSPFW-]{}()-2") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-2" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-2"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = 500m / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } } else { swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCM0006-L[SSPFZ-]{}()-4")); swComp.SetSuppression2(0); //2解压缩,0压缩. //重命名装配体内部 compReName = "FNCM0004[SSPFW-" + tree.Module + ".L]{" + (int)(item.Length - 10m) + "}(" + (int)item.LeftLength + ")"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0004-L[SSPFW-]{}()-2") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-2" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-2"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = item.LeftLength / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } } //右边 if (item.RightType == "Z") { //重命名装配体内部 compReName = "FNCM0006[SSPFZ-" + tree.Module + ".R]{" + (int)(item.Length - 10m) + "}(" + (int)item.RightLength + ")"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0006-R[SSPFZ-]{}()-3") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-3" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-3"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = item.RightLength / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } //重命名装配体内部 compReName = "FNCM0004[SSPFW-" + tree.Module + ".R]{" + (int)(item.Length - 10m) + "}(500)"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0004-R[SSPFW-]{}()-3") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-3" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-3"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = 500m / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } } else { swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCM0006-R[SSPFZ-]{}()-3")); swComp.SetSuppression2(0); //2解压缩,0压缩. //重命名装配体内部 compReName = "FNCM0004[SSPFW-" + tree.Module + ".R]{" + (int)(item.Length - 10m) + "}(" + (int)item.RightLength + ")"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0004-R[SSPFW-]{}()-3") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-3" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-3"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = item.RightLength / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } } //----------标准M板---------- //重命名装配体内部 compReName = "FNCM0005[SSPFM-" + tree.Module + "]{" + (int)(item.Length - 10m) + "}(500)"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0005[SSPFM-]{}-3") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-3" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-3"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = 500m / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } //----------标准W板---------- if (item.MPanelNo == 1) { swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCM0004[SSPFW-]{}-2")); swComp.SetSuppression2(0); //2解压缩,0压缩. swFeat = swAssy.FeatureByName("LocalLPattern2"); swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 swFeat = swAssy.FeatureByName("LocalLPattern1"); swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } else { //重命名装配体内部 compReName = "FNCM0004[SSPFW-" + tree.Module + "]{" + (int)(item.Length - 10m) + "}(500)"; status = swModelDocExt.SelectByID2(CommonFunc.AddSuffix(suffix, "FNCM0004[SSPFW-]{}-2") + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); if (status) swModelDocExt.RenameDocument(compReName); swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2(compReName + "-2" + "@" + assyName, "COMPONENT", 0, 0, 0, false, 0, null, 0); swModel.ClearSelection2(true); if (status) { swComp = swAssy.GetComponentByName(compReName + "-2"); swComp.SetSuppression2(2); //2解压缩,0压缩. swPart = swComp.GetModelDoc2(); //打开零件 swPart.Parameter("D2@Skizze1").SystemValue = (item.Length -10m) / 1000m; swPart.Parameter("D1@Skizze1").SystemValue = 500m / 1000m; swFeat = swComp.FeatureByName("LED"); if (item.LightType == "LED60") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩 } swFeat = swAssy.FeatureByName("LocalLPattern2"); swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 swFeat = swAssy.FeatureByName("LocalLPattern1"); swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩 swModel.Parameter("D1@LocalLPattern2").SystemValue = item.MPanelNo; swModel.Parameter("D1@LocalLPattern1").SystemValue = item.MPanelNo - 1; } swModel.ForceRebuild3(true);//设置成true,直接更新顶层,速度很快,设置成false,每个零件都会更新,很慢 swModel.Save();//保存,很耗时间 swApp.CloseDoc(packedAssyPath);//关闭,很快 } catch (Exception ex) { throw new Exception(packedAssyPath + "作图过程发生异常,详细:" + ex.Message); } finally { swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用 } } } }
60.238971
199
0.515532
[ "MIT" ]
felixzhu1989/Compass
SolidWorksHelper/CeilingAutoDrawing/SSPFLATAutoDrawing.cs
17,773
C#
using System; using System.Collections.Generic; using System.Text; namespace GraInfrastruktura.Entities { public class WynikEntity { public string Name { get; set; } public int IloscRuchow { get; set; } public TimeSpan Czas { get; set; } } }
20
44
0.653571
[ "MIT" ]
MarcinK-wsei/zgadywankalab3n
GraZaDuzoZaMalo/GraInfrastruktura/Entities/WynikEntity.cs
282
C#
using System.Security.Claims; using IdentityModel; using JWT.Models; using JWT.UnitTests.Extensions; using Xunit; namespace JWT.UnitTests { public class KeyInfoTests { [Fact] public void KeyInfo_Payload_Dictionary_Should_Contain_All_JwtClaimTypes() { var allJwtClaimTypes = typeof(JwtClaimTypes).GetAllPublicConstantValues<string>(); foreach (var jwtClaimType in allJwtClaimTypes) { Assert.True(KeyInfo.KeyInfoPayload.TryGetValue(jwtClaimType, out _)); } } [Fact] public void KeyInfo_Payload_Dictionary_Should_Contain_All_ClaimTypes() { var allClaimTypes = typeof(ClaimTypes).GetAllPublicConstantValues<string>(); foreach (var claimType in allClaimTypes) { Assert.True(KeyInfo.KeyInfoPayload.TryGetValue(claimType, out _)); } } } }
29.3125
94
0.641791
[ "MIT" ]
piraces/JWT
JWT.UnitTests/KeyInfoTests.cs
938
C#
#region license // // homer - The complete home automation for Homer Simpson. // Copyright (C) 2020, Hüseyin Uslu - shalafiraistlin at gmail dot com // https://github.com/bonesoul/homer // // “Commons Clause” License Condition v1.0 // // The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. // // Without limiting other conditions in the License, the grant of rights under the License will not include, and the License // does not grant to you, the right to Sell the Software. // // For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you under the License to provide // to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support // services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality // of the Software.Any license notice or attribution required by the License must also include this Commons Clause License // Condition notice. // // License: MIT License // Licensor: Hüseyin Uslu #endregion using Homer.Platform.HomeKit.Characteristics.Definitions; namespace Homer.Platform.HomeKit.Services.Definitions { public class Fanv2Service: Service { public const string Uuid = "000000B7-0000-1000-8000-0026BB765291"; public Fanv2Service() : base("000000B7-0000-1000-8000-0026BB765291", "Fan v2") { // required characteristics AddCharacteristic(typeof(ActiveCharacteristic)) ; // optional characteristics AddOptionalCharacteristic(typeof(CurrentFanStateCharacteristic)) .AddOptionalCharacteristic(typeof(TargetFanStateCharacteristic)) .AddOptionalCharacteristic(typeof(LockPhysicalControlsCharacteristic)) .AddOptionalCharacteristic(typeof(NameCharacteristic)) .AddOptionalCharacteristic(typeof(RotationDirectionCharacteristic)) .AddOptionalCharacteristic(typeof(RotationSpeedCharacteristic)) .AddOptionalCharacteristic(typeof(SwingModeCharacteristic)) ; } } }
43.846154
134
0.707018
[ "MIT" ]
bonesoul/homer
dotnet-core/src/platforms/homekit/Services/Definitions/Fanv2Service.cs
2,290
C#
using UnityEngine; namespace BattleshipGame.Core { [CreateAssetMenu(fileName = "Options", menuName = "Battleship/Options")] public class Options : ScriptableObject { public Difficulty aiDifficulty = Difficulty.Easy; public bool vibration = true; } }
25.727273
76
0.696113
[ "MIT" ]
MusapKahraman/Battleship
Battleship-Client/Assets/Scripts/Core/Options.cs
285
C#
using Microsoft.AspNetCore.Mvc; using ScheduleManager.Domain.Common; using ScheduleManager.Domain.Entities; namespace ScheduleManager.Api.Controllers.Api.V1.Common { [Area("Api_V1")] public class CourseController : ItemsController<Course> { public CourseController(IAsyncProvider<Course> itemProvider) : base(itemProvider) { } } }
26.5
89
0.727763
[ "MIT" ]
unsinedz/ScheduleManager
ScheduleManager.Api/Controllers/Api/V1/Common/CourseController.cs
371
C#
using System.ComponentModel; namespace Money.Enums { /// <summary> /// The CurrencyPositivePattern property is used with the "C" standard format string /// to define pattern of positive currency values. For more information, /// see Standard Numeric Format Strings. /// /// This property has one of the values in the following table. The symbol "$" is /// the CurrencySymbol and n is a number. /// /// https://docs.microsoft.com/en-us/dotnet/api/system.globalization.numberformatinfo.currencypositivepattern?view=net-6.0#remarks /// </summary> public enum PositivePosition { [Description("$n")] Before = 0, [Description("n$")] After = 1, [Description("$ n")] BeforeWithSpace = 2, [Description("n $")] AfterWithSpace = 3 } }
31.222222
134
0.627521
[ "MIT" ]
Money-NET/Money
Money/Enums/PositivePosition.cs
845
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Blogging.Models; namespace Blogging.Controllers { public class PostsController : Controller { private readonly BloggingContext _context; public PostsController(BloggingContext context) { _context = context; } // GET: Posts public async Task<IActionResult> Index() { // get all posts in the database, be sure to include the Blog model var allPosts = _context.Posts.Where(x => x.PostId != 0).Include(p => p.Blog); return View(await allPosts.ToListAsync()); } // GET: Posts/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var posts = await _context.Posts .Include(p => p.Blog) .FirstOrDefaultAsync(m => m.PostId == id); if (posts == null) { return NotFound(); } return View(posts); } // GET: Posts/Create public IActionResult Create() { ViewData["BlogId"] = new SelectList(_context.Blogs, "BlogId", "Url"); return View(); } // POST: Posts/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("PostId,BlogId,Content,Title")] Post post) { if (ModelState.IsValid) { // get the blog and add it to this model var blog = _context.Blogs.Where(x => x.BlogId == post.BlogId).SingleOrDefault(); // set the blog property of the post to the blog post.Blog = blog; _context.Add(post); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["BlogId"] = new SelectList(_context.Blogs, "BlogId", "Url", post.BlogId); return View(post); } // GET: Posts/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var post = await _context.Posts.FindAsync(id); if (post == null) { return NotFound(); } ViewData["BlogId"] = new SelectList(_context.Blogs, "BlogId", "Url", post.BlogId); return View(post); } // POST: Posts/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("PostId,BlogId,Content,Title")] Post post) { if (id != post.PostId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(post); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostExists(post.PostId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["BlogId"] = new SelectList(_context.Blogs, "BlogId", "Url", post.BlogId); return View(post); } // GET: Posts/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var post = await _context.Posts .Include(p => p.Blog) .FirstOrDefaultAsync(m => m.PostId == id); if (post == null) { return NotFound(); } return View(post); } // POST: Posts/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var post = await _context.Posts.FindAsync(id); _context.Posts.Remove(post); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool PostExists(int id) { return _context.Posts.Any(e => e.PostId == id); } } }
30.511905
111
0.502926
[ "MIT" ]
ABION-Technology/Blogging
Blogging/Controllers/PostsController.cs
5,128
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Hub.MqttBrokerAdapter { using System; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Azure.Devices.Edge.Util.Json; using Newtonsoft.Json; /// <summary> /// BrokerServiceIdentity is a Data Transfer Object used for sending authorized identities with /// their AuthChains from EdgeHub core to Mqtt Broker. /// </summary> public class BrokerServiceIdentity : IComparable { public BrokerServiceIdentity(string identity, Option<string> authChain) { this.Identity = Preconditions.CheckNonWhiteSpace(identity, nameof(identity)); this.AuthChain = authChain; } [JsonConstructor] public BrokerServiceIdentity(string identity, string authChain) { this.Identity = Preconditions.CheckNonWhiteSpace(identity, nameof(identity)); this.AuthChain = Option.Maybe(authChain); } [JsonProperty("Identity")] public string Identity { get; } [JsonProperty("AuthChain")] [JsonConverter(typeof(OptionConverter<string>))] public Option<string> AuthChain { get; } public int CompareTo(object obj) { BrokerServiceIdentity brokerServiceIdentity = (BrokerServiceIdentity)obj; if (this.Identity.Equals(brokerServiceIdentity.Identity)) { if (this.AuthChain.HasValue && brokerServiceIdentity.AuthChain.HasValue) { if (this.AuthChain.OrDefault().Equals(brokerServiceIdentity.AuthChain.OrDefault())) { return 0; } } else if (!this.AuthChain.HasValue && !brokerServiceIdentity.AuthChain.HasValue) { return 0; } } return -1; } } }
34.508772
103
0.600407
[ "MIT" ]
ArchanaMSFT/iotedge
edge-hub/core/src/Microsoft.Azure.Devices.Edge.Hub.MqttBrokerAdapter/BrokerServiceIdentity.cs
1,967
C#
namespace HandyControlDemo.UserControl { public partial class GravatarDemoCtl { public GravatarDemoCtl() { InitializeComponent(); } } }
18.4
40
0.592391
[ "MIT" ]
DingpingZhang/HandyControl
Net40/HandyControlDemo_Net40/UserControl/Controls/GravatarDemoCtl.xaml.cs
186
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("L2_Lab7")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("L2_Lab7")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ec17d7ae-f85b-4c60-9738-5f9cb838d00b")] // 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.351351
84
0.74602
[ "MIT" ]
doXi70/Homework_SoftUni
L2_Lab7/Properties/AssemblyInfo.cs
1,385
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.AspNetCore.Authorization; namespace APIViewWeb { public class RevisionOwnerRequirement : IAuthorizationRequirement { protected RevisionOwnerRequirement() { } public static RevisionOwnerRequirement Instance { get; } = new RevisionOwnerRequirement(); } }
25.75
98
0.718447
[ "MIT" ]
AlexGhiondea/azure-sdk-tools
src/dotnet/APIView/APIViewWeb/Account/RevisionOwnerRequirement.cs
414
C#
using HotChocolate.Language; using Xunit; namespace HotChocolate.Validation { public class ValuesOfCorrectTypeRuleTests : ValidationTestBase { public ValuesOfCorrectTypeRuleTests() : base(new ValuesOfCorrectTypeRule()) { } [Fact] public void GoodBooleanArg() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" { arguments { ...goodBooleanArg } } fragment goodBooleanArg on Arguments { booleanArgField(booleanArg: true) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.False(result.HasErrors); } [Fact] public void CoercedIntIntoFloatArg() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" { arguments { ...coercedIntIntoFloatArg } } fragment coercedIntIntoFloatArg on Arguments { # Note: The input coercion rules for Float allow Int literals. floatArgField(floatArg: 123) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.False(result.HasErrors); } [Fact] public void GoodComplexDefaultValue() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query goodComplexDefaultValue($search: ComplexInput = { name: ""Fido"" }) { findDog(complex: $search) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.False(result.HasErrors); } [Fact] public void StringIntoInt() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" { arguments { ...stringIntoInt } } fragment stringIntoInt on Arguments { intArgField(intArg: ""123"") } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.True(result.HasErrors); Assert.Collection(result.Errors, t => Assert.Equal( "The specified value type of argument `intArg` " + "does not match the argument type.", t.Message)); } [Fact] public void BadComplexValueArgument() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query badComplexValue { findDog(complex: { name: 123 }) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.True(result.HasErrors); Assert.Collection(result.Errors, t => Assert.Equal( "The specified value type of field `name` " + "does not match the field type.", t.Message)); } [Fact] public void BadComplexValueVariable() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query goodComplexDefaultValue($search: ComplexInput = { name: 123 }) { findDog(complex: $search) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.True(result.HasErrors); Assert.Collection(result.Errors, t => Assert.Equal( "The specified value type of field `name` " + "does not match the field type.", t.Message)); } [Fact] public void BadValueVariable() { // arrange Schema schema = ValidationUtils.CreateSchema(); DocumentNode query = Parser.Default.Parse(@" query goodComplexDefaultValue($search: ComplexInput = 123) { findDog(complex: $search) } "); // act QueryValidationResult result = Rule.Validate(schema, query); // assert Assert.True(result.HasErrors); Assert.Collection(result.Errors, t => Assert.Equal( "The specified value type of variable `search` " + "does not match the variable type.", t.Message)); } } }
30.066667
91
0.474871
[ "MIT" ]
gmiserez/hotchocolate
src/Core.Tests/Validation/ValuesOfCorrectTypeRuleTests.cs
5,412
C#
// <auto-generated /> using System; using Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Infrastructure.Migrations { [DbContext(typeof(StructureDBContext))] partial class StructureDBContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.6") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Domain.Entities.DCAppCanonicalURL", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppStructureId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppStructureId"); b.ToTable("DCAppCanonicalURL"); }); modelBuilder.Entity("Domain.Entities.DCAppCapability", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("CapabilityType") .HasColumnType("int"); b.Property<Guid?>("DCAppControlActionId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DataId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppControlActionId"); b.HasIndex("DataId"); b.ToTable("DCAppCapability"); }); modelBuilder.Entity("Domain.Entities.DCAppControl", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("DCAppPageId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DataFieldId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppPageId"); b.HasIndex("DataFieldId"); b.ToTable("DAppControls"); }); modelBuilder.Entity("Domain.Entities.DCAppControlAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppControlId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppControlId"); b.ToTable("DAppControlAction"); }); modelBuilder.Entity("Domain.Entities.DCAppControlProperty", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppControlId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppControlId"); b.ToTable("DAppControlProperties"); }); modelBuilder.Entity("Domain.Entities.DCAppDataDefinitionBase", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<bool>("AllowNullValue") .HasColumnType("bit"); b.Property<bool>("AllowOnlyUniqueValue") .HasColumnType("bit"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("DCAppDataDefinitions"); b.HasDiscriminator<string>("Discriminator").HasValue("DCAppDataDefinitionBase"); }); modelBuilder.Entity("Domain.Entities.DCAppDataField", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("DCAppDataModelId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppRolePermissionId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DataDefinitionId") .HasColumnType("uniqueidentifier"); b.Property<string>("DataType") .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppDataModelId"); b.HasIndex("DCAppRolePermissionId"); b.HasIndex("DataDefinitionId"); b.ToTable("DAppDataFields"); }); modelBuilder.Entity("Domain.Entities.DCAppDataModel", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("GroupId") .HasColumnType("uniqueidentifier"); b.Property<bool>("IsInternal") .HasColumnType("bit"); b.Property<bool>("IsSingleRecord") .HasColumnType("bit"); b.Property<bool>("IsSystemBased") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("GroupId"); b.ToTable("DAppDataModels"); b.HasDiscriminator<string>("Discriminator").HasValue("DCAppDataModel"); }); modelBuilder.Entity("Domain.Entities.DCAppDataValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("BaseDataFieldId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("BaseDataModelId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DataFieldId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("MultipleReferenceRowIds") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<Guid>("RowId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("SingleReferenceRowId") .HasColumnType("uniqueidentifier"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("BaseDataFieldId"); b.HasIndex("BaseDataModelId"); b.HasIndex("DataFieldId"); b.HasIndex("Name"); b.ToTable("DAppDataValues"); }); modelBuilder.Entity("Domain.Entities.DCAppEntityRowReference", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("DCAppEntityRowReferences"); }); modelBuilder.Entity("Domain.Entities.DCAppFeature", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("GroupId") .HasColumnType("uniqueidentifier"); b.Property<bool>("IsInternal") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("GroupId"); b.ToTable("DAppFeatures"); }); modelBuilder.Entity("Domain.Entities.DCAppGroup", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsInternal") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("ParentGroupId") .HasColumnType("uniqueidentifier"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("ParentGroupId"); b.ToTable("DAppGroups"); b.HasDiscriminator<string>("Discriminator").HasValue("DCAppGroup"); }); modelBuilder.Entity("Domain.Entities.DCAppPage", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("DCAppWorkFlowId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppWorkFlowId"); b.HasIndex("Name"); b.ToTable("DAppPages"); }); modelBuilder.Entity("Domain.Entities.DCAppRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("GroupId") .HasColumnType("uniqueidentifier"); b.Property<bool>("IsInternal") .HasColumnType("bit"); b.Property<bool>("IsSystemDefined") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("GroupId"); b.HasIndex("Name"); b.ToTable("DAppRoles"); }); modelBuilder.Entity("Domain.Entities.DCAppRoleAccessGroup", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsSource") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("ParentRoleId") .HasColumnType("uniqueidentifier"); b.Property<string>("ParentUserId") .HasColumnType("nvarchar(450)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.Property<Guid>("WorkFlowId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("ParentRoleId"); b.HasIndex("ParentUserId"); b.HasIndex("WorkFlowId"); b.ToTable("DAppRoleAccessGroups"); }); modelBuilder.Entity("Domain.Entities.DCAppRolePermission", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.Property<Guid>("WorkFlowId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("Name"); b.HasIndex("WorkFlowId"); b.ToTable("DAppRolePermissions"); }); modelBuilder.Entity("Domain.Entities.DCAppRoleRule", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ChildRoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppRolePermissionId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<Guid?>("ParentRoleId") .HasColumnType("uniqueidentifier"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("ChildRoleId"); b.HasIndex("DCAppRolePermissionId"); b.HasIndex("Name"); b.HasIndex("ParentRoleId"); b.ToTable("DAppRoleRules"); }); modelBuilder.Entity("Domain.Entities.DCAppStructure", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("ExternalGroupId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("InternalGroupId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Validity") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("ExternalGroupId"); b.HasIndex("InternalGroupId"); b.HasIndex("Name"); b.ToTable("DAppStructures"); }); modelBuilder.Entity("Domain.Entities.DCAppUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FirstName") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsInternal") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .HasColumnType("nvarchar(max)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("MiddleName") .HasColumnType("nvarchar(max)"); b.Property<string>("Mobile") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("Name"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); b.HasDiscriminator<string>("Discriminator").HasValue("DCAppUser"); }); modelBuilder.Entity("Domain.Entities.DCAppUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppUserRoleRoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("DCAppUserRoleUserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserId1") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId1"); b.HasIndex("DCAppUserRoleUserId", "DCAppUserRoleRoleId"); b.ToTable("DAppUserRoles"); }); modelBuilder.Entity("Domain.Entities.DCAppWorkFlow", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("DCAppDataModelId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("DCAppFeatureId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsSingleRecord") .HasColumnType("bit"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DCAppFeatureId"); b.HasIndex("Name"); b.ToTable("DAppWorkFlows"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppDataChoiceItem", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ChoiceGroup") .HasColumnType("nvarchar(max)"); b.Property<Guid>("ChoiceParentId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SortName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("ChoiceParentId"); b.ToTable("DAppDataChoiceItems"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("LastModifiedDate") .HasColumnType("datetime2"); b.Property<string>("LastModifiedUser") .HasColumnType("nvarchar(max)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppBoolDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.HasDiscriminator().HasValue("DCAppBoolDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppChoiceDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<bool>("AllowMultipleSelection") .HasColumnType("bit"); b.HasDiscriminator().HasValue("DCAppChoiceDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppDateTimeDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<string>("Format") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(max)") .HasDefaultValue("DD/MMM/YY"); b.HasDiscriminator().HasValue("DCAppDateTimeDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppFileDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<string>("Location") .HasColumnType("nvarchar(max)"); b.HasDiscriminator().HasValue("DCAppFileDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppNumberDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<short>("DecimalPlaces") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)2); b.Property<bool>("HasDecimals") .HasColumnType("bit"); b.HasDiscriminator().HasValue("DCAppNumberDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppRefEntityDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<bool>("IsSingleRecord") .HasColumnType("bit"); b.Property<bool>("IsSystemBuilt") .HasColumnType("bit"); b.Property<Guid>("RefDataModelId") .HasColumnType("uniqueidentifier"); b.Property<string>("SystemTableName") .HasColumnType("nvarchar(max)"); b.HasIndex("RefDataModelId"); b.HasDiscriminator().HasValue("DCAppRefEntityDataDefinition"); }); modelBuilder.Entity("Domain.Entities.Data.DCAppStringDataDefinition", b => { b.HasBaseType("Domain.Entities.DCAppDataDefinitionBase"); b.Property<string>("Format") .HasColumnName("DCAppStringDataDefinition_Format") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsMultiLine") .HasColumnType("bit"); b.Property<bool>("IsRegularExpressionFormat") .HasColumnType("bit"); b.Property<short>("Length") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)100); b.HasDiscriminator().HasValue("DCAppStringDataDefinition"); }); modelBuilder.Entity("Domain.Entities.DCAppCapabilityDataModel", b => { b.HasBaseType("Domain.Entities.DCAppDataModel"); b.Property<Guid?>("DCAppGroupId") .HasColumnType("uniqueidentifier"); b.HasIndex("DCAppGroupId"); b.HasDiscriminator().HasValue("DCAppCapabilityDataModel"); }); modelBuilder.Entity("Domain.Entities.DCAppExternalGroup", b => { b.HasBaseType("Domain.Entities.DCAppGroup"); b.HasDiscriminator().HasValue("DCAppExternalGroup"); }); modelBuilder.Entity("Domain.Entities.DCAppInternalGroup", b => { b.HasBaseType("Domain.Entities.DCAppGroup"); b.HasDiscriminator().HasValue("DCAppInternalGroup"); }); modelBuilder.Entity("Domain.Entities.DCAppExternalUser", b => { b.HasBaseType("Domain.Entities.DCAppUser"); b.Property<Guid?>("DCAppStructureId") .HasColumnType("uniqueidentifier"); b.HasIndex("DCAppStructureId"); b.HasDiscriminator().HasValue("DCAppExternalUser"); }); modelBuilder.Entity("Domain.Entities.DCAppInternalUser", b => { b.HasBaseType("Domain.Entities.DCAppUser"); b.Property<Guid?>("DCAppStructureId") .HasColumnName("DCAppInternalUser_DCAppStructureId") .HasColumnType("uniqueidentifier"); b.HasIndex("DCAppStructureId"); b.HasDiscriminator().HasValue("DCAppInternalUser"); }); modelBuilder.Entity("Domain.Entities.DCAppCanonicalURL", b => { b.HasOne("Domain.Entities.DCAppStructure", null) .WithMany("URLs") .HasForeignKey("DCAppStructureId"); }); modelBuilder.Entity("Domain.Entities.DCAppCapability", b => { b.HasOne("Domain.Entities.DCAppControlAction", null) .WithMany("Capabilities") .HasForeignKey("DCAppControlActionId"); b.HasOne("Domain.Entities.DCAppCapabilityDataModel", "Data") .WithMany() .HasForeignKey("DataId"); }); modelBuilder.Entity("Domain.Entities.DCAppControl", b => { b.HasOne("Domain.Entities.DCAppPage", "DCAppPage") .WithMany("Controls") .HasForeignKey("DCAppPageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Domain.Entities.DCAppDataField", "DataField") .WithMany() .HasForeignKey("DataFieldId"); }); modelBuilder.Entity("Domain.Entities.DCAppControlAction", b => { b.HasOne("Domain.Entities.DCAppControl", null) .WithMany("Actions") .HasForeignKey("DCAppControlId"); }); modelBuilder.Entity("Domain.Entities.DCAppControlProperty", b => { b.HasOne("Domain.Entities.DCAppControl", null) .WithMany("Properties") .HasForeignKey("DCAppControlId"); }); modelBuilder.Entity("Domain.Entities.DCAppDataField", b => { b.HasOne("Domain.Entities.DCAppDataModel", "DCAppDataModel") .WithMany("DataFields") .HasForeignKey("DCAppDataModelId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Domain.Entities.DCAppRolePermission", null) .WithMany("RestrictAccessFields") .HasForeignKey("DCAppRolePermissionId"); b.HasOne("Domain.Entities.DCAppDataDefinitionBase", "DataDefinition") .WithMany() .HasForeignKey("DataDefinitionId"); }); modelBuilder.Entity("Domain.Entities.DCAppDataModel", b => { b.HasOne("Domain.Entities.DCAppGroup", "Group") .WithMany("DataModels") .HasForeignKey("GroupId"); }); modelBuilder.Entity("Domain.Entities.DCAppDataValue", b => { b.HasOne("Domain.Entities.DCAppDataField", "BaseDataField") .WithMany() .HasForeignKey("BaseDataFieldId"); b.HasOne("Domain.Entities.DCAppDataModel", "BaseDataModel") .WithMany() .HasForeignKey("BaseDataModelId"); b.HasOne("Domain.Entities.DCAppDataField", "DataField") .WithMany() .HasForeignKey("DataFieldId"); }); modelBuilder.Entity("Domain.Entities.DCAppFeature", b => { b.HasOne("Domain.Entities.DCAppGroup", "Group") .WithMany("Features") .HasForeignKey("GroupId"); }); modelBuilder.Entity("Domain.Entities.DCAppGroup", b => { b.HasOne("Domain.Entities.DCAppGroup", "ParentGroup") .WithMany("ChildGroups") .HasForeignKey("ParentGroupId"); }); modelBuilder.Entity("Domain.Entities.DCAppPage", b => { b.HasOne("Domain.Entities.DCAppWorkFlow", "DCAppWorkFlow") .WithMany("Pages") .HasForeignKey("DCAppWorkFlowId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Domain.Entities.DCAppRole", b => { b.HasOne("Domain.Entities.DCAppGroup", "Group") .WithMany("Roles") .HasForeignKey("GroupId"); b.OwnsOne("Domain.ValueObjects.SystemRoleType", "SystemRole", b1 => { b1.Property<Guid>("DCAppRoleId") .HasColumnType("uniqueidentifier"); b1.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b1.Property<string>("Value") .HasColumnType("nvarchar(max)"); b1.HasKey("DCAppRoleId"); b1.ToTable("DAppRoles"); b1.WithOwner() .HasForeignKey("DCAppRoleId"); }); }); modelBuilder.Entity("Domain.Entities.DCAppRoleAccessGroup", b => { b.HasOne("Domain.Entities.DCAppRole", "ParentRole") .WithMany() .HasForeignKey("ParentRoleId"); b.HasOne("Domain.Entities.DCAppUser", "ParentUser") .WithMany() .HasForeignKey("ParentUserId"); b.HasOne("Domain.Entities.DCAppWorkFlow", "WorkFlow") .WithMany("AccessGroups") .HasForeignKey("WorkFlowId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Domain.Entities.DCAppRolePermission", b => { b.HasOne("Domain.Entities.DCAppWorkFlow", "WorkFlow") .WithMany("RoleAccessPermissions") .HasForeignKey("WorkFlowId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.OwnsOne("Domain.ValueObjects.AccessLevelType", "AccessLevel", b1 => { b1.Property<Guid>("DCAppRolePermissionId") .HasColumnType("uniqueidentifier"); b1.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b1.Property<string>("Value") .HasColumnType("nvarchar(max)"); b1.HasKey("DCAppRolePermissionId"); b1.ToTable("DAppRolePermissions"); b1.WithOwner() .HasForeignKey("DCAppRolePermissionId"); }); }); modelBuilder.Entity("Domain.Entities.DCAppRoleRule", b => { b.HasOne("Domain.Entities.DCAppRole", "ChildRole") .WithMany() .HasForeignKey("ChildRoleId"); b.HasOne("Domain.Entities.DCAppRolePermission", null) .WithMany("RoleRules") .HasForeignKey("DCAppRolePermissionId"); b.HasOne("Domain.Entities.DCAppRole", "ParentRole") .WithMany() .HasForeignKey("ParentRoleId"); b.OwnsOne("Domain.ValueObjects.RoleRuleType", "RuleType", b1 => { b1.Property<Guid>("DCAppRoleRuleId") .HasColumnType("uniqueidentifier"); b1.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b1.Property<string>("Value") .HasColumnType("nvarchar(max)"); b1.HasKey("DCAppRoleRuleId"); b1.ToTable("DAppRoleRules"); b1.WithOwner() .HasForeignKey("DCAppRoleRuleId"); }); }); modelBuilder.Entity("Domain.Entities.DCAppStructure", b => { b.HasOne("Domain.Entities.DCAppExternalGroup", "ExternalGroup") .WithMany() .HasForeignKey("ExternalGroupId"); b.HasOne("Domain.Entities.DCAppInternalGroup", "InternalGroup") .WithMany() .HasForeignKey("InternalGroupId"); }); modelBuilder.Entity("Domain.Entities.DCAppUserRole", b => { b.HasOne("Domain.Entities.DCAppRole", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Domain.Entities.DCAppUser", "User") .WithMany() .HasForeignKey("UserId1"); b.HasOne("Domain.Entities.DCAppUserRole", null) .WithMany("ReportsTo") .HasForeignKey("DCAppUserRoleUserId", "DCAppUserRoleRoleId"); }); modelBuilder.Entity("Domain.Entities.DCAppWorkFlow", b => { b.HasOne("Domain.Entities.DCAppFeature", "DCAppFeature") .WithMany("WorkFlows") .HasForeignKey("DCAppFeatureId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.OwnsOne("Domain.ValueObjects.DataRowAccessType", "RowAccessType", b1 => { b1.Property<Guid>("DCAppWorkFlowId") .HasColumnType("uniqueidentifier"); b1.Property<string>("DisplayName") .HasColumnType("nvarchar(max)"); b1.Property<string>("Value") .HasColumnType("nvarchar(max)"); b1.HasKey("DCAppWorkFlowId"); b1.ToTable("DAppWorkFlows"); b1.WithOwner() .HasForeignKey("DCAppWorkFlowId"); }); }); modelBuilder.Entity("Domain.Entities.Data.DCAppDataChoiceItem", b => { b.HasOne("Domain.Entities.Data.DCAppChoiceDataDefinition", "ChoiceParent") .WithMany("Choices") .HasForeignKey("ChoiceParentId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Domain.Entities.DCAppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Domain.Entities.DCAppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Domain.Entities.DCAppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Domain.Entities.DCAppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Domain.Entities.Data.DCAppRefEntityDataDefinition", b => { b.HasOne("Domain.Entities.DCAppDataModel", "RefDataModel") .WithMany() .HasForeignKey("RefDataModelId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Domain.Entities.DCAppCapabilityDataModel", b => { b.HasOne("Domain.Entities.DCAppGroup", null) .WithMany("CapabilityDataModels") .HasForeignKey("DCAppGroupId"); }); modelBuilder.Entity("Domain.Entities.DCAppExternalUser", b => { b.HasOne("Domain.Entities.DCAppStructure", null) .WithMany("External") .HasForeignKey("DCAppStructureId"); }); modelBuilder.Entity("Domain.Entities.DCAppInternalUser", b => { b.HasOne("Domain.Entities.DCAppStructure", null) .WithMany("Internal") .HasForeignKey("DCAppStructureId"); }); #pragma warning restore 612, 618 } } }
36.900782
125
0.450836
[ "MIT" ]
valstekt/opensource-application-design
src/Infrastructure/Migrations/StructureDBContextModelSnapshot.cs
61,368
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.ML; using Microsoft.ML.Data; namespace Samples.Dynamic.Trainers.Regression { public static class LbfgsPoissonRegression { public static void Example() { // Create a new context for ML.NET operations. It can be used for // exception tracking and logging, as a catalog of available operations // and as the source of randomness. Setting the seed to a fixed number // in this example to make outputs deterministic. var mlContext = new MLContext(seed: 0); // Create a list of training data points. var dataPoints = GenerateRandomDataPoints(1000); // Convert the list of data points to an IDataView object, which is // consumable by ML.NET API. var trainingData = mlContext.Data.LoadFromEnumerable(dataPoints); // Define the trainer. var pipeline = mlContext.Regression.Trainers. LbfgsPoissonRegression( labelColumnName: nameof(DataPoint.Label), featureColumnName: nameof(DataPoint.Features)); // Train the model. var model = pipeline.Fit(trainingData); // Create testing data. Use different random seed to make it different // from training data. var testData = mlContext.Data.LoadFromEnumerable( GenerateRandomDataPoints(5, seed: 123)); // Run the model on test data set. var transformedTestData = model.Transform(testData); // Convert IDataView object to a list. var predictions = mlContext.Data.CreateEnumerable<Prediction>( transformedTestData, reuseRowObject: false).ToList(); // Look at 5 predictions for the Label, side by side with the actual // Label for comparison. foreach (var p in predictions) Console.WriteLine($"Label: {p.Label:F3}, Prediction: {p.Score:F3}"); // Expected output: // Label: 0.985, Prediction: 1.109 // Label: 0.155, Prediction: 0.171 // Label: 0.515, Prediction: 0.400 // Label: 0.566, Prediction: 0.417 // Label: 0.096, Prediction: 0.172 // Evaluate the overall metrics var metrics = mlContext.Regression.Evaluate(transformedTestData); PrintMetrics(metrics); // Expected output: // Mean Absolute Error: 0.07 // Mean Squared Error: 0.01 // Root Mean Squared Error: 0.08 // RSquared: 0.93 (closer to 1 is better. The worst case is 0) } private static IEnumerable<DataPoint> GenerateRandomDataPoints(int count, int seed = 0) { var random = new Random(seed); for (int i = 0; i < count; i++) { float label = (float)random.NextDouble(); yield return new DataPoint { Label = label, // Create random features that are correlated with the label. Features = Enumerable.Repeat(label, 50).Select( x => x + (float)random.NextDouble()).ToArray() }; } } // Example with label and 50 feature values. A data set is a collection of // such examples. private class DataPoint { public float Label { get; set; } [VectorType(50)] public float[] Features { get; set; } } // Class used to capture predictions. private class Prediction { // Original label. public float Label { get; set; } // Predicted score from the trainer. public float Score { get; set; } } // Print some evaluation metrics to regression problems. private static void PrintMetrics(RegressionMetrics metrics) { Console.WriteLine("Mean Absolute Error: " + metrics.MeanAbsoluteError); Console.WriteLine("Mean Squared Error: " + metrics.MeanSquaredError); Console.WriteLine( "Root Mean Squared Error: " + metrics.RootMeanSquaredError); Console.WriteLine("RSquared: " + metrics.RSquared); } } }
37.771186
84
0.568768
[ "MIT" ]
GitHubPang/machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/LbfgsPoissonRegression.cs
4,459
C#
// Copyright (c) 2018 Alachisoft // // 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.Text; using System.Collections; using Alachisoft.NCache.Caching; using System.Collections.Generic; using Alachisoft.NCache.Common; using Alachisoft.NCache.Caching.Messaging; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Runtime.DatasourceProviders; using Alachisoft.NCache.Common.DataStructures.Clustered; namespace Alachisoft.NCache.SocketServer.Util { internal sealed class KeyPackageBuilder { private static Caching.Cache _cache = null; /// <summary> /// Cache Object used for deciding which Data Format mode current cache have. /// </summary> internal static Caching.Cache Cache { get { return KeyPackageBuilder._cache; } set { KeyPackageBuilder._cache = value; } } /// <summary> /// Make a package containing quote separated keys from list /// </summary> /// <param name="keysList">list of keys to be packaged</param> /// <returns>key package being constructed</returns> internal static string PackageKeys(ArrayList keyList) { StringBuilder keyPackage = new StringBuilder(keyList.Count * 256); for (int i = 0; i < keyList.Count; i++) keyPackage.Append((string)keyList[i] + "\""); return keyPackage.ToString(); } /// <summary> /// Make a package containing quote separated keys from list /// </summary> /// <param name="keysList">list of keys to be packaged</param> /// <returns>key package being constructed</returns> internal static string PackageKeys(ICollection keyList) { string packagedKeys = ""; if (keyList != null && keyList.Count > 0) { StringBuilder keyPackage = new StringBuilder(keyList.Count * 256); IEnumerator ie = keyList.GetEnumerator(); while(ie.MoveNext()) keyPackage.Append((string)ie.Current + "\""); packagedKeys = keyPackage.ToString(); } return packagedKeys; } internal static void PackageKeys(IDictionaryEnumerator dicEnu, out string keyPackage, out int keyCount) { StringBuilder keys = new StringBuilder(1024); keyCount = 0; while (dicEnu.MoveNext()) { keys.Append(dicEnu.Key + "\""); keyCount++; } keyPackage = keys.ToString(); } internal static void PackageKeys(IEnumerator enumerator, System.Collections.Generic.List<string> keys) { if (enumerator is IDictionaryEnumerator) { IDictionaryEnumerator ide = enumerator as IDictionaryEnumerator; while (ide.MoveNext()) { keys.Add((string)ide.Key); } } else { while (enumerator.MoveNext()) { keys.Add((string)enumerator.Current); } } } internal static IList PackageKeys(IEnumerator enumerator) { int estimatedSize = 0; IList ListOfKeyPackage = new ClusteredArrayList(); IList<string> keysChunkList = new ClusteredList<string>(); if (enumerator is IDictionaryEnumerator) { IDictionaryEnumerator ide = enumerator as IDictionaryEnumerator; while (ide.MoveNext()) { keysChunkList.Add((string)ide.Key); estimatedSize = estimatedSize + (((string)ide.Key).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) // If size is greater than specified size then add it and create new chunck { ListOfKeyPackage.Add(keysChunkList); keysChunkList = new ClusteredList<string>(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackage.Add(keysChunkList); } } else { while (enumerator.MoveNext()) { keysChunkList.Add((string)enumerator.Current); estimatedSize = estimatedSize + (((string)enumerator.Current).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) // If size is greater than specified size then add it and create new chunck { ListOfKeyPackage.Add(keysChunkList); keysChunkList = new ClusteredList<string>(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackage.Add(keysChunkList); } } if (ListOfKeyPackage.Count <= 0) { ListOfKeyPackage.Add(keysChunkList); } return ListOfKeyPackage; } /// <summary> /// Makes a key and data package form the keys and values of hashtable /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> /// <param name="currentContext">Current cache</param> internal static IList PackageKeysValues(IDictionary dic) { int estimatedSize = 0; IList ListOfKeyPackageResponse = new ClusteredArrayList(); if (dic != null && dic.Count > 0) { Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { Alachisoft.NCache.Common.Protobuf.Value value = new Alachisoft.NCache.Common.Protobuf.Value(); CompressedValueEntry cmpEntry= (CompressedValueEntry)enu.Value; UserBinaryObject ubObject = null; if (cmpEntry != null) { if (cmpEntry.Value is UserBinaryObject) ubObject = (UserBinaryObject)cmpEntry.Value; else ubObject = (UserBinaryObject)Cache.SocketServerDataService.GetClientData(cmpEntry.Value, ref cmpEntry.Flag, LanguageContext.DOTNET); } value.data.AddRange(ubObject.DataList); keyPackageResponse.keys.Add((string)enu.Key); keyPackageResponse.flag.Add(cmpEntry.Flag.Data); keyPackageResponse.values.Add(value); estimatedSize = estimatedSize + ubObject.Size + (((string)enu.Key).Length * sizeof(Char)); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) // If size is greater than specified size then add it and create new chunck { ListOfKeyPackageResponse.Add(keyPackageResponse); keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfKeyPackageResponse.Add(keyPackageResponse); } } else { ListOfKeyPackageResponse.Add(new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse()); } return ListOfKeyPackageResponse; } /// <summary> /// Makes a key and data package form the keys and values of hashtable /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> /// <param name="currentContext">Current cache</param> internal static Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse PackageKeysValues(IDictionary dic, Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse keyPackageResponse) { if (dic != null && dic.Count > 0) { if (keyPackageResponse == null) keyPackageResponse = new Alachisoft.NCache.Common.Protobuf.KeyValuePackageResponse(); ; IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { keyPackageResponse.keys.Add((string)enu.Key); CompressedValueEntry cmpEntry= (CompressedValueEntry)enu.Value; UserBinaryObject ubObject = Cache.SocketServerDataService.GetClientData(cmpEntry.Value, ref cmpEntry.Flag, LanguageContext.DOTNET) as UserBinaryObject; Alachisoft.NCache.Common.Protobuf.Value value = new Alachisoft.NCache.Common.Protobuf.Value(); value.data.AddRange(ubObject.DataList); keyPackageResponse.flag.Add(cmpEntry.Flag.Data); keyPackageResponse.values.Add(value); } } return keyPackageResponse; } /// <summary> /// Makes a key and data package form the keys and values of hashtable, for bulk operations /// </summary> /// <param name="dic">Hashtable containing the keys and values to be packaged</param> /// <param name="keys">Contains packaged keys after execution</param> /// <param name="data">Contains packaged data after execution</param> internal static void PackageKeysExceptions(Hashtable dic, Alachisoft.NCache.Common.Protobuf.KeyExceptionPackageResponse keyExceptionPackage) { if (dic != null && dic.Count > 0) { IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { Exception ex = enu.Value as Exception; if (ex != null) { keyExceptionPackage.keys.Add((string)enu.Key); Alachisoft.NCache.Common.Protobuf.Exception exc = new Alachisoft.NCache.Common.Protobuf.Exception(); exc.message = ex.Message; exc.exception = ex.ToString(); exc.type = Alachisoft.NCache.Common.Protobuf.Exception.Type.GENERALFAILURE; keyExceptionPackage.exceptions.Add(exc); } // for DS write failed operations if (enu.Value is OperationResult.Status) { OperationResult.Status status = (OperationResult.Status)enu.Value; if (status == OperationResult.Status.Failure || status == OperationResult.Status.FailureDontRemove) { keyExceptionPackage.keys.Add((string)enu.Key); Alachisoft.NCache.Common.Protobuf.Exception message = new Alachisoft.NCache.Common.Protobuf.Exception(); message.message = enu.Value.ToString(); message.exception = enu.Value.ToString(); message.type = Alachisoft.NCache.Common.Protobuf.Exception.Type.GENERALFAILURE; keyExceptionPackage.exceptions.Add(message); } } } } } internal static void PackageKeysVersion(IDictionary dic, Alachisoft.NCache.Common.Protobuf.KeyVersionPackageResponse keyVersionPackage) { if (dic != null && dic.Count > 0) { IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { ulong ver = Convert.ToUInt64(enu.Value.ToString()); if (ver != null) { keyVersionPackage.keys.Add((string)enu.Key); keyVersionPackage.versions.Add(ver); } } } } /// <summary> /// Package keys and values where values can be Exception or not. If they are no exception, currently, /// 0 bytes is returned /// </summary> /// <param name="dic"></param> /// <param name="keyPackage"></param> /// <param name="dataPackage"></param> internal static void PackageMisc(Hashtable dic, List<Alachisoft.NCache.Common.Protobuf.DSUpdatedCallbackResult> results) { if (dic != null && dic.Count > 0) { IDictionaryEnumerator enu = dic.GetEnumerator(); while (enu.MoveNext()) { Common.Protobuf.DSUpdatedCallbackResult result = new Alachisoft.NCache.Common.Protobuf.DSUpdatedCallbackResult(); result.key = (string)enu.Key; if (enu.Value is Exception) { result.success = false; Common.Protobuf.Exception ex = new Alachisoft.NCache.Common.Protobuf.Exception(); ex.message = ((Exception)enu.Value).Message; ex.exception = ((Exception)enu.Value).ToString(); ex.type = Alachisoft.NCache.Common.Protobuf.Exception.Type.GENERALFAILURE; result.exception = ex; } else if (enu.Value is OperationResult.Status) { switch ((OperationResult.Status)enu.Value) { case OperationResult.Status.Success: result.success = true; break; case OperationResult.Status.Failure: case OperationResult.Status.FailureDontRemove: result.success = false; break; } } results.Add(result); } } } internal static ClusteredList<List<Common.Protobuf.Message>> GetMessages(IList<object> result) { int estimatedSize = 0; ClusteredList<List<Common.Protobuf.Message>> ListOfMessagesResponse = new ClusteredList<List<Common.Protobuf.Message>>(); if (result != null && result.Count > 0) { List<Common.Protobuf.Message> messagesList = new List<Common.Protobuf.Message>(); IEnumerator<object> enu = result.GetEnumerator(); while (enu.MoveNext()) { var message = new Common.Protobuf.Message(); var value = new Common.Protobuf.Value(); var entry = (Message)enu.Current; BitSet flag = entry.FlagMap; UserBinaryObject ubObject = null; if (entry != null) { var binaryObject = entry.PayLoad as UserBinaryObject; if (binaryObject != null) ubObject = binaryObject; } if (ubObject != null) { value.data.AddRange(ubObject.DataList); estimatedSize = estimatedSize + ubObject.Size + entry.MessageId.Length * sizeof(char); } message.messageId = entry.MessageId; message.flag = flag.Data; message.payload = value; message.creationTime = entry.CreationTime.Ticks; message.expirationTime = entry.MessageMetaData.ExpirationTime; message.deliveryOption = (int)entry.MessageMetaData.DeliveryOption; message.subscriptionType = (int)entry.MessageMetaData.SubscriptionType; message.messageRemoveReason = (int)entry.MessageMetaData.MessgeFailureReason; if (entry.MessageMetaData.RecepientList != null) message.recipientList.AddRange(entry.MessageMetaData.RecepientList); messagesList.Add(message); if (estimatedSize >= ServiceConfiguration.ResponseDataSize) // If size is greater than specified size then add it and create new chunck { ListOfMessagesResponse.Add(messagesList); messagesList = new List<Common.Protobuf.Message>(); estimatedSize = 0; } } if (estimatedSize != 0) { ListOfMessagesResponse.Add(messagesList); } } else { ListOfMessagesResponse.Add(new List<Common.Protobuf.Message>()); } return ListOfMessagesResponse; } private static Common.Protobuf.MessageKeyValueResponse GetKeyValue(Message entry) { Common.Protobuf.MessageKeyValueResponse messageKeyValue = new Common.Protobuf.MessageKeyValueResponse(); Common.Protobuf.KeyValuePair keyValue = new Common.Protobuf.KeyValuePair(); keyValue.key = TopicConstant.DeliveryOption; int deliveryOption = (int)entry.MessageMetaData.DeliveryOption; keyValue.value = deliveryOption.ToString(); messageKeyValue.keyValuePair.Add(keyValue); return messageKeyValue; } } }
44.366822
194
0.544894
[ "Apache-2.0" ]
arstorey/NCache
Src/NCSocketServer/SocketServer/Util/KeyPackageBuilder.cs
18,989
C#
using System; using Xunit; using Xunit.Abstractions; namespace dexih.functions.ml.tests { public class regression { private readonly ITestOutputHelper _output; public regression(ITestOutputHelper output) { _output = output; } [Fact] public void RegressionLbfgsPoisson() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionLbfgsPoissonTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionLbfgsPoissonTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); Assert.True(prediction1 > 4 && prediction1 < 6); } [Fact] public void RegressionGam() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionGamTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionGamTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } //TODO Missing Library Issue. // [Fact] // public void RegressionOls() // { // var regression = new RegressionAnalysis(); // // // create data that easily clusters into two areas. // var labels = new[] {"x", "y"}; // var hotEncode = new[] {EEncoding.None, EEncoding.None}; // // // predict a simple linear line // for (var i = 1; i < 10; i++) // { // regression.RegressionOlsTrain(i, labels, new object[] {i, 2 * i}, hotEncode); // } // // var model = regression.RegressionOlsTrainResult(); // // Assert.NotNull(model); // // // check the clusters // var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); // // _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); // // } [Fact] public void RegressionFastForest() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionFastForestTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionFastForestTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } [Fact] public void RegressionSdca() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionSdcaTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionSdcaTrainResult(maximumNumberOfIterations:5); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 0); } [Fact] public void RegressionFastTree() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionFastTreeTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionFastTreeTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } [Fact] public void RegressionOnlineGradientDescent() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionOnlineGradientDescentTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionOnlineGradientDescentTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } [Fact] public void RegressionFastTreeTweedie() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 10; i++) { regression.RegressionFastTreeTweedieTrain(i, labels, new object[] {i, 2 * i}, hotEncode); } var model = regression.RegressionFastTreeTweedieTrainResult(); Assert.NotNull(model); // check the clusters var prediction1 = regression.RegressionPredict(model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } [Fact] public void RegressionBest() { var regression = new RegressionAnalysis(); // create data that easily clusters into two areas. var labels = new[] {"x", "y"}; var hotEncode = new[] {EEncoding.None, EEncoding.None}; // predict a simple linear line for (var i = 1; i < 50; i++) { regression.RegressionExperimentBest(i, labels, new object[] {i, 2 * i}, hotEncode); } var result = regression.RegressionExperimentBestResult(60); Assert.NotNull(result.Model); // check the clusters var prediction1 = regression.RegressionPredict(result.Model, labels, new object[] {5, 10}); _output.WriteLine($"Prediction: {prediction1}"); // Assert.True(prediction1 > 4 && prediction1 < 6); } } }
33.774319
111
0.522696
[ "Apache-2.0" ]
DataExperts/dexih.transforms
test/dexih.functions.ml.tests/regression.cs
8,680
C#
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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 HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using System.Linq; namespace Bam.Core { /// <summary> /// Singleton representing the single point of reference for all build functionality. /// This can be thought about as a layer on top of the DependencyGraph. /// </summary> public sealed class Graph : System.Collections.Generic.IEnumerable<ModuleCollection> { private string TheBuildRoot; static Graph() { Instance = new Graph(); Instance.Initialize(); } /// <summary> /// Obtain the singleton instance of the Graph. /// </summary> /// <value>Singleton instance.</value> public static Graph Instance { get; private set; } private void Initialize() { this.ProcessState = new BamState(); this.Modules = new System.Collections.Generic.Dictionary<Environment, System.Collections.Generic.List<Module>>(); this.ReferencedModules = new System.Collections.Generic.Dictionary<Environment, Array<Module>>(); this.TopLevelModules = new System.Collections.Generic.List<Module>(); this.Macros = new MacroList(this.GetType().FullName); this.BuildEnvironmentInternal = null; this.CommonModuleType = new PeekableStack<System.Type>(); this.ModuleStack = new PeekableStack<Module>(); this.DependencyGraph = new DependencyGraph(); this.MetaData = null; this.InternalPackageRepositories = new Array<PackageRepository>(); try { var primaryPackageRepoPath = System.IO.Directory.GetParent( System.IO.Directory.GetParent( System.IO.Directory.GetParent( this.ProcessState.ExecutableDirectory ).FullName ).FullName ).FullName; if (!System.IO.Directory.Exists(primaryPackageRepoPath)) { throw new Exception( $"Standard BAM package directory '{primaryPackageRepoPath}' does not exist" ); } this.AddPackageRepository(primaryPackageRepoPath); } catch (System.ArgumentNullException) { // this can happen during unit testing } this.ForceDefinitionFileUpdate = CommandLineProcessor.Evaluate(new Options.ForceDefinitionFileUpdate()); this.UpdateBamAssemblyVersions = CommandLineProcessor.Evaluate(new Options.UpdateBamAssemblyVersion()); this.CompileWithDebugSymbols = CommandLineProcessor.Evaluate(new Options.UseDebugSymbols()); } /// <summary> /// Add the module to the flat list of all modules in the current build environment. /// </summary> /// <param name="module">Module to be added</param> public void AddModule( Module module) => this.Modules[this.BuildEnvironmentInternal].Add(module); /// <summary> /// Stack of module types, that are pushed when a new module is created, and popped post-creation. /// This is so that modules created as dependencies can inspect their module parental hierarchy at construction time. /// </summary> /// <value>The stack of module types</value> public PeekableStack<System.Type> CommonModuleType { get; private set; } /// <summary> /// Stack of modules that were created prior to the current module. /// This is so that modules created as dependencies can inspect their module parental hierarchy at construction time. /// </summary> public PeekableStack<Module> ModuleStack { get; private set; } /// <summary> /// A referenced module is one that is referenced by it's class type. This is normally in use when specifying /// a dependency. There can be one and only one copy, in a build environment, of this type of module. /// A non-referenced module, is one that is never referred to explicitly in user scripts, but are created behind /// the scenes by packages. There can be many instances of these modules. /// The graph maintains a list of all referenced modules. /// This function either finds an existing referenced module in the current build Environment, or will create an /// instance. Since the current build Environment is inspected, this function cal only be called from within the /// Init() calling hierarchy of a Module. /// </summary> /// <returns>The instance of the referenced module.</returns> /// <typeparam name="T">The type of module being referenced.</typeparam> public T FindReferencedModule<T>() where T : Module, new() { if (null == this.BuildEnvironmentInternal) { var message = new System.Text.StringBuilder(); message.AppendLine("Unable to find a module either within a patch or after the build has started."); message.AppendLine("If called within a patch function, please modify the calling code to invoke this call within the module's Init method."); message.AppendLine("If it must called elsewhere, please use the overloaded version accepting an Environment argument."); throw new Exception(message.ToString()); } var referencedModules = this.ReferencedModules[this.BuildEnvironmentInternal]; var matchedModule = referencedModules.FirstOrDefault(item => item.GetType() == typeof(T)); if (null != matchedModule) { return matchedModule as T; } this.CommonModuleType.Push(typeof(T)); var moduleStackAppended = false; try { var newModule = Module.Create<T>(preInitCallback: module => { if (null != module) { this.ModuleStack.Push(module); moduleStackAppended = true; referencedModules.Add(module); } }); return newModule; } catch (UnableToBuildModuleException) { // remove the failed to create module from the referenced list // and also any modules and strings created in its Init function, potentially // of child module types var moduleTypeToRemove = this.CommonModuleType.Peek(); TokenizedString.RemoveEncapsulatedStrings(moduleTypeToRemove); Module.RemoveEncapsulatedModules(moduleTypeToRemove); referencedModules.Remove(referencedModules.First(item => item.GetType() == typeof(T))); var moduleEnvList = this.Modules[this.BuildEnvironmentInternal]; moduleEnvList.Remove(moduleEnvList.First(item => item.GetType() == typeof(T))); throw; } finally { if (moduleStackAppended) { this.ModuleStack.Pop(); } this.CommonModuleType.Pop(); } } /// <summary> /// Find an existing instance of a referenced module, by its type, in the provided build Environment. /// If no such instance can be found, an exception is thrown. /// </summary> /// <typeparam name="T">Type of the referenced Module sought</typeparam> /// <param name="env">Environment in which the referenced Module should exist.</param> /// <returns>Instance of the matched Module type in the Environment's referenced Modules.</returns> public T FindReferencedModule<T>( Environment env) where T : Module, new() { if (null == env) { throw new Exception("Must provide a valid Environment"); } var referencedModules = this.ReferencedModules[env]; var matchedModule = referencedModules.FirstOrDefault(item => item.GetType() == typeof(T)); if (null == matchedModule) { throw new Exception( $"Unable to locate a referenced module of type {typeof(T).ToString()} in the provided build environment" ); } return matchedModule as T; } private readonly System.Collections.Generic.Dictionary<System.Type, System.Func<Module>> compiledFindRefModuleCache = new System.Collections.Generic.Dictionary<System.Type, System.Func<Module>>(); private Module MakeModuleOfType( System.Type moduleType) { try { if (!this.compiledFindRefModuleCache.ContainsKey(moduleType)) { // find method for the module type requested // (the caching is based on this being 'expensive' as it's based on reflection) var findReferencedModuleMethod = typeof(Graph).GetMethod("FindReferencedModule", System.Type.EmptyTypes); var genericVersionForModuleType = findReferencedModuleMethod.MakeGenericMethod(moduleType); // now compile it, so that we don't have to repeat the above var instance = System.Linq.Expressions.Expression.Constant(this); var call = System.Linq.Expressions.Expression.Call( instance, genericVersionForModuleType); var lambda = System.Linq.Expressions.Expression.Lambda<System.Func<Module>>(call); var func = lambda.Compile(); // and store it this.compiledFindRefModuleCache.Add(moduleType, func); } var newModule = this.compiledFindRefModuleCache[moduleType](); Log.DetailProgress(Module.Count.ToString()); return newModule; } catch (UnableToBuildModuleException exception) { Log.Info( $"Unable to instantiate module of type {moduleType.ToString()} because {exception.Message} from {exception.ModuleType.ToString()}" ); return null; } catch (System.Reflection.TargetInvocationException ex) { var exModuleType = (ex.InnerException is ModuleCreationException) ? (ex.InnerException as ModuleCreationException).ModuleType : moduleType; var realException = ex.InnerException; if (null == realException) { realException = ex; } throw new Exception(realException, $"Failed to create module of type {exModuleType.ToString()}"); } } /// <summary> /// Create an unreferenced module instance of the specified type. /// </summary> /// <returns>The module of type.</returns> /// <param name="moduleType">Module type.</param> /// <typeparam name="ModuleType">The 1st type parameter.</typeparam> public ModuleType MakeModuleOfType<ModuleType>( System.Type moduleType) where ModuleType : Module => this.MakeModuleOfType(moduleType) as ModuleType; /// <summary> /// Create all modules in the top level namespace, which is the namespace of the package in which Bam is invoked. /// </summary> /// <param name="assembly">Package assembly</param> /// <param name="env">Environment to create the modules for.</param> /// <param name="ns">Namespace of the package in which Bam is invoked.</param> public void CreateTopLevelModules( System.Reflection.Assembly assembly, Environment env, string ns) { var allTypes = assembly.GetTypes(); var allModuleTypesInPackage = allTypes.Where(type => (System.String.Equals(ns, type.Namespace, System.StringComparison.Ordinal) || (this.UseTestsNamespace && System.String.Equals(ns + ".tests", type.Namespace, System.StringComparison.Ordinal))) && type.IsSubclassOf(typeof(Module)) ); if (!allModuleTypesInPackage.Any()) { throw new Exception( $"No modules found in the namespace '{ns}'. Please define some modules in the build scripts to use {ns} as a master package." ); } System.Collections.Generic.IEnumerable<System.Type> allTopLevelModuleTypesInPackage; var commandLineTopLevelModules = CommandLineProcessor.Evaluate(new Options.SetTopLevelModules()); if (null != commandLineTopLevelModules && commandLineTopLevelModules.Any()) { allTopLevelModuleTypesInPackage = allModuleTypesInPackage.Where( allItem => commandLineTopLevelModules.First().Any( cmdModuleName => allItem.Name.Contains(cmdModuleName, System.StringComparison.Ordinal) ) ); } else { allTopLevelModuleTypesInPackage = allModuleTypesInPackage.Where(type => type.IsSealed); } if (!allTopLevelModuleTypesInPackage.Any()) { ICommandLineArgument tlmOption = new Options.SetTopLevelModules(); var tlmOptionEqualsIndex = tlmOption.LongName.IndexOf('='); var message = new System.Text.StringBuilder(); message.AppendLine( $"No top-level modules found in the namespace '{ns}'. Please mark some of the modules below as 'sealed', or use the '{tlmOption.LongName.Substring(0, tlmOptionEqualsIndex)}' command line option, to identify them as top-level, and thus buildable when {ns} is the master package:" ); foreach (var moduleType in allModuleTypesInPackage) { message.AppendLine($"\t{moduleType.ToString()}"); } throw new Exception(message.ToString()); } try { this.CreateTopLevelModuleFromTypes(allTopLevelModuleTypesInPackage, env); } catch (Exception ex) { throw new Exception(ex, $"An error occurred creating top-level modules in namespace '{ns}':"); } } /// <summary> /// Create top-level modules from a list of types. /// </summary> /// <param name="moduleTypes">List of module types to create.</param> /// <param name="env">Build environment to create modules for.</param> public void CreateTopLevelModuleFromTypes( System.Collections.Generic.IEnumerable<System.Type> moduleTypes, Environment env) { this.BuildEnvironment = env; foreach (var moduleType in moduleTypes) { MakeModuleOfType(moduleType); } this.BuildEnvironment = null; // scan all modules in the build environment for "top-level" status // as although they should just be from the list of incoming moduleTypes // it's possible for new modules to be introduced that depend on them foreach (var module in this.Modules[env]) { if (module.TopLevel) { this.TopLevelModules.Add(module); } } if (!this.TopLevelModules.Any()) { var message = new System.Text.StringBuilder(); message.AppendLine("Top-level module types detected, but none could be instantiated:"); foreach (var moduleType in moduleTypes) { message.AppendLine($"\t{moduleType.ToString()}"); } throw new Exception(message.ToString()); } } /// <summary> /// Apply any patches associated with modules. /// </summary> public void ApplySettingsPatches() { Log.Detail("Apply settings to modules..."); var scale = 100.0f / Module.Count; var count = 0; foreach (var rank in this.DependencyGraph.Reverse()) { foreach (var module in rank.Value) { module.ApplySettingsPatches(); Log.DetailProgress("{0,3}%", (int)(++count * scale)); } } } private System.Collections.Generic.List<Module> TopLevelModules { get; set; } private System.Collections.Generic.Dictionary<Environment, System.Collections.Generic.List<Module>> Modules { get; set; } private System.Collections.Generic.Dictionary<Environment, Array<Module>> ReferencedModules { get; set; } /// <summary> /// Obtain the build mode. /// </summary> /// <value>The mode.</value> public string Mode { get; set; } /// <summary> /// Whether the 'tests' namespace of the master package is to be queried for top-level modules. /// </summary> public bool UseTestsNamespace { get; set; } /// <summary> /// Obtain global macros. /// </summary> /// <value>The macros.</value> public MacroList Macros { get; set; } /// <summary> /// Get or set metadata associated with the Graph. This is used for multi-threaded builds. /// </summary> /// <value>The meta data.</value> public object MetaData { get; set; } private Environment BuildEnvironmentInternal = null; /// <summary> /// Get the current build environment. /// </summary> /// <value>The build environment.</value> public Environment BuildEnvironment { get { return this.BuildEnvironmentInternal; } private set { this.BuildEnvironmentInternal = value; if (null != value) { this.Modules.Add(value, new System.Collections.Generic.List<Module>()); this.ReferencedModules.Add(value, new Array<Module>()); } } } /// <summary> /// Get the actual graph of module dependencies. /// </summary> /// <value>The dependency graph.</value> public DependencyGraph DependencyGraph { get; private set; } private void ApplyGroupDependenciesToChildren( Module module, System.Collections.Generic.IEnumerable<Module> children, System.Collections.Generic.IEnumerable<Module> dependencies) { // find all dependencies that are not children of this module var nonChildDependents = dependencies.Where(item => !(item is IChildModule) || (item as IChildModule).Parent != module); if (!nonChildDependents.Any()) { return; } foreach (var c in children) { c.DependsOn(nonChildDependents); } } private void ApplyGroupRequirementsToChildren( Module module, System.Collections.Generic.IEnumerable<Module> children, System.Collections.Generic.IEnumerable<Module> dependencies) { // find all dependencies that are not children of this module var nonChildDependents = dependencies.Where(item => !(item is IChildModule) || (item as IChildModule).Parent != module); if (!nonChildDependents.Any()) { return; } foreach (var c in children) { c.Requires(nonChildDependents); } } private void SetModuleRank( System.Collections.Generic.Dictionary<Module, int> map, Module module, int rankIndex) { if (map.ContainsKey(module)) { throw new Exception($"Module {module.ToString()} rank initialized more than once"); } map.Add(module, rankIndex); } private void MoveModuleRankBy( System.Collections.Generic.Dictionary<Module, int> map, Module module, int rankDelta) { if (!map.ContainsKey(module)) { // a dependency hasn't yet been initialized, so don't try to move it return; } map[module] += rankDelta; foreach (var dep in module.Dependents) { MoveModuleRankBy(map, dep, rankDelta); } foreach (var dep in module.Requirements) { MoveModuleRankBy(map, dep, rankDelta); } } private void MoveModuleRankTo( System.Collections.Generic.Dictionary<Module, int> map, Module module, int rankIndex) { if (!map.ContainsKey(module)) { throw new Exception($"Module {module.ToString()} has yet to be initialized"); } var currentRank = map[module]; var rankDelta = rankIndex - currentRank; MoveModuleRankBy(map, module, rankDelta); } private void ProcessModule( System.Collections.Generic.Dictionary<Module, int> map, System.Collections.Generic.Queue<Module> toProcess, Module module, int rankIndex) { if (module.Tool != null) { if (null == module.Settings) { module.Requires(module.Tool); var child = module as IChildModule; if ((null == child) || (null == child.Parent)) { // children inherit the settings from their parents module.UsePublicPatches(module.Tool); } try { // this handles connecting the module to the settings and vice versa too var settings = module.MakeSettings(); settings?.SetModuleAndDefaultPropertyValues(module); } catch (System.TypeInitializationException ex) { throw ex.InnerException; } catch (System.Reflection.TargetInvocationException ex) { var realException = ex.InnerException; if (null == realException) { realException = ex; } throw new Exception(realException, "Settings creation:"); } } } if (!module.Dependents.Any() && !module.Requirements.Any()) { return; } if (module is IModuleGroup) { var children = module.Children; this.ApplyGroupDependenciesToChildren(module, children, module.Dependents); this.ApplyGroupRequirementsToChildren(module, children, module.Requirements); } var nextRankIndex = rankIndex + 1; foreach (var dep in module.Dependents) { if (map.ContainsKey(dep)) { if (map[dep] < nextRankIndex) { MoveModuleRankTo(map, dep, nextRankIndex); } } else { SetModuleRank(map, dep, nextRankIndex); toProcess.Enqueue(dep); } } foreach (var dep in module.Requirements) { if (map.ContainsKey(dep)) { if (map[dep] < nextRankIndex) { MoveModuleRankTo(map, dep, nextRankIndex); } } else { SetModuleRank(map, dep, nextRankIndex); toProcess.Enqueue(dep); } } } /// <summary> /// Sort all dependencies, invoking Init functions, creating all additional dependencies, placing /// modules into their correct rank. /// Settings classes are also created and set to default property values if modules have a Tool associated with them. /// </summary> public void SortDependencies() { Log.Detail("Analysing module dependencies..."); var moduleRanks = new System.Collections.Generic.Dictionary<Module, int>(); var modulesToProcess = new System.Collections.Generic.Queue<Module>(); var totalProgress = 3 * Module.Count; // all modules are iterated over three times (twice in here, and once in CompleteModules) var scale = 100.0f / totalProgress; // initialize the map with top-level modules // and populate the to-process list var progress = 0; Log.DetailProgress("{0,3}%", (int)(progress * scale)); foreach (var module in this.TopLevelModules) { SetModuleRank(moduleRanks, module, 0); ProcessModule(moduleRanks, modulesToProcess, module, 0); Log.DetailProgress("{0,3}%", (int)((++progress) * scale)); } // process all modules by initializing them to a best-guess rank // but then potentially moving them to a higher rank if they re-appear as dependencies while (modulesToProcess.Any()) { var module = modulesToProcess.Dequeue(); ProcessModule(moduleRanks, modulesToProcess, module, moduleRanks[module]); Log.DetailProgress("{0,3}%", (int)((++progress) * scale)); } // moduleRanks[*].Value is now sparse - there may be gaps between successive ranks with modules // this needs to be collapsed so that the rank indices are contiguous (the order is correct, the indices are just wrong) // assign modules, for each rank index, into collections var contiguousRankIndex = 0; var lastRankIndex = 0; foreach (var nextModule in moduleRanks.OrderBy(item => item.Value)) { if (lastRankIndex != nextModule.Value) { lastRankIndex = nextModule.Value; contiguousRankIndex++; } var rank = this.DependencyGraph[contiguousRankIndex]; rank.Add(nextModule.Key); Log.DetailProgress("{0,3}%", (int)((++progress) * scale)); } Module.CompleteModules(); } private static void DumpModule( System.Text.StringBuilder builder, int depth, char? prefix, Module module, Array<Module> visited) { if (prefix.HasValue) { builder.Append($"{new string(' ', depth)}{prefix.Value}{module.ToString()}"); } else { builder.Append($"{new string(' ', depth)}{module.ToString()}"); } if (visited.Contains(module)) { builder.AppendLine("*"); return; } visited.Add(module); if (module is IInputPath inputPath) { builder.AppendLine($" {inputPath.InputPath.ToString()}"); } foreach (var req in module.Requirements) { DumpModule(builder, depth + 1, '-', req, visited); } foreach (var dep in module.Dependents) { DumpModule(builder, depth + 1, '+', dep, visited); } } private void DumpModuleHierarchy() { Log.Message(this.VerbosityLevel, "Module hierarchy"); var visited = new Array<Module>(); foreach (var module in this.TopLevelModules) { var text = new System.Text.StringBuilder(); DumpModule(text, 0, null, module, visited); Log.Message(this.VerbosityLevel, text.ToString()); } } private void DumpRankHierarchy() { Log.Message(this.VerbosityLevel, "Rank hierarchy"); foreach (var rank in this.DependencyGraph) { var text = new System.Text.StringBuilder(); text.AppendLine(); text.AppendLine($"Rank {rank.Key}: {rank.Value.Count()} modules"); text.AppendLine(new string('-', 80)); foreach (var m in rank.Value) { text.AppendLine(m.ToString()); if (m is IInputPath inputPath) { text.AppendLine($"\tInput: {inputPath.InputPath.ToString()}"); } foreach (var s in m.GeneratedPaths) { text.AppendLine($"\t{s.Key} : {s.Value}"); } } Log.Message(this.VerbosityLevel, text.ToString()); } } /// <summary> /// Dump a representation of the dependency graph to the console. /// Initially a representation of module hierarchies /// depth of dependency is indicated by indentation /// a direct dependency is a + prefix /// an indirect dependency is a - prefix /// Then a representation of rank hierarchies, i.e. the order in which /// modules will be built. /// </summary> public void Dump() { Log.Message(this.VerbosityLevel, new string('*', 80)); Log.Message(this.VerbosityLevel, "{0,50}", "DEPENDENCY GRAPH VIEW"); Log.Message(this.VerbosityLevel, new string('*', 80)); this.DumpModuleHierarchy(); this.DumpRankHierarchy(); Log.Message(this.VerbosityLevel, new string('*', 80)); Log.Message(this.VerbosityLevel, "{0,50}", "END DEPENDENCY GRAPH VIEW"); Log.Message(this.VerbosityLevel, new string('*', 80)); } private void InternalValidateGraph( int parentRankIndex, System.Collections.Generic.IEnumerable<Module> modules) { foreach (var c in modules) { var childCollection = c.OwningRank; if (null == childCollection) { throw new Exception("Dependency has no rank"); } try { var childRank = this.DependencyGraph.First(item => item.Value == childCollection); var childRankIndex = childRank.Key; if (childRankIndex <= parentRankIndex) { throw new Exception( $"Dependent module {c.ToString()} found at a lower rank {childRankIndex} than the dependee {parentRankIndex}" ); } } catch (System.InvalidOperationException) { throw new Exception("Module collection not found in graph"); } } } /// <summary> /// Perform a validation step to ensure that all modules exist and are in correct ranks. /// </summary> public void Validate() { foreach (var rank in this.DependencyGraph) { foreach (var m in rank.Value) { this.InternalValidateGraph(rank.Key, m.Dependents); this.InternalValidateGraph(rank.Key, m.Requirements); } } Log.DebugMessage("Used packages:"); foreach (var package in this.PackageDefinitions.Where(item => item.CreatedModules().Any())) { Log.DebugMessage($"\t{package.Name}"); foreach (var module in package.CreatedModules()) { Log.DebugMessage($"\t\t{module.ToString()}"); } } Log.DebugMessage("Unused packages:"); foreach (var package in this.PackageDefinitions.Where(item => !item.CreatedModules().Any())) { Log.DebugMessage($"\t{package.Name}"); } } /// <summary> /// Wrapper around the enumerator of the DependencyGraph, but only returning the rank module collections. /// </summary> /// <returns>The enumerator.</returns> public System.Collections.Generic.IEnumerator<ModuleCollection> GetEnumerator() { foreach (var rank in this.DependencyGraph) { yield return rank.Value; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Determines whether the specified module is referenced or unreferenced. /// </summary> /// <returns><c>true</c> if this instance is referenced; otherwise, <c>false</c>.</returns> /// <param name="module">Module to check.</param> public bool IsReferencedModule( Module module) => this.ReferencedModules[module.BuildEnvironment].Contains(module); /// <summary> /// Returns a enumeration of all the named/referenced/encapsulating modules /// for the specified Environment. /// </summary> /// <returns>The collection of modules</returns> /// <param name="env">The Environment to query for named modules.</param> public System.Collections.Generic.IEnumerable<Module> EncapsulatingModules( Environment env) => this.ReferencedModules[env]; /// <summary> /// Obtain the list of build environments defined for this Graph. /// </summary> /// <value>The build environments.</value> public System.Collections.Generic.List<Environment> BuildEnvironments => this.Modules.Keys.ToList(); private System.Collections.Generic.IEnumerable<PackageDefinition> PackageDefinitions { get; set; } /// <summary> /// Obtain the master package (the package in which Bam was invoked). /// </summary> /// <value>The master package.</value> public PackageDefinition MasterPackage { get { if (null == this.PackageDefinitions) { throw new Exception("No master package was detected"); } return this.PackageDefinitions.First(); } } /// <summary> /// Assign the array of package definitions to the Graph. /// Macros added to the Graph are: /// 'masterpackagename' /// Packages with external sources are fetched at this point. /// </summary> /// <param name="packages">Array of package definitions.</param> public void SetPackageDefinitions( System.Collections.Generic.IEnumerable<PackageDefinition> packages) { this.PackageDefinitions = packages; this.Macros.AddVerbatim(GraphMacroNames.MasterPackageName, this.MasterPackage.Name); } /// <summary> /// Enumerate the package definitions associated with the Graph. /// </summary> /// <value>The packages.</value> public System.Collections.Generic.IEnumerable<PackageDefinition> Packages { get { if (null == this.PackageDefinitions) { throw new Exception("No packages were defined in the build"); } foreach (var package in this.PackageDefinitions) { yield return package; } } } /// <summary> /// Obtain the metadata associated with the chosen build mode. /// </summary> /// <value>The build mode meta data.</value> public IBuildModeMetaData BuildModeMetaData { get; set; } static internal PackageMetaData InstantiatePackageMetaData( System.Type metaDataType) { try { return System.Activator.CreateInstance(metaDataType) as PackageMetaData; } catch (Exception exception) { throw exception; } catch (System.Reflection.TargetInvocationException exception) { throw new Exception(exception, "Failed to create package metadata"); } } static internal PackageMetaData InstantiatePackageMetaData<MetaDataType>() => InstantiatePackageMetaData(typeof(MetaDataType)); /// <summary> /// For a given package, obtain the metadata and cast it to MetaDataType. /// </summary> /// <returns>The meta data.</returns> /// <param name="packageName">Package name.</param> /// <typeparam name="MetaDataType">The 1st type parameter.</typeparam> public MetaDataType PackageMetaData<MetaDataType>( string packageName) where MetaDataType : class { var package = Bam.Core.Graph.Instance.Packages.FirstOrDefault(item => item.Name.Equals(packageName, System.StringComparison.Ordinal)); if (null == package) { throw new Exception($"Unable to locate package '{packageName}'"); } if (null == package.MetaData) { package.MetaData = InstantiatePackageMetaData<MetaDataType>(); } return package.MetaData as MetaDataType; } /// <summary> /// Get or set the build root to write all build output to. /// Macros added to the graph: /// 'buildroot' /// </summary> /// <value>The build root.</value> public string BuildRoot { get { return this.TheBuildRoot; } set { if (null != this.TheBuildRoot) { throw new Exception("The build root has already been set"); } var absoluteBuildRootPath = RelativePathUtilities.ConvertRelativePathToAbsolute( Graph.Instance.ProcessState.WorkingDirectory, value ); this.TheBuildRoot = absoluteBuildRootPath; this.Macros.AddVerbatim(GraphMacroNames.BuildRoot, absoluteBuildRootPath); } } /// <summary> /// Get or set the logging verbosity level to use across the build. /// </summary> /// <value>The verbosity level.</value> public EVerboseLevel VerbosityLevel { get; set; } private Array<PackageRepository> InternalPackageRepositories { get; set; } /// <summary> /// Adds a new package repository, if not already added. /// </summary> /// <param name="repoPath">Path to the new package repository.</param> /// <param name="insertedDefinitionFiles">Optional array of PackageDefinitions to insert at the front.</param> /// <returns>The PackageRepository added (or that was already present).</returns> public PackageRepository AddPackageRepository( string repoPath, params PackageDefinition[] insertedDefinitionFiles) { var repo = this.InternalPackageRepositories.FirstOrDefault(item => IOWrapper.PathsAreEqual(item.RootPath, repoPath) ); if (null != repo) { return repo; } if (repoPath.EndsWith("packages") || repoPath.EndsWith("tests")) { // needs to be added as structured repoPath = System.IO.Path.GetDirectoryName(repoPath); // re-test repo = this.InternalPackageRepositories.FirstOrDefault(item => IOWrapper.PathsAreEqual(item.RootPath, repoPath) ); if (null != repo) { return repo; } } repo = new PackageRepository(repoPath, insertedDefinitionFiles); this.InternalPackageRepositories.Add(repo); return repo; } /// <summary> /// Enumerates the package repositories known about in the build. /// </summary> /// <value>Each package repository path.</value> public System.Collections.Generic.IEnumerable<PackageRepository> PackageRepositories { get { foreach (var pkgRepo in this.InternalPackageRepositories) { yield return pkgRepo; } } } /// <summary> /// Determine whether package definition files are automatically updated after being read. /// </summary> /// <value><c>true</c> if force definition file update; otherwise, <c>false</c>.</value> public bool ForceDefinitionFileUpdate { get; private set; } /// <summary> /// Determine whether package definition files read have their BAM assembly versions updated /// to the current version of BAM running. /// Requires forced updates to definition files to be enabled. /// </summary> /// <value><c>true</c> to update bam assembly versions; otherwise, <c>false</c>.</value> public bool UpdateBamAssemblyVersions { get; private set; } /// <summary> /// Determine whether package assembly compilation occurs with debug symbol information. /// </summary> /// <value><c>true</c> if compile with debug symbols; otherwise, <c>false</c>.</value> public bool CompileWithDebugSymbols { get; set; } /// <summary> /// Get or set the path of the package script assembly. /// </summary> /// <value>The script assembly pathname.</value> public string ScriptAssemblyPathname { get; set; } /// <summary> /// Get or set the compiled package script assembly. /// </summary> /// <value>The script assembly.</value> public System.Reflection.Assembly ScriptAssembly { get; set; } /// <summary> /// Obtain the current state of Bam. /// </summary> /// <value>The state of the process.</value> public BamState ProcessState { get; private set; } /// <summary> /// Obtain the named referenced module for a given environment and the type of the module required. /// An exception will be thrown if the type does not refer to any referenced module in that environment. /// </summary> /// <param name="env">Environment in which the referenced module was created.</param> /// <param name="type">The type of the module requested.</param> /// <returns>The instance of the referenced module requested.</returns> public Module GetReferencedModule( Environment env, System.Type type) { try { return this.ReferencedModules[env].First(item => item.GetType() == type); } catch (System.InvalidOperationException) { Log.ErrorMessage($"Unable to locate a referenced module of type {type.ToString()}"); throw; } } /// <summary> /// Obtain the IProductDefinition instance (if it exists) from the package assembly. /// </summary> public IProductDefinition ProductDefinition { get; set; } /// <summary> /// Obtain the IOverrideModuleConfiguration instance (if it exists) from the package assembly. /// </summary> public IOverrideModuleConfiguration OverrideModuleConfiguration { get; set; } /// <summary> /// Can the use of BuildAMation skip package source downloads? Default is false. /// </summary> public bool SkipPackageSourceDownloads { get; set; } = false; } }
41.715799
298
0.553889
[ "BSD-3-Clause" ]
markfinal/BuildAMation
Bam.Core/Graph.cs
47,264
C#
using System; namespace FoldAndSum { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()) * 4; int[] arrOriginal = new int[n]; int[] arrA = new int[n / 2]; int[] arrB = new int[n / 2]; int countA = 0; int countB = 0; for (int i = 0; i < n; i += 1) { arrOriginal[i] = int.Parse(Console.ReadLine()); if (i >= n && i < 3 * n) { arrA[countA] = arrOriginal[i]; countA += 1; } else if (i < n) { arrB[(n - 1) - countB] = arrOriginal[i]; countB += 1; } else if (i >= 3 * n) { arrB[countB + (n - 1)] = arrOriginal[i]; countB -= 1; } } for (int j = 0; j < n * 2; j += 1) { int sum = (arrA[j]) + (arrB[j]); Console.Write(sum + " "); } } } }
28.139535
64
0.306612
[ "MIT" ]
MishoParvanov/Arrays
Program.cs
1,212
C#
using SysVer = System.Version; namespace MetalBot { public static class Version { public static SysVer AsDotNetVersion() => new SysVer(Major, Minor, Patch, Hotfix); private static int Major => 4; private static int Minor => 0; private static int Patch => 0; private static int Hotfix => 0; public static DevelopmentStage ReleaseType => DevelopmentStage.Development; public static string FullVersion => $"{Major}.{Minor}.{Patch}.{Hotfix}-{ReleaseType}"; public enum DevelopmentStage { Development, Release } } }
29.952381
94
0.616852
[ "MIT" ]
DeonduPreez/MetalBot
MetalBot/Version.cs
631
C#
using System.Linq; using EventStore.ClientAPI; using EventStore.ClientAPI.SystemData; using EventStore.Core.Data; using EventStore.Core.Services; using EventStore.Core.Tests.ClientAPI.Helpers; using EventStore.Core.Tests.Helpers; using NUnit.Framework; using ExpectedVersion = EventStore.ClientAPI.ExpectedVersion; using StreamMetadata = EventStore.ClientAPI.StreamMetadata; namespace EventStore.Core.Tests.ClientAPI { [TestFixture, Category("ClientAPI"), Category("LongRunning")] public class read_all_events_forward_with_hard_deleted_stream_should : SpecificationWithMiniNode { private EventData[] _testEvents; protected override void When() { _conn.SetStreamMetadataAsync( "$all", -1, StreamMetadata.Build().SetReadRole(SystemRoles.All), new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword)) .Wait(); _testEvents = Enumerable.Range(0, 20).Select(x => TestEvent.NewTestEvent(x.ToString())).ToArray(); _conn.AppendToStreamAsync("stream", ExpectedVersion.EmptyStream, _testEvents).Wait(); _conn.DeleteStreamAsync("stream", ExpectedVersion.Any, hardDelete: true).Wait(); } [Test, Category("LongRunning")] public void ensure_deleted_stream() { var res = _conn.ReadStreamEventsForwardAsync("stream", 0, 100, false).Result; Assert.AreEqual(SliceReadStatus.StreamDeleted, res.Status); Assert.AreEqual(0, res.Events.Length); } [Test, Category("LongRunning")] public void returns_all_events_including_tombstone() { AllEventsSlice read = _conn.ReadAllEventsForwardAsync(Position.Start, _testEvents.Length + 10, false).Result; Assert.That( EventDataComparer.Equal( _testEvents.ToArray(), read.Events.Skip(read.Events.Length - _testEvents.Length - 1) .Take(_testEvents.Length) .Select(x => x.Event) .ToArray())); var lastEvent = read.Events.Last().Event; Assert.AreEqual("stream", lastEvent.EventStreamId); Assert.AreEqual(SystemEventTypes.StreamDeleted, lastEvent.EventType); } } }
41.535714
121
0.656922
[ "Apache-2.0", "CC0-1.0" ]
BertschiAG/EventStore
src/EventStore.Core.Tests/ClientAPI/read_all_events_forward_with_hard_deleted_stream_should.cs
2,326
C#
using Agoda.Analyzers.AgodaCustom; using Agoda.Analyzers.Test.Helpers; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; using System.Threading.Tasks; namespace Agoda.Analyzers.Test.AgodaCustom { internal class AG0023UnitTests : DiagnosticVerifier { protected override DiagnosticAnalyzer DiagnosticAnalyzer => new AG0023PreventUseOfThreadSleep(); protected override string DiagnosticId => AG0023PreventUseOfThreadSleep.DIAGNOSTIC_ID; [Test] public async Task AG0023_WhenThreadYield_ShouldNotShowWarning() { var code = @" using System.Threading; class TestClass { public void TestMethod1() { Thread.Yield(); } } "; await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults); } [Test] public async Task AG0023_WhenDifferentNameSpaceThreadSleep_ShouldNotShowWarning() { var code = @" public static class Thread { public static void Sleep(int time) {} } class TestClass { public void TestMethod1() { Thread.Sleep(100); } } "; await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults); } [Test] public async Task AG0023_WhenThreadSleepWithInt_ShouldShowWarning() { var code = @" using System.Threading; class TestClass { public void TestMethod1() { Thread.Sleep(100); } } "; await VerifyDiagnosticsAsync(code, new DiagnosticLocation(8, 9)); } [Test] public async Task AG0023_WhenThreadSleepWithTimeSpan_ShouldShowWarning() { var code = @" using System.Threading; using System; class TestClass { public void TestMethod1() { Thread.Sleep(TimeSpan.FromMilliseconds(3000)); } } "; await VerifyDiagnosticsAsync(code, new DiagnosticLocation(9, 9)); } } }
22.065217
105
0.614778
[ "Apache-2.0" ]
agoda-com/AgodaAnalyzers
src/Agoda.Analyzers.Test/AgodaCustom/AG0023UnitTests.cs
2,032
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ApiManagement.V20200601Preview { public static class GetApiManagementService { public static Task<GetApiManagementServiceResult> InvokeAsync(GetApiManagementServiceArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetApiManagementServiceResult>("azure-nextgen:apimanagement/v20200601preview:getApiManagementService", args ?? new GetApiManagementServiceArgs(), options.WithVersion()); } public sealed class GetApiManagementServiceArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public string ServiceName { get; set; } = null!; public GetApiManagementServiceArgs() { } } [OutputType] public sealed class GetApiManagementServiceResult { /// <summary> /// Additional datacenter locations of the API Management service. /// </summary> public readonly ImmutableArray<Outputs.AdditionalLocationResponse> AdditionalLocations; /// <summary> /// Control Plane Apis version constraint for the API Management service. /// </summary> public readonly Outputs.ApiVersionConstraintResponse? ApiVersionConstraint; /// <summary> /// List of Certificates that need to be installed in the API Management service. Max supported certificates that can be installed is 10. /// </summary> public readonly ImmutableArray<Outputs.CertificateConfigurationResponse> Certificates; /// <summary> /// Creation UTC date of the API Management service.The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard. /// </summary> public readonly string CreatedAtUtc; /// <summary> /// Custom properties of the API Management service.&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TripleDes168` will disable the cipher TLS_RSA_WITH_3DES_EDE_CBC_SHA for all TLS(1.0, 1.1 and 1.2).&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls11` can be used to disable just TLS 1.1.&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls10` can be used to disable TLS 1.0 on an API Management service.&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Backend.Protocols.Tls11` can be used to disable just TLS 1.1 for communications with backends.&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Backend.Protocols.Tls10` can be used to disable TLS 1.0 for communications with backends.&lt;/br&gt;Setting `Microsoft.WindowsAzure.ApiManagement.Gateway.Protocols.Server.Http2` can be used to enable HTTP2 protocol on an API Management service.&lt;/br&gt;Not specifying any of these properties on PATCH operation will reset omitted properties' values to their defaults. For all the settings except Http2 the default value is `True` if the service was created on or before April 1st 2018 and `False` otherwise. Http2 setting's default value is `False`.&lt;/br&gt;&lt;/br&gt;You can disable any of next ciphers by using settings `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.[cipher_name]`: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA. For example, `Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TLS_RSA_WITH_AES_128_CBC_SHA256`:`false`. The default value is `true` for them. Note: next ciphers can't be disabled since they are required by Azure CloudService internal components: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_256_GCM_SHA384 /// </summary> public readonly ImmutableDictionary<string, string>? CustomProperties; /// <summary> /// DEveloper Portal endpoint URL of the API Management service. /// </summary> public readonly string DeveloperPortalUrl; /// <summary> /// Property only valid for an Api Management service deployed in multiple locations. This can be used to disable the gateway in master region. /// </summary> public readonly bool? DisableGateway; /// <summary> /// Property only meant to be used for Consumption SKU Service. This enforces a client certificate to be presented on each request to the gateway. This also enables the ability to authenticate the certificate in the policy on the gateway. /// </summary> public readonly bool? EnableClientCertificate; /// <summary> /// ETag of the resource. /// </summary> public readonly string Etag; /// <summary> /// Gateway URL of the API Management service in the Default Region. /// </summary> public readonly string GatewayRegionalUrl; /// <summary> /// Gateway URL of the API Management service. /// </summary> public readonly string GatewayUrl; /// <summary> /// Custom hostname configuration of the API Management service. /// </summary> public readonly ImmutableArray<Outputs.HostnameConfigurationResponse> HostnameConfigurations; /// <summary> /// Managed service identity of the Api Management service. /// </summary> public readonly Outputs.ApiManagementServiceIdentityResponse? Identity; /// <summary> /// Resource location. /// </summary> public readonly string Location; /// <summary> /// Management API endpoint URL of the API Management service. /// </summary> public readonly string ManagementApiUrl; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// Email address from which the notification will be sent. /// </summary> public readonly string? NotificationSenderEmail; /// <summary> /// Publisher portal endpoint Url of the API Management service. /// </summary> public readonly string PortalUrl; /// <summary> /// Private Static Load Balanced IP addresses of the API Management service in Primary region which is deployed in an Internal Virtual Network. Available only for Basic, Standard, Premium and Isolated SKU. /// </summary> public readonly ImmutableArray<string> PrivateIPAddresses; /// <summary> /// The current provisioning state of the API Management service which can be one of the following: Created/Activating/Succeeded/Updating/Failed/Stopped/Terminating/TerminationFailed/Deleted. /// </summary> public readonly string ProvisioningState; /// <summary> /// Public Static Load Balanced IP addresses of the API Management service in Primary region. Available only for Basic, Standard, Premium and Isolated SKU. /// </summary> public readonly ImmutableArray<string> PublicIPAddresses; /// <summary> /// Publisher email. /// </summary> public readonly string PublisherEmail; /// <summary> /// Publisher name. /// </summary> public readonly string PublisherName; /// <summary> /// Undelete Api Management Service if it was previously soft-deleted. If this flag is specified and set to True all other properties will be ignored. /// </summary> public readonly bool? Restore; /// <summary> /// SCM endpoint URL of the API Management service. /// </summary> public readonly string ScmUrl; /// <summary> /// SKU properties of the API Management service. /// </summary> public readonly Outputs.ApiManagementServiceSkuPropertiesResponse Sku; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// The provisioning state of the API Management service, which is targeted by the long running operation started on the service. /// </summary> public readonly string TargetProvisioningState; /// <summary> /// Resource type for API Management resource is set to Microsoft.ApiManagement. /// </summary> public readonly string Type; /// <summary> /// Virtual network configuration of the API Management service. /// </summary> public readonly Outputs.VirtualNetworkConfigurationResponse? VirtualNetworkConfiguration; /// <summary> /// The type of VPN in which API Management service needs to be configured in. None (Default Value) means the API Management service is not part of any Virtual Network, External means the API Management deployment is set up inside a Virtual Network having an Internet Facing Endpoint, and Internal means that API Management deployment is setup inside a Virtual Network having an Intranet Facing Endpoint only. /// </summary> public readonly string? VirtualNetworkType; /// <summary> /// A list of availability zones denoting where the resource needs to come from. /// </summary> public readonly ImmutableArray<string> Zones; [OutputConstructor] private GetApiManagementServiceResult( ImmutableArray<Outputs.AdditionalLocationResponse> additionalLocations, Outputs.ApiVersionConstraintResponse? apiVersionConstraint, ImmutableArray<Outputs.CertificateConfigurationResponse> certificates, string createdAtUtc, ImmutableDictionary<string, string>? customProperties, string developerPortalUrl, bool? disableGateway, bool? enableClientCertificate, string etag, string gatewayRegionalUrl, string gatewayUrl, ImmutableArray<Outputs.HostnameConfigurationResponse> hostnameConfigurations, Outputs.ApiManagementServiceIdentityResponse? identity, string location, string managementApiUrl, string name, string? notificationSenderEmail, string portalUrl, ImmutableArray<string> privateIPAddresses, string provisioningState, ImmutableArray<string> publicIPAddresses, string publisherEmail, string publisherName, bool? restore, string scmUrl, Outputs.ApiManagementServiceSkuPropertiesResponse sku, ImmutableDictionary<string, string>? tags, string targetProvisioningState, string type, Outputs.VirtualNetworkConfigurationResponse? virtualNetworkConfiguration, string? virtualNetworkType, ImmutableArray<string> zones) { AdditionalLocations = additionalLocations; ApiVersionConstraint = apiVersionConstraint; Certificates = certificates; CreatedAtUtc = createdAtUtc; CustomProperties = customProperties; DeveloperPortalUrl = developerPortalUrl; DisableGateway = disableGateway; EnableClientCertificate = enableClientCertificate; Etag = etag; GatewayRegionalUrl = gatewayRegionalUrl; GatewayUrl = gatewayUrl; HostnameConfigurations = hostnameConfigurations; Identity = identity; Location = location; ManagementApiUrl = managementApiUrl; Name = name; NotificationSenderEmail = notificationSenderEmail; PortalUrl = portalUrl; PrivateIPAddresses = privateIPAddresses; ProvisioningState = provisioningState; PublicIPAddresses = publicIPAddresses; PublisherEmail = publisherEmail; PublisherName = publisherName; Restore = restore; ScmUrl = scmUrl; Sku = sku; Tags = tags; TargetProvisioningState = targetProvisioningState; Type = type; VirtualNetworkConfiguration = virtualNetworkConfiguration; VirtualNetworkType = virtualNetworkType; Zones = zones; } } }
49.386029
2,377
0.683243
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/V20200601Preview/GetApiManagementService.cs
13,433
C#
using System; using System.Linq; using System.Web.Mvc; using FluentSecurity.TestHelper.Expectations; using FluentSecurity.TestHelper.Specification.TestData; using NUnit.Framework; namespace FluentSecurity.TestHelper.Specification { [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_AdminController { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(); } [Test] public void Should_have_type_set_to_AdminController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(AdminController))); } [Test] public void Should_have_action_set_to_null() { Assert.That(_expectationExpression.Action, Is.Null); } [Test] public void Should_have_0_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(0)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_AdminController_Login { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(x => x.Login()); } [Test] public void Should_have_type_set_to_AdminController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(AdminController))); } [Test] public void Should_have_action_set_to_null() { Assert.That(_expectationExpression.Action, Is.EqualTo("Login")); } [Test] public void Should_have_0_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(0)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_adding_expectations_to_an_expectation_expression_for_AdminController_Login { private ExpectationExpression<AdminController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<AdminController>(x => x.Login()); } [Test] public void Should_throw_when_expectation_is_null() { // Arrange IExpectation expectation = null; // Act & assert Assert.Throws<ArgumentNullException>(() => _expectationExpression.Add(expectation)); } [Test] public void Should_have_1_expectations() { // Arrange var expectation = new HasTypeExpectation<DenyInternetExplorerPolicy>(); // Act _expectationExpression.Add(expectation); // Assert Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } [Test] public void Should_have_2_expectations() { // Arrange var expectation1 = new HasTypeExpectation<DenyInternetExplorerPolicy>(); var expectation2 = new DoesNotHaveTypeExpectation<DenyInternetExplorerPolicy>(); // Act _expectationExpression.Add(expectation1).Add(expectation2); // Assert Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(2)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_SampleController_AliasedAction { private ExpectationExpression<SampleController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<SampleController>(x => x.ActualAction()); } [Test] public void Should_resolve_actual_action_to_aliased_action() { Assert.That(_expectationExpression.Action, Is.EqualTo("AliasedAction")); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_TaskController_ActionResult { private ExpectationExpression<TaskController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<TaskController>(x => x.LongRunningAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_TypeController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(TaskController))); } [Test] public void Should_have_action_set_to_LongRunningAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("LongRunningAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_TaskController_JsonResult { private ExpectationExpression<TaskController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<TaskController>(x => x.LongRunningJsonAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_TaskController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(TaskController))); } [Test] public void Should_have_action_set_to_LongRunningAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("LongRunningJsonAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } [TestFixture] [Category("ExpectationExpressionSpec")] public class When_creating_an_expectation_expression_for_SampleController_VoidAction { private ExpectationExpression<SampleController> _expectationExpression; [SetUp] public void SetUp() { _expectationExpression = new ExpectationExpression<SampleController>(x => x.VoidAction()); _expectationExpression.Add(new HasTypeExpectation<DenyInternetExplorerPolicy>()); } [Test] public void Should_have_type_set_to_SampleController() { Assert.That(_expectationExpression.Controller, Is.EqualTo(typeof(SampleController))); } [Test] public void Should_have_action_set_to_VoidAction() { Assert.That(_expectationExpression.Action, Is.EqualTo("VoidAction")); } [Test] public void Should_have_1_expectations() { Assert.That(_expectationExpression.Expectations.Count(), Is.EqualTo(1)); } } }
27.417722
103
0.744998
[ "MIT" ]
DiogenesPolanco/FluentSecurity
FluentSecurity.TestHelper.Specification/ExpectationExpressionSpec.cs
6,498
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("Example.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Example.iOS")] [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("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // 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.702703
84
0.743369
[ "MIT" ]
Danielbahe/Fluxamarin
Example/Example.iOS/Properties/AssemblyInfo.cs
1,398
C#
namespace FillOrBustCP.Data; [SingletonGame] [UseLabelGrid] [AutoReset] public partial class FillOrBustVMData : IBasicCardGamesData<FillOrBustCardInformation>, ICup<SimpleDice> { [LabelColumn] public string NormalTurn { get; set; } = ""; [LabelColumn] public string Status { get; set; } = ""; [LabelColumn] public int DiceScore { get; set; } [LabelColumn] public int TempScore { get; set; } [LabelColumn] public string Instructions { get; set; } = ""; private readonly CommandContainer _command; private readonly IGamePackageResolver _resolver; public FillOrBustVMData(CommandContainer command, IGamePackageResolver resolver) { Deck1 = new (command); Pile1 = new (command); PlayerHand1 = new (command); _command = command; _resolver = resolver; } public void LoadCup(FillOrBustSaveInfo saveRoot, bool autoResume) { if (Cup != null && autoResume) { return; } Cup = new DiceCup<SimpleDice>(saveRoot.DiceList, _resolver, _command); if (autoResume == true) { Cup.CanShowDice = true; } else { Cup.HowManyDice = 6; } } public DiceCup<SimpleDice>? Cup { get; set; } public DeckObservablePile<FillOrBustCardInformation> Deck1 { get; set; } public SingleObservablePile<FillOrBustCardInformation> Pile1 { get; set; } public HandObservable<FillOrBustCardInformation> PlayerHand1 { get; set; } public SingleObservablePile<FillOrBustCardInformation>? OtherPile { get; set; } }
31.979592
104
0.668794
[ "MIT" ]
musictopia2/GamingPackXV3
CP/Games/FillOrBustCP/Data/FillOrBustVMData.cs
1,567
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Frapper.Web.Helpers { public class AlertViewModel { public string AlertType { get; set; } public string AlertTitle { get; set; } public string AlertMessage { get; set; } public AlertViewModel(string type, string title, string message) { AlertType = type; AlertTitle = title; AlertMessage = message; } } }
23.227273
72
0.620352
[ "MIT" ]
Ramasagar/Frapper
Frapper.Web/Frapper.Web/Helpers/AlertViewModel.cs
513
C#
namespace JexusManager.Wizards.ConnectionWizard { using System.ComponentModel; using System.Windows.Forms; partial class TypePage { /// <summary> /// Required designer variable. /// </summary> private 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 Component 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(); this.label2 = new System.Windows.Forms.Label(); this.rbJexus = new System.Windows.Forms.RadioButton(); this.rbIisExpress = new System.Windows.Forms.RadioButton(); this.rbIis = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.label2.Location = new System.Drawing.Point(21, 20); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 13); this.label2.TabIndex = 5; this.label2.Text = "Server type:"; // // rbJexus // this.rbJexus.AutoSize = true; this.rbJexus.Location = new System.Drawing.Point(24, 54); this.rbJexus.Name = "rbJexus"; this.rbJexus.Size = new System.Drawing.Size(86, 17); this.rbJexus.TabIndex = 6; this.rbJexus.Text = "Jexus Server"; this.rbJexus.UseVisualStyleBackColor = true; this.rbJexus.CheckedChanged += new System.EventHandler(this.RbJexusCheckedChanged); // // rbIisExpress // this.rbIisExpress.AutoSize = true; this.rbIisExpress.Location = new System.Drawing.Point(24, 129); this.rbIisExpress.Name = "rbIisExpress"; this.rbIisExpress.Size = new System.Drawing.Size(162, 17); this.rbIisExpress.TabIndex = 7; this.rbIisExpress.Text = "IIS Express Configuration File"; this.rbIisExpress.UseVisualStyleBackColor = true; this.rbIisExpress.CheckedChanged += new System.EventHandler(this.RbJexusCheckedChanged); // // rbIis // this.rbIis.AutoSize = true; this.rbIis.Enabled = false; this.rbIis.Location = new System.Drawing.Point(24, 206); this.rbIis.Name = "rbIis"; this.rbIis.Size = new System.Drawing.Size(78, 17); this.rbIis.TabIndex = 8; this.rbIis.Text = "Remote IIS"; this.rbIis.UseVisualStyleBackColor = true; this.rbIis.CheckedChanged += new System.EventHandler(this.RbJexusCheckedChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(39, 74); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(385, 13); this.label1.TabIndex = 9; this.label1.Text = "Jexus web server is a Linux based web server that supports ASP.NET and PHP."; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(39, 149); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(338, 13); this.label3.TabIndex = 10; this.label3.Text = "IIS Express configuration files can be added as individual web servers."; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(39, 226); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(183, 13); this.label4.TabIndex = 11; this.label4.Text = "Remote IIS web servers (unavailable)"; // // TypePage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label1); this.Controls.Add(this.rbIis); this.Controls.Add(this.rbIisExpress); this.Controls.Add(this.rbJexus); this.Controls.Add(this.label2); this.Name = "TypePage"; this.Size = new System.Drawing.Size(670, 380); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Label label2; private RadioButton rbJexus; private RadioButton rbIisExpress; private RadioButton rbIis; private Label label1; private Label label3; private Label label4; private ToolTip toolTip1; } }
40.424658
109
0.563368
[ "MIT" ]
68681395/JexusManager
JexusManager/Wizards/ConnectionWizard/TypePage.Designer.cs
5,904
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// The sku type. /// </summary> public partial class Sku { /// <summary> /// Initializes a new instance of the Sku class. /// </summary> public Sku() { } /// <summary> /// Initializes a new instance of the Sku class. /// </summary> public Sku(SkuName name, ResourceReference plan = default(ResourceReference)) { Name = name; Plan = plan; } /// <summary> /// Gets or sets the name. Possible values include: 'NotSpecified', /// 'Free', 'Shared', 'Basic', 'Standard', 'Premium' /// </summary> [JsonProperty(PropertyName = "name")] public SkuName Name { get; set; } /// <summary> /// Gets or sets the reference to plan. /// </summary> [JsonProperty(PropertyName = "plan")] public ResourceReference Plan { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { } } }
28.741935
85
0.580247
[ "MIT" ]
dnelly/azure-sdk-for-net
src/ResourceManagement/Logic/Microsoft.Azure.Management.Logic/Generated/Models/Sku.cs
1,782
C#
// Copyright (c) .NET Foundation. 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.Runtime.CompilerServices; namespace PlatformBenchmarks { internal class BatchUpdateString { private const int MaxBatch = 500; private static string[] _queries = new string[MaxBatch]; public static IList<BatchUpdateString> Strings { get; } = Enumerable.Range(0, MaxBatch) .Select(i => new BatchUpdateString { Id = $"Id_{i}", Random = $"Random_{i}", BatchSize = i }).ToArray(); private int BatchSize { get; set; } public string Id { get; set; } public string Random { get; set; } public string UpdateQuery => _queries[BatchSize] ?? CreateQuery(BatchSize); [MethodImpl(MethodImplOptions.NoInlining)] private string CreateQuery(int batchSize) { var sb = StringBuilderCache.Acquire(); foreach (var q in Enumerable.Range(0, batchSize + 1) .Select(i => $"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};")) { sb.Append(q); } var query = sb.ToString(); _queries[batchSize] = query; return query; } public static void Initalize() { Observe(Strings[0].UpdateQuery); Observe(Strings[4].UpdateQuery); Observe(Strings[9].UpdateQuery); Observe(Strings[14].UpdateQuery); Observe(Strings[19].UpdateQuery); } [MethodImpl(MethodImplOptions.NoInlining)] private static void Observe(string query) { } } }
33.842105
112
0.55832
[ "BSD-3-Clause" ]
ADmad/FrameworkBenchmarks
frameworks/CSharp/aspnetcore-mono/PlatformBenchmarks/Data/BatchUpdateString.cs
1,929
C#
// // Copyright (C) DataStax 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 System.Collections.Generic; using Gremlin.Net.Process.Traversal; namespace Cassandra.DataStax.Graph { /// <summary> /// Represents a group of traversals to allow executing multiple DSE Graph mutation operations inside the /// same transaction. /// </summary> /// <inheritdoc /> public interface ITraversalBatch : IReadOnlyCollection<ITraversal> { /// <summary> /// Adds a new traversal to this batch. /// </summary> /// <returns>This instance.</returns> ITraversalBatch Add(ITraversal traversal); /// <summary> /// Converts this batch into a <see cref="IGraphStatement"/> that can be executed using /// a <see cref="ISession"/>. /// </summary> /// <exception cref="InvalidOperationException"> /// Throws InvalidOperationException when the batch does not contain any traversals. /// </exception> IGraphStatement ToGraphStatement(); } }
35.8
109
0.666046
[ "Apache-2.0" ]
datastax/csharp-driver-graph
src/Cassandra.DataStax.Graph/ITraversalBatch.cs
1,613
C#
using System; using System.Collections.Generic; using System.Text; namespace SynchronizationScheduler.Domain.Models.Application { /// <summary> /// Person application model. /// </summary> public class Person { public int Id { get; set; } public int CloudId { get; set; } public string Name { get; set; } public string Email { get; set; } public ICollection<Post> Posts { get; set; } } }
19.125
60
0.610022
[ "MIT" ]
green1971weekend/SynchronizationScheduler
src/SynchronizationScheduler.Domain/Models/Application/Person.cs
461
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 appstream-2016-12-01.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.AppStream.Model { /// <summary> /// Describes a user in the user pool. /// </summary> public partial class User { private string _arn; private AuthenticationType _authenticationType; private DateTime? _createdTime; private bool? _enabled; private string _firstName; private string _lastName; private string _status; private string _userName; /// <summary> /// Gets and sets the property Arn. /// <para> /// The ARN of the user. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property AuthenticationType. /// <para> /// The authentication type for the user. /// </para> /// </summary> [AWSProperty(Required=true)] public AuthenticationType AuthenticationType { get { return this._authenticationType; } set { this._authenticationType = value; } } // Check to see if AuthenticationType property is set internal bool IsSetAuthenticationType() { return this._authenticationType != null; } /// <summary> /// Gets and sets the property CreatedTime. /// <para> /// The date and time the user was created in the user pool. /// </para> /// </summary> public DateTime CreatedTime { get { return this._createdTime.GetValueOrDefault(); } set { this._createdTime = value; } } // Check to see if CreatedTime property is set internal bool IsSetCreatedTime() { return this._createdTime.HasValue; } /// <summary> /// Gets and sets the property Enabled. /// <para> /// Specifies whether the user in the user pool is enabled. /// </para> /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property FirstName. /// <para> /// The first name, or given name, of the user. /// </para> /// </summary> [AWSProperty(Max=2048)] public string FirstName { get { return this._firstName; } set { this._firstName = value; } } // Check to see if FirstName property is set internal bool IsSetFirstName() { return this._firstName != null; } /// <summary> /// Gets and sets the property LastName. /// <para> /// The last name, or surname, of the user. /// </para> /// </summary> [AWSProperty(Max=2048)] public string LastName { get { return this._lastName; } set { this._lastName = value; } } // Check to see if LastName property is set internal bool IsSetLastName() { return this._lastName != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the user in the user pool. The status can be one of the following: /// </para> /// <ul> <li> /// <para> /// UNCONFIRMED – The user is created but not confirmed. /// </para> /// </li> <li> /// <para> /// CONFIRMED – The user is confirmed. /// </para> /// </li> <li> /// <para> /// ARCHIVED – The user is no longer active. /// </para> /// </li> <li> /// <para> /// COMPROMISED – The user is disabled because of a potential security threat. /// </para> /// </li> <li> /// <para> /// UNKNOWN – The user status is not known. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Min=1)] public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property UserName. /// <para> /// The email address of the user. /// </para> /// <note> /// <para> /// Users' email addresses are case-sensitive. /// </para> /// </note> /// </summary> [AWSProperty(Min=1, Max=128)] public string UserName { get { return this._userName; } set { this._userName = value; } } // Check to see if UserName property is set internal bool IsSetUserName() { return this._userName != null; } } }
28.38914
107
0.525821
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AppStream/Generated/Model/User.cs
6,284
C#
// -- FILE ------------------------------------------------------------------ // name : ITimePeriodContainer.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace TimePeriod { // ------------------------------------------------------------------------ public interface ITimePeriodContainer : IList<ITimePeriod>, ITimePeriod { // ---------------------------------------------------------------------- new bool IsReadOnly { get; } // ---------------------------------------------------------------------- bool ContainsPeriod( ITimePeriod test ); // ---------------------------------------------------------------------- void AddAll( IEnumerable<ITimePeriod> periods ); // ---------------------------------------------------------------------- void Move( TimeSpan delta ); } // class ITimePeriodContainer } // namespace Itenso.TimePeriod // -- EOF -------------------------------------------------------------------
33.861111
77
0.358491
[ "MIT" ]
nevind7/TimePeriodLibrary
TimePeriod/ITimePeriodContainer.cs
1,219
C#
//------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a CodeSmith Template. // // DO NOT MODIFY contents of this file. Changes to this // file will be lost if the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; namespace Petshop.Data.Mapping { public partial class ItemMap : Microsoft.EntityFrameworkCore.IEntityTypeConfiguration<Petshop.Data.Entities.Item> { public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Petshop.Data.Entities.Item> builder) { // table builder.ToTable("Item", "dbo"); // keys builder.HasKey(t => t.ItemId); // Properties builder.Property(t => t.ItemId) .IsRequired() .HasColumnName("ItemId") .HasColumnType("varchar") .HasMaxLength(10) .ValueGeneratedNever(); builder.Property(t => t.ProductId) .IsRequired() .HasColumnName("ProductId") .HasColumnType("varchar") .HasMaxLength(10); builder.Property(t => t.ListPrice) .HasColumnName("ListPrice") .HasColumnType("decimal"); builder.Property(t => t.UnitCost) .HasColumnName("UnitCost") .HasColumnType("decimal"); builder.Property(t => t.Supplier) .HasColumnName("Supplier") .HasColumnType("int"); builder.Property(t => t.Status) .HasColumnName("Status") .HasColumnType("varchar") .HasMaxLength(2); builder.Property(t => t.Attr1) .HasColumnName("Attr1") .HasColumnType("varchar") .HasMaxLength(80); builder.Property(t => t.Attr2) .HasColumnName("Attr2") .HasColumnType("varchar") .HasMaxLength(80); builder.Property(t => t.Attr3) .HasColumnName("Attr3") .HasColumnType("varchar") .HasMaxLength(80); builder.Property(t => t.Attr4) .HasColumnName("Attr4") .HasColumnType("varchar") .HasMaxLength(80); builder.Property(t => t.Attr5) .HasColumnName("Attr5") .HasColumnType("varchar") .HasMaxLength(80); // Relationships builder.HasOne(t => t.Product) .WithMany(t => t.Items) .HasForeignKey(d => d.ProductId) .HasConstraintName("FK__Item__ProductId__38996AB5"); builder.HasOne(t => t.Supplier1) .WithMany(t => t.Items) .HasForeignKey(d => d.Supplier) .HasConstraintName("FK__Item__Supplier__398D8EEE"); InitializeMapping(builder); } partial void InitializeMapping(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Petshop.Data.Entities.Item> builder); } }
37.166667
142
0.515097
[ "Apache-2.0" ]
loresoft/PLINQO.EntityFrameworkCore
Source/Samples/Petshop.Data/Mapping/ItemMap.Generated.cs
3,347
C#
using System; using System.Web; using Orchard.Environment.Extensions.Models; using Orchard.Security; using Orchard.Settings; namespace Orchard { /// <summary> /// A work context for work context scope /// </summary> public abstract class WorkContext { /// <summary> /// Resolves a registered dependency type. /// </summary> /// <typeparam name="T">The type of the dependency.</typeparam> /// <returns>An instance of the dependency if it could be resolved.</returns> public abstract T Resolve<T>(); /// <summary> /// Resolves a registered dependency type. /// </summary> /// <param name="serviceType">The type of the dependency.</param> /// <returns>An instance of the dependency if it could be resolved.</returns> public abstract object Resolve(Type serviceType); /// <summary> /// Tries to resolve a registered dependency type. /// </summary> /// <typeparam name="T">The type of the dependency.</typeparam> /// <param name="service">An instance of the dependency if it could be resolved.</param> /// <returns>True if the dependency could be resolved, false otherwise.</returns> public abstract bool TryResolve<T>(out T service); /// <summary> /// Tries to resolve a registered dependency type. /// </summary> /// <param name="serviceType">The type of the dependency.</param> /// <param name="service">An instance of the dependency if it could be resolved.</param> /// <returns>True if the dependency could be resolved, false otherwise.</returns> public abstract bool TryResolve(Type serviceType, out object service); public abstract T GetState<T>(string name); public abstract void SetState<T>(string name, T value); /// <summary> /// The http context corresponding to the work context /// </summary> public HttpContextBase HttpContext { get { return GetState<HttpContextBase>("HttpContext"); } set { SetState("HttpContext", value); } } /// <summary> /// The Layout shape corresponding to the work context /// </summary> public dynamic Layout { get { return GetState<dynamic>("Layout"); } set { SetState("Layout", value); } } /// <summary> /// Settings of the site corresponding to the work context /// </summary> public ISite CurrentSite { get { return GetState<ISite>("CurrentSite"); } set { SetState("CurrentSite", value); } } /// <summary> /// The user, if there is any corresponding to the work context /// </summary> public IUser CurrentUser { get { return GetState<IUser>("CurrentUser"); } set { SetState("CurrentUser", value); } } /// <summary> /// The theme used in the work context /// </summary> public ExtensionDescriptor CurrentTheme { get { return GetState<ExtensionDescriptor>("CurrentTheme"); } set { SetState("CurrentTheme", value); } } /// <summary> /// Active culture of the work context /// </summary> public string CurrentCulture { get { return GetState<string>("CurrentCulture"); } set { SetState("CurrentCulture", value); } } /// <summary> /// Active calendar of the work context /// </summary> public string CurrentCalendar { get { return GetState<string>("CurrentCalendar"); } set { SetState("CurrentCalendar", value); } } /// <summary> /// Time zone of the work context /// </summary> public TimeZoneInfo CurrentTimeZone { get { return GetState<TimeZoneInfo>("CurrentTimeZone"); } set { SetState("CurrentTimeZone", value); } } } }
36.618182
96
0.580933
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard/WorkContext.cs
4,030
C#
using System.IO; using Xunit; namespace DartSassBuilder.ExcludeTests { // This project is configured to run DartSassBuilder in DartSassBuilder.DirectoryTests.csproj excluding foo & bar directories public class ExcludeTests { private readonly string _fileDirectory; public ExcludeTests() { _fileDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; } [Fact] public void ExcludeFooFilesTest() { var fooFile = Path.Join(_fileDirectory, "foo/foo.css"); var barFile = Path.Join(_fileDirectory, "bar/bar.css"); var testFile = Path.Join(_fileDirectory, "test.css"); Assert.False(File.Exists(fooFile)); // excluded foo Assert.False(File.Exists(barFile)); // excluded bar Assert.True(File.Exists(testFile)); File.Delete(testFile); } } }
26.193548
126
0.738916
[ "MIT" ]
deanwiseman/DartSassBuilder
src/DartSassBuilder.ExcludeTests/ExcludeTests.cs
812
C#
using System; using System.Globalization; using Xamarin.Forms; namespace Diabetic.Converter { public class StringToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter != null && parameter.GetType() == typeof(string)) { return ImageSource.FromResource($"Diabetic.Assets.Img.{parameter}"); } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
29.347826
103
0.626667
[ "Apache-2.0" ]
kevinhipeau/workshop-gusto
Diabetic/Diabetic/Converter/StringToImageConverter.cs
677
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LicenseDRIVER.Models { public class StudentViewModel:UserViewModel { public Guid StudentId { get; set; } public string Class { get; set; } public Guid TeacherId { get; set; } } }
21.6
47
0.682099
[ "Apache-2.0" ]
EmmaSleghel/LicenseDriver
LicenseDRIVER/LicenseDRIVER/Models/StudentViewModel.cs
326
C#
/* The MIT License (MIT) Copyright (c) 2007 - 2021 Microting A/S Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Microting.ItemsGroupPlanningBase.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using eForm.Infrastructure.Constants; using Infrastructure.Data.Entities; using Microsoft.EntityFrameworkCore; using NUnit.Framework; [TestFixture] public class ItemUTest : DbTestFixture { [Test] public async Task Item_Save_DoesSave() { // Arrange ItemList itemList = new ItemList { Name = Guid.NewGuid().ToString() }; await itemList.Create(DbContext); Item item = new Item { Name = Guid.NewGuid().ToString(), Description = Guid.NewGuid().ToString(), Enabled = true, ItemListId = itemList.Id, UpdatedByUserId = 1, CreatedByUserId = 1, Version = 1, WorkflowState = Constants.WorkflowStates.Created, ItemNumber = "1", LocationCode = "2", Sku = "3", }; // Act await item.Create(DbContext); List<Item> items = DbContext.Items.AsNoTracking().ToList(); List<ItemVersion> itemVersions = DbContext.ItemVersions.AsNoTracking().ToList(); // Assert Assert.AreEqual(1, items.Count); Assert.AreEqual(1, itemVersions.Count); Assert.AreEqual(item.Name, items[0].Name); Assert.AreEqual(item.Description, items[0].Description); Assert.AreEqual(item.Enabled, items[0].Enabled); Assert.AreEqual(item.ItemListId, items[0].ItemListId); Assert.AreEqual(item.UpdatedByUserId, items[0].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, items[0].CreatedByUserId); Assert.AreEqual(item.Version, items[0].Version); Assert.AreEqual(item.WorkflowState, items[0].WorkflowState); Assert.AreEqual(item.ItemNumber, items[0].ItemNumber); Assert.AreEqual(item.LocationCode, items[0].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Created, items[0].WorkflowState); Assert.AreEqual(item.Id, items[0].Id); Assert.AreEqual(1, items[0].Version); Assert.AreEqual(item.Name, itemVersions[0].Name); Assert.AreEqual(item.Description, itemVersions[0].Description); Assert.AreEqual(item.Enabled, itemVersions[0].Enabled); Assert.AreEqual(item.ItemListId, itemVersions[0].ItemListId); Assert.AreEqual(item.UpdatedByUserId, itemVersions[0].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, itemVersions[0].CreatedByUserId); Assert.AreEqual(item.Version, itemVersions[0].Version); Assert.AreEqual(item.WorkflowState, itemVersions[0].WorkflowState); Assert.AreEqual(item.ItemNumber, itemVersions[0].ItemNumber); Assert.AreEqual(item.LocationCode, itemVersions[0].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Created, itemVersions[0].WorkflowState); Assert.AreEqual(1, itemVersions[0].Version); } [Test] public async Task Item_Update_DoesUpdate() { // Arrange ItemList itemList = new ItemList { Name = Guid.NewGuid().ToString() }; await itemList.Create(DbContext); Item item = new Item { Name = Guid.NewGuid().ToString(), Description = Guid.NewGuid().ToString(), Enabled = true, ItemListId = itemList.Id, UpdatedByUserId = 1, CreatedByUserId = 1, ItemNumber = "1", LocationCode = "2", Sku = "3", }; await item.Create(DbContext); // Act item = await DbContext.Items.FirstOrDefaultAsync(); string oldName = item.Name; item.Name = "hello"; await item.Update(DbContext); List<Item> items = DbContext.Items.AsNoTracking().ToList(); List<ItemVersion> itemVersions = DbContext.ItemVersions.AsNoTracking().ToList(); // Assert Assert.AreEqual(1, items.Count); Assert.AreEqual(2, itemVersions.Count); Assert.AreEqual("hello", items[0].Name); Assert.AreEqual(item.Description, items[0].Description); Assert.AreEqual(item.Enabled, items[0].Enabled); Assert.AreEqual(item.ItemListId, items[0].ItemListId); Assert.AreEqual(item.UpdatedByUserId, items[0].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, items[0].CreatedByUserId); Assert.AreEqual(item.WorkflowState, items[0].WorkflowState); Assert.AreEqual(item.ItemNumber, items[0].ItemNumber); Assert.AreEqual(item.LocationCode, items[0].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Created, items[0].WorkflowState); Assert.AreEqual(item.Id, items[0].Id); Assert.AreEqual(2, items[0].Version); Assert.AreEqual(oldName, itemVersions[0].Name); Assert.AreEqual(item.Description, itemVersions[0].Description); Assert.AreEqual(item.Enabled, itemVersions[0].Enabled); Assert.AreEqual(item.ItemListId, itemVersions[0].ItemListId); Assert.AreEqual(item.UpdatedByUserId, itemVersions[0].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, itemVersions[0].CreatedByUserId); Assert.AreEqual(item.Version, itemVersions[1].Version); Assert.AreEqual(item.WorkflowState, itemVersions[0].WorkflowState); Assert.AreEqual(item.ItemNumber, itemVersions[0].ItemNumber); Assert.AreEqual(item.LocationCode, itemVersions[0].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Created, itemVersions[0].WorkflowState); Assert.AreEqual(item.Id, itemVersions[0].ItemId); Assert.AreEqual(1, itemVersions[0].Version); Assert.AreEqual("hello", itemVersions[1].Name); Assert.AreEqual(item.Description, itemVersions[1].Description); Assert.AreEqual(item.Enabled, itemVersions[1].Enabled); Assert.AreEqual(item.ItemListId, itemVersions[1].ItemListId); Assert.AreEqual(item.UpdatedByUserId, itemVersions[1].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, itemVersions[1].CreatedByUserId); Assert.AreEqual(2, itemVersions[1].Version); Assert.AreEqual(item.WorkflowState, itemVersions[1].WorkflowState); Assert.AreEqual(item.ItemNumber, itemVersions[1].ItemNumber); Assert.AreEqual(item.LocationCode, itemVersions[1].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Created, itemVersions[1].WorkflowState); Assert.AreEqual(item.Id, itemVersions[1].ItemId); } [Test] public async Task Item_Delete_DoesDelete() { // Arrange ItemList itemList = new ItemList { Name = Guid.NewGuid().ToString() }; await itemList.Create(DbContext); Item item = new Item { Name = Guid.NewGuid().ToString(), Description = Guid.NewGuid().ToString(), Enabled = true, ItemListId = itemList.Id, UpdatedByUserId = 1, CreatedByUserId = 1, Version = 1, WorkflowState = Constants.WorkflowStates.Created, ItemNumber = "1", LocationCode = "2", Sku = "3", }; await item.Create(DbContext); // Act item = await DbContext.Items.FirstOrDefaultAsync(); await item.Delete(DbContext); List<Item> items = DbContext.Items.AsNoTracking().ToList(); List<ItemVersion> itemVersions = DbContext.ItemVersions.AsNoTracking().ToList(); // Assert Assert.AreEqual(1, items.Count); Assert.AreEqual(2, itemVersions.Count); Assert.AreEqual(item.Name, items[0].Name); Assert.AreEqual(item.Description, items[0].Description); Assert.AreEqual(item.Enabled, items[0].Enabled); Assert.AreEqual(item.ItemListId, items[0].ItemListId); Assert.AreEqual(item.UpdatedByUserId, items[0].UpdatedByUserId); Assert.AreEqual(item.CreatedByUserId, items[0].CreatedByUserId); Assert.AreEqual(item.Version, items[0].Version); Assert.AreEqual(item.WorkflowState, items[0].WorkflowState); Assert.AreEqual(item.ItemNumber, items[0].ItemNumber); Assert.AreEqual(item.LocationCode, items[0].LocationCode); Assert.AreEqual(Constants.WorkflowStates.Removed, items[0].WorkflowState); Assert.AreEqual(item.Id, items[0].Id); Assert.AreEqual(2, items[0].Version); Assert.AreEqual(item.Name, itemVersions[0].Name); Assert.AreEqual(item.Description, itemVersions[0].Description); Assert.AreEqual(item.Enabled, itemVersions[0].Enabled); Assert.AreEqual(item.ItemListId, itemVersions[0].ItemListId); Assert.AreEqual(Constants.WorkflowStates.Created, itemVersions[0].WorkflowState); Assert.AreEqual(item.Id, itemVersions[0].ItemId); Assert.AreEqual(1, itemVersions[0].Version); Assert.AreEqual(item.Name, itemVersions[1].Name); Assert.AreEqual(item.Description, itemVersions[1].Description); Assert.AreEqual(item.Enabled, itemVersions[1].Enabled); Assert.AreEqual(item.ItemListId, itemVersions[1].ItemListId); Assert.AreEqual(Constants.WorkflowStates.Removed, itemVersions[1].WorkflowState); Assert.AreEqual(item.Id, itemVersions[1].ItemId); Assert.AreEqual(2, itemVersions[1].Version); } } }
44.362595
93
0.610858
[ "MIT" ]
Gid733/eform-items-group-planning-base
Microting.ItemsGroupPlanningBase.Tests/ItemUTest.cs
11,623
C#
using System.Collections.Generic; namespace Howatworks.SubEtha.Journal.Other { public class Synthesis : JournalEntryBase { public class MaterialItem { public string Name { get; set; } public int Count { get; set; } } public string Name { get; set; } public List<MaterialItem> Materials { get; set; } } }
22.529412
57
0.592689
[ "MIT" ]
johnnysaucepn/SubEtha
src/Journal/Howatworks.SubEtha.Journal/Other/Synthesis.cs
385
C#
using AppointmentScheduling.Data.Events; using NUnit.Framework; using System; using System.Linq; using Newtonsoft.Json; using System.Data.SqlClient; namespace AppointmentScheduling.IntegrationTests.Events { [TestFixture] public class ServiceBrokerTester { private readonly string ConnectionString = "Data Source=localhost;Initial Catalog=ServiceBrokerTest;Integrated Security=True;MultipleActiveResultSets=True"; private readonly string MessageType = "SBMessage"; private readonly string Contract = "SBContract"; private readonly string SchedulerQueue = "SchedulerQueue"; private readonly string NotifierQueue = "NotifierQueue"; private readonly string SchedulerService = "SchedulerService"; private readonly string NotifierService = "NotifierService"; private class TestMessage { public Guid ID { get; private set; } public string Message { get; private set; } public DateTime TimeSent { get; set; } public TestMessage(string messageContents) { ID = Guid.NewGuid(); Message = messageContents; } } [Test] public void SendMessageFromSchedulerToNotifier() { var message = new TestMessage("Test: From Scheduler to Notifier."); using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { // Always begin and end a conversation var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, SchedulerService, NotifierService, Contract); // Set the time from the source machine when the message was sent message.TimeSent = DateTime.UtcNow; // Serialize the transport message string json = JsonConvert.SerializeObject(message, Formatting.None); ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, MessageType, ServiceBrokerWrapper.GetBytes(json)); ServiceBrokerWrapper.EndConversation(sqlTransaction, conversationHandle); sqlTransaction.Commit(); } sqlConnection.Close(); } } [Test] public void SendMessageFromNotifierToScheduler() { var message = new TestMessage("Test: From Notifier to Scheduler."); using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { // Always begin and end a conversation var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, NotifierService, SchedulerService, Contract); // Set the time from the source machine when the message was sent message.TimeSent = DateTime.UtcNow; // Serialize the transport message string json = JsonConvert.SerializeObject(message, Formatting.None); ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, MessageType, ServiceBrokerWrapper.GetBytes(json)); ServiceBrokerWrapper.EndConversation(sqlTransaction, conversationHandle); sqlTransaction.Commit(); } sqlConnection.Close(); } } [Test] public void CountMessagesInNotifierQueue() { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { int messageCount = ServiceBrokerWrapper.QueryMessageCount(sqlTransaction, NotifierQueue, MessageType); Console.WriteLine("Message Count: " + messageCount); sqlTransaction.Commit(); } sqlConnection.Close(); } } [Test] public void CountMessagesInSchedulerQueue() { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { int messageCount = ServiceBrokerWrapper.QueryMessageCount(sqlTransaction, SchedulerQueue, MessageType); Console.WriteLine("Message Count: " + messageCount); sqlTransaction.Commit(); } sqlConnection.Close(); } } [Test] public void ReceiveMessageOnNotifierQueue() { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { var rawMessage = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, NotifierQueue, 10 * 1000); if (rawMessage != null && rawMessage.Body.Length > 0) { Console.WriteLine("Raw Message: " + ServiceBrokerWrapper.GetString(rawMessage.Body)); TestMessage message = JsonConvert.DeserializeObject<TestMessage>(ServiceBrokerWrapper.GetString(rawMessage.Body)); Console.WriteLine("Message: " + message.Message); } sqlTransaction.Commit(); } sqlConnection.Close(); } } [Test] public void ReceiveMessageOnSchedulerQueue() { using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); using (var sqlTransaction = sqlConnection.BeginTransaction()) { var rawMessage = ServiceBrokerWrapper.WaitAndReceive(sqlTransaction, SchedulerQueue, 10 * 1000); if (rawMessage != null && rawMessage.Body.Length > 0) { Console.WriteLine("Raw Message: " + ServiceBrokerWrapper.GetString(rawMessage.Body)); TestMessage message = JsonConvert.DeserializeObject<TestMessage>(ServiceBrokerWrapper.GetString(rawMessage.Body)); Console.WriteLine("Message: " + message.Message); } sqlTransaction.Commit(); } sqlConnection.Close(); } } } }
39.485714
164
0.577569
[ "Apache-2.0" ]
abhishekgoenka/VetClinic
FrontDeskSolution/AppointmentScheduling.IntegrationTests/Events/ServiceBrokerTester.cs
6,912
C#
using System; using System.Collections.Generic; using System.Text; namespace hangman { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Welcome to hangman. You get seven chances to guess the hidden word."); string yesNo = string.Empty; do { Console.WriteLine(); yesNo = PlayGame(); } while (yesNo.ToUpper().Equals("Y")); } private static string PlayGame() { Words words = new Words(); Word pickedWord = words.Pick; PlayHangman playHangman = new PlayHangman(); playHangman.PickedWord = pickedWord; ConsoleKeyInfo yesNo = new ConsoleKeyInfo(); for (int i = 0; i < pickedWord.WordLength; i++) { Console.ForegroundColor = ConsoleColor.Magenta; Console.Write(" _ "); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); while (playHangman.Result() == GAMERESULT.CONTINUE) { Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("Pick a letter --> "); ConsoleKeyInfo guessedLetter = Console.ReadKey(); Console.WriteLine(); if (playHangman.AddGuessedLetters(guessedLetter.KeyChar)) { playHangman.Play(); } } if (playHangman.Result() == GAMERESULT.LOST) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Game Over !"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("The word was : " + pickedWord.Content.ToUpper()); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Do you want to play again ? Y/N"); yesNo = Console.ReadKey(); return yesNo.KeyChar.ToString(); } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("You Won !!"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Do you want to play again ? Y/N"); yesNo = Console.ReadKey(); return yesNo.KeyChar.ToString(); } } } }
32.785714
102
0.5
[ "MIT" ]
WebSamuel90/C-Game
hangman/hangman/Program.cs
2,756
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IEventInstancesCollectionRequest. /// </summary> public partial interface IEventInstancesCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified Event to the collection via POST. /// </summary> /// <param name="instancesEvent">The Event to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Event.</returns> System.Threading.Tasks.Task<Event> AddAsync(Event instancesEvent, CancellationToken cancellationToken = default); /// <summary> /// Adds the specified Event to the collection via POST and returns a <see cref="GraphResponse{Event}"/> object of the request. /// </summary> /// <param name="instancesEvent">The Event to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{Event}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<Event>> AddResponseAsync(Event instancesEvent, CancellationToken cancellationToken = default); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IEventInstancesCollectionPage> GetAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets the collection page and returns a <see cref="GraphResponse{EventInstancesCollectionResponse}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{EventInstancesCollectionResponse}"/> object.</returns> System.Threading.Tasks.Task<GraphResponse<EventInstancesCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Expand(Expression<Func<Event, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Select(Expression<Func<Event, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IEventInstancesCollectionRequest OrderBy(string value); } }
46.990991
153
0.631902
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IEventInstancesCollectionRequest.cs
5,216
C#
using System.Collections.Generic; using System.Linq; using FluentAssertions; using Xunit; namespace OrderByNullsLast.Test { public class EnumerableExtensionsTests { [Fact] public void KeyIsNullableStruct_OrderByAscendingNullsFirst_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element(3), new Element(structVal: null), new Element(1), new Element(2), new Element(structVal: null) }; var expected = new double?[] { null, null, 1, 2, 3 }; // Act var actual = list.OrderBy(x => x.StructValue, NullOrder.NullsFirst).Select(x => x.StructValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsNullableStruct_OrderByAscendingNullsLast_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element(3), new Element(structVal: null), new Element(1), new Element(2), new Element(structVal: null) }; var expected = new double?[] { 1, 2, 3, null, null }; // Act var actual = list.OrderBy(x => x.StructValue, NullOrder.NullsLast).Select(x => x.StructValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsNullableStruct_OrderByDescendingNullsLast_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element(3), new Element(structVal: null), new Element(1), new Element(2), new Element(structVal: null) }; var expected = new double?[] { 3, 2, 1, null, null }; // Act var actual = list.OrderByDescending(x => x.StructValue, NullOrder.NullsLast).Select(x => x.StructValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsNullableStruct_OrderByDescendingNullsFirst_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element(3), new Element(structVal: null), new Element(1), new Element(2), new Element(structVal: null) }; var expected = new double?[] { null, null, 3, 2, 1 }; // Act var actual = list.OrderByDescending(x => x.StructValue, NullOrder.NullsFirst).Select(x => x.StructValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsClass_OrderByAscendingNullsFirst_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element("3"), new Element(stringVal: null), new Element("1"), new Element("2"), new Element(stringVal: null) }; object[] expected = { null, null, "1", "2", "3" }; // Act var actual = list.OrderBy(x => x.ClassValue, NullOrder.NullsFirst).Select(x => x.ClassValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsClass_OrderByAscendingNullsLast_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element("3"), new Element(stringVal: null), new Element("1"), new Element("2"), new Element(stringVal: null) }; object[] expected = { "1", "2", "3", null, null }; // Act var actual = list.OrderBy(x => x.ClassValue, NullOrder.NullsLast).Select(x => x.ClassValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsClass_OrderByDescendingNullsLast_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element("3"), new Element(stringVal: null), new Element("1"), new Element("2"), new Element(stringVal: null) }; object[] expected = { "3", "2", "1", null, null }; // Act var actual = list.OrderByDescending(x => x.ClassValue, NullOrder.NullsLast).Select(x => x.ClassValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } [Fact] public void KeyIsClass_OrderByDescendingNullsFirst_CorrectlyOrderedListReturned() { // Arrange var list = new List<Element> { new Element("3"), new Element(stringVal: null), new Element("1"), new Element("2"), new Element(stringVal: null) }; object[] expected = { null, null, "3", "2", "1" }; // Act var actual = list.OrderByDescending(x => x.ClassValue, NullOrder.NullsFirst).Select(x => x.ClassValue); // Assert actual.Should().HaveSameCount(expected).And.ContainInOrder(expected); } } }
31.741935
117
0.512873
[ "MIT" ]
parekhkb/OrderByNullsLast
test/OrderByNullsLast.Test/EnumerableExtensionsTests.cs
5,904
C#
using System; using System.Collections.Generic; using System.Linq; public static class Program { public static void Main () { IEnumerable<string> strs = new string[] { "foo", "bar", "baz", "qux" }; List<string> list = strs.ToList(); Console.WriteLine(list.Count); Console.WriteLine(list[0]); } }
25.923077
79
0.626113
[ "MIT" ]
RedpointGames/JSIL
Tests/SimpleTestCases/EnumerableToList.cs
337
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Azure.ServiceBus.Core.Transport { using Microsoft.Azure.ServiceBus.Management; public interface ReceiveSettings : ClientSettings { QueueDescription GetQueueDescription(); /// <summary> /// If TRUE, subscriptions will be removed on shutdown to avoid overflowing the topic /// </summary> bool RemoveSubscriptions { get; } } }
37.535714
93
0.7098
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit.Azure.ServiceBus.Core/Transport/ReceiveSettings.cs
1,051
C#
using System.Windows; using TwitchLeecher.Setup.Gui.ViewModels; namespace TwitchLeecher.Setup.Gui.Views { /// <summary> /// Interaction logic for FilesInUseWindow.xaml /// </summary> public partial class FilesInUseWindow : Window { public FilesInUseWindow() { InitializeComponent(); this.DataContextChanged += FilesInUseWindow_DataContextChanged; } private void FilesInUseWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { FilesInUseWindowVM filesInUseWindowVM = e.NewValue as FilesInUseWindowVM; if (filesInUseWindowVM != null) { filesInUseWindowVM.SetWindowCloseAction(this.Close); filesInUseWindowVM.SetSetDialogResultAction((result) => this.DialogResult = result); } } } }
30.586207
109
0.652762
[ "MIT" ]
dstftw/TwitchLeecher
TwitchLeecher.Setup/TwitchLeecher.Setup.Gui/Views/FilesInUseWindow.xaml.cs
889
C#