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 (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Threading; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { /// <summary> /// Base class for helper which creates instances. We have two derived types: One for user /// defined types which prepends the type before calling, and one for .NET types which /// doesn't prepend the type. /// </summary> abstract class InstanceCreator { private readonly PythonType/*!*/ _type; protected InstanceCreator(PythonType type) { Assert.NotNull(type); _type = type; } public static InstanceCreator Make(PythonType type) { if (type.IsSystemType) { return new SystemInstanceCreator(type); } return new UserInstanceCreator(type); } protected PythonType Type { get { return _type; } } internal abstract object CreateInstance(CodeContext/*!*/ context); internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0); internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1); internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1, object arg2); internal abstract object CreateInstance(CodeContext/*!*/ context, params object[] args); internal abstract object CreateInstance(CodeContext context, object[] args, string[] names); } class UserInstanceCreator : InstanceCreator { private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object[], object>> _ctorSite; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object>> _ctorSite0; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object>> _ctorSite1; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object>> _ctorSite2; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object, object>> _ctorSite3; public UserInstanceCreator(PythonType/*!*/ type) : base(type) { } internal override object CreateInstance(CodeContext context) { if (_ctorSite0 == null) { Interlocked.CompareExchange( ref _ctorSite0, CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object>>.Create( context.LanguageContext.InvokeOne ), null ); } return _ctorSite0.Target(_ctorSite0, context, Type.Ctor, Type); } internal override object CreateInstance(CodeContext context, object arg0) { if (_ctorSite1 == null) { Interlocked.CompareExchange( ref _ctorSite1, CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(2) ) ), null ); } return _ctorSite1.Target(_ctorSite1, context, Type.Ctor, Type, arg0); } internal override object CreateInstance(CodeContext context, object arg0, object arg1) { if (_ctorSite2 == null) { Interlocked.CompareExchange( ref _ctorSite2, CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(3) ) ), null ); } return _ctorSite2.Target(_ctorSite2, context, Type.Ctor, Type, arg0, arg1); } internal override object CreateInstance(CodeContext context, object arg0, object arg1, object arg2) { if (_ctorSite3 == null) { Interlocked.CompareExchange( ref _ctorSite3, CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(4) ) ), null ); } return _ctorSite3.Target(_ctorSite3, context, Type.Ctor, Type, arg0, arg1, arg2); } internal override object CreateInstance(CodeContext context, params object[] args) { if (_ctorSite == null) { Interlocked.CompareExchange( ref _ctorSite, CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object[], object>>.Create( context.LanguageContext.Invoke( new CallSignature( new Argument(ArgumentType.Simple), new Argument(ArgumentType.List) ) ) ), null ); } return _ctorSite.Target(_ctorSite, context, Type.Ctor, Type, args); } internal override object CreateInstance(CodeContext context, object[] args, string[] names) { return PythonOps.CallWithKeywordArgs(context, Type.Ctor, ArrayUtils.Insert(Type, args), names); } } class SystemInstanceCreator : InstanceCreator { private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object[], object>> _ctorSite; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object>> _ctorSite0; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>> _ctorSite1; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object>> _ctorSite2; private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object, object>> _ctorSite3; public SystemInstanceCreator(PythonType/*!*/ type) : base(type) { } internal override object CreateInstance(CodeContext context) { if (_ctorSite0 == null) { Interlocked.CompareExchange( ref _ctorSite0, CallSite<Func<CallSite, CodeContext, BuiltinFunction, object>>.Create( context.LanguageContext.InvokeNone ), null ); } return _ctorSite0.Target(_ctorSite0, context, Type.Ctor); } internal override object CreateInstance(CodeContext context, object arg0) { if (_ctorSite1 == null) { Interlocked.CompareExchange( ref _ctorSite1, CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(1) ) ), null ); } return _ctorSite1.Target(_ctorSite1, context, Type.Ctor, arg0); } internal override object CreateInstance(CodeContext context, object arg0, object arg1) { if (_ctorSite2 == null) { Interlocked.CompareExchange( ref _ctorSite2, CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(2) ) ), null ); } return _ctorSite2.Target(_ctorSite2, context, Type.Ctor, arg0, arg1); } internal override object CreateInstance(CodeContext context, object arg0, object arg1, object arg2) { if (_ctorSite3 == null) { Interlocked.CompareExchange( ref _ctorSite3, CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object, object>>.Create( context.LanguageContext.Invoke( new CallSignature(3) ) ), null ); } return _ctorSite3.Target(_ctorSite3, context, Type.Ctor, arg0, arg1, arg2); } internal override object CreateInstance(CodeContext context, params object[] args) { if (_ctorSite == null) { Interlocked.CompareExchange( ref _ctorSite, CallSite<Func<CallSite, CodeContext, BuiltinFunction, object[], object>>.Create( context.LanguageContext.Invoke( new CallSignature( new Argument(ArgumentType.List) ) ) ), null ); } return _ctorSite.Target(_ctorSite, context, Type.Ctor, args); } internal override object CreateInstance(CodeContext context, object[] args, string[] names) { return PythonOps.CallWithKeywordArgs(context, Type.Ctor, args, names); } } }
41.317647
126
0.55448
[ "Apache-2.0" ]
SueDou/python
Src/IronPython/Runtime/Types/InstanceCreator.cs
10,538
C#
using System; using UnityEngine; public class LanguageChangeListener : MonoBehaviour { }
10.222222
51
0.793478
[ "Apache-2.0" ]
ITALIA195/AoTTG-Mod
LanguageChangeListener.cs
92
C#
using System; using System.Reactive.Threading.Tasks; using System.Reactive.Linq; using GitterSharp.Model.Webhook; namespace GitterSharp.Services { public interface IReactiveWebhookService { /// <summary> /// Send event message to a dedicated room /// </summary> /// <param name="url">The webhook url used to send data</param> /// <param name="message">Content of the event message</param> /// <param name="level">Level of the message</param> /// <returns></returns> IObservable<bool> Post(string url, string message, MessageLevel level = MessageLevel.Info); } public class ReactiveWebhookService : IReactiveWebhookService { #region Fields private IWebhookService _webhookService = new WebhookService(); #endregion #region Methods public IObservable<bool> Post(string url, string message, MessageLevel level = MessageLevel.Info) { return _webhookService.PostAsync(url, message, level).ToObservable(); } #endregion } }
28.657895
105
0.651974
[ "Apache-2.0" ]
Odonno/gitter-api-pcl
GitterSharp/GitterSharp/Services/ReactiveWebhookService.cs
1,091
C#
[assembly: System.Reflection.AssemblyVersionAttribute("2.1.0.0")]
33
65
0.787879
[ "MIT" ]
NikolaMilosavljevic/source-build
src/reference-assemblies/Microsoft.CodeAnalysis.CSharp/netstandard1.3/2.1.0.0/AssemblyVersion.cs
66
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.Risk.Models { public class QueryRiskSwitchRequest : TeaModel { [NameInMap("biz_op")] [Validation(Required=false)] public string BizOp { get; set; } [NameInMap("biz_tag")] [Validation(Required=false)] public string BizTag { get; set; } [NameInMap("group")] [Validation(Required=false)] public string Group { get; set; } [NameInMap("sec_request_url")] [Validation(Required=false)] public string SecRequestUrl { get; set; } } }
22.290323
54
0.626628
[ "MIT" ]
sdk-team/antchain-openapi-prod-sdk
risk/csharp/core/Models/QueryRiskSwitchRequest.cs
691
C#
using Telegram.Bot.Framework.Abstractions; namespace Telegram.Bot.Framework { public abstract class BotBase : IBot { protected BotBase(string username, ITelegramBotClient client) { Username = username; Client = client; } protected BotBase(string username, string token) : this(username, new TelegramBotClient(token)) { } protected BotBase(BotOptions options) : this(options.Username, new TelegramBotClient(options.ApiToken)) { } public ITelegramBotClient Client { get; } public string Username { get; } } }
25.346154
77
0.605463
[ "MIT" ]
suxrobGM/Telegram.Bot.Framework
src/Telegram.Bot.Framework/BotBase.cs
661
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Terraria_World { public static class Profiler { public static bool Enabled { get { return _enabled; } set { _enabled = value; if (!value) foreach (var p in _profiles.Values) p.Stopwatch.Reset(); } } public static Texture2D LowestIcon { get; internal set; } public static Texture2D AverageIcon { get; internal set; } public static Texture2D HighestIcon { get; internal set; } public static double TotalTime { get; private set; } private static Vector2 _textScale; private static Vector2 _iconScale; private static Dictionary<string, Profile> _profiles = new Dictionary<string, Profile>(); private static bool _enabled = true; static double _profileResetTimer; static Profiler() { _textScale = new Vector2(.8f); _iconScale = (_textScale * .5f); LowestIcon = Texture2D.FromStream(Program.Game.GraphicsDevice, new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAlUlEQVRIS+1UwQ2AMAik6QJ1kybsPwIzOIJuoGkjPgwKWn7Cp0lD7trjuAROVWstOecZAIoAuSYnHjiIljs8N6JGgIhbO4noxOW7IHoc6bB0mqOIaHKZkeYoHv7wj7TXBtFnR5mlQ8QWHWJGWRz1hqhHh1QWEEtPjyC2ZRBdF1Rd2JCOTRPS/XyPLOkh9XAEWUJ1qGcHBkFPegdkD7UAAAAASUVORK5CYII="))); AverageIcon = Texture2D.FromStream(Program.Game.GraphicsDevice, new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAkElEQVRIS2NkoBIwMDAQYGZmvs/AwCCAxcgPjFSyhwFq0Xtc5lHNIpAFxsbG/0H02bNn4ebCxEYtwhulVAk6Y2NjUERjTVFnz54VpFocwVyLzUuwyKeWj8ApatQikvMRVeKIlBRFURyR4tpRi1ASw2jQoScIooug0aAbDTpQCIAbJ9RODNiKKZhFxFTTFKkBACPnD3qJIMGkAAAAAElFTkSuQmCC"))); HighestIcon = Texture2D.FromStream(Program.Game.GraphicsDevice, new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAdElEQVRIS2NkoCIwNjZ+z8DAIIDFyA+MVLSHwdjY+D8u80YtwhvSQyvo8KWos2fPCoK8ShUf4TPk7Nmz4EQ1ahHWlDW0go7SFEV0YqA0WEYtwpraiAkWYtQQzNHEGEKMmlGLyI7H0aAbOkGHs+GHVE1TpAYAIO+3a8NOImoAAAAASUVORK5CYII="))); } public static void Start(string name) { if (!_enabled) return; if (!_profiles.ContainsKey(name)) _profiles.Add(name, new Profile()); _profiles[name].Stopwatch.Start(); } public static void Stop(string name) { if (!_enabled) return; double totalMs = _profiles[name].Stopwatch.Elapsed.TotalMilliseconds; _profiles[name]._records[_profiles[name]._index++] = totalMs; if ((_profiles[name].Highest == null) || (totalMs > _profiles[name].Highest)) _profiles[name].Highest = totalMs; if ((_profiles[name].Lowest == null) || (totalMs < _profiles[name].Lowest)) _profiles[name].Lowest = totalMs; if (_profiles[name]._index >= _profiles[name]._records.Length) _profiles[name]._index = 0; if (_profiles[name]._recorded < _profiles[name]._records.Length) _profiles[name]._recorded++; _profiles[name].Stopwatch.Reset(); TotalTime = Math.Max(0, (TotalTime - _profiles[name].Average)); _profiles[name].Average = 0; for (var i = 0; i < _profiles[name]._recorded; i++) _profiles[name].Average += _profiles[name]._records[i]; _profiles[name].Average /= _profiles[name]._recorded; _profiles[name].Average = Math.Round(_profiles[name].Average, 3); TotalTime += _profiles[name].Average; } public static void Update(GameTime time) { if (!_enabled) return; _profileResetTimer -= time.ElapsedGameTime.TotalSeconds; if (_profileResetTimer <= 0) { foreach (Profile p in _profiles.Values) p.Lowest = p.Highest = null; _profileResetTimer += 5; } } public static void Draw(SpriteBatch spriteBatch, SpriteFont font, int screenWidth, int screenHeight) { const int iconWidth = 32; const int maxTimeTextWidth = 100; const int timeTextsWidth = ((iconWidth + maxTimeTextWidth) * 3); lock (_profiles) { float screenWidthOver20 = (screenWidth * .05f); spriteBatch.Begin(); Vector2 textPosition = new Vector2(0, (screenHeight - (screenHeight / 20f))); foreach (string name in _profiles.Keys) { Profile profile = _profiles[name]; textPosition.Y += 2; string text = name; Vector2 textSize = (font.MeasureString(text) * _textScale); textPosition.X = screenWidthOver20; spriteBatch.DrawString(font, text, new Vector2((textPosition.X + 1), (textPosition.Y + 1)), Color.Black, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, .000001f); spriteBatch.DrawString(font, text, textPosition, Color.White, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, 0); textPosition.X += (screenWidth - timeTextsWidth - screenWidthOver20); spriteBatch.Draw(LowestIcon, new Vector2(textPosition.X, textPosition.Y), null, Color.White, 0, new Vector2(0, 12), _iconScale, SpriteEffects.None, 0); text = string.Format("{0} ms", Math.Round((profile.Lowest ?? 0), 3)); textSize = (font.MeasureString(text) * _textScale); textPosition.X += (iconWidth * _iconScale.X); spriteBatch.DrawString(font, text, new Vector2((textPosition.X + 1), (textPosition.Y + 1)), Color.Black, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, .000001f); spriteBatch.DrawString(font, text, new Vector2(textPosition.X, textPosition.Y), Color.White, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, 0); textPosition.X += (maxTimeTextWidth * _textScale.X); spriteBatch.Draw(AverageIcon, new Vector2(textPosition.X, textPosition.Y), null, Color.White, 0, new Vector2(0, 12), _iconScale, SpriteEffects.None, 0); text = string.Format("{0} ms", profile.Average); textSize = (font.MeasureString(text) * _textScale); textPosition.X += (iconWidth * _iconScale.X); spriteBatch.DrawString(font, text, new Vector2((textPosition.X + 1), (textPosition.Y + 1)), Color.Black, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, .000001f); spriteBatch.DrawString(font, text, new Vector2(textPosition.X, textPosition.Y), Color.White, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, 0); textPosition.X += (maxTimeTextWidth * _textScale.X); spriteBatch.Draw(HighestIcon, new Vector2(textPosition.X, textPosition.Y), null, Color.White, 0, new Vector2(0, 12), _iconScale, SpriteEffects.None, 0); text = string.Format("{0} ms", Math.Round((profile.Highest ?? 0), 3)); textSize = (font.MeasureString(text) * _textScale); textPosition.X += (iconWidth * _iconScale.X); spriteBatch.DrawString(font, text, new Vector2((textPosition.X + 1), (textPosition.Y + 1)), Color.Black, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, .000001f); spriteBatch.DrawString(font, text, new Vector2(textPosition.X, textPosition.Y), Color.White, 0, new Vector2(0, (textSize.Y / 2)), _textScale, SpriteEffects.None, 0); textPosition.Y -= (18 * _textScale.Y); } spriteBatch.End(); } } internal class Profile { public Stopwatch Stopwatch; public double? Lowest { get; internal set; } public double Average { get; internal set; } public double? Highest { get; internal set; } internal byte _index; internal double[] _records; internal byte _recorded; public Profile() { _records = new double[50]; Stopwatch = new Stopwatch(); } } } }
55.968153
399
0.614999
[ "Unlicense" ]
DeanReynolds/MonoGame-Tile-Engine
Terraria World/Profiler.cs
8,789
C#
using System.Collections.Generic; using UnityEditor; using UnityEditor.Presets; using UnityEditorInternal; using UnityEngine; namespace PresetKit { public class PresetKitEditor : EditorWindow { [MenuItem("Assets/Create/PresetKit/Preset", false, 0)] private static void CreatePreset() { UnityEngine.Object obj = Selection.activeObject; string path = AssetDatabase.GetAssetPath(obj); AssetImporter importer = AssetImporter.GetAtPath(path); Preset preset = new Preset(importer); string presetSavePath = EditorUtility.SaveFilePanel("保存Preset", Application.dataPath, "DefaultPreset", "preset"); if (string.IsNullOrEmpty(presetSavePath)) { EditorUtility.DisplayDialog("提示", "请选择一个正确的保存目录", "确定"); return; } presetSavePath = FileUtil.GetProjectRelativePath(presetSavePath); AssetDatabase.CreateAsset(preset, presetSavePath); AssetDatabase.Refresh(); Debug.LogFormat("创建Preset成功! path={0}", presetSavePath); } [MenuItem("Assets/Create/PresetKit/PresetRule", false, 0)] private static void CreatePresetRule() { UnityEngine.Object obj = Selection.activeObject; string dir = AssetDatabase.GetAssetPath(obj);//folder PresetObject rule = ScriptableObject.CreateInstance<PresetObject>(); rule.path = dir; string saveFile = $"{dir}/PresetRule.asset"; AssetDatabase.CreateAsset(rule, saveFile); AssetDatabase.Refresh(); Debug.LogFormat("创建PresetRule成功! path={0}", saveFile); } [MenuItem("GameKits/PresetKitEditor")] public static void ShowWindow() { var wnd = GetWindow<PresetKitEditor>(); wnd.titleContent = new GUIContent("PresetKitEditor"); wnd.minSize = new Vector2(300, 500); wnd.Show(); } private List<PresetObject> ruleObjects; private PresetObject selectObj; private Vector2 pos; private ReorderableList objReorderableList; private ReorderableList presetReorderableList; private SerializedObject so; private void OnEnable() { ruleObjects = new List<PresetObject>(); string[] guids = AssetDatabase.FindAssets("t:PresetObject"); if (guids != null && guids.Length > 0) { foreach (var guid in guids) { var p = AssetDatabase.GUIDToAssetPath(guid); var obj = AssetDatabase.LoadAssetAtPath<PresetObject>(p); if (obj != null) { ruleObjects.Add(obj); } } } selectObj = ruleObjects[0]; DrawRuleList(); DrawRuleItem(); } private void OnGUI() { pos = EditorGUILayout.BeginScrollView(pos); objReorderableList.DoLayoutList(); presetReorderableList?.DoLayoutList(); EditorGUILayout.EndScrollView(); } private void DrawRuleList() { objReorderableList = new ReorderableList(ruleObjects, typeof(PresetObject), true, true, false, false); objReorderableList.elementHeight = 30; //绘制Header objReorderableList.drawHeaderCallback = (rect) => { EditorGUI.LabelField(rect, "PresetRuleSets"); }; //绘制背景 objReorderableList.drawElementBackgroundCallback = (rect, index, isActive, isFocused) => { if (Event.current.type == EventType.Repaint) { rect.x += 2; rect.width -= 4; rect.y += 2; rect.height -= 4; EditorStyles.helpBox.Draw(rect, false, isActive, isFocused, false); } }; //绘制元素 objReorderableList.drawElementCallback = (rect, index, isActive, isFocused) => { var element = ruleObjects[index]; rect.height -= 4; rect.y += 2; EditorGUI.LabelField(rect, element.name); }; objReorderableList.onSelectCallback = (ReorderableList l) => { selectObj = ruleObjects[l.index]; if (selectObj != null) EditorGUIUtility.PingObject(selectObj); DrawRuleItem(); }; } private void DrawRuleItem() { so = new SerializedObject(selectObj); var presetsProp = so.FindProperty("rules"); presetReorderableList = new ReorderableList(so, presetsProp, true, true, false, false); presetReorderableList.elementHeight = 70; //绘制Header presetReorderableList.drawHeaderCallback = (rect) => { EditorGUI.LabelField(rect, "PresetRules"); }; //绘制背景 presetReorderableList.drawElementBackgroundCallback = (rect, index, isActive, isFocused) => { if (Event.current.type == EventType.Repaint) { rect.x += 2; rect.width -= 4; rect.y += 2; rect.height -= 4; EditorStyles.helpBox.Draw(rect, false, isActive, isFocused, false); } }; //绘制元素 presetReorderableList.drawElementCallback = (rect, index, isActive, isFocused) => { var element = presetsProp.GetArrayElementAtIndex(index); rect.height -= 4; rect.y += 2; EditorGUI.PropertyField(rect, element); }; } } }
33.20442
125
0.536772
[ "MIT" ]
zwdxsky10000/PresetKit
Assets/Editor/PresetKit/GUI/PresetKitEditor.cs
6,102
C#
using System.Windows.Controls; namespace tweetz.core.Views { public partial class SettingsView : UserControl { public SettingsView() { InitializeComponent(); } } }
17.75
51
0.600939
[ "MIT" ]
Mr-Kyary/tweetz
src/tweetz.core/Views/SettingsView.xaml.cs
215
C#
// ---------------------------------------------------------------------- // @Namespace : NewtonVgo.Schema.ParticleSystems // @Class : VGO_PS_Renderer // ---------------------------------------------------------------------- namespace NewtonVgo.Schema.ParticleSystems { using Newtonsoft.Json; using System; using System.Numerics; /// <summary> /// VGO Particle System Renderer /// </summary> [Serializable] [JsonObject("vgo.ps.renderer")] public class VGO_PS_Renderer { /// <summary>Makes the rendered 3D object visible if enabled.</summary> [JsonProperty("enabled")] public bool enabled; /// <summary>Specifies how the system draws particles.</summary> [JsonProperty("renderMode")] public ParticleSystemRenderMode renderMode; /// <summary>How much do the particles stretch depending on the Camera's speed.</summary> [JsonProperty("cameraVelocityScale")] public float cameraVelocityScale; /// <summary>Specifies how much particles stretch depending on their velocity.</summary> [JsonProperty("velocityScale")] public float velocityScale; /// <summary>How much are the particles stretched in their direction of motion.</summary> [JsonProperty("lengthScale")] public float lengthScale; /// <summary>Specifies how much a billboard particle orients its normals towards the Camera.</summary> [JsonProperty("normalDirection")] public float normalDirection; ///// <summary>The Mesh that the particle uses instead of a billboarded Texture.</summary> //[JsonProperty("mesh")] //public Mesh mesh; ///// <summary>The number of Meshes the system uses for particle rendering.</summary> //[JsonProperty("meshCount")] //public int meshCount { get; } ///// <summary>Returns the first instantiated Material assigned to the renderer.</summary> //public Material material; /// <summary>The shared material of this object.</summary> [JsonProperty("sharedMaterialIndex")] //public Material sharedMaterial; public int sharedMaterial; /// <summary>Set the Material that the TrailModule uses to attach trails to particles.</summary> [JsonProperty("trailMaterialIndex")] //public Material trailMaterial; public int trailMaterialIndex; /// <summary>Specifies how to sort particles within a system.</summary> [JsonProperty("sortMode")] public ParticleSystemSortMode sortMode; /// <summary>Biases Particle System sorting amongst other transparencies.</summary> [JsonProperty("sortingFudge")] public float sortingFudge; /// <summary>Clamp the minimum particle size.</summary> [JsonProperty("minParticleSize")] public float minParticleSize; /// <summary>Clamp the maximum particle size.</summary> [JsonProperty("maxParticleSize")] public float maxParticleSize; /// <summary>Control the direction that particles face.</summary> [JsonProperty("alignment")] //[NativeName("RenderAlignment")] public ParticleSystemRenderSpace alignment; /// <summary>Flip a percentage of the particles, along each axis.</summary> [JsonProperty("flip")] public Vector3? flip; /// <summary>Allow billboard particles to roll around their z-axis.</summary> [JsonProperty("allowRoll")] public bool allowRoll; /// <summary>Modify the pivot point used for rotating particles.</summary> [JsonProperty("pivot")] public Vector3? pivot; /// <summary>Specifies how the Particle System Renderer interacts with SpriteMask.</summary> [JsonProperty("maskInteraction")] public SpriteMaskInteraction maskInteraction; /// <summary>Enables GPU Instancing on platforms that support it.</summary> [JsonProperty("enableGPUInstancing")] public bool enableGPUInstancing; /// <summary>Does this object cast shadows?</summary> [JsonProperty("shadowCastingMode")] public ShadowCastingMode shadowCastingMode; /// <summary>Does this object receive shadows?</summary> [JsonProperty("receiveShadows")] public bool receiveShadows; /// <summary>Apply a shadow bias to prevent self-shadowing layouts. The specified value is the proportion of the particle size.</summary> [JsonProperty("shadowBias")] public float shadowBias; /// <summary>Specifies the mode for motion vector rendering.</summary> [JsonProperty("motionVectorGenerationMode")] public MotionVectorGenerationMode motionVectorGenerationMode; /// <summary>Allows turning off rendering for a specific component.</summary> [JsonProperty("forceRenderingOff")] public bool forceRenderingOff; /// <summary>This value sorts renderers by priority. Lower values are rendered first and higher values are rendered last.</summary> [JsonProperty("rendererPriority")] public int rendererPriority; /// <summary>Determines which rendering layer this renderer lives on.</summary> [JsonProperty("renderingLayerMask")] public uint renderingLayerMask; /// <summary>Unique ID of the Renderer's sorting layer.</summary> [JsonProperty("sortingLayerID")] public int sortingLayerID; /// <summary>Renderer's order within a sorting layer.</summary> [JsonProperty("sortingOrder")] public int sortingOrder; /// <summary>The light probe interpolation type.</summary> [JsonProperty("lightProbeUsage")] public LightProbeUsage lightProbeUsage; /// <summary>Should reflection probes be used for this Renderer?</summary> [JsonProperty("reflectionProbeUsage")] public ReflectionProbeUsage reflectionProbeUsage; /// <summary>If set, Renderer will use this Transform's position to find the light or reflection probe.</summary> [JsonProperty("probeAnchor")] public VgoTransform probeAnchor; ///// <summary>The number of currently active custom vertex streams.</summary> //[JsonProperty("activeVertexStreamsCount")] //public int activeVertexStreamsCount { get; } } }
41.866242
146
0.640195
[ "MIT" ]
izayoijiichan/VGO2
NewtonVgo/Runtime/Schema/Layouts/ParticleSystems/VGO_PS_Renderer.cs
6,575
C#
using System; using System.Collections.Generic; using UnityEngine; namespace AudioRender { public class GfxRenderDevice : MonoBehaviour, IRenderDevice { public void Dispose() { } void Start() { if (decayMaterial == null) { decayMaterial = Resources.Load("Materials/OscilloscopeDecay", typeof(Material)) as Material; } if (decayMaterial == null) { Debug.LogError("No decayMaterial found for GfxRenderDevice!"); enabled = false; return; } if (lineMaterial == null) { lineMaterial = Resources.Load("Materials/OscilloscopeLine", typeof(Material)) as Material; } if (lineMaterial == null) { Debug.LogError("No lineMaterial found for GfxRenderDevice!"); enabled = false; return; } Camera.main.clearFlags = CameraClearFlags.Nothing; Camera.onPostRender += OnPostRenderCallback; } void OnDestroy() { Camera.onPostRender -= OnPostRenderCallback; } public bool WaitSync() { return true; } public void Begin() { this.lines = new List<GfxLine>(); this.submittedLines = new List<GfxLine>(); this.gfxRenderer = new GfxRenderer(); this.position = Vector2.zero; this.intensity = 1.0f; } public void Submit() { var temp = lines; this.lines = submittedLines; this.submittedLines = temp; lines.Clear(); } public Rect GetViewPort() { return new Rect(0, 0, 1, 1); } public void SetPoint(Vector2 point) { this.position = point; } public void SetIntensity(float intensity) { this.intensity = intensity; } public void DrawCircle(float radius) { throw new NotImplementedException("DrawCircle not implemented yet."); } public void DrawLine(Vector2 point, float intensity = -1) { if (intensity >= 0.0f) { this.intensity = intensity; } lines.Add(new GfxLine(this.position, point, this.intensity)); this.position = point; } public void SyncPoint(IntPtr device, Vector2 point) { this.position = point; } private void OnPostRenderCallback(Camera camera) { if (camera == Camera.main) { gfxRenderer.Render(submittedLines, decayMaterial, lineMaterial); } } [SerializeField] private Material decayMaterial; [SerializeField] private Material lineMaterial; private GfxRenderer gfxRenderer; private List<GfxLine> lines; private List<GfxLine> submittedLines; private Vector2 position; private float intensity; } }
26.347107
108
0.521016
[ "MIT" ]
ptimonen/AudioRenderUnity
Assets/Plugins/AudioRender/Scripts/Rendering/GfxRender/GfxRenderDevice.cs
3,188
C#
// ========================================================================== // Field.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Collections.Generic; using Microsoft.OData.Edm; using Newtonsoft.Json.Linq; using NJsonSchema; using Squidex.Domain.Apps.Core.Schemas.Validators; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Core.Schemas { public abstract class Field : CloneableBase { private readonly Lazy<List<IValidator>> validators; private readonly long fieldId; private readonly Partitioning partitioning; private string fieldName; private bool isDisabled; private bool isHidden; private bool isLocked; public long Id { get { return fieldId; } } public string Name { get { return fieldName; } } public bool IsLocked { get { return isLocked; } } public bool IsHidden { get { return isHidden; } } public bool IsDisabled { get { return isDisabled; } } public Partitioning Paritioning { get { return partitioning; } } public IReadOnlyList<IValidator> Validators { get { return validators.Value; } } public abstract FieldProperties RawProperties { get; } protected Field(long id, string name, Partitioning partitioning) { Guard.ValidPropertyName(name, nameof(name)); Guard.GreaterThan(id, 0, nameof(id)); Guard.NotNull(partitioning, nameof(partitioning)); fieldId = id; fieldName = name; this.partitioning = partitioning; validators = new Lazy<List<IValidator>>(() => new List<IValidator>(CreateValidators())); } protected abstract Field UpdateInternal(FieldProperties newProperties); public abstract object ConvertValue(JToken value); public Field Lock() { return Clone<Field>(clone => clone.isLocked = true); } public Field Hide() { return Clone<Field>(clone => clone.isHidden = true); } public Field Show() { return Clone<Field>(clone => clone.isHidden = false); } public Field Disable() { return Clone<Field>(clone => clone.isDisabled = true); } public Field Enable() { return Clone<Field>(clone => clone.isDisabled = false); } public Field Update(FieldProperties newProperties) { ThrowIfLocked(); return UpdateInternal(newProperties); } public Field Rename(string newName) { ThrowIfLocked(); ThrowIfSameName(newName); return Clone<Field>(clone => clone.fieldName = newName); } private void ThrowIfLocked() { if (isLocked) { throw new DomainException($"Field {fieldId} is locked."); } } private void ThrowIfSameName(string newName) { if (!newName.IsSlug()) { var error = new ValidationError("Name must be a valid slug", "Name"); throw new ValidationException($"Cannot rename the field '{fieldName}' ({fieldId})", error); } } public void AddToEdmType(EdmStructuredType edmType, PartitionResolver partitionResolver, string schemaName, Func<EdmComplexType, EdmComplexType> typeResolver) { Guard.NotNull(edmType, nameof(edmType)); Guard.NotNull(typeResolver, nameof(typeResolver)); Guard.NotNull(partitionResolver, nameof(partitionResolver)); var edmValueType = CreateEdmType(); if (edmValueType == null) { return; } var partitionType = typeResolver(new EdmComplexType("Squidex", $"{schemaName}{Name.ToPascalCase()}Property")); var partition = partitionResolver(partitioning); foreach (var partitionItem in partition) { partitionType.AddStructuralProperty(partitionItem.Key, edmValueType); } edmType.AddStructuralProperty(Name.EscapeEdmField(), new EdmComplexTypeReference(partitionType, false)); } public void AddToJsonSchema(JsonSchema4 schema, PartitionResolver partitionResolver, string schemaName, Func<string, JsonSchema4, JsonSchema4> schemaResolver) { Guard.NotNull(schema, nameof(schema)); Guard.NotNull(schemaResolver, nameof(schemaResolver)); Guard.NotNull(partitionResolver, nameof(partitionResolver)); var partitionProperty = CreateProperty(); var partitionObject = new JsonSchema4 { Type = JsonObjectType.Object, AllowAdditionalProperties = false }; var partition = partitionResolver(partitioning); foreach (var partitionItem in partition) { var partitionItemProperty = new JsonProperty { Description = partitionItem.Name, IsRequired = RawProperties.IsRequired }; PrepareJsonSchema(partitionItemProperty, schemaResolver); partitionObject.Properties.Add(partitionItem.Key, partitionItemProperty); } partitionProperty.Reference = schemaResolver($"{schemaName}{Name.ToPascalCase()}Property", partitionObject); schema.Properties.Add(Name, partitionProperty); } public JsonProperty CreateProperty() { var jsonProperty = new JsonProperty { IsRequired = RawProperties.IsRequired, Type = JsonObjectType.Object }; if (!string.IsNullOrWhiteSpace(RawProperties.Hints)) { jsonProperty.Description = RawProperties.Hints; } else { jsonProperty.Description = Name; } if (!string.IsNullOrWhiteSpace(RawProperties.Hints)) { jsonProperty.Description += $" ({RawProperties.Hints})."; } return jsonProperty; } protected abstract IEnumerable<IValidator> CreateValidators(); protected abstract IEdmTypeReference CreateEdmType(); protected abstract void PrepareJsonSchema(JsonProperty jsonProperty, Func<string, JsonSchema4, JsonSchema4> schemaResolver); } }
31.281106
166
0.576606
[ "MIT" ]
andrewhoi/squidex
src/Squidex.Domain.Apps.Core/Schemas/Field.cs
6,788
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: Templates\CSharp\Requests\EntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The type GraphServiceSharesCollectionRequestBuilder. /// </summary> public partial class GraphServiceSharesCollectionRequestBuilder : BaseRequestBuilder, IGraphServiceSharesCollectionRequestBuilder { /// <summary> /// Constructs a new GraphServiceSharesCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public GraphServiceSharesCollectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public IGraphServiceSharesCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public IGraphServiceSharesCollectionRequest Request(IEnumerable<Option> options) { return new GraphServiceSharesCollectionRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets an <see cref="ISharedDriveItemRequestBuilder"/> for the specified GraphServiceSharedDriveItem. /// </summary> /// <param name="id">The ID for the GraphServiceSharedDriveItem.</param> /// <returns>The <see cref="ISharedDriveItemRequestBuilder"/>.</returns> public ISharedDriveItemRequestBuilder this[string id] { get { return new SharedDriveItemRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client); } } } }
38.530303
153
0.598506
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/GraphServiceSharesCollectionRequestBuilder.cs
2,543
C#
using System; using System.Collections.Generic; #nullable disable namespace KZ.AdventureWorks.Products.Api.Models { public partial class VSalesPersonSalesByFiscalYear { public int? SalesPersonId { get; set; } public string FullName { get; set; } public string JobTitle { get; set; } public string SalesTerritory { get; set; } public decimal? _2002 { get; set; } public decimal? _2003 { get; set; } public decimal? _2004 { get; set; } } }
26.789474
54
0.644401
[ "MIT" ]
az00s/KZ.AdventureWorks.Products.Api
KZ.AdventureWorks.Products.Api/Models/VSalesPersonSalesByFiscalYear.cs
511
C#
// Copyright 2015 Tosho Toshev // // 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 ElmCommunicatorPortable.Responses.ObdIIResponses.ShowCurrentData; using NUnit.Framework; namespace ElmCommunicatorTests.Responses.ObdIIResponses.ShowCurrentData { [TestFixture] public class FuelTrimResponseTests { private FuelTrimResponse _response; [Test] public void ShouldParseTheResponse() { string message = "41 07 55"; double expectedTrim = -33.59375; _response = new FuelTrimResponse(); _response.Parse(message); Assert.AreEqual(expectedTrim, _response.FuelTrim); } [Test] public void ShouldSetTheCommandFromTheResponse() { string message = "41 09 55"; string expectedCommand = "4109"; _response = new FuelTrimResponse(); _response.Parse(message); Assert.AreEqual(expectedCommand, _response.Command); } [Test] public void ShouldReturnNullWhenWrongCommand() { string message = "41 01 55"; _response = new FuelTrimResponse(); var result = _response.Parse(message); Assert.IsNull(result); } } }
32.482143
78
0.641012
[ "Apache-2.0" ]
cracker4o/elm327lib
ElmCommunicator/ElmCommunicatorTests/Responses/ObdIIResponses/ShowCurrentData/FuelTrimResponseTests.cs
1,821
C#
using CrypTool.CrypAnalysisViewControl; using CrypTool.PluginBase; using CrypTool.PluginBase.Miscellaneous; using System; using System.ComponentModel; using System.Text; using System.Threading; using System.Windows.Controls; using System.Windows.Threading; namespace IDPAnalyser { [Author("George Lasry, Armin Krauß", "krauss@CrypTool.org", "CrypTool", "http://www.uni-due.de")] [PluginInfo("IDPAnalyser.Properties.Resources", "PluginCaption", "PluginTooltip", "IDPAnalyser/DetailedDescription/doc.xml", "IDPAnalyser/icon.png")] [ComponentCategory(ComponentCategory.CryptanalysisSpecific)] public class IDPAnalyser : ICrypComponent { private string _input; private string _output; private string[] _keywords; private HighscoreList _highscoreList; private ValueKeyComparer _valueKeyComparer; private readonly Random _random = new Random(DateTime.Now.Millisecond); private readonly AutoResetEvent _autoResetEvent; private readonly IDPAnalyserSettings _settings; private readonly IDPAnalyserQuickWatchPresentation _presentation; private int[] Key1MinColEnd, Key1MaxColEnd; #region Properties [PropertyInfo(Direction.InputData, "InputCaption", "InputTooltip", true)] public string Input { get => _input; set { _input = value; OnPropertyChange("Input"); } } [PropertyInfo(Direction.InputData, "KeywordsCaption", "KeywordsTooltip", false)] public string[] Keywords { get => _keywords; set { _keywords = value; OnPropertyChange("Keywords"); } } #endregion /// <summary> /// Constructor /// </summary> public IDPAnalyser() { _settings = new IDPAnalyserSettings(); _presentation = new IDPAnalyserQuickWatchPresentation(); Presentation = _presentation; _presentation.SelectedResultEntry += SelectedResultEntry; _autoResetEvent = new AutoResetEvent(false); } private void SelectedResultEntry(ResultEntry resultEntry) { try { Output = resultEntry.Text; } catch (Exception) { } } [PropertyInfo(Direction.OutputData, "OutputCaption", "OutputTooltip")] public string Output { get => _output; set { _output = value; OnPropertyChanged("Output"); } } public void GuiLogMessage(string message, NotificationLevel loglevel) { if (OnGuiLogNotificationOccured != null) { OnGuiLogNotificationOccured(this, new GuiLogEventArgs(message, this, loglevel)); } } #region IPlugin Member public event CrypTool.PluginBase.StatusChangedEventHandler OnPluginStatusChanged; public event CrypTool.PluginBase.GuiLogNotificationEventHandler OnGuiLogNotificationOccured; public event CrypTool.PluginBase.PluginProgressChangedEventHandler OnPluginProgressChanged; public ISettings Settings => _settings; public UserControl Presentation { get; private set; } public void PreExecution() { } public void Execute() { Bigrams.InitLanguage(_settings.Language); if (_input == null) { GuiLogMessage("No input!", NotificationLevel.Error); return; } _valueKeyComparer = new ValueKeyComparer(false); _highscoreList = new HighscoreList(_valueKeyComparer, 10); _presentation.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate { _presentation.Entries.Clear(); }, null); switch (_settings.Analysis_method) { case 0: GuiLogMessage("Starting Dictionary Attack", NotificationLevel.Info); DictionaryAttack(); break; case 1: GuiLogMessage("Starting Hill Climbing Analysis", NotificationLevel.Info); HillClimbingAnalysis(); break; } if (_highscoreList.Count > 0) { Output = UTF8Encoding.UTF8.GetString(_highscoreList[0].plaintext); } else { GuiLogMessage("No candidates found", NotificationLevel.Warning); } ProgressChanged(1, 1); } public void PostExecution() { } private bool stop; public void Stop() { _autoResetEvent.Set(); stop = true; } public void Initialize() { _settings.UpdateTaskPaneVisibility(); } public void Dispose() { } public void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } private void OnPropertyChange(string propertyname) { EventsHelper.PropertyChanged(PropertyChanged, this, new PropertyChangedEventArgs(propertyname)); } public void ProgressChanged(double value, double max) { if (OnPluginProgressChanged != null) { OnPluginProgressChanged(this, new PluginProgressEventArgs(value, max)); } } private void showProgress(DateTime startTime, ulong totalKeys, ulong doneKeys) { if (!Presentation.IsVisible || stop) { return; } long ticksPerSecond = 10000000; TimeSpan elapsedtime = DateTime.Now.Subtract(startTime); double totalSeconds = elapsedtime.TotalSeconds; if (totalSeconds == 0) { totalSeconds = 0.001; } elapsedtime = new TimeSpan(elapsedtime.Ticks - (elapsedtime.Ticks % ticksPerSecond)); // truncate to seconds TimeSpan timeleft = new TimeSpan(); DateTime endTime = new DateTime(); double secstodo; double keysPerSec = doneKeys / totalSeconds; if (keysPerSec > 0) { if (totalKeys < doneKeys) { totalKeys = doneKeys; } secstodo = (totalKeys - doneKeys) / keysPerSec; timeleft = new TimeSpan((long)secstodo * ticksPerSecond); endTime = DateTime.Now.AddSeconds(secstodo); endTime = new DateTime(endTime.Ticks - (endTime.Ticks % ticksPerSecond)); // truncate to seconds } ((IDPAnalyserQuickWatchPresentation)Presentation).Dispatcher.BeginInvoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate { System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentUICulture; _presentation.StartTime.Value = "" + startTime; _presentation.KeysPerSecond.Value = string.Format(culture, "{0:##,#}", (ulong)keysPerSec); if (keysPerSec > 0) { _presentation.TimeLeft.Value = "" + timeleft; _presentation.ElapsedTime.Value = "" + elapsedtime; _presentation.EndTime.Value = "" + endTime; } else { _presentation.TimeLeft.Value = "incalculable"; _presentation.EndTime.Value = "in a galaxy far, far away..."; } _presentation.Entries.Clear(); for (int i = 0; i < _highscoreList.Count; i++) { ValueKey v = _highscoreList[i]; ResultEntry entry = new ResultEntry { Ranking = i + 1, Value = string.Format("{0:0.00000}", v.score), KeyArray = v.key, KeyPhrase = v.keyphrase, Key = "[" + string.Join(",", v.key) + "]", Text = Encoding.GetEncoding(1252).GetString(v.plaintext) }; _presentation.Entries.Add(entry); } } , null); } private void UpdatePresentationList(ulong totalKeys, ulong doneKeys, DateTime starttime) { showProgress(starttime, totalKeys, doneKeys); ProgressChanged(doneKeys, totalKeys); } #endregion #region INotifyPropertyChanged Member public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; #endregion #region DictionaryAttack public static void getKeyFromKeyword(string phrase, byte[] key, int keylen) { for (int i = 0; i < keylen; i++) { key[i] = 0xff; } for (int i = 0; i < keylen; i++) { int minJ = -1; for (int j = 0; j < keylen; j++) { if (key[j] != 0xff) { continue; } if ((minJ == -1) || (phrase[j] < phrase[minJ])) { minJ = j; } } key[minJ] = (byte)i; } } private const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // used for converting the numeric key to a keyword // Convert the numeric key to a keyword based upon the alphabet string private string getKeywordFromKey(byte[] key) { string keyword = ""; foreach (byte i in key) { keyword += alphabet[i]; } return keyword; } private void DictionaryAttack() { if (Keywords == null || Keywords.Length == 0) { GuiLogMessage("Check dictionary", NotificationLevel.Error); return; } if (_settings.Key1Min < 2) { GuiLogMessage("The minimum size for key 1 is 2.", NotificationLevel.Error); return; } if (_settings.Key1Max < _settings.Key1Min) { GuiLogMessage("The maximum size for key 1 must be bigger than the minimum size.", NotificationLevel.Error); return; } if (_settings.Key2Min < 2) { GuiLogMessage("The minimum size for key 2 is 2.", NotificationLevel.Error); return; } if (_settings.Key2Max < _settings.Key2Min) { GuiLogMessage("The maximum size for key 2 must be bigger than the minimum size.", NotificationLevel.Error); return; } DateTime startTime = DateTime.Now; DateTime nextUpdate = DateTime.Now.AddMilliseconds(100); ValueKey vk = new ValueKey(); ulong totalKeys = 0; foreach (string keyword in Keywords) { if (keyword.Length >= _settings.Key2Min && keyword.Length <= _settings.Key2Max) { totalKeys++; } } totalKeys *= (ulong)(_settings.Key1Max - _settings.Key1Min + 1); ulong doneKeys = 0; stop = false; byte[] mybuffer = new byte[_input.Length]; byte[] ciphertext = UTF8Encoding.UTF8.GetBytes(_input); for (int key1size = _settings.Key1Min; key1size <= _settings.Key1Max; key1size++) { computeKey1MinMaxColEnding(_input.Length, key1size); for (int key2size = _settings.Key2Min; key2size <= _settings.Key2Max; key2size++) { byte[] key2 = new byte[key2size]; foreach (string keyword in Keywords) { if (stop) { break; } if (keyword.Length != key2size) { continue; } getKeyFromKeyword(keyword, key2, key2size); //decrypt(vk, key); vk.key = key2; vk.keyphrase = keyword; decrypt2(vk.key, vk.key.Length, ciphertext, _input.Length, mybuffer); vk.plaintext = mybuffer; vk.score = evalIDPKey2(vk.plaintext, key1size); _highscoreList.Add(vk); doneKeys++; if (DateTime.Now >= nextUpdate) { UpdatePresentationList(totalKeys, doneKeys, startTime); nextUpdate = DateTime.Now.AddMilliseconds(1000); } } UpdatePresentationList(totalKeys, doneKeys, startTime); } } } #endregion #region Hill Climbing private void HillClimbingAnalysis() { if (_settings.Iterations < 2) { GuiLogMessage("Check iterations.", NotificationLevel.Error); return; } if (_settings.Key1Size < 2) { GuiLogMessage("The minimum size for key 1 is 2.", NotificationLevel.Error); return; } if (_settings.Key2Size < 2) { GuiLogMessage("The minimum size for key 2 is 2.", NotificationLevel.Error); return; } computeKey1MinMaxColEnding(_input.Length, _settings.Key1Size); byte[] mybuffer = new byte[_input.Length]; DateTime startTime = DateTime.Now; DateTime nextUpdate = DateTime.Now.AddMilliseconds(100); HighscoreList ROUNDLIST = new HighscoreList(_valueKeyComparer, 10); ValueKey vk = new ValueKey(); ulong totalKeys = (ulong)_settings.Repeatings * (ulong)_settings.Iterations; ulong doneKeys = 0; stop = false; byte[] ciphertext = UTF8Encoding.UTF8.GetBytes(_input); for (int repeating = 0; repeating < _settings.Repeatings; repeating++) { if (stop) { break; } ROUNDLIST.Clear(); byte[] key = randomArray(_settings.Key2Size); byte[] oldkey = new byte[_settings.Key2Size]; for (int iteration = 0; iteration < _settings.Iterations; iteration++) { if (stop) { break; } Array.Copy(key, oldkey, key.Length); int r = _random.Next(100); if (r < 50) { for (int i = 0; i < _random.Next(10); i++) { swap(key, _random.Next(key.Length), _random.Next(key.Length)); } } else if (r < 70) { for (int i = 0; i < _random.Next(3); i++) { int l = _random.Next(key.Length - 1) + 1; int f = _random.Next(key.Length); int t = (f + l + _random.Next(key.Length - l)) % key.Length; blockswap(key, f, t, l); } } else if (r < 90) { int l = 1 + _random.Next(key.Length - 1); int f = _random.Next(key.Length); int t = (f + 1 + _random.Next(key.Length - 1)) % key.Length; blockshift(key, f, t, l); } else { pivot(key, _random.Next(key.Length - 1) + 1); } vk.key = key; decrypt2(vk.key, vk.key.Length, ciphertext, _input.Length, mybuffer); vk.plaintext = mybuffer; vk.score = evalIDPKey2(vk.plaintext, _settings.Key1Size); vk.keyphrase = getKeywordFromKey(vk.key); if (ROUNDLIST.Add(vk)) { if (_highscoreList.isBetter(vk)) { _highscoreList.Add(vk); //Output = vk.plaintext; } } else { Array.Copy(oldkey, key, key.Length); } doneKeys++; if (DateTime.Now >= nextUpdate) { _highscoreList.Merge(ROUNDLIST); UpdatePresentationList(totalKeys, doneKeys, startTime); nextUpdate = DateTime.Now.AddMilliseconds(1000); } } } _highscoreList.Merge(ROUNDLIST); UpdatePresentationList(totalKeys, doneKeys, startTime); } private void computeKey1MinMaxColEnding(int ciphertextLength, int keylength) { Key1MinColEnd = new int[keylength]; Key1MaxColEnd = new int[keylength]; int fullRows = ciphertextLength / keylength; int numberOfLongColumns = ciphertextLength % keylength; for (int i = 0; i < keylength; i++) { Key1MinColEnd[i] = fullRows * (i + 1) - 1; if (i < numberOfLongColumns) { Key1MaxColEnd[i] = fullRows * (i + 1) + i; } else { Key1MaxColEnd[i] = Key1MinColEnd[i] + numberOfLongColumns; } } for (int i = 0; i < keylength; i++) { int index = keylength - 1 - i; Key1MaxColEnd[index] = Math.Min(Key1MaxColEnd[index], ciphertextLength - 1 - fullRows * i); if (i < numberOfLongColumns) { Key1MinColEnd[index] = Math.Max(Key1MinColEnd[index], ciphertextLength - 1 - fullRows * i - i); } else { Key1MinColEnd[index] = Math.Max(Key1MinColEnd[index], Key1MaxColEnd[index] - numberOfLongColumns); } } } // The core algorithm for IDP (index of Digraphic Potential) public long evalIDPKey2(byte[] ciphertext, int keylen) { long[,] p1p2Best = new long[keylen, keylen]; // CCT: All columns always start at multiples of nrows. No need to sweep for different // ending positions if ((ciphertext.Length % keylen) == 0) { int fullRows = ciphertext.Length / keylen; for (int c1 = 0; c1 < keylen; c1++) { for (int c2 = 0; c2 < keylen; c2++) { if (c1 == c2) { continue; } int p1 = Key1MinColEnd[c1]; int p2 = Key1MinColEnd[c2]; long sum = 0; for (int l = 0; l < fullRows; l++) { sum += Bigrams.FlatList2[(ciphertext[p1 - l] << 8) + ciphertext[p2 - l]]; } p1p2Best[c1, c2] = sum / fullRows; } } } else if ((ciphertext.Length % keylen) != 0) { // ICT - we sweep all possible C1-C2-C3 combinations as well // as all posible ending positions (P1, P2, P3). int fullRows = ciphertext.Length / keylen; long[] base_ = new long[fullRows + keylen]; for (int c1 = 0; c1 < keylen; c1++) { int minP1 = Key1MinColEnd[c1]; int maxP1 = Key1MaxColEnd[c1]; for (int c2 = 0; c2 < keylen; c2++) { if (c1 == c2) { continue; } int minP2 = Key1MinColEnd[c2]; int maxP2 = Key1MaxColEnd[c2]; int offset1 = maxP1 - minP1; int offset2 = maxP2 - minP2; int start1 = minP1 - fullRows + 1; int start2 = minP2 - fullRows + 1; long best = 0; for (int offset = 0; offset <= offset2; offset++) { long sum = 0; int p1 = start1; int p2 = start2 + offset; for (int i = 0; i < fullRows; i++) { long val = base_[i] = Bigrams.FlatList2[(ciphertext[p1++] << 8) + ciphertext[p2++]]; sum += val; } if (best < sum) { best = sum; } int iMinusFullRows = 0; while ((p1 <= maxP1) && (p2 <= maxP2)) { sum -= base_[iMinusFullRows++]; sum += Bigrams.FlatList2[(ciphertext[p1++] << 8) + ciphertext[p2++]]; if (best < sum) { best = sum; } } } // we test only once with offset = 0; for (int offset = 1; offset <= offset1; offset++) { long sum = 0; int p1 = start1 + offset; int p2 = start2; for (int i = 0; i < fullRows; i++) { long val = base_[i] = Bigrams.FlatList2[(ciphertext[p1++] << 8) + ciphertext[p2++]]; sum += val; } if (best < sum) { best = sum; } int iMinusFullRows = 0; while ((p1 <= maxP1) && (p2 <= maxP2)) { sum -= base_[iMinusFullRows++]; sum += Bigrams.FlatList2[(ciphertext[p1++] << 8) + ciphertext[p2++]]; if (best < sum) { best = sum; } } } p1p2Best[c1, c2] = best / fullRows; } } } return getMatrixScore(p1p2Best); } private static long getMatrixScore(long[,] matrix) { int dimension = matrix.GetLength(0); int[] left = new int[dimension]; int[] right = new int[dimension]; for (int i = 0; i < dimension; i++) { left[i] = right[i] = -1; } long sum = 0; for (int i = 1; i <= dimension; i++) { long best = 0; int bestP1 = -1; int bestP2 = -1; for (int p1 = 0; p1 < dimension; p1++) { if (right[p1] != -1) { continue; } bool[] inP1LeftCycle = new bool[dimension]; if (i != dimension) { int curr = p1; while (left[curr] != -1) { curr = left[curr]; inP1LeftCycle[curr] = true; } } for (int p2 = 0; p2 < dimension; p2++) { if (left[p2] != -1) { continue; } if (inP1LeftCycle[p2]) { continue; } if (p1 == p2) { continue; } if (best < matrix[p1, p2]) { best = matrix[p1, p2]; bestP1 = p1; bestP2 = p2; } } } sum += best; if (bestP1 == -1) { Console.Write("-1\n"); } else { left[bestP2] = bestP1; right[bestP1] = bestP2; } } return sum / dimension; } public static void decrypt2(byte[] key, int keylen, byte[] ciphertext, int ciphertextLength, byte[] plaintext) { int[] invkey = new int[keylen]; for (int i = 0; i < keylen; i++) { invkey[key[i]] = i; } int c = 0; for (int trcol = 0; trcol < keylen; trcol++) { for (int p = invkey[trcol]; p < ciphertextLength; p += keylen) { plaintext[p] = ciphertext[c++]; } } } #endregion private void swap(byte[] arr, int i, int j) { byte tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } private void blockswap(byte[] arr, int f, int t, int l) { for (int i = 0; i < l; i++) { swap(arr, (f + i) % arr.Length, (t + i) % arr.Length); } } private void pivot(byte[] arr, int p) { byte[] tmp = new byte[arr.Length]; Array.Copy(arr, tmp, arr.Length); Array.Copy(tmp, p, arr, 0, arr.Length - p); Array.Copy(tmp, 0, arr, arr.Length - p, p); } private void blockshift(byte[] arr, int f, int t, int l) { byte[] tmp = new byte[arr.Length]; Array.Copy(arr, tmp, arr.Length); int t0 = (t - f + arr.Length) % arr.Length; int n = (t0 + l) % arr.Length; for (int i = 0; i < n; i++) { int ff = (f + i) % arr.Length; int tt = (((t0 + i) % n) + f) % arr.Length; arr[tt] = tmp[ff]; } } private byte[] randomArray(int length) { byte[] result = new byte[length]; for (int i = 0; i < length; i++) { result[i] = (byte)i; } for (int i = 0; i < length; i++) { swap(result, _random.Next(length), _random.Next(length)); } return result; } } public class ResultEntry : ICrypAnalysisResultListEntry, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int ranking; public int Ranking { get => ranking; set { ranking = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Ranking))); } } public string Value { get; set; } public string Key { get; set; } public string KeyPhrase { get; set; } public byte[] KeyArray { get; set; } public string Text { get; set; } public string ClipboardValue => Value; public string ClipboardKey => Key; public string ClipboardText => Text; public string ClipboardEntry => "Rank: " + Ranking + Environment.NewLine + "Value: " + Value + Environment.NewLine + "Key (numeric): " + string.Join(" ", KeyArray) + Environment.NewLine + "Key (alphabetic): " + KeyPhrase + Environment.NewLine + "Text: " + Text; } }
32.734066
159
0.436451
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/IDPAttack/IDPAnalyser.cs
29,791
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System.Numerics; using SixLabors.ImageSharp.PixelFormats; using Xunit; // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Tests.PixelFormats { [Trait("Category", "PixelFormats")] public class L8Tests { public static readonly TheoryData<byte> LuminanceData = new TheoryData<byte> { 0, 1, 2, 3, 5, 13, 31, 71, 73, 79, 83, 109, 127, 128, 131, 199, 250, 251, 254, 255 }; [Theory] [InlineData(0)] [InlineData(255)] [InlineData(10)] [InlineData(42)] public void L8_PackedValue_EqualsInput(byte input) => Assert.Equal(input, new L8(input).PackedValue); [Fact] public void AreEqual() { var color1 = new L8(100); var color2 = new L8(100); Assert.Equal(color1, color2); } [Fact] public void AreNotEqual() { var color1 = new L8(100); var color2 = new L8(200); Assert.NotEqual(color1, color2); } [Fact] public void L8_FromScaledVector4() { // Arrange L8 gray = default; const byte expected = 128; Vector4 scaled = new L8(expected).ToScaledVector4(); // Act gray.FromScaledVector4(scaled); byte actual = gray.PackedValue; // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(LuminanceData))] public void L8_ToScaledVector4(byte input) { // Arrange var gray = new L8(input); // Act Vector4 actual = gray.ToScaledVector4(); // Assert float scaledInput = input / 255F; Assert.Equal(scaledInput, actual.X); Assert.Equal(scaledInput, actual.Y); Assert.Equal(scaledInput, actual.Z); Assert.Equal(1, actual.W); } [Theory] [MemberData(nameof(LuminanceData))] public void L8_FromVector4(byte luminance) { // Arrange L8 gray = default; var vector = new L8(luminance).ToVector4(); // Act gray.FromVector4(vector); byte actual = gray.PackedValue; // Assert Assert.Equal(luminance, actual); } [Theory] [MemberData(nameof(LuminanceData))] public void L8_ToVector4(byte input) { // Arrange var gray = new L8(input); // Act var actual = gray.ToVector4(); // Assert float scaledInput = input / 255F; Assert.Equal(scaledInput, actual.X); Assert.Equal(scaledInput, actual.Y); Assert.Equal(scaledInput, actual.Z); Assert.Equal(1, actual.W); } [Theory] [MemberData(nameof(LuminanceData))] public void L8_FromRgba32(byte rgb) { // Arrange L8 gray = default; byte expected = ColorNumerics.Get8BitBT709Luminance(rgb, rgb, rgb); // Act gray.FromRgba32(new Rgba32(rgb, rgb, rgb)); byte actual = gray.PackedValue; // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(LuminanceData))] public void L8_ToRgba32(byte luminance) { // Arrange var gray = new L8(luminance); // Act Rgba32 actual = default; gray.ToRgba32(ref actual); // Assert Assert.Equal(luminance, actual.R); Assert.Equal(luminance, actual.G); Assert.Equal(luminance, actual.B); Assert.Equal(byte.MaxValue, actual.A); } [Fact] public void L8_FromBgra5551() { // arrange var grey = default(L8); byte expected = byte.MaxValue; // act grey.FromBgra5551(new Bgra5551(1.0f, 1.0f, 1.0f, 1.0f)); // assert Assert.Equal(expected, grey.PackedValue); } public class Rgba32Compatibility { // ReSharper disable once MemberHidesStaticFromOuterClass public static readonly TheoryData<byte> LuminanceData = L8Tests.LuminanceData; [Theory] [MemberData(nameof(LuminanceData))] public void L8_FromRgba32_IsInverseOf_ToRgba32(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); L8 mirror = default; mirror.FromRgba32(rgba); Assert.Equal(original, mirror); } [Theory] [MemberData(nameof(LuminanceData))] public void Rgba32_ToL8_IsInverseOf_L8_ToRgba32(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); L8 mirror = default; mirror.FromRgba32(rgba); Assert.Equal(original, mirror); } [Theory] [MemberData(nameof(LuminanceData))] public void ToVector4_IsRgba32Compatible(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); var l8Vector = original.ToVector4(); var rgbaVector = original.ToVector4(); Assert.Equal(l8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] [MemberData(nameof(LuminanceData))] public void FromVector4_IsRgba32Compatible(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); var rgbaVector = original.ToVector4(); L8 mirror = default; mirror.FromVector4(rgbaVector); Assert.Equal(original, mirror); } [Theory] [MemberData(nameof(LuminanceData))] public void ToScaledVector4_IsRgba32Compatible(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); Vector4 l8Vector = original.ToScaledVector4(); Vector4 rgbaVector = original.ToScaledVector4(); Assert.Equal(l8Vector, rgbaVector, new ApproximateFloatComparer(1e-5f)); } [Theory] [MemberData(nameof(LuminanceData))] public void FromScaledVector4_IsRgba32Compatible(byte luminance) { var original = new L8(luminance); Rgba32 rgba = default; original.ToRgba32(ref rgba); Vector4 rgbaVector = original.ToScaledVector4(); L8 mirror = default; mirror.FromScaledVector4(rgbaVector); Assert.Equal(original, mirror); } } } }
27.427562
90
0.501546
[ "Apache-2.0" ]
CKoewing/ImageSharp
tests/ImageSharp.Tests/PixelFormats/L8Tests.cs
7,762
C#
using Xunit; namespace Unit.Tests.Encryption.PasswordValidator { public class ConvertSecureStringToStringTests { [Theory] [InlineData("Test32g342gh34")] [InlineData("LogTest321")] [InlineData("!fwe235423GE")] public void Ensure_we_build_a_secure_string(string item) { var ss = PwMLib.PasswordValidator.ConvertSecureStringToString(GetSecureString(item)); Assert.Equal(item, ss); } private static System.Security.SecureString GetSecureString(string item) { var ss = new System.Security.SecureString(); foreach (char c in item) { ss.AppendChar(c); } return ss; } } }
26.703704
97
0.621359
[ "MIT" ]
0x78654C/PwM
Unit.Tests/Encryption/PasswordValidator/ConvertSecureStringToStringTests.cs
723
C#
using System.Web.Mvc; using KnockoutMvcDemo.Models; namespace KnockoutMvcDemo.Controllers { public class UserScriptController : BaseController { public ActionResult Index() { InitializeViewBag("User script"); var model = new UserScriptModel { Message = "Knockout" }; return View(model); } public ActionResult AddLetter(UserScriptModel model) { model.AddLetter(); return Json(model); } } }
20.545455
63
0.674779
[ "MIT" ]
NigelWhatling/knockout-mvc
KnockoutMvcDemo/Controllers/UserScriptController.cs
454
C#
using _3.WildFarm.Models.Foods.Entities; using System; using System.Collections.Generic; namespace _3.WildFarm.Models.Animals.Entities { public class Owl : Bird { public Owl(string name, double weight, double wingSize) : base(name, weight, wingSize) { } public override string AskForFood() { return "Hoot hoot"; } protected override List<Type> PreferredFoodTypes => new List<Type> { typeof(Meat) }; // typeof работи с класа GetType() с инстанцията protected override double WeightMultiplier => 0.25; } }
25.416667
141
0.632787
[ "MIT" ]
BorisLechev/CSharp-Advanced
C# OOP/5. Polymorphism/Exercise/3.WildFarm/Models/Animals/Entities/Owl.cs
636
C#
using MediaWikiApi.Requests; using MediaWikiApi.Wiki.Handler.Abstractions; using MediaWikiApi.Wiki.Handler.Exceptions; using MediaWikiApi.Wiki.Response.Query; using MediaWikiApi.Wiki.Response.Query.Extracts; namespace MediaWikiApi.Wiki.Handler { public class ExtractResponseHandler<T> : QueryHandler<T, T, ExtractContinueParams> where T : IExtractPage, IPage, new() { public ExtractResponseHandler(string wikiUrl) : base(wikiUrl) { } public override RequestHandler GetQueryRequestHandler(string wikiBaseUrl) { return base .GetQueryRequestHandler(wikiBaseUrl) .AddArgument("prop", "extracts"); } protected override T ComputeContinuedBehavior(T newData, T existingData) { existingData.Extract += newData.Extract; return existingData; } protected override T GetRequestedFromResponse(T parsedResponse) { if (parsedResponse.Missing) throw new PageNotFoundException(parsedResponse.Title); return parsedResponse; } protected override bool IsContinue(IQuery<ExtractContinueParams> parsedResponse, RequestHandler parametrizedRequestHandler, out RequestHandler continueRequestHandler) { if (parsedResponse.Continue == null) { continueRequestHandler = null; return false; } // Since the arguments are of type single they are overwritten continueRequestHandler = parametrizedRequestHandler .AddArgument("continue", parsedResponse.Continue.Continue) .AddArgument("excontinue", parsedResponse.Continue.ExContinue); return !(parsedResponse.BatchComplete); } } }
41.857143
176
0.683732
[ "MIT" ]
Adrian-Akro/MediaWikiAPI
MediaWikiApi/Wiki/Handler/ExtractResponseHandler.cs
1,760
C#
using System.IO; using WhateverDevs.Core.Runtime.Persistence; namespace WhateverDevs.Core.Runtime.Configuration { /// <summary> /// Json file persister that adds a prefix for storing the configuration on the local folder. /// </summary> public class ConfigurationJsonFilePersisterOnLocalFolder : JsonFilePersister { /// <summary> /// Path to the configuration that is automatically added to the destination. /// </summary> protected virtual string ConfigurationPath => "Configuration/"; /// <summary> /// Saves data to the given destination in a Json file. /// </summary> /// <param name="data">Data to save.</param> /// <param name="destination">File path for the json.</param> /// <param name="suppressErrors">Don't log errors, this is useful for systems that can still work /// without the resource existing, like the configuration manager.</param> /// <typeparam name="TOriginal">Type of the original data.</typeparam> /// <returns>True if it was successful.</returns> public override bool Save<TOriginal>(TOriginal data, string destination, bool suppressErrors = false) { CheckFolderAndCreate(); return base.Save(data, ConfigurationPath + destination, suppressErrors); } /// <summary> /// Loads the data from the given json file path. /// </summary> /// <param name="data">Object that will store the data.</param> /// <param name="origin">File path of the json file.</param> /// <param name="suppressErrors">Don't log errors, this is useful for systems that can still work /// without the resource existing, like the configuration manager.</param> /// <typeparam name="TOriginal">Type of the original data.</typeparam> /// <returns>True if it was successful.</returns> public override bool Load<TOriginal>(out TOriginal data, string origin, bool suppressErrors = false) { try { bool success = base.Load(out data, ConfigurationPath + origin, suppressErrors); return success; } catch { data = default; return false; } } /// <summary> /// Checks if the configuration folder exists and creates it if it doesn't. /// </summary> private void CheckFolderAndCreate() { if (!Directory.Exists(ConfigurationPath)) Directory.CreateDirectory(ConfigurationPath); } } }
42.435484
109
0.613075
[ "MIT" ]
WhateverDevs/Core
Runtime/Configuration/ConfigurationJsonFilePersisterOnLocalFolder.cs
2,631
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Data.Common { public static class DbMetaDataCollectionNames { public static readonly string MetaDataCollections = "MetaDataCollections"; public static readonly string DataSourceInformation = "DataSourceInformation"; public static readonly string DataTypes = "DataTypes"; public static readonly string Restrictions = "Restrictions"; public static readonly string ReservedWords = "ReservedWords"; } }
42
86
0.745536
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataCollectionNames.cs
672
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !NETSTANDARD1_5 using System; using System.Runtime.Serialization; #endif using MongoDB.Driver.Core.Connections; namespace MongoDB.Driver { /// <summary> /// Represents a MongoDB duplicate key exception. /// </summary> #if !NETSTANDARD1_5 [Serializable] #endif public class MongoDuplicateKeyException : MongoWriteConcernException { /// <summary> /// Initializes a new instance of the <see cref="MongoDuplicateKeyException" /> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> /// <param name="commandResult">The command result.</param> public MongoDuplicateKeyException(ConnectionId connectionId, string message, WriteConcernResult commandResult) : base(connectionId, message, commandResult) { } #if !NETSTANDARD1_5 /// <summary> /// Initializes a new instance of the <see cref="MongoDuplicateKeyException"/> class. /// </summary> /// <param name="info">The SerializationInfo.</param> /// <param name="context">The StreamingContext.</param> public MongoDuplicateKeyException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
34.482143
118
0.687209
[ "Apache-2.0" ]
JohnFedorchak/mongo-csharp-driver
src/MongoDB.Driver.Core/MongoDuplicateKeyException.cs
1,931
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("AsmDiff.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AsmDiff.NET")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7235dbd6-152c-49ef-a261-d9688ecfab0f")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
37.702703
84
0.743369
[ "MIT" ]
KLIM8D/AsmDiff.NET
AsmDiff.NET/Properties/AssemblyInfo.cs
1,398
C#
using Encog.ML.EA.Train; using Encog.Neural.NEAT; using Encog.Neural.Networks.Training; using MyProject01.Controller.Jobs; using MyProject01.Factorys.PopulationFactorys; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyProject01.Controller { class NewTrainer : Trainer { private int _inVecLen; private int _outVecLen; private TrainerContex _context; public BasicPopulationFactory PopulationFacotry; public ICalculateScore ScoreCtrl; public NewTrainer(int inVectorLength, int outVectorLength) { _inVecLen = inVectorLength; _outVecLen = outVectorLength; } protected override void PostItration() { _context.Epoch = Epoch; _context.CurrentDate = DateTime.Now; CheckCtrl.Do(_context); } protected override TrainEA CreateTrainEA() { _context = new TrainerContex(); _context.Trainer = this; TrainEA train = NEATUtil.ConstructNEATTrainer( PopulationFacotry.Get(_inVecLen, _outVecLen), ScoreCtrl); _context.trainEA = train; return train; } } }
27.291667
66
0.633588
[ "BSD-3-Clause" ]
a7866353/encog-dotnet-core_work01
MyProject/MyProject01/Controller/NewTrainer.cs
1,312
C#
using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FactorySpace.Models { [Index(nameof(EngineerId), nameof(MachineId), IsUnique = true)] public class MachineEngineer { public int MachineEngineerId { get; set; } public int EngineerId { get; set; } public int MachineId { get; set; } public virtual Engineer Engineer { get; set; } public virtual Machine Machine { get; set; } } }
30.647059
65
0.708253
[ "Unlicense" ]
yesthecarlos/Factory
Factory/Models/MachineEngineer.cs
521
C#
namespace PaninApi.Abstractions.Enums { public enum OrderStatus { Creating, Payed, Accepted, Ready, Rejected, Expired // Not in the database (only at runtime when we receive a request) } }
20.666667
82
0.58871
[ "MIT" ]
fablabromagna-org/PaninAPI
src/PaninApi.Abstractions/Enums/OrderStatus.cs
248
C#
/*The MIT License (MIT) Copyright (c) 2013 Philipp Schröck <philsch@hotmail.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ using System; namespace PluginSystem { public enum StreamStatus { Created, Loaded, Closed, Playing, Paused, Stopped } public class Vector3 { public float x,y,z; public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public Vector3(float xyz) { x = xyz; y = xyz; z = xyz; } } public interface ISoundStream { StreamStatus Status { get; } bool IsSupport(string path); bool Create(ISoundSystem AudioSystem); void Destroy(); void Set3DMinMaxDistance(float min, float max); bool Set3DSettings(Vector3 pos, Vector3 vel); int GetPosition(); bool SetPosition(uint pos); int GetLenght(); bool SetChannelMix(float fleft, float fright, float rleft, float rright, float sleft, float sright, float center, float bass); void SetVolume(float vol); bool LoadStream(string FileName, bool b3D = false); bool LoadStream(System.IO.Stream stream, bool b3D = false); bool CloseStream(); bool PlayStream(Vector3 Position, float minDistance = 1.0f, float maxDistance = 100.0f); bool PauseStream(); bool StopStream(); IntPtr GetTag(string key); } }
32.944444
110
0.705312
[ "MIT" ]
RoseLeBlood/rap
SoundOut/SoundInterface/ISoundStream.cs
2,375
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; using System.Collections.Generic; using System.Linq; namespace Microsoft.AspNetCore.Routing.Patterns { internal static class RouteParameterParser { // This code parses the inside of the route parameter // // Ex: {hello} - this method is responsible for parsing 'hello' // The factoring between this class and RoutePatternParser is due to legacy. public static RoutePatternParameterPart ParseRouteParameter(string parameter) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } if (parameter.Length == 0) { return new RoutePatternParameterPart(string.Empty, null, RoutePatternParameterKind.Standard, Array.Empty<RoutePatternParameterPolicyReference>()); } var startIndex = 0; var endIndex = parameter.Length - 1; var encodeSlashes = true; var parameterKind = RoutePatternParameterKind.Standard; if (parameter.StartsWith("**", StringComparison.Ordinal)) { encodeSlashes = false; parameterKind = RoutePatternParameterKind.CatchAll; startIndex += 2; } else if (parameter[0] == '*') { parameterKind = RoutePatternParameterKind.CatchAll; startIndex++; } if (parameter[endIndex] == '?') { parameterKind = RoutePatternParameterKind.Optional; endIndex--; } var currentIndex = startIndex; // Parse parameter name var parameterName = string.Empty; while (currentIndex <= endIndex) { var currentChar = parameter[currentIndex]; if ((currentChar == ':' || currentChar == '=') && startIndex != currentIndex) { // Parameter names are allowed to start with delimiters used to denote constraints or default values. // i.e. "=foo" or ":bar" would be treated as parameter names rather than default value or constraint // specifications. parameterName = parameter.Substring(startIndex, currentIndex - startIndex); // Roll the index back and move to the constraint parsing stage. currentIndex--; break; } else if (currentIndex == endIndex) { parameterName = parameter.Substring(startIndex, currentIndex - startIndex + 1); } currentIndex++; } var parseResults = ParseConstraints(parameter, parameterName, currentIndex, endIndex); currentIndex = parseResults.CurrentIndex; string defaultValue = null; if (currentIndex <= endIndex && parameter[currentIndex] == '=') { defaultValue = parameter.Substring(currentIndex + 1, endIndex - currentIndex); } return new RoutePatternParameterPart( parameterName, defaultValue, parameterKind, parseResults.ParameterPolicies.ToArray(), encodeSlashes); } private static ParameterPolicyParseResults ParseConstraints( string text, string parameterName, int currentIndex, int endIndex) { var constraints = new List<RoutePatternParameterPolicyReference>(); var state = ParseState.Start; var startIndex = currentIndex; do { var currentChar = currentIndex > endIndex ? null : (char?)text[currentIndex]; switch (state) { case ParseState.Start: switch (currentChar) { case null: state = ParseState.End; break; case ':': state = ParseState.ParsingName; startIndex = currentIndex + 1; break; case '(': state = ParseState.InsideParenthesis; break; case '=': state = ParseState.End; currentIndex--; break; } break; case ParseState.InsideParenthesis: switch (currentChar) { case null: state = ParseState.End; var constraintText = text.Substring(startIndex, currentIndex - startIndex); constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); break; case ')': // Only consume a ')' token if // (a) it is the last token // (b) the next character is the start of the new constraint ':' // (c) the next character is the start of the default value. var nextChar = currentIndex + 1 > endIndex ? null : (char?)text[currentIndex + 1]; switch (nextChar) { case null: state = ParseState.End; constraintText = text.Substring(startIndex, currentIndex - startIndex + 1); constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); break; case ':': state = ParseState.Start; constraintText = text.Substring(startIndex, currentIndex - startIndex + 1); constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); startIndex = currentIndex + 1; break; case '=': state = ParseState.End; constraintText = text.Substring(startIndex, currentIndex - startIndex + 1); constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); break; } break; case ':': case '=': // In the original implementation, the Regex would've backtracked if it encountered an // unbalanced opening bracket followed by (not necessarily immediatiely) a delimiter. // Simply verifying that the parantheses will eventually be closed should suffice to // determine if the terminator needs to be consumed as part of the current constraint // specification. var indexOfClosingParantheses = text.IndexOf(')', currentIndex + 1); if (indexOfClosingParantheses == -1) { constraintText = text.Substring(startIndex, currentIndex - startIndex); constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); if (currentChar == ':') { state = ParseState.ParsingName; startIndex = currentIndex + 1; } else { state = ParseState.End; currentIndex--; } } else { currentIndex = indexOfClosingParantheses; } break; } break; case ParseState.ParsingName: switch (currentChar) { case null: state = ParseState.End; var constraintText = text.Substring(startIndex, currentIndex - startIndex); if (constraintText.Length > 0) { constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); } break; case ':': constraintText = text.Substring(startIndex, currentIndex - startIndex); if (constraintText.Length > 0) { constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); } startIndex = currentIndex + 1; break; case '(': state = ParseState.InsideParenthesis; break; case '=': state = ParseState.End; constraintText = text.Substring(startIndex, currentIndex - startIndex); if (constraintText.Length > 0) { constraints.Add(RoutePatternFactory.ParameterPolicy(constraintText)); } currentIndex--; break; } break; } currentIndex++; } while (state != ParseState.End); return new ParameterPolicyParseResults(currentIndex, constraints); } private enum ParseState { Start, ParsingName, InsideParenthesis, End } private readonly struct ParameterPolicyParseResults { public readonly int CurrentIndex; public readonly IReadOnlyList<RoutePatternParameterPolicyReference> ParameterPolicies; public ParameterPolicyParseResults(int currentIndex, IReadOnlyList<RoutePatternParameterPolicyReference> parameterPolicies) { CurrentIndex = currentIndex; ParameterPolicies = parameterPolicies; } } } }
45.038314
162
0.436835
[ "Apache-2.0" ]
akrisiun/AspNetCore
src/Http/Routing/src/Patterns/RouteParameterParser.cs
11,755
C#
namespace Checkout.ApiServices.Tokens.ResponseModels { public class CardTokenCreate { public string Id { get; set; } public string LiveMode { get; set; } public string Created { get; set; } public string Used { get; set; } public Cards.ResponseModels.Card Card { get; set; } } }
27.666667
59
0.620482
[ "MIT" ]
CKOTech/checkout-net-library
Checkout.ApiClient.NetStandard/ApiServices/Tokens/ResponseModels/CardTokenCreate.cs
334
C#
using Domain; using HeatingApi.Attributes; using HeatingControl.Application.Commands; using HeatingControl.Application.Queries; using HeatingControl.Models; using Microsoft.AspNetCore.Mvc; namespace HeatingApi.Controllers { /// <summary> /// Controller for dashboard. /// </summary> [Route("/api/dashboard")] public class DashboardController : BaseController { private readonly IHeatingControl _heatingControl; private readonly IDashboardSnapshotProvider _dashboardSnapshotProvider; private readonly IZoneDetailsProvider _zoneDetailsProvider; private readonly ICommandHandler _commandHandler; public DashboardController(IHeatingControl heatingControl, IDashboardSnapshotProvider dashboardSnapshotProvider, IZoneDetailsProvider zoneDetailsProvider, ICommandHandler commandHandler) { _heatingControl = heatingControl; _dashboardSnapshotProvider = dashboardSnapshotProvider; _zoneDetailsProvider = zoneDetailsProvider; _commandHandler = commandHandler; } /// <summary> /// Snapshot of current controller state. Should be periodically pulled by main view. /// </summary> /// <returns>Building state and notifications</returns> [HttpGet] [RequiredPermission(Permission.Dashboard)] public DashboardSnapshotProviderOutput GetSnapshot() { return _dashboardSnapshotProvider.Provide(_heatingControl.State.Model, _heatingControl.State); } /// <summary> /// Returns data about timers, setpoints and schedule. To be used by zone details. /// </summary> [HttpGet("zone/{zoneId}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public ZoneDetailsProviderResult GetDetails(int zoneId) { return _zoneDetailsProvider.Provide(zoneId, _heatingControl.State, _heatingControl.State.Model); } /// <summary> /// Switches zone control mode(0 - off/lo, 1 - on/high, 2 - schedule). To be used by zone tile on dashboard. /// </summary> [HttpPost("zone/{zoneId}/setMode/{controlMode}")] [RequiredPermission(Permission.Dashboard)] public IActionResult SetControlMode(int zoneId, ZoneControlMode controlMode) { var command = new SetZoneControlModeCommand { ZoneId = zoneId, ControlMode = controlMode }; return _commandHandler.ExecuteCommand(command, UserId); } /// <summary> /// Clears zone counters. To be used by zone counters view. /// </summary> [HttpDelete("zone/{zoneId}/resetCounters")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult ResetCounters(int zoneId) { var command = new ResetCounterCommand { ZoneId = zoneId, UserId = UserId }; return _commandHandler.ExecuteCommand(command, UserId); } /// <summary> /// Allows to set zone low setpoint. To be used by zone temperature setpoints view. /// </summary> [HttpPost("zone/{zoneId}/setLowSetPoint/{value}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult SetLowSetPoint(int zoneId, float value) { return SetSetPoint(zoneId, value, SetPointType.Low); } /// <summary> /// Allows to set zone high setpoint. To be used by zone temperature setpoints view. /// </summary> [HttpPost("zone/{zoneId}/setHighSetPoint/{value}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult SetHighSetPoint(int zoneId, float value) { return SetSetPoint(zoneId, value, SetPointType.High); } /// <summary> /// Allows to set zone schedule default setpoint. To be used by zone temperature setpoints view. /// </summary> [HttpPost("zone/{zoneId}/setScheduleSetPoint/{value}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult SetScheduleSetPoint(int zoneId, float value) { return SetSetPoint(zoneId, value, SetPointType.Schedule); } /// <summary> /// Allows to set zone hysteresis. To be used by zone temperature setpoints view. /// </summary> [HttpPost("zone/{zoneId}/setHysteresisSetPoint/{value}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult SetHysteresisSetPoint(int zoneId, float value) { return SetSetPoint(zoneId, value, SetPointType.Hysteresis); } /// <summary> /// Adds new schedule item to zone. To be used by zone schedule editor. /// </summary> [HttpPost("zone/schedule")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult NewScheduleItem([FromBody] NewScheduleItemCommand command) { return _commandHandler.ExecuteCommand(command, UserId); } [HttpDelete("zone/{zoneId}/schedule/{scheduleItemId}")] [RequiredPermission(Permission.Dashboard_ZoneSettings)] public IActionResult RemoveScheduleItem(int zoneId, int scheduleItemId) { var command = new RemoveScheduleItemCommand { ZoneId = zoneId, ScheduleItemId = scheduleItemId }; return _commandHandler.ExecuteCommand(command, UserId); } private IActionResult SetSetPoint(int zoneId, float value, SetPointType setPointType) { var command = new SetTemperatureCommand { SetPointType = setPointType, ZoneId = zoneId, Value = value }; return _commandHandler.ExecuteCommand(command, UserId); } } }
39.73913
116
0.604408
[ "MIT" ]
flarestudiopl/shiny-system-rpi
HeatingApi/Controllers/DashboardController.cs
6,400
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.Tailscale { /// <summary> /// The device_tags resource is used to apply tags to Tailscale devices. See https://tailscale.com/kb/1068/acl-tags/ for more details. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Tailscale = Pulumi.Tailscale; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var sampleDevice = Output.Create(Tailscale.GetDevice.InvokeAsync(new Tailscale.GetDeviceArgs /// { /// Name = "device.example.com", /// })); /// var sampleTags = new Tailscale.DeviceTags("sampleTags", new Tailscale.DeviceTagsArgs /// { /// DeviceId = sampleDevice.Apply(sampleDevice =&gt; sampleDevice.Id), /// Tags = /// { /// "room:bedroom", /// }, /// }); /// } /// /// } /// ``` /// </summary> [TailscaleResourceType("tailscale:index/deviceTags:DeviceTags")] public partial class DeviceTags : Pulumi.CustomResource { /// <summary> /// The device to set tags for /// </summary> [Output("deviceId")] public Output<string> DeviceId { get; private set; } = null!; /// <summary> /// The tags to apply to the device /// </summary> [Output("tags")] public Output<ImmutableArray<string>> Tags { get; private set; } = null!; /// <summary> /// Create a DeviceTags resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public DeviceTags(string name, DeviceTagsArgs args, CustomResourceOptions? options = null) : base("tailscale:index/deviceTags:DeviceTags", name, args ?? new DeviceTagsArgs(), MakeResourceOptions(options, "")) { } private DeviceTags(string name, Input<string> id, DeviceTagsState? state = null, CustomResourceOptions? options = null) : base("tailscale:index/deviceTags:DeviceTags", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing DeviceTags resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static DeviceTags Get(string name, Input<string> id, DeviceTagsState? state = null, CustomResourceOptions? options = null) { return new DeviceTags(name, id, state, options); } } public sealed class DeviceTagsArgs : Pulumi.ResourceArgs { /// <summary> /// The device to set tags for /// </summary> [Input("deviceId", required: true)] public Input<string> DeviceId { get; set; } = null!; [Input("tags", required: true)] private InputList<string>? _tags; /// <summary> /// The tags to apply to the device /// </summary> public InputList<string> Tags { get => _tags ?? (_tags = new InputList<string>()); set => _tags = value; } public DeviceTagsArgs() { } } public sealed class DeviceTagsState : Pulumi.ResourceArgs { /// <summary> /// The device to set tags for /// </summary> [Input("deviceId")] public Input<string>? DeviceId { get; set; } [Input("tags")] private InputList<string>? _tags; /// <summary> /// The tags to apply to the device /// </summary> public InputList<string> Tags { get => _tags ?? (_tags = new InputList<string>()); set => _tags = value; } public DeviceTagsState() { } } }
35.119205
138
0.567226
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-tailscale
sdk/dotnet/DeviceTags.cs
5,303
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Xunit; namespace System.Formats.Tar.Tests { public abstract partial class TarTestsBase : FileCleanupTestBase { protected void SetPosixProperties(PosixTarEntry entry) { Assert.Equal(DefaultGName, entry.GroupName); entry.GroupName = TestGName; Assert.Equal(DefaultUName, entry.UserName); entry.UserName = TestUName; } private void SetBlockDeviceProperties(PosixTarEntry device) { Assert.NotNull(device); Assert.Equal(TarEntryType.BlockDevice, device.EntryType); SetCommonProperties(device); SetPosixProperties(device); // DeviceMajor Assert.Equal(DefaultDeviceMajor, device.DeviceMajor); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMajor = -1); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMajor = 2097152); device.DeviceMajor = TestBlockDeviceMajor; // DeviceMinor Assert.Equal(DefaultDeviceMinor, device.DeviceMinor); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMinor = -1); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMinor = 2097152); device.DeviceMinor = TestBlockDeviceMinor; } private void SetCharacterDeviceProperties(PosixTarEntry device) { Assert.NotNull(device); Assert.Equal(TarEntryType.CharacterDevice, device.EntryType); SetCommonProperties(device); SetPosixProperties(device); // DeviceMajor Assert.Equal(DefaultDeviceMajor, device.DeviceMajor); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMajor = -1); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMajor = 2097152); device.DeviceMajor = TestCharacterDeviceMajor; // DeviceMinor Assert.Equal(DefaultDeviceMinor, device.DeviceMinor); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMinor = -1); Assert.Throws<ArgumentOutOfRangeException>(() => device.DeviceMinor = 2097152); device.DeviceMinor = TestCharacterDeviceMinor; } private void SetFifoProperties(PosixTarEntry fifo) { Assert.NotNull(fifo); Assert.Equal(TarEntryType.Fifo, fifo.EntryType); SetCommonProperties(fifo); SetPosixProperties(fifo); } protected void VerifyPosixProperties(PosixTarEntry entry) { entry.GroupName = TestGName; Assert.Equal(TestGName, entry.GroupName); entry.UserName = TestUName; Assert.Equal(TestUName, entry.UserName); } protected void VerifyPosixRegularFile(PosixTarEntry regularFile, bool isWritable) { VerifyCommonRegularFile(regularFile, isWritable); VerifyUnsupportedDeviceProperties(regularFile); } protected void VerifyPosixDirectory(PosixTarEntry directory) { VerifyCommonDirectory(directory); VerifyUnsupportedDeviceProperties(directory); } protected void VerifyPosixHardLink(PosixTarEntry hardLink) { VerifyCommonHardLink(hardLink); VerifyUnsupportedDeviceProperties(hardLink); } protected void VerifyPosixSymbolicLink(PosixTarEntry symbolicLink) { VerifyCommonSymbolicLink(symbolicLink); VerifyUnsupportedDeviceProperties(symbolicLink); } protected void VerifyPosixCharacterDevice(PosixTarEntry device) { Assert.NotNull(device); Assert.Equal(TarEntryType.CharacterDevice, device.EntryType); VerifyCommonProperties(device); VerifyUnsupportedLinkProperty(device); VerifyUnsupportedDataStream(device); Assert.Equal(TestCharacterDeviceMajor, device.DeviceMajor); Assert.Equal(TestCharacterDeviceMinor, device.DeviceMinor); } protected void VerifyPosixBlockDevice(PosixTarEntry device) { Assert.NotNull(device); Assert.Equal(TarEntryType.BlockDevice, device.EntryType); VerifyCommonProperties(device); VerifyUnsupportedLinkProperty(device); VerifyUnsupportedDataStream(device); Assert.Equal(TestBlockDeviceMajor, device.DeviceMajor); Assert.Equal(TestBlockDeviceMinor, device.DeviceMinor); } protected void VerifyPosixFifo(PosixTarEntry fifo) { Assert.NotNull(fifo); Assert.Equal(TarEntryType.Fifo, fifo.EntryType); VerifyCommonProperties(fifo); VerifyPosixProperties(fifo); VerifyUnsupportedDeviceProperties(fifo); VerifyUnsupportedLinkProperty(fifo); VerifyUnsupportedDataStream(fifo); } protected void VerifyUnsupportedDeviceProperties(PosixTarEntry entry) { Assert.True(entry.EntryType is not TarEntryType.CharacterDevice and not TarEntryType.BlockDevice); Assert.Equal(0, entry.DeviceMajor); Assert.Throws<InvalidOperationException>(() => entry.DeviceMajor = 5); Assert.Equal(0, entry.DeviceMajor); // No change Assert.Equal(0, entry.DeviceMinor); Assert.Throws<InvalidOperationException>(() => entry.DeviceMinor = 5); Assert.Equal(0, entry.DeviceMinor); // No change } } }
38.731544
110
0.648414
[ "MIT" ]
Ali-YousefiTelori/runtime
src/libraries/System.Formats.Tar/tests/TarTestsBase.Posix.cs
5,773
C#
namespace Dracoon.Sdk.Model { /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/PasswordCharacterSetType/*'/> public enum PasswordCharacterSetType { /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/None/*'/> None, /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/Uppercase/*'/> Uppercase, /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/Lowercase/*'/> Lowercase, /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/Numeric/*'/> Numeric, /// <include file = "ModelDoc.xml" path='docs/members[@name="passwordCharacterSetType"]/Special/*'/> Special } }
55.6
121
0.652278
[ "Apache-2.0" ]
DAVISOL-GmbH/dracoon-csharp-sdk
DracoonSdk/SdkPublic/Model/PasswordCharacterSetType.cs
836
C#
using System.Collections.Generic; namespace EShopOnAbp.BasketService; public class BasketDto { public float TotalPrice { get; set; } public List<BasketItemDto> Items { get; set; } public BasketDto() { Items = new List<BasketItemDto>(); } }
19.285714
50
0.674074
[ "MIT" ]
abpframework/eShopOnAbp
services/basket/src/EShopOnAbp.BasketService.Application.Contracts/BasketDto.cs
270
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.ComIntegration.IPersistStream.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.ComIntegration { internal partial interface IPersistStream : IPersist { #region Methods and constructors void GetClassID(out Guid pClassID); void GetSizeMax(out long pcbSize); int IsDirty(); void Load(System.Runtime.InteropServices.ComTypes.IStream pStm); void Save(System.Runtime.InteropServices.ComTypes.IStream pStm, bool fClearDirty); #endregion } }
43.196429
463
0.77594
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.ServiceModel/Sources/System.ServiceModel.ComIntegration.IPersistStream.cs
2,419
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.EKS; using Amazon.EKS.Model; namespace Amazon.PowerShell.Cmdlets.EKS { /// <summary> /// Connects a Kubernetes cluster to the Amazon EKS control plane. /// /// /// <para> /// Any Kubernetes cluster can be connected to the Amazon EKS control plane to view current /// information about the cluster and its nodes. /// </para><para> /// Cluster connection requires two steps. First, send a <code><a>RegisterClusterRequest</a></code> to add it to the Amazon EKS control plane. /// </para><para> /// Second, a <a href="https://amazon-eks.s3.us-west-2.amazonaws.com/eks-connector/manifests/eks-connector/latest/eks-connector.yaml">Manifest</a> /// containing the <code>activationID</code> and <code>activationCode</code> must be applied /// to the Kubernetes cluster through it's native provider to provide visibility. /// </para><para> /// After the Manifest is updated and applied, then the connected cluster is visible to /// the Amazon EKS control plane. If the Manifest is not applied within a set amount of /// time, then the connected cluster will no longer be visible and must be deregistered. /// See <a>DeregisterCluster</a>. /// </para> /// </summary> [Cmdlet("Register", "EKSCluster", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.EKS.Model.Cluster")] [AWSCmdlet("Calls the Amazon Elastic Container Service for Kubernetes RegisterCluster API operation.", Operation = new[] {"RegisterCluster"}, SelectReturnType = typeof(Amazon.EKS.Model.RegisterClusterResponse))] [AWSCmdletOutput("Amazon.EKS.Model.Cluster or Amazon.EKS.Model.RegisterClusterResponse", "This cmdlet returns an Amazon.EKS.Model.Cluster object.", "The service call response (type Amazon.EKS.Model.RegisterClusterResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RegisterEKSClusterCmdlet : AmazonEKSClientCmdlet, IExecutor { #region Parameter ClientRequestToken /// <summary> /// <para> /// <para>Unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientRequestToken { get; set; } #endregion #region Parameter Name /// <summary> /// <para> /// <para>Define a unique name for this cluster within your AWS account.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String Name { get; set; } #endregion #region Parameter ConnectorConfig_Provider /// <summary> /// <para> /// <para>The cloud provider for the target cluster to connect.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [AWSConstantClassSource("Amazon.EKS.ConnectorConfigProvider")] public Amazon.EKS.ConnectorConfigProvider ConnectorConfig_Provider { get; set; } #endregion #region Parameter ConnectorConfig_RoleArn /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of the role that is authorized to request the connector /// configuration.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String ConnectorConfig_RoleArn { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Cluster'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.EKS.Model.RegisterClusterResponse). /// Specifying the name of a property of type Amazon.EKS.Model.RegisterClusterResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "Cluster"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the Name parameter. /// The -PassThru parameter is deprecated, use -Select '^Name' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Name' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.Name), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Register-EKSCluster (RegisterCluster)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.EKS.Model.RegisterClusterResponse, RegisterEKSClusterCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.Name; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.ClientRequestToken = this.ClientRequestToken; context.ConnectorConfig_Provider = this.ConnectorConfig_Provider; #if MODULAR if (this.ConnectorConfig_Provider == null && ParameterWasBound(nameof(this.ConnectorConfig_Provider))) { WriteWarning("You are passing $null as a value for parameter ConnectorConfig_Provider which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ConnectorConfig_RoleArn = this.ConnectorConfig_RoleArn; #if MODULAR if (this.ConnectorConfig_RoleArn == null && ParameterWasBound(nameof(this.ConnectorConfig_RoleArn))) { WriteWarning("You are passing $null as a value for parameter ConnectorConfig_RoleArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.Name = this.Name; #if MODULAR if (this.Name == null && ParameterWasBound(nameof(this.Name))) { WriteWarning("You are passing $null as a value for parameter Name which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.EKS.Model.RegisterClusterRequest(); if (cmdletContext.ClientRequestToken != null) { request.ClientRequestToken = cmdletContext.ClientRequestToken; } // populate ConnectorConfig var requestConnectorConfigIsNull = true; request.ConnectorConfig = new Amazon.EKS.Model.ConnectorConfigRequest(); Amazon.EKS.ConnectorConfigProvider requestConnectorConfig_connectorConfig_Provider = null; if (cmdletContext.ConnectorConfig_Provider != null) { requestConnectorConfig_connectorConfig_Provider = cmdletContext.ConnectorConfig_Provider; } if (requestConnectorConfig_connectorConfig_Provider != null) { request.ConnectorConfig.Provider = requestConnectorConfig_connectorConfig_Provider; requestConnectorConfigIsNull = false; } System.String requestConnectorConfig_connectorConfig_RoleArn = null; if (cmdletContext.ConnectorConfig_RoleArn != null) { requestConnectorConfig_connectorConfig_RoleArn = cmdletContext.ConnectorConfig_RoleArn; } if (requestConnectorConfig_connectorConfig_RoleArn != null) { request.ConnectorConfig.RoleArn = requestConnectorConfig_connectorConfig_RoleArn; requestConnectorConfigIsNull = false; } // determine if request.ConnectorConfig should be set to null if (requestConnectorConfigIsNull) { request.ConnectorConfig = null; } if (cmdletContext.Name != null) { request.Name = cmdletContext.Name; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.EKS.Model.RegisterClusterResponse CallAWSServiceOperation(IAmazonEKS client, Amazon.EKS.Model.RegisterClusterRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Container Service for Kubernetes", "RegisterCluster"); try { #if DESKTOP return client.RegisterCluster(request); #elif CORECLR return client.RegisterClusterAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String ClientRequestToken { get; set; } public Amazon.EKS.ConnectorConfigProvider ConnectorConfig_Provider { get; set; } public System.String ConnectorConfig_RoleArn { get; set; } public System.String Name { get; set; } public System.Func<Amazon.EKS.Model.RegisterClusterResponse, RegisterEKSClusterCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Cluster; } } }
47.533333
295
0.6261
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/EKS/Basic/Register-EKSCluster-Cmdlet.cs
15,686
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace Core.FrontEnd.Areas.HelpPage.ModelDescriptions { public class ParameterDescription { public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); } public Collection<ParameterAnnotation> Annotations { get; private set; } public string Documentation { get; set; } public string Name { get; set; } public ModelDescription TypeDescription { get; set; } } }
25.904762
80
0.676471
[ "MIT" ]
badpaybad/opendotnet-ecommerce-platform
Core.FrontEnd/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
544
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading; using System.Threading.Tasks; namespace ResilientCommand.Tests { [TestClass] public class SemaphoreTests { [TestMethod] [ExpectedException(typeof(SemaphoreRejectedException))] public async Task Semaphore_WithFullPool_RejectsExecution() { var cmdKey = new CommandKey(Guid.NewGuid().ToString()); var semaphore = new Semaphore(cmdKey, new TestNotifier(), new SemaphoreSettings(maxParalellism: 1)); semaphore.ExecuteAsync(async (ct) => { await Task.Delay(1000); return 2; }, default); await semaphore.ExecuteAsync(async (ct) => 2, default); } [TestMethod] [ExpectedException(typeof(OperationCanceledException))] public async Task Semaphore_WithCancelledToken_Cancels() { var cmdKey = new CommandKey(Guid.NewGuid().ToString()); var semaphore = new Semaphore(cmdKey, new TestNotifier(), SemaphoreSettings.DefaultSemaphoreSettings); var cts = new CancellationTokenSource(); cts.Cancel(); await semaphore.ExecuteAsync<int>(async (token) => 2, cts.Token); } } }
35.25
114
0.651694
[ "Unlicense" ]
VisualBean/ResilientCommand
ResilientCommand.Tests/SemaphoreTests.cs
1,271
C#
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 using System.Linq; using System.Net; using System.Threading.Tasks; using Gigya.Common.Contracts.HttpService; using Newtonsoft.Json; namespace Gigya.Microdot.Hosting.HttpService.Endpoints { public class SchemaEndpoint : ICustomEndpoint { private readonly string _jsonSchema; public SchemaEndpoint(IServiceInterfaceMapper mapper) { _jsonSchema = JsonConvert.SerializeObject(new ServiceSchema(mapper.ServiceInterfaceTypes.ToArray()), Formatting.Indented); } public async Task<bool> TryHandle(HttpListenerContext context, WriteResponseDelegate writeResponse) { if (context.Request.Url.AbsolutePath.EndsWith("/schema")) { await writeResponse(_jsonSchema).ConfigureAwait(false); return true; } return false; } } }
36.833333
134
0.71644
[ "Apache-2.0" ]
amccool/microdot
Gigya.Microdot.Hosting/HttpService/Endpoints/SchemaEndpoint.cs
1,991
C#
using System; using System.Runtime.InteropServices; namespace Steamworks { public sealed class Callback<T> { public Callback(global::Steamworks.Callback<T>.DispatchDelegate func, bool bGameServer = false) { this.m_bGameServer = bGameServer; this.BuildCCallbackBase(); this.Register(func); } private event global::Steamworks.Callback<T>.DispatchDelegate m_Func; public static global::Steamworks.Callback<T> Create(global::Steamworks.Callback<T>.DispatchDelegate func) { return new global::Steamworks.Callback<T>(func, false); } public static global::Steamworks.Callback<T> CreateGameServer(global::Steamworks.Callback<T>.DispatchDelegate func) { return new global::Steamworks.Callback<T>(func, true); } ~Callback() { this.Unregister(); if (this.m_pVTable != global::System.IntPtr.Zero) { global::System.Runtime.InteropServices.Marshal.FreeHGlobal(this.m_pVTable); } if (this.m_pCCallbackBase.IsAllocated) { this.m_pCCallbackBase.Free(); } } public void Register(global::Steamworks.Callback<T>.DispatchDelegate func) { if (func == null) { throw new global::System.Exception("Callback function must not be null."); } if ((this.m_CCallbackBase.m_nCallbackFlags & 1) == 1) { this.Unregister(); } if (this.m_bGameServer) { this.SetGameserverFlag(); } this.m_Func = func; global::Steamworks.NativeMethods.SteamAPI_RegisterCallback(this.m_pCCallbackBase.AddrOfPinnedObject(), global::Steamworks.CallbackIdentities.GetCallbackIdentity(typeof(T))); } public void Unregister() { global::Steamworks.NativeMethods.SteamAPI_UnregisterCallback(this.m_pCCallbackBase.AddrOfPinnedObject()); } public void SetGameserverFlag() { global::Steamworks.CCallbackBase ccallbackBase = this.m_CCallbackBase; ccallbackBase.m_nCallbackFlags |= 2; } private void OnRunCallback(global::System.IntPtr thisptr, global::System.IntPtr pvParam) { try { this.m_Func((T)((object)global::System.Runtime.InteropServices.Marshal.PtrToStructure(pvParam, typeof(T)))); } catch (global::System.Exception e) { global::Steamworks.CallbackDispatcher.ExceptionHandler(e); } } private void OnRunCallResult(global::System.IntPtr thisptr, global::System.IntPtr pvParam, bool bFailed, ulong hSteamAPICall) { try { this.m_Func((T)((object)global::System.Runtime.InteropServices.Marshal.PtrToStructure(pvParam, typeof(T)))); } catch (global::System.Exception e) { global::Steamworks.CallbackDispatcher.ExceptionHandler(e); } } private int OnGetCallbackSizeBytes(global::System.IntPtr thisptr) { return this.m_size; } private void BuildCCallbackBase() { this.VTable = new global::Steamworks.CCallbackBaseVTable { m_RunCallResult = new global::Steamworks.CCallbackBaseVTable.RunCRDel(this.OnRunCallResult), m_RunCallback = new global::Steamworks.CCallbackBaseVTable.RunCBDel(this.OnRunCallback), m_GetCallbackSizeBytes = new global::Steamworks.CCallbackBaseVTable.GetCallbackSizeBytesDel(this.OnGetCallbackSizeBytes) }; this.m_pVTable = global::System.Runtime.InteropServices.Marshal.AllocHGlobal(global::System.Runtime.InteropServices.Marshal.SizeOf(typeof(global::Steamworks.CCallbackBaseVTable))); global::System.Runtime.InteropServices.Marshal.StructureToPtr(this.VTable, this.m_pVTable, false); this.m_CCallbackBase = new global::Steamworks.CCallbackBase { m_vfptr = this.m_pVTable, m_nCallbackFlags = 0, m_iCallback = global::Steamworks.CallbackIdentities.GetCallbackIdentity(typeof(T)) }; this.m_pCCallbackBase = global::System.Runtime.InteropServices.GCHandle.Alloc(this.m_CCallbackBase, global::System.Runtime.InteropServices.GCHandleType.Pinned); } private global::Steamworks.CCallbackBaseVTable VTable; private global::System.IntPtr m_pVTable = global::System.IntPtr.Zero; private global::Steamworks.CCallbackBase m_CCallbackBase; private global::System.Runtime.InteropServices.GCHandle m_pCCallbackBase; private bool m_bGameServer; private readonly int m_size = global::System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); public delegate void DispatchDelegate(T param); } }
32.159091
183
0.751708
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/Steamworks/Callback.cs
4,247
C#
using System; using System.Collections.Generic; using System.Linq; using GraphQL.Types; namespace GraphQL.EntityFramework { public partial interface IEfGraphQLService { FieldType AddQueryField<TReturn>( ObjectGraphType graph, string name, Func<ResolveFieldContext<object>, IQueryable<TReturn>> resolve, Type graphType = null, IEnumerable<QueryArgument> arguments = null) where TReturn : class; FieldType AddQueryField<TSource, TReturn>( ObjectGraphType<TSource> graph, string name, Func<ResolveFieldContext<TSource>, IQueryable<TReturn>> resolve, Type graphType = null, IEnumerable<QueryArgument> arguments = null) where TReturn : class; FieldType AddQueryField<TSource, TReturn>( ObjectGraphType graph, string name, Func<ResolveFieldContext<TSource>, IQueryable<TReturn>> resolve, Type graphType = null, IEnumerable<QueryArgument> arguments = null) where TReturn : class; } }
33.294118
76
0.630742
[ "MIT" ]
timvandesteeg/GraphQL.EntityFramework
src/GraphQL.EntityFramework/IEfGraphQLService_Queryable.cs
1,134
C#
using System.Threading.Tasks; namespace ArtworkSourceSpecification { public static class ArtworkCacheExtensions { public static async Task<string> WhoamiAsync(this IArtworkSource source) { var user = await source.GetUserAsync(); return user.Name; } public static async Task<string> GetUserIconAsync(this IArtworkSource source) { var user = await source.GetUserAsync(); return user.IconUrl; } } }
26.3125
81
0.75772
[ "MIT" ]
libertyernie/ArtSync
CrosspostSharp3/ArtworkSourceSpecification/Extensions.cs
423
C#
using System.Runtime.Serialization; using Service.BitGo.SignTransaction.Domain.Models; namespace Service.BitGo.SignTransaction.Grpc.Models { [DataContract] public class UpdatePendingApprovalRequest { [DataMember(Order = 1)] public string BrokerId { get; set; } [DataMember(Order = 2)] public string UserId { get; set; } [DataMember(Order = 3)] public string Otp { get; set; } [DataMember(Order = 4)] public string PendingApprovalId { get; set; } [DataMember(Order = 5)] public PendingApprovalUpdatedState State { get; set; } [DataMember(Order = 6)] public string UpdatedBy { get; set; } [DataMember(Order = 7)] public string CoinId { get; set; } } }
42.529412
86
0.670816
[ "MIT" ]
MyJetWallet/Service.BitGo.SignTransaction
src/Service.BitGo.SignTransaction.Grpc/Models/UpdatePendingApprovalRequest.cs
725
C#
using System; using Windows.Data.Xml.Dom; using System.Linq; using System.Threading; using System.Collections.Generic; using SmartHive.CloudConnection.Events; using Windows.ApplicationModel.Core; using System.Globalization; using System.Net.Http; namespace SmartHive.CloudConnection { public sealed class HttpConnection { #pragma warning disable CS0067 // The event 'HttpConnection.OnNotification' is never used public event EventHandler<OnNotificationEventArgs> OnNotification; #pragma warning restore CS0067 // The event 'HttpConnection.OnNotification' is never used public event EventHandler<string> OnServiceBusConnected; public event EventHandler<OnScheduleUpdateEventArgs> OnScheduleUpdate; public event EventHandler<OnEvenLogWriteEventArgs> OnEventLog; Mutex ReaderMutex = new Mutex(false); TimeSpan MutexWaitTime = TimeSpan.FromMinutes(1); private HttpClientHelper HttpHelper = null; private string UrlAddress = null; public HttpConnection(string ServiceUrl) { this.UrlAddress = ServiceUrl; } public async void InitSubscription() { try { HttpHelper = new HttpClientHelper(this); var dispatcher = DispatcherHelper.GetDispatcher;; await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (OnServiceBusConnected != null) { OnServiceBusConnected.Invoke(this.UrlAddress, this.UrlAddress); this.LogEvent(EventTypeConsts.Info, "Binding done", "Web service handler listining for messages."); } else { this.LogEvent(EventTypeConsts.Error, "Error", "WebService handler not set"); } }); } catch (Exception ex) { this.LogEvent(EventTypeConsts.Error, "Webservice request error", ex.Message + " " + ex.StackTrace); }finally { // Log view mode to collect data for Kiosks this.LogEvent(EventTypeConsts.Info, "View mode", String.Format("View IsMain: {0}, view count: {1} ", CoreApplication.GetCurrentView().IsMain, CoreApplication.Views.Count)); } } private static Appointment[] FilterAppointments(Appointment[] Schedule, string Location, int eventsExpiration) { if (Schedule == null || Schedule.Length == 0 || string.IsNullOrWhiteSpace(Location)) { return new Appointment[0]; } else { //return all engagements where matched location and not finished yet or finished not leater then eventsExpiration minutes DateTime expirationTime = DateTime.Now.AddMinutes(eventsExpiration * -1); //return all engagements and not finished yet or finished not leater then eventsExpiration minutes Appointment[] retVal = Schedule.Where<Appointment>(a => !string.IsNullOrEmpty(a.Location) && a.Location.Contains(Location) && expirationTime.CompareTo(DateTime.ParseExact(a.EndTime, OnScheduleUpdateEventArgs.DateTimeFormat, CultureInfo.InvariantCulture)) <= 0).ToArray<Appointment>(); return retVal; } } public async void ReadMessageAsync(string Location, int eventsExpiration) { if (string.IsNullOrEmpty(Location)) { this.LogEvent(EventTypeConsts.Error, "Invalid argument Locaton", " value is null or empty"); return; } ReaderMutex.WaitOne(MutexWaitTime); // Wait one minute for mutex try { string[] Locations = Location.Split(';'); string sXml = await HttpHelper.GetStringResponse(this.UrlAddress); if (!string.IsNullOrEmpty(sXml)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(sXml); XmlNodeList eventsNodes = doc.SelectNodes("Appointments/Appointment"); List<Appointment> Appointments = new List<Appointment>(); foreach (string tmpLocation in Locations) { Appointment[] roomAppointments = ReadEventForLocation(eventsNodes, tmpLocation, eventsExpiration); if (roomAppointments != null) { Appointments.AddRange(roomAppointments); } } OnScheduleUpdateEventArgs eventData = new OnScheduleUpdateEventArgs() { RoomId = Location }; if (Appointments.Count > 0) eventData.Schedule = Appointments.Distinct<Appointment>(new AppointmentComparer()).ToArray(); else eventData.Schedule = new Appointment[0]; var dispatcher = DispatcherHelper.GetDispatcher; //CoreApplication.GetCurrentView().Dispatcher; await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (OnScheduleUpdate != null) OnScheduleUpdate.Invoke("", eventData); }); } else { this.LogEvent(EventTypeConsts.Error, "Empty response from WebService", this.UrlAddress); } } catch (Exception ex) { this.LogEvent(EventTypeConsts.Error, "Webservice read message error", ex.Message + " " + ex.StackTrace); }finally { ReaderMutex.ReleaseMutex(); } } private static Appointment[] ReadEventForLocation(XmlNodeList eventsNodes, string Location, int eventsExpiration) { var result = from IXmlNode eventNode in eventsNodes select (new Appointment() { StartTime = eventNode.SelectSingleNode("StartTime").InnerText, EndTime = eventNode.SelectSingleNode("EndTime").InnerText, Title = eventNode.SelectSingleNode("Title").InnerText, Location = eventNode.SelectSingleNode("Location").InnerText, //appointment.Location, Category = eventNode.SelectSingleNode("Category").InnerText }); if (result.Count<Appointment>() > 0) { return FilterAppointments(result.ToArray<Appointment>(), Location, eventsExpiration); } return null; } internal async void LogEvent(EventTypeConsts eventType, string Message, string Description) { string EventTypeName = Enum.GetName(typeof(EventTypeConsts), eventType); if (OnEventLog != null) { var dispatcher = DispatcherHelper.GetDispatcher; await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { OnEventLog.Invoke(EventTypeName, new OnEvenLogWriteEventArgs() { EventType = EventTypeName, Message = Message, Description = Description }); }); } else { MessageHelper.ShowToastMessage(Message, Description); } } } }
42.474227
188
0.533131
[ "Apache-2.0" ]
Microsoft/SmartHive
SmartHive.ScheduleBoard/SmartHive.CloudConnection/HttpConnection.cs
8,242
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("03. Point in Rectangle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Point in Rectangle")] [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("99d8ee3a-1d80-4d8c-aeac-d9f3ddbd2d15")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.297297
84
0.743119
[ "MIT" ]
Filirien/Programing-Basics-August-2017
Complex Conditional Statements/03. Point in Rectangle/Properties/AssemblyInfo.cs
1,420
C#
using System; using System.ComponentModel.Composition; namespace NuPattern.Runtime.Bindings { /// <summary> /// Provides a dynamic binding context to provide additional exports /// for binding evaluation. /// </summary> public interface IDynamicBindingContext : IDisposable { /// <summary> /// Gets the composition service backing the context. /// </summary> ICompositionService CompositionService { get; } /// <summary> /// Adds the given instance with the contract specified. /// </summary> /// <typeparam name="T">The type of the contract to export the instance with.</typeparam> /// <param name="instance">The exported value.</param> void AddExport<T>(T instance) where T : class; /// <summary> /// Adds the given instance with the contract type and name specified. /// </summary> /// <typeparam name="T">The type of the contract to export the instance with.</typeparam> /// <param name="instance">The exported value.</param> /// <param name="contractName">Name of the contract.</param> void AddExport<T>(T instance, string contractName) where T : class; } }
35.857143
97
0.61992
[ "Apache-2.0" ]
dbremner/nupattern
Src/Runtime/Source/Runtime.Extensibility/Bindings/IDynamicBindingContext.cs
1,255
C#
using System; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Mage { internal class NewOrUpdateMageTool : MageTool<BaseNewAndUpdateMageSettings> { /// <summary> /// Runs a new or update Mage.exe command /// </summary> /// <param name="settings">The settings.</param> public void NewOrUpdate(BaseNewAndUpdateMageSettings settings) => Run(settings, GetNewOrUpdateArguments(settings)); private ProcessArgumentBuilder GetNewOrUpdateArguments(BaseNewAndUpdateMageSettings settings) { if (string.IsNullOrWhiteSpace(settings.Password) == false && settings.CertFile == null) throw new ArgumentException("Password requires CertFile to be set", nameof(settings.CertFile)); var builder = new ProcessArgumentBuilder(); var newOrUpdateApplicationSettings = settings as BaseNewAndUpdateApplicationSettings; if (newOrUpdateApplicationSettings != null) { if (newOrUpdateApplicationSettings is NewApplicationSettings) { builder = builder.Append("-new Application"); } else { var updatePath = ((UpdateApplicationSettings)newOrUpdateApplicationSettings).FileToUpdate.MakeAbsolute(Environment).FullPath; builder = builder.AppendSwitchQuoted("-update", updatePath); } builder = builder.AppendNonNullDirectoryPathSwitch("-fd", newOrUpdateApplicationSettings.FromDirectory, Environment) .AppendNonNullRelativeFilePathSwitch("-if", newOrUpdateApplicationSettings.IconFile, Environment) .AppendIfNotDefaultSwitch("-tr", newOrUpdateApplicationSettings.TrustLevel, TrustLevel.Default) .AppendIfNotDefaultSwitch("-um", newOrUpdateApplicationSettings.UseManifestForTrust, false); } else { var newOrUpdateDeploymentSettings = (BaseNewAndUpdateDeploymentSettings)settings; if (newOrUpdateDeploymentSettings.AppCodeBaseUri != null && newOrUpdateDeploymentSettings.AppCodeBaseFilePath != null) throw new ArgumentException("Both AppCodeBaseUri and AppCodeBaseFilePath cannot be specified."); if (newOrUpdateDeploymentSettings is NewDeploymentSettings) { builder = builder.Append("-new Deployment"); } else { var updatePath = ((UpdateDeploymentSettings)newOrUpdateDeploymentSettings).FileToUpdate.MakeAbsolute(Environment).FullPath; builder = builder.AppendSwitchQuoted("-update", updatePath); } builder = builder .AppendNonNullUriSwitch("-appc", newOrUpdateDeploymentSettings.AppCodeBaseUri) .AppendNonNullRelativeFilePathSwitch("-appc", newOrUpdateDeploymentSettings.AppCodeBaseFilePath, Environment) .AppendNonNullRelativeFilePathSwitch("-appm", newOrUpdateDeploymentSettings.AppManifest, Environment) .AppendIfNotDefaultSwitch("-i", newOrUpdateDeploymentSettings.Install, false) .AppendNonEmptySwitch("-mv", newOrUpdateDeploymentSettings.MinVersion) .AppendIfNotDefaultSwitch("-ip", newOrUpdateDeploymentSettings.IncludeProviderUrl, true) .AppendNonNullUriSwitch("-pu", newOrUpdateDeploymentSettings.ProviderUrl); } return builder .AppendIfNotDefaultSwitch("-a", settings.Algorithm, Algorithm.SHA1RSA) .AppendNonNullFilePathSwitch("-cf", settings.CertFile, Environment) .AppendNonEmptySwitch("-certHash", settings.CertHash) .AppendNonEmptyQuotedSwitch("-n", settings.Name) .AppendNonEmptySecretSwitch("-pwd", settings.Password) .AppendIfNotDefaultSwitch("-p", settings.Processor, Processor.Msil) .AppendNonEmptyQuotedSwitch("-pub", settings.Publisher) .AppendNonNullUriSwitch("-s", settings.SupportUrl) .AppendNonNullUriSwitch("-ti", settings.TimeStampUri) .AppendNonNullFilePathSwitch("-t", settings.ToFile, Environment) .AppendNonEmptySwitch("-v", settings.Version) .AppendIfNotDefaultSwitch("-w", settings.WpfBrowserApp, false); } internal NewOrUpdateMageTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, IRegistry registry, ICakeLog log, DotNetToolResolver dotNetToolResolver) : base(fileSystem, environment, processRunner, tools, registry, log, dotNetToolResolver) { } } }
55.52809
302
0.650344
[ "MIT" ]
cake-contrib/Cake.Mage
src/Cake.Mage/NewOrUpdateMageTool.cs
4,944
C#
using BattleTech; using BattleTech.Data; using BattleTech.Framework; using Harmony; using HBS.Collections; using System; using System.Collections.Generic; namespace RepeatableFlashpoints { [HarmonyPatch(typeof(SimGameState), "CompleteFlashpoint")] public static class SimGameState_CompleteFlashpoint_Patch { private static void Postfix(SimGameState __instance, Flashpoint fp, FlashpointEndType howItEnded) { try { if (howItEnded == FlashpointEndType.Completed && fp.Def.Repeatable) { __instance.completedFlashpoints.Remove(fp.Def.Description.Id); } } catch (Exception e) { Logger.LogError(e); } } } [HarmonyPatch(typeof(SimGameState), "GenerateFlashpoint")] public static class SimGameState_GenerateFlashpoint_Patch { private static void Prefix(SimGameState __instance, ref bool useInitial, ref List<FlashpointDef> ___flashpointPool) { try { useInitial = false; if (Helper.Settings.randomPlanet || Helper.Settings.debugAllRepeat) { foreach (FlashpointDef fp in ___flashpointPool) { if (Helper.Settings.randomPlanet) { foreach (string tag in fp.LocationRequirements.RequirementTags) { if (tag.Contains("planet_name")) { fp.LocationRequirements.RequirementTags.Remove(tag); } } } if (Helper.Settings.debugAllRepeat) { fp.Repeatable = true; } } } } catch (Exception e) { Logger.LogError(e); } } } [HarmonyPatch(typeof(SimGameState), "ApplyEventAction")] public static class SimGameState_ApplyEventAction_Patch { private static void Prefix(SimGameState __instance, ref SimGameResultAction action) { try { if (action.Type == SimGameResultAction.ActionType.Flashpoint_AddContract || action.Type == SimGameResultAction.ActionType.Flashpoint_StartContract) { Logger.LogLine("FP name = " + action.additionalValues[2]); SimGameState simulation = UnityGameInstance.BattleTechGame.Simulation; if (action.additionalValues[3].Equals("{RANDOM}")) { Array values = Enum.GetValues(typeof(Faction)); Random random = new Random(); Faction randomFaction; do { randomFaction = (Faction)values.GetValue(random.Next(values.Length)); } while (Helper.IsExcluded(randomFaction)); action.additionalValues[3] = randomFaction.ToString(); } else if (action.additionalValues[3].Equals("{PLANETOWNER}")) { action.additionalValues[3] = simulation.ActiveFlashpoint.CurSystem.Owner.ToString(); } if (action.additionalValues[4].Equals("{RANDOM}")) { Array values = Enum.GetValues(typeof(Faction)); Random random = new Random(); Faction randomFaction; do { randomFaction = (Faction)values.GetValue(random.Next(values.Length)); } while (Helper.IsExcluded(randomFaction)); action.additionalValues[4] = randomFaction.ToString(); } else if (action.additionalValues[4].Equals("{PLANETOWNER}")) { action.additionalValues[4] = simulation.ActiveFlashpoint.CurSystem.Owner.ToString(); } if (string.IsNullOrEmpty(action.value)) { ContractOverride contractOverride = simulation.DataManager.ContractOverrides.Get(action.additionalValues[2]).Copy(); ContractType contractType = contractOverride.contractType; List<MapAndEncounters> releasedMapsAndEncountersByContractTypeAndOwnership = MetadataDatabase.Instance.GetReleasedMapsAndEncountersByContractTypeAndOwnership(new ContractType[] { contractType }); releasedMapsAndEncountersByContractTypeAndOwnership.Shuffle(); MapAndEncounters mapAndEncounters = releasedMapsAndEncountersByContractTypeAndOwnership[0]; action.value = mapAndEncounters.Map.MapName; } } } catch (Exception e) { Logger.LogError(e); } } } }
49.188119
218
0.551731
[ "MIT" ]
Morphyum/RepeatableFlashpoints
RepeatableFlashpoints/RepeatableFlashpoints/Patch.cs
4,970
C#
namespace TestSolution.TestAssembly { public class Class1 { public string Property1 { get; } public class Class2 { public string Property2 { get; } public class Class3 { public string Property3 { get; } } } } }
19.294118
48
0.47561
[ "Apache-2.0" ]
veton/dotScript
test/test-cases/.NotSupported/Nested/TestAssembly/Class1.cs
328
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace MARIA { public partial class MARIAWebRequestCollection { private Dictionary<string, MARIAWebRequest> AvailableWebRequests { get; set; } public MARIAWebRequestCollection() { this.AvailableWebRequests = new Dictionary<string, MARIAWebRequest>(); } public StatusObject AddWebRequest(string NewWebRequestName, MARIAWebRequest NewWebRequest) { StatusObject SO = new StatusObject(); try { this.AvailableWebRequests.Add(NewWebRequestName, NewWebRequest); } catch(Exception e) { SO = new StatusObject(e, "WEBREQUESTMANAGER_ADDWEBREQUEST"); } return SO; } /// <summary> /// This function will execute all the web requests in the order they were inserted /// </summary> /// <returns></returns> public StatusObject ExecuteSequential(int Iterations) { StatusObject SO = new StatusObject(); try { for(int i = 0; i < Iterations; i++) { foreach (KeyValuePair<string, MARIAWebRequest> AvailableWebRequest in this.AvailableWebRequests) { Console.WriteLine("{0} {1}", AvailableWebRequest.Key, i); AvailableWebRequest.Value.Execute(); } } } catch(Exception e) { SO = new StatusObject(e, "WEBREQUESTCOLLECTION_EXECUTESEQUENTIAL"); } return SO; } /// <summary> /// This function will execute all the webrequests listed in the web request collection in parallel /// </summary> /// <param name="Iterations"></param> /// <returns></returns> public StatusObject ExecuteParallel(int Iterations) { StatusObject SO = new StatusObject(); try { ServicePointManager.DefaultConnectionLimit = Iterations; List<int> IterationList = new List<int>(); for (int i = 0; i < Iterations; i++) { IterationList.Add(i); } Parallel.ForEach(IterationList, (Iteration) => { foreach (KeyValuePair<string, MARIAWebRequest> AvailableWebRequest in this.AvailableWebRequests) { Console.WriteLine("{0} {1}", AvailableWebRequest.Key, Iteration); AvailableWebRequest.Value.Execute(); } }); } catch(Exception e) { SO = new StatusObject(e, "WEBREQUESTCOLLECTION_EXECUTEPARALLEL"); } return SO; } } }
35.717647
116
0.527009
[ "MIT" ]
kirbyprojects/MARIA
MARIA/MARIAWebRequestCollection.cs
3,038
C#
using DiscordMusicBot.LoungeBot; using Newtonsoft.Json; using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace DiscordMusicBot { internal class Program { public static #if FALLBACK MusicBot #else LoungeBot.LoungeBot #endif Bot; private static CancellationTokenSource _cts; private static void Main(string[] args) { ConsoleHelper.Set(); Console.Title = "Music Bot (Loading...)"; Console.WriteLine("(Press Ctrl + C or close this Window to exit Bot)"); try { #region JSON.NET Config cfg; //Create the config.json on first run if (!File.Exists("config.json")) { FileStream newConfig = File.Create("config.json"); cfg = new Config(); JsonSerializer serializer = new JsonSerializer(); using (StreamWriter sw = new StreamWriter(newConfig)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, cfg); } } else { string json = File.ReadAllText("config.json"); cfg = JsonConvert.DeserializeObject<Config>(json); } //if (cfg == new Config()) // throw new Exception("Please insert values into Config.json!"); #endregion #region TXT Reading //string[] config = File.ReadAllLines("config.txt"); //Config cfg = new Config() { // BotName = config[0].Split(':')[1], // ChannelName = config[1].Split(':')[1], // ClientId = config[2].Split(':')[1], // ClientSecret = config[3].Split(':')[1], // ServerName = config[4].Split(':')[1], // Token = config[5].Split(':')[1], //}; #endregion } catch (Exception e) { MusicBot.Print("Your config.json has incorrect formatting, or is not readable!", ConsoleColor.Red); MusicBot.Print(e.Message, ConsoleColor.Red); try { //Open up for editing Process.Start("config.json"); } catch { // file not found, process not started, etc. } Console.ReadKey(); return; } Do().GetAwaiter().GetResult(); //Thread Block //Thread.Sleep(-1); } private static async Task Do() { try { _cts = new CancellationTokenSource(); Bot = new #if FALLBACK MusicBot #else LoungeBot.LoungeBot #endif (); //Async Thread Block await Task.Delay(-1, _cts.Token); } catch (TaskCanceledException) { // Task Canceled } } } }
32.693878
115
0.470974
[ "MIT" ]
Pegasust/DiscordLoungeBot
DiscordMusicBot/Program.cs
3,206
C#
using System; using System.Collections.Generic; using System.Text; namespace DataAggregator { public interface IAggregator { int AggregateData(Options opts); } }
15.333333
40
0.711957
[ "MIT" ]
ecrin-github/DataAggregator
TopLevelClasses/Interfaces/IAggregator.cs
186
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("AWSSDK.MigrationHub")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Migration Hub. AWS Migration Hub provides a single location to track migrations across multiple AWS and partner solutions. Using Migration Hub allows you to choose the AWS and partner migration tools that best fit your needs, while providing visibility into the status of your entire migration portfolio. Migration Hub also provides key metrics and progress for individual applications, regardless of which tools are being used to migrate them. For example, you might use AWS Database Migration Service, AWS Server Migration Service, and partner migration tools to migrate an application comprised of a database, virtualized web servers, and a bare metal server. Using Migration Hub will provide you with a single screen that shows the migration progress of all the resources in the application. This allows you to quickly get progress updates across all of your migrations, easily identify and troubleshoot any issues, and reduce the overall time and effort spent on your migration projects. Migration Hub is available to all AWS customers at no additional charge. You only pay for the cost of the migration tools you use, and any resources being consumed on AWS. ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.100.20")]
78.96875
1,249
0.781163
[ "Apache-2.0" ]
k0lpak/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/MigrationHub/Properties/AssemblyInfo.cs
2,527
C#
using ZPLForge.Common; using ZPLForge.Configuration; namespace ZPLForge.Builders { public sealed class RectangleBuilder : ElementBuilderBase<RectangleElement, RectangleBuilder> { internal RectangleBuilder() { } public RectangleBuilder SetDimensions(int width, int height) { Context.Width = width; Context.Height = height; return this; } public RectangleBuilder SetBorder(LabelColor color, int thickness, int cornerRounding) { Context.BorderColor = color; Context.BorderThickness = thickness; Context.CornerRounding = cornerRounding; return this; } public RectangleBuilder SetBorder(LabelColor color, int thickness) => SetBorder(color, thickness, ZPLForgeDefaults.Elements.Rectangle.CornerRounding); public RectangleBuilder SetBorder(int thickness) => SetBorder(ZPLForgeDefaults.Elements.Rectangle.BorderColor, thickness); } }
28.189189
97
0.653883
[ "MIT" ]
MQUELHAS/ZPLForge
src/ZPLForge/Builders/RectangleBuilder.cs
1,045
C#
using System; using System.Device.Gpio; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Iot.Device.Multiplexing.Utility; namespace Iot.Device.Multiplexing { /// <summary> /// Provides support for Charlieplex multiplexing. /// https://wikipedia.org/wiki/Charlieplexing /// </summary> public class CharlieplexSegment : IOutputSegment, IDisposable { private readonly bool _shouldDispose; private readonly int[] _pins; private readonly CharlieplexSegmentNode[] _nodes; private readonly int _nodeCount; private readonly VirtualOutputSegment _segment; private GpioController _gpioController; private CharlieplexSegmentNode _lastNode; /// <summary> /// Initializes a new Charlieplex type that can be use for multiplex over a relatively small number of GPIO pins. /// </summary> /// <param name="pins">The set of pins to use.</param> /// <param name="nodeCount">The count of nodes (like LEDs) that will be addressable. If 0, then the Charlieplex maximum is used for the pins provided (n^2-n).</param> /// <param name="gpioController">The GPIO Controller used for interrupt handling.</param> /// <param name="shouldDispose">True (the default) if the GPIO controller shall be disposed when disposing this instance.</param> public CharlieplexSegment(int[] pins, int nodeCount = 0, GpioController? gpioController = null, bool shouldDispose = true) { if (pins.Length < 2) { throw new ArgumentException(nameof(CharlieplexSegment), "2 or more pins must be provided."); } int charlieCount = (pins.Length * pins.Length) - pins.Length; if (nodeCount > charlieCount) { throw new ArgumentException(nameof(CharlieplexSegment), $"Maximum count is {charlieCount} based on {pins.Length} pins. {nodeCount} was specified as the count."); } if (nodeCount == 0) { nodeCount = charlieCount; } _shouldDispose = shouldDispose || gpioController is null; _gpioController = gpioController ?? new(); // first two pins will be needed as Output. _gpioController.OpenPin(pins[0], PinMode.Output); _gpioController.OpenPin(pins[1], PinMode.Output); // remaining pins should be input type // prevents participating in the circuit until needed for (int i = 2; i < pins.Length; i++) { _gpioController.OpenPin(pins[i], PinMode.Input); } _lastNode = new CharlieplexSegmentNode() { Anode = pins[1], Cathode = pins[0] }; _pins = pins; _nodeCount = nodeCount; _nodes = GetNodes(pins, nodeCount); _segment = new VirtualOutputSegment(_nodeCount); } /// <summary> /// Provides the set of Charlie nodes given the set of pins and the count provided. /// If count = 0, then the Charlieplex maximum is used for the pins provided (n^2-n). /// </summary> /// <param name="pins">The pins to use for the segment.</param> /// <param name="nodeCount">The number of nodes to use. Default is the Charlieplex maximum.</param> public static CharlieplexSegmentNode[] GetNodes(int[] pins, int nodeCount = 0) { int pinCount = pins.Length; if (nodeCount == 0) { nodeCount = (int)Math.Pow(pinCount, 2) - pinCount; } CharlieplexSegmentNode[] nodes = new CharlieplexSegmentNode[nodeCount]; int pin = 0; int pinJump = 1; int resetCount = pinCount - 1; bool firstLeg = false; for (int i = 0; i < nodeCount; i++) { if ((pin > 0 && pin % resetCount == 0) || pin + pinJump > resetCount) { pin = 0; pinJump++; } CharlieplexSegmentNode node = new CharlieplexSegmentNode(); if (!firstLeg) { node.Anode = pins[pin]; node.Cathode = pins[pin + pinJump]; firstLeg = true; } else { node.Anode = pins[pin + pinJump]; node.Cathode = pins[pin]; firstLeg = false; pin++; } nodes[i] = node; } return nodes; } /// <summary> /// The number of nodes (like LEDs) that can be addressed. /// </summary> public int NodeCount => _nodeCount; /// <summary> /// Write a PinValue to a node, to update Charlieplex segment. /// Address scheme is 0-based. Given 8 nodes, addresses would be 0-7. /// Displays nodes in their updated configuration for the specified duration. /// </summary> /// <param name="node">Node to update.</param> /// <param name="value">Value to write.</param> /// <param name="duration">Time to display segment, in milliseconds (default is 0; not displayed).</param> public void Write(int node, PinValue value, TimeSpan duration = default(TimeSpan)) { _nodes[node].Value = value; if (duration == default(TimeSpan)) { return; } using CancellationTokenSource cts = new CancellationTokenSource(duration); Display(cts.Token); } /// <summary> /// Displays nodes in their current configuration for the specified duration. /// </summary> /// <param name="token">CancellationToken used to signal when method should exit.</param> public void Display(CancellationToken token) { /* Cases to consider node.Cathode == _lastNode.Cathode node.Cathode == _lastNode.Anode -- drop low node.Anode == _lastNode.Cathode node.Anode == _lastNode.Anode node.Anode != _lastNode.Cathode | _lastNode.Anode node.Cathode != _lastNode.Cathode | _lastNode.Anode */ while (!token.IsCancellationRequested) { for (int i = 0; i < _nodes.Length; i++) { CharlieplexSegmentNode node = _nodes[i]; // skip updating pinmode when possible if (_lastNode.Anode != node.Anode && _lastNode.Anode != node.Cathode) { _gpioController.SetPinMode(_lastNode.Anode, PinMode.Input); } if (_lastNode.Cathode != node.Anode && _lastNode.Cathode != node.Cathode) { _gpioController.SetPinMode(_lastNode.Cathode, PinMode.Input); } if (node.Cathode != _lastNode.Anode && node.Cathode != _lastNode.Cathode) { _gpioController.SetPinMode(node.Cathode, PinMode.Output); } if (node.Anode != _lastNode.Anode && node.Anode != _lastNode.Cathode) { _gpioController.SetPinMode(node.Anode, PinMode.Output); } _gpioController.Write(node.Anode, node.Value); // It is necessary to sleep for the LED to be seen with full brightness Thread.SpinWait(1); _gpioController.Write(node.Anode, 0); _lastNode.Anode = node.Anode; _lastNode.Cathode = node.Cathode; } } } /// <summary> /// Cleanup. /// Failing to dispose this class, especially when callbacks are active, may lead to undefined behavior. /// </summary> public void Dispose() { // this condition only applies to GPIO devices if (_shouldDispose) { _gpioController?.Dispose(); _gpioController = null!; } } // IOutputSegment Implementation // Only supported when shift register is connected with GPIO /// <summary> /// The length of the segment; the number of GPIO pins it exposes. /// </summary> public int Length => _segment.Length; /// <summary> /// Segment values. /// </summary> PinValue IOutputSegment.this[int index] { get => _segment[index]; set => _segment[index] = value; } /// <summary> /// Writes a PinValue to a virtual segment. /// Does not display output. /// </summary> void IOutputSegment.Write(int index, PinValue value) { _segment[index] = value; } /// <summary> /// Writes discrete underlying bits to a virtual segment. /// Writes each bit, left to right. Least significant bit will written to index 0. /// Does not display output. /// </summary> void IOutputSegment.Write(byte value) { _segment.Write(value); } /// <summary> /// Writes discrete underlying bits to a virtual output. /// Writes each byte, left to right. Least significant bit will written to index 0. /// Does not display output. /// </summary> void IOutputSegment.Write(ReadOnlySpanByte value) { _segment.Write(value); } /// <summary> /// Clears shift register. /// Performs a latch. /// </summary> void IOutputSegment.TurnOffAll() { _segment.TurnOffAll(); } /// <summary> /// Displays current state of segment. /// Segment is displayed at least until token receives a cancellation signal, possibly due to a specified duration expiring. /// </summary> void IOutputSegment.Display(CancellationToken token) { for (int i = 0; i < _segment.Length; i++) { _nodes[i].Value = _segment[i]; } Display(token); } /// <summary> /// Displays current state of segment. /// Segment is displayed at least until token receives a cancellation signal, possibly due to a specified duration expiring. /// </summary> Task IOutputSegment.DisplayAsync(CancellationToken token) { for (int i = 0; i < _segment.Length; i++) { _nodes[i].Value = _segment[i]; } return Task.Run(() => Display(token), token); } } }
37.715232
178
0.5223
[ "MIT" ]
gukoff/nanoFramework.IoT.Device
src/devices_generated/Charlieplex/CharlieplexSegment.cs
11,390
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Ecdn.V20191012.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeIpStatusResponse : AbstractModel { /// <summary> /// 节点列表 /// </summary> [JsonProperty("Ips")] public IpStatus[] Ips{ get; set; } /// <summary> /// 节点总个数 /// </summary> [JsonProperty("TotalCount")] public long? TotalCount{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArrayObj(map, prefix + "Ips.", this.Ips); this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.344828
81
0.624432
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Ecdn/V20191012/Models/DescribeIpStatusResponse.cs
1,836
C#
using Application.Interfaces.Contexts; using Application.Interfaces.Services.Role; using Common.Messages; using Common.ViewModel.Role; using Entity.Tools; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Application.Services.Role.Query { public class RoleQUERYServices : IRoleQUERYServices { private readonly ISiteDbContext _context; public RoleQUERYServices(ISiteDbContext context) { _context = context; } public async Task<bool> IfExist(long ReqID, bool? IsActive, CancellationToken CT) { var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable(); var DbResult = await Query.Where(a => a.ID == ReqID).ToListAsync(CT); if (DbResult != null) return true; return false; } public async Task<bool> IfExist(RoleVM ReqVM, bool? IsActive, CancellationToken CT) { var errors = new List<ValidationResult>(); bool ValidateResult = Validator.TryValidateObject(ReqVM, new ValidationContext(ReqVM), errors, true); if (ValidateResult) { var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable(); var DbResult = await Query.Where(a => a.Name.Equals(ReqVM.Name)).FirstOrDefaultAsync(CT); if (DbResult != null) if (ReqVM.Permision == DbResult.Permision) return true; } return false; } public async Task<RespMsg<RoleVM>> Get(long ReqID, bool? IsActive, CancellationToken CT) { IResponseMessage Response; var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable(); var DbResult = await Query.Where(x => x.ID == ReqID).FirstOrDefaultAsync(CT); if (DbResult != null) //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(DbResult, new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.OK, "نقش مورد نظر پیدا شد.") }); else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.RecordNotFound, "نقش مورد نظر پیدا نشد.") }); return (RespMsg<RoleVM>)Response; } public async Task<RespMsg<RoleVM>> Get(Permision ReqPermision, bool? IsActive, CancellationToken CT) { IResponseMessage Response; var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable(); var DbResult = await Query.Where(x => x.Permision == ReqPermision).FirstOrDefaultAsync(CT); if (DbResult != null) //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(DbResult, new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.OK, "نقش مورد نظر پیدا شد.") }); else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.RecordNotFound, "نقش مورد نظر پیدا نشد.") }); return (RespMsg<RoleVM>)Response; } public async Task<RespMsg<RoleVM>> Get(string ReqRoleName, bool? IsActive, CancellationToken CT) { IResponseMessage Response; var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable(); var DbResult = await Query.Where(x => x.Name == ReqRoleName).FirstOrDefaultAsync(CT); if (DbResult != null) //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(DbResult, new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.OK, "نقش مورد نظر پیدا شد.") }); else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.RecordNotFound, "نقش مورد نظر پیدا نشد.") }); return (RespMsg<RoleVM>)Response; } public async Task<RespMsg_List<RoleVM>> Filter(RoleFilterVM ReqFilter, CancellationToken CT) { IResponseMessage Response; var errors = new List<ValidationResult>(); bool ValidateResult = Validator.TryValidateObject(ReqFilter, new ValidationContext(ReqFilter), errors, true); if (ValidateResult) { var Query = _context.Roles.AsQueryable(); Query = ReqFilter.MakeQuery(Query);//Prepair Query var Result = await Query.ToListAsync(CT);//Get Query Result if (Result != null) //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(Result, new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.OK, "فیلتر انجام شد.") }); else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.RecordNotFound, "جست و جو انجام و نتیجه ای در بر نداشت.") }); } else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.HasModelValidationError, "داده های ارسالی دارای مقدار نامتعارف است.") }); return (RespMsg_List<RoleVM>)Response; } public async Task<RespMsg_List<RoleVM>> GetAll(bool? IsActive, CancellationToken CT) { IResponseMessage Response; var Query = _context.Roles.AsQueryable(); if (IsActive.HasValue) Query = Query.Where(x => x.IsActive.Equals(IsActive)).AsQueryable();//Prepair Query var Result = await Query.ToListAsync(CT);//Get Query Result if (Result != null) //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(Result, new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.OK, "جست و جو انجام شد.") }); else //Make Statuse Mesasage(Erro / Mssage) Response = Role_MakeResponse.MakeResponse(new List<(ServiceStatus ServiceStatus, string Message)> { (ServiceStatus.RecordNotFound, "جست و جو انجام و نتیجه ای در بر نداشت.") }); return (RespMsg_List<RoleVM>)Response; } } }
46.296512
125
0.56863
[ "Unlicense" ]
rezaamooee/SimpleWebSite
Application/Services/Role/Query/RoleQUERYServices.cs
8,179
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.WorkspaceServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { #if MEF [ExportWorkspaceServiceFactory(typeof(IFileTrackingService), WorkspaceKind.Any)] #endif internal class FileTrackingServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(IWorkspaceServiceProvider workspaceServices) { return new FileTrackingService(); } private class FileTrackingService : IFileTrackingService { public IFileTracker CreateFileTracker() { return new FileSetTracker(); } } private class FileSetTracker : IFileTracker { // guards watchers and actions private readonly NonReentrantLock guard = new NonReentrantLock(); private readonly Dictionary<string, FileSystemWatcher> watchers = new Dictionary<string, FileSystemWatcher>(); private readonly Dictionary<string, FileTracker> fileTrackers = new Dictionary<string, FileTracker>(); public FileSetTracker() { } private FileTracker GetFileTracker_NoLock(string path) { guard.AssertHasLock(); FileTracker tracker; if (!this.fileTrackers.TryGetValue(path, out tracker)) { tracker = new FileTracker(this, path); this.fileTrackers.Add(path, tracker); } return tracker; } public bool IsTracking(string path) { if (path == null) { return false; } using (guard.DisposableWait()) { return this.fileTrackers.ContainsKey(path); } } public void Track(string path, Action action) { if (path == null) { throw new ArgumentNullException("path"); } using (guard.DisposableWait()) { var tracker = this.GetFileTracker_NoLock(path); tracker.AddAction_NoLock(action); var directory = Path.GetDirectoryName(path); if (!watchers.ContainsKey(directory)) { var watcher = new FileSystemWatcher(directory); watcher.Changed += OnFileChanged; watcher.EnableRaisingEvents = true; } } } public void StopTracking(string path) { if (path != null) { using (guard.DisposableWait()) { this.fileTrackers.Remove(path); } } } private void OnFileChanged(object sender, FileSystemEventArgs args) { FileTracker tracker; using (this.guard.DisposableWait()) { tracker = this.GetFileTracker_NoLock(args.FullPath); } tracker.OnFileChanged(); } public void Dispose() { using (this.guard.DisposableWait()) { foreach (var watcher in watchers.Values) { watcher.Dispose(); } watchers.Clear(); fileTrackers.Clear(); } } private class FileTracker { private FileSetTracker tracker; private readonly string path; private ImmutableList<Action> actions; private Task invokeTask; public FileTracker(FileSetTracker tracker, string path) { this.tracker = tracker; this.path = path; this.actions = ImmutableList.Create<Action>(); } public void AddAction_NoLock(Action action) { this.tracker.guard.AssertHasLock(); this.actions = this.actions.Add(action); } public void OnFileChanged() { using (this.tracker.guard.DisposableWait()) { // only start invoke task if one is not already running if (this.invokeTask == null) { this.invokeTask = Task.Factory.StartNew(() => { }); this.invokeTask.ContinueWithAfterDelay(() => TryInvokeActions(this.actions), CancellationToken.None, 100, TaskContinuationOptions.None, TaskScheduler.Current); } } } private void TryInvokeActions(ImmutableList<Action> actions) { if (actions.Count == 0) { return; } // only invoke actions if the writer that caused the event is done // determine this by checking to see if we can read the file using (var stream = Kernel32File.Open(this.path, FileAccess.Read, FileMode.Open, throwException: false)) { if (stream != null) { stream.Close(); foreach (var action in actions) { action(); } // clear invoke task so any following changes get additional invocations using (this.tracker.guard.DisposableWait()) { this.invokeTask = null; } } else { // try again after a short delay using (this.tracker.guard.DisposableWait()) { this.invokeTask.ContinueWithAfterDelay(() => TryInvokeActions(this.actions), CancellationToken.None, 100, TaskContinuationOptions.None, TaskScheduler.Current); } } } } } } } }
34.379808
191
0.468326
[ "ECL-2.0", "Apache-2.0" ]
binsys/roslyn_java
Src/Workspaces/Core/Workspace/Host/FileTracking/FileTrackingServiceFactory.cs
7,153
C#
using System; using System.IO; using Amazon.S3; using Amazon.S3.Model; using RadPdf.Lite; using RadPdf.Integration; namespace RadPdfDemoNoService.CustomProviders { // This example uses the Amazon Simple Storage Service (S3) API, see: // https://www.nuget.org/packages/AWSSDK.S3/ // Using a key-value / NoSQL store like this, RAD PDF can easily scale with even the largest deployments. // Cosmos or Mongo DB could also be used, but each have relatively low (2 MB and 16 MB, respectively) document size limits. public class S3LiteStorageProvider : PdfLiteStorageProvider { private readonly string _bucketName; private readonly AmazonS3Client _client; const string Seperator = "/"; public S3LiteStorageProvider() : base() { AppSettings settings = AppSettings.LoadAppSettings(); // Get bucket name used by this code _bucketName = settings.S3BucketName; // Get client for our container (load credentials from default location) _client = new AmazonS3Client(); } public override void DeleteData(PdfLiteSession session) { string continuationToken = null; for ( ; ; ) { var listRequest = new ListObjectsV2Request(); listRequest.BucketName = _bucketName; listRequest.ContinuationToken = continuationToken; listRequest.Prefix = session.ID + Seperator; // List all objects var listResponse = _client.ListObjectsV2Async(listRequest); listResponse.Wait(); // Init DeleteObjects request var delRequest = new DeleteObjectsRequest(); foreach (S3Object obj in listResponse.Result.S3Objects) { // Add key delRequest.AddKey(obj.Key); } // Delete any objects we have added if (delRequest.Objects.Count > 0) { var delResponse = _client.DeleteObjectsAsync(delRequest); delResponse.Wait(); } // If done if (!listResponse.Result.IsTruncated) { return; } // Set continuation token for next loop continuationToken = listResponse.Result.NextContinuationToken; } } public override byte[] GetData(PdfLiteSession session, int subtype) { try { string key = CreateStorageKey(session, subtype); var getRequest = new GetObjectRequest(); getRequest.BucketName = _bucketName; getRequest.Key = key; // Get object var getResponse = _client.GetObjectAsync(getRequest); getResponse.Wait(); // Read stream and return using (var stream = getResponse.Result.ResponseStream) { byte[] ret = new byte[getResponse.Result.ContentLength]; stream.Read(ret); return ret; } } catch (AmazonS3Exception ex) { // If not found, return null if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } throw ex; } } public override void SetData(PdfLiteSession session, int subtype, byte[] value) { string key = CreateStorageKey(session, subtype); var putRequest = new PutObjectRequest(); putRequest.BucketName = _bucketName; putRequest.Key = key; putRequest.InputStream = new MemoryStream(value); // Put object var putResponse = _client.PutObjectAsync(putRequest); putResponse.Wait(); } private static string CreateStorageKey(PdfLiteSession session, int subtype) { return session.ID.ToString("N") + Seperator + subtype.ToString(); } } }
32.24812
127
0.543483
[ "MIT" ]
radpdf/samples
CS_NET6_No_Service/CustomProviders/S3LiteStorageProvider.cs
4,291
C#
using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using Ordering.Application.Contracts.Persistence; using Ordering.Application.Exceptions; using Ordering.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ordering.Application.Features.Commands.UpdateOrder { public class UpdateOrderCommandHandler : IRequestHandler<UpdateOrderCommand> { private readonly IOrderRepository _orderRepository; private readonly IMapper _mapper; private readonly ILogger<UpdateOrderCommandHandler> _logger; public UpdateOrderCommandHandler(IOrderRepository orderRepository, IMapper mapper, ILogger<UpdateOrderCommandHandler> logger) { _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<Unit> Handle(UpdateOrderCommand request, CancellationToken cancellationToken) { var orderToUpdate = await _orderRepository.GetByIdAsync(request.Id); if (orderToUpdate == null) { throw new NotFoundException(nameof(Order), request.Id); } _mapper.Map(request, orderToUpdate, typeof(UpdateOrderCommand), typeof(Order)); await _orderRepository.UpdateAsync(orderToUpdate); _logger.LogInformation($"Order {orderToUpdate.Id} is successfully updated."); return Unit.Value; } } }
36.404255
133
0.717124
[ "MIT" ]
Loominex/AspCoreMicroService_Udemy
MicroService_Udemy/Services/Ordering/Ordering.Application/Features/Commands/UpdateOrder/UpdateOrderCommandHandler.cs
1,713
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace MessageBoard.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "ApplicationUser", columns: table => new { Id = table.Column<string>(type: "varchar(255) CHARACTER SET utf8mb4", nullable: false), UserName = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), NormalizedUserName = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), Email = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), NormalizedEmail = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), EmailConfirmed = table.Column<bool>(type: "tinyint(1)", nullable: false), PasswordHash = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), SecurityStamp = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), ConcurrencyStamp = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), PhoneNumber = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), PhoneNumberConfirmed = table.Column<bool>(type: "tinyint(1)", nullable: false), TwoFactorEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false), LockoutEnd = table.Column<DateTimeOffset>(type: "datetime(6)", nullable: true), LockoutEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false), AccessFailedCount = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApplicationUser", x => x.Id); }); migrationBuilder.CreateTable( name: "Messages", columns: table => new { MessageId = table.Column<int>(type: "int", nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), Title = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), MessageBody = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), Group = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), MessageDate = table.Column<DateTime>(type: "datetime(6)", nullable: false), UserName = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true), UserId = table.Column<string>(type: "varchar(255) CHARACTER SET utf8mb4", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Messages", x => x.MessageId); table.ForeignKey( name: "FK_Messages_ApplicationUser_UserId", column: x => x.UserId, principalTable: "ApplicationUser", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.InsertData( table: "Messages", columns: new[] { "MessageId", "Group", "MessageBody", "MessageDate", "Title", "UserId", "UserName" }, values: new object[,] { { 1, "Recipes", "This is a test", new DateTime(2000, 11, 17, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 1", null, "user2@test.com" }, { 2, "Giveaways", "This is another test", new DateTime(2002, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 2", null, "user@test.com" }, { 3, "Random", "This is another another test", new DateTime(2003, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 3", null, "user2@test.com" }, { 4, "Recipes", "This is a title", new DateTime(2004, 11, 17, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 4", null, "user2@test.com" }, { 5, "Giveaways", "This is another title", new DateTime(2005, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 5", null, "user@test.com" }, { 6, "Random", "This is another another title", new DateTime(2006, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 6", null, "user2@test.com" }, { 7, "Recipes", "This is a test", new DateTime(2000, 11, 17, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 1", null, "user2@test.com" }, { 8, "Giveaways", "This is another test", new DateTime(2002, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 2", null, "user@test.com" }, { 9, "Random", "This is another another test", new DateTime(2003, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 3", null, "user2@test.com" }, { 10, "Recipes", "This is a title", new DateTime(2004, 11, 17, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 4", null, "user2@test.com" }, { 11, "Giveaways", "This is another title", new DateTime(2005, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 5", null, "user@test.com" }, { 12, "Random", "This is another another title", new DateTime(2006, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), "Test 6", null, "user2@test.com" } }); migrationBuilder.CreateIndex( name: "IX_Messages_UserId", table: "Messages", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Messages"); migrationBuilder.DropTable( name: "ApplicationUser"); } } }
66.105263
169
0.561146
[ "Unlicense" ]
lavinbrenna/MessageBoard.Solution
MessageBoard/Migrations/20220330230926_initial.cs
6,282
C#
using System; using System.Windows.Forms; using Serilog; namespace HASSAgent.Controls.Onboarding { // ReSharper disable once InconsistentNaming public partial class MQTT : UserControl { public MQTT() { InitializeComponent(); } private void MQTT_Load(object sender, EventArgs e) { // hide group seperator TbIntMqttPort.NumberGroupSeparator = ""; // let's see if we can get the host from the provided HASS uri if (!string.IsNullOrEmpty(Variables.AppSettings.HassUri)) { try { var host = new Uri(Variables.AppSettings.HassUri).Host; TbMqttAddress.Text = host; } catch (Exception ex) { Log.Error("[MQTT] Unable to parse URI {uri}: {msg}", Variables.AppSettings.HassUri, ex.Message); } } // if the above process failed somewhere, just enter the entire address (if any) if (string.IsNullOrEmpty(TbMqttAddress.Text)) TbMqttAddress.Text = Variables.AppSettings.MqttAddress; // optionally set default port if (Variables.AppSettings.MqttPort < 1) Variables.AppSettings.MqttPort = 1883; TbIntMqttPort.IntegerValue = Variables.AppSettings.MqttPort; CbMqttTls.Checked = Variables.AppSettings.MqttUseTls; TbMqttUsername.Text = Variables.AppSettings.MqttUsername; TbMqttPassword.Text = Variables.AppSettings.MqttPassword; TbMqttDiscoveryPrefix.Text = Variables.AppSettings.MqttDiscoveryPrefix; ActiveControl = !string.IsNullOrEmpty(TbMqttAddress.Text) ? TbMqttUsername : TbMqttAddress; } internal bool Store() { Variables.AppSettings.MqttAddress = TbMqttAddress.Text; Variables.AppSettings.MqttPort = (int)TbIntMqttPort.IntegerValue; Variables.AppSettings.MqttUseTls = CbMqttTls.Checked; Variables.AppSettings.MqttUsername = TbMqttUsername.Text; Variables.AppSettings.MqttPassword = TbMqttPassword.Text; Variables.AppSettings.MqttDiscoveryPrefix = TbMqttDiscoveryPrefix.Text; return true; } } }
39.229508
117
0.600919
[ "MIT" ]
Syntoxr/HASS.Agent
src/HASS.Agent/HASSAgent/Controls/Onboarding/6-MQTT.cs
2,395
C#
// Copyright (c) 2020 Ryuju Orchestra using System; using System.Runtime.CompilerServices; using RyujuEngine.Mathematics; namespace RyujuEngine.Units { /// <summary> /// A struct that contains a position on a beat. /// あるタイミングの時刻を拍数で表す構造体です。 /// </summary> public readonly struct BeatPoint : IComparable , IComparable<BeatPoint> , IEquatable<BeatPoint> { /// <summary> /// An instance that indicates the origin position on a beat. /// 原点となる時刻です。 /// </summary> public static readonly BeatPoint Zero = new BeatPoint(BeatDuration.Zero); /// <summary> /// A minimum value. /// 扱える最小の時刻です。 /// </summary> public static readonly BeatPoint Min = new BeatPoint(BeatDuration.Min); /// <summary> /// A maximum value. /// 扱える最大の時刻です。 /// </summary> public static readonly BeatPoint Max = new BeatPoint(BeatDuration.Max); /// <summary> /// Create an instance from floated beats using rationalization. /// 浮動小数点で表された原点からの拍数から、指定した解像度でインスタンスを生成します。 /// </summary> /// <param name="beats"> /// A floated beats. /// 小数点以下も含む拍数です。 /// </param> /// <param name="resolution"> /// A resolution in a beat. /// 1 拍あたりの分割解像度です。 /// </param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint Rationalize(BeatPointFloat beats, uint resolution) => new BeatPoint(BeatDuration.Rationalize(beats.DurationFromZero, resolution)); /// <summary> /// Create an instance from the beats and sub-beats. /// 原点からの拍数と分数を組み合わせてインスタンスを生成します。 /// </summary> /// <param name="beats"> /// The beats. /// 拍数です。 /// </param> /// <param name="subBeatPosition"> /// An additional beats from the `beats` parameter. /// 分数で表された追加の拍数です。 /// </param> /// <param name="subBeatResolution"> /// An resolution of the sub-beats. /// sub-beat の解像度です。 /// </param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint At(int beats, long subBeatPosition, int subBeatResolution) => new BeatPoint(BeatDuration.Of(beats, subBeatPosition, subBeatResolution)); /// <summary> /// Create an instance with the specified duration from the origin. /// 原点からの秒数からインスタンスを生成します。 /// </summary> /// <param name="durationFromZero"> /// A duration from zero. /// 原点からの時間です。 /// </param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint At(in BeatDuration durationFromZero) => new BeatPoint(durationFromZero); [MethodImpl(MethodImplOptions.AggressiveInlining)] private BeatPoint(in BeatDuration durationFromZero) => DurationFromZero = durationFromZero; /// <summary> /// A duration from the origin. /// 原点からの経過時間です。 /// </summary> public readonly BeatDuration DurationFromZero; /// <summary> /// A hash value. /// ハッシュ値を求めます。 /// </summary> public override int GetHashCode() => DurationFromZero.GetHashCode(); #if UNITY_EDITOR /// <summary> /// A string for debugging. /// デバッグ用の文字列表現を返します。 /// </summary> public override string ToString() => DurationFromZero.ToString(); #endif #region Basic arithmetic operations. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint operator +(in BeatPoint x, in BeatDuration y) => new BeatPoint(x.DurationFromZero + y); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint operator +(in BeatDuration y, in BeatPoint x) => new BeatPoint(x.DurationFromZero + y); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatPoint operator -(in BeatPoint x, in BeatDuration y) => new BeatPoint(x.DurationFromZero - y); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BeatDuration operator -(in BeatPoint x, in BeatPoint y) => x.DurationFromZero - y.DurationFromZero; #endregion #region Equal and not equal. /// <summary> /// Detect the same values. /// 同じ値かどうかを確かめます。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (obj is null) { return false; } return obj is BeatPoint point && Equals(point); } /// <summary> /// Detect the same values. /// 同じ値かどうかを確かめます。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(object obj) { if (obj is null) { return 1; } return obj is BeatPoint point ? CompareTo(point) : throw new ArgumentException(nameof(obj)); } /// <summary> /// Detect the same values. /// 同じ値かどうかを確かめます。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(BeatPoint x) => this == x; /// <summary> /// Detect the same values. /// 同じ値かどうかを確かめます。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(in BeatPoint x) => this == x; /// <summary> /// Compare the values. /// 値を比較します。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(BeatPoint x) => this < x ? -1 : this == x ? 0 : 1; /// <summary> /// Compare the values. /// 値を比較します。 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(in BeatPoint x) => this < x ? -1 : this == x ? 0 : 1; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(in BeatPoint x, in BeatPoint y) => x.DurationFromZero == y.DurationFromZero; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(in BeatPoint x, in BeatPoint y) => x.DurationFromZero != y.DurationFromZero; #endregion #region Compare operators. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator <(in BeatPoint x, in BeatPoint y) => x.DurationFromZero < y.DurationFromZero; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator >(in BeatPoint x, in BeatPoint y) => x.DurationFromZero > y.DurationFromZero; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator <=(in BeatPoint x, in BeatPoint y) => x.DurationFromZero <= y.DurationFromZero; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator >=(in BeatPoint x, in BeatPoint y) => x.DurationFromZero >= y.DurationFromZero; #endregion } }
28.15625
98
0.695418
[ "MIT" ]
RyujuOrchestra/RyujuEngine
Runtime/RyujuEngine.Units/BeatPoint.cs
6,951
C#
using System; using System.Collections.Generic; // ReSharper disable once CheckNamespace namespace Ricoh { /// <summary> /// Allows for external metadata to be added to properities or classes which can be inspected at runtime. /// </summary> class RicohDeviceCapabilityMetaDataAttribute: Attribute { /// <summary>The external identifier for the access control.</summary> public string Name { get; set; } /// <param name="name">The external identifiers for the access control.</param> public RicohDeviceCapabilityMetaDataAttribute(string name) { Name = name; } } }
29.142857
107
0.710784
[ "MIT" ]
gheeres/Ricoh.NET
Attributes/RicohDeviceCapabilityMetaDataAttribute.cs
614
C#
using Grpc.Core; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestsStorageService.API; using TestsStorageService.Db; using Utilities.Types; using Utilities.Extensions; using Newtonsoft.Json; using Microsoft.EntityFrameworkCore; using SharedT; using MessageHub; using SharedT.Types; using System.Linq.Expressions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace TestsStorageService { [ApiController, Microsoft.AspNetCore.Mvc.Route("api/v1")] public class MainController : ControllerBase { [Inject] public IMessageProducer MessageProducer { get; set; } [Inject] public TestsContext Db { get; set; } [Inject] public ILogger<MainController> Logger { get; set; } public MainController(IDependencyResolver di) { di.ResolveProperties(this); } [Microsoft.AspNetCore.Mvc.Route("list"), HttpPost] public async Task<ListTestsDataResponse> ListTestsData(ListTestsDataRequest request) { IQueryable<TestCase> cases = Db.Cases .AsNoTracking() .IncludeGroup(EntityGroups.ALL, Db) .Where(c => request.ReturnNotSaved ? c.State == TestCaseState.RecordedButNotSaved : c.State == TestCaseState.Saved) .OrderByDescending(c => c.CreationDate); cases = filterCases(cases, request.FilteringOrders); var totalCount = cases is Microsoft.EntityFrameworkCore.Query.Internal.IAsyncQueryProvider ? await cases.CountAsync() : cases.Count(); if (request.Range != null) { var count = (request.Range.To - request.Range.From).NegativeToZero(); cases = cases.Take(count); } var result = cases is Microsoft.EntityFrameworkCore.Query.Internal.IAsyncQueryProvider ? await cases.ToArrayAsync() : cases.ToArray(); if (!request.IncludeData) { foreach (var r in result) { r.Data.Data = null; } } return new ListTestsDataResponse(result, totalCount); } [Microsoft.AspNetCore.Mvc.Route("delete"), HttpPost] public async Task<DeleteTestResponse> DeleteTest(DeleteTestRequest request) { var cases = Db.Cases.IncludeGroup(EntityGroups.ALL, Db); var casesToDelete = await filterCases(cases, request.FilteringOrders) .ToArrayAsync(); if (casesToDelete.Length > 0) { foreach (var caseToDelete in casesToDelete) { Db.Cases.Remove(caseToDelete); await Db.SaveChangesAsync(); // i know... MessageProducer.FireTestDeleted(new TestDeletedMessage(caseToDelete.TestId, caseToDelete.TestName)); } } return new DeleteTestResponse(); } [Microsoft.AspNetCore.Mvc.Route("save"), HttpPost] public async Task<IActionResult> SaveTest(SaveTestRequest request) { var test = await Db.Cases.FirstOrDefaultAsync(c => c.TestId == request.TestId); if (test?.State == TestCaseState.RecordedButNotSaved) { test.AuthorName = request.AuthorName; test.TestDescription = request.Description; test.TestName = request.Name; test.State = TestCaseState.Saved; await Db.SaveChangesAsync(); MessageProducer.FireTestAdded(new TestAddedMessage(test.TestId, test.TestName, test.AuthorName)); return Ok(new SaveTestResponse()); } else { return NotFound(); } } IQueryable<TestCase> filterCases(IQueryable<TestCase> cases, IFilterOrder[] filteringorders) { foreach (var filterOrder in filteringorders) { if (filterOrder is ByTestIdsFilter ids) { cases = cases.Where(c => ids.TestIds.Contains(c.TestId)); } else if (filterOrder is ByTestNamesFilter namesFilter) { foreach (var nameFilter in namesFilter.TestNameFilters) { cases = cases .Where(r => r.TestName == nameFilter || r.TestName.StartsWith(nameFilter + ".")); } } else if (filterOrder is ByKeyParametersFilter parameters) { foreach (var parameter in parameters.TestParameters) { if (parameter.Value != null) { cases = cases .Where(c => c.Data.KeyParameters .Any(p => p.Key == parameter.Key && p.Value == parameter.Value)); } } } else if (filterOrder is ByQueryFilter query) { if (query.Query.IsNotNullOrEmpty() && query.Query.IsNotNullOrWhiteSpace()) { var queryKeywords = query.Query .Split(' ', StringSplitOptions.RemoveEmptyEntries) .Take(6) .ToArray(); cases = cases .AsEnumerable() .Select(c => new { Case = c, Keywords = c.Data.KeyParameters .Select(p => p.Value) .Concat(c.TestDescription.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Concat(new[] { c.TestName }) .ToArray(), }) .Select(c => new { Case = c.Case, Match = c.Keywords.Select(k => queryKeywords.Select(qk => k.FindAll(qk).Count() * qk.Length).Sum()).Sum() / (double)c.Keywords.Sum(k => k.Length) }) .Where(c => c.Match != 0) .OrderByDescending(c => c.Match) .Select(c => c.Case) .AsQueryable(); } } else if (filterOrder is ByAuthorsFilter authors) { foreach (var author in authors.AuthorNames) { cases = cases.Where(c => c.AuthorName == author); } } else { Logger.LogWarning("Unsupported filter order {@FilterOrder}", filterOrder); } } return cases; } } }
39.191489
177
0.491178
[ "MIT" ]
GataullinRR/Testkit
TestsStorage/MainController.cs
7,370
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TripTracker.BackService.Models { public class Repository { private List<Trip> MyTrips = new List<Trip> { new Trip { Id = 1, Name = "MVP Summit", StartDate = new DateTime(2018, 3, 5), EndDate = new DateTime(2018, 3, 8) }, new Trip { Id = 2, Name ="DevIntersection Orlando 2018", StartDate = new DateTime(2018, 3, 25), EndDate = new DateTime(2018, 3, 27) }, new Trip { Id = 3, Name = "Build 2018", StartDate = new DateTime(2018, 5, 7), EndDate = new DateTime(2018, 5, 9) } }; public List<Trip> Get() { return MyTrips; } public Trip Get(int id) { return MyTrips.First(t => t.Id == id); } public void Add(Trip newTrip) { MyTrips.Add(newTrip); } public void Update(Trip tripToUpdate) { MyTrips.Remove(MyTrips.First(t => t.Id == tripToUpdate.Id)); Add(tripToUpdate); } public void Remove(int id) { MyTrips.Remove(MyTrips.First(t => t.Id == id)); } } }
23.296875
72
0.445339
[ "Apache-2.0" ]
klpinto22/TripTracker
TripTracker.BackService/Models/Repository.cs
1,493
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // </copyright> // <summary> // Implements the program class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleSettings.JsonConfiguration { using System.Threading.Tasks; using Kephas; using Kephas.Application; class Program { public static async Task Main(string[] args) { await new App(ambientServices => ambientServices .WithNLogManager() .WithDynamicAppRuntime() .BuildWithAutofac()).BootstrapAsync(new AppArgs(args)); } } }
32.678571
120
0.442623
[ "MIT" ]
kephas-software/kephas
Samples/Configuration/ConsoleSettings.JsonConfiguration/Program.cs
917
C#
// // WSEncryptedXml.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Cryptography.Xml; using System.Xml; namespace System.ServiceModel.Channels { // See http://blogs.msdn.com/shawnfa/archive/2004/04/05/108098.aspx :) class WSEncryptedXml : EncryptedXml { public WSEncryptedXml () { } public WSEncryptedXml (XmlDocument doc) : base (doc) { } public override XmlElement GetIdElement (XmlDocument doc, string id) { return SearchChildren (doc, id); } XmlElement SearchChildren (XmlNode node, string id) { for (XmlNode n = node.FirstChild; n != null; n = n.NextSibling) { XmlElement el = n as XmlElement; if (el == null) continue; if (el.GetAttribute ("Id", Constants.WsuNamespace) == id || el.GetAttribute ("Id") == id) return el; XmlElement el2 = SearchChildren (el, id); if (el2 != null) return el2; } return null; } } }
31.208955
93
0.712578
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.ServiceModel/System.ServiceModel.Channels/WSEncryptedXml.cs
2,091
C#
// // DO NOT MODIFY. THIS IS AUTOMATICALLY GENERATED FILE. // #nullable enable #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. using System; using System.Collections.Generic; namespace CefNet.DevTools.Protocol.Network { /// <summary>[Experimental] </summary> public sealed class CrossOriginEmbedderPolicyStatus { public CefNet.DevTools.Protocol.Network.CrossOriginEmbedderPolicyValue Value { get; set; } public CefNet.DevTools.Protocol.Network.CrossOriginEmbedderPolicyValue ReportOnlyValue { get; set; } public string? ReportingEndpoint { get; set; } public string? ReportOnlyReportingEndpoint { get; set; } } }
32.956522
140
0.746702
[ "MIT" ]
CefNet/CefNet.DevTools.Protocol
CefNet.DevTools.Protocol/Generated/Network/CrossOriginEmbedderPolicyStatus.g.cs
758
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument")] public interface IWafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] string Name { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument")] internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] public string Name { get => GetInstanceProperty<string>()!; } } } }
42.258065
250
0.725954
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2WebAclRuleStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument.cs
1,310
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; namespace RefactorMe { internal class Drawer { private static float s_xPos; private static float s_yPos; private static Graphics s_graphics; public const float FirstSidePosition = 0.375f; public const float SecondSidePosition = 0.04f; public static void Initialize(Graphics newGraphics) { s_graphics = newGraphics; s_graphics.SmoothingMode = SmoothingMode.None; s_graphics.Clear(Color.Black); } public static void SetPosition(float x0, float y0) { s_xPos = x0; s_yPos = y0; } public static void DrawPartOfTheSide(Pen pen, double distance, double degree) { float x1 = (float)(s_xPos + distance * Math.Cos(degree)); float y1 = (float)(s_yPos + distance * Math.Sin(degree)); s_graphics.DrawLine(pen, s_xPos, s_yPos, x1, y1); s_xPos = x1; s_yPos = y1; } public static void ChangePosition(double distance, double degree) { s_xPos = (float)(s_xPos + distance * Math.Cos(degree)); s_yPos = (float)(s_yPos + distance * Math.Sin(degree)); } private enum SquareSide { Zero = 0, One = 1, MinusOne = -1, Two = 2, } public static void DrawSide(Pen color, int distance, int multiplier = 1, int divider = 1) { DrawPartOfTheSide(color, distance * FirstSidePosition, multiplier * Math.PI / divider); DrawPartOfTheSide(color, distance * SecondSidePosition * Math.Sqrt(2), (multiplier * Math.PI / divider) + Math.PI / 4); DrawPartOfTheSide(color, distance * FirstSidePosition, (multiplier * Math.PI /divider) + Math.PI); DrawPartOfTheSide(color, distance * FirstSidePosition - distance * SecondSidePosition, (multiplier * Math.PI / divider) + Math.PI / 2); ChangePosition(distance * SecondSidePosition, (multiplier * Math.PI / divider) - Math.PI); ChangePosition(distance * SecondSidePosition * Math.Sqrt(2), (multiplier * Math.PI / divider) + 3 * Math.PI / 4); } public static void DrawSquare(Pen color, int distance) { DrawSide(color, distance, (int)SquareSide.Zero, (int)SquareSide.One); DrawSide(color, distance, (int)SquareSide.MinusOne, (int)SquareSide.Two); DrawSide(color, distance, (int)SquareSide.One, (int)SquareSide.One); DrawSide(color, distance, (int)SquareSide.One, (int)SquareSide.Two); } } public class ImpossibleSquare { public static void Draw(int width, int height, double angle, Graphics graphic) { Drawer.Initialize(graphic); int distance = Math.Min(width, height); double diagonalLength = Math.Sqrt(2) * (distance * Drawer.FirstSidePosition + distance * Drawer.SecondSidePosition) / 2; float x0 = (float)(diagonalLength * Math.Cos(Math.PI / 4 + Math.PI)) + width / 2f; float y0 = (float)(diagonalLength * Math.Sin(Math.PI / 4 + Math.PI)) + height / 2f; Drawer.SetPosition(x0, y0); Drawer.DrawSquare(Pens.Yellow, distance); } } }
35.019608
86
0.565789
[ "MIT" ]
VsIG-official/Study-Projects
CSharp/ULearn/Risovatel/DrawingProgram.cs
3,574
C#
using System; using System.Collections.Generic; using System.Text; namespace Keutmann.SharePoint.WSPBuilder.Library { public enum DLLType : int { Managed = 0, Resource = 1, Unmanaged = 2 } }
16.357143
48
0.637555
[ "MIT" ]
keutmann/wspbuilder
WSPTools/App/WSPBuilder/Library/DLLType.cs
231
C#
namespace MountainSocialNetwork.Web.ViewModels.Administration { using System; using MountainSocialNetwork.Data.Models; using MountainSocialNetwork.Services.Mapping; public class NewsFeedPostAdministrationViewModel : IMapFrom<NewsFeedPost> { public int Id { get; set; } public string Content { get; set; } public string ShortContent { get { return this.Content.Length > 50 ? this.Content.Substring(0, 50) + "..." : this.Content; } } public int IsDelete { get; set; } public DateTime CreatedOn { get; set; } public string UserFirstName { get; set; } public string UserLastName { get; set; } public string UserUserName { get; set; } } }
24.242424
103
0.6025
[ "MIT" ]
Ventsislav-Ignatov/MountainSocialNetwork
src/Web/MountainSocialNetwork.Web.ViewModels/Administration/NewsFeedPostAdministrationViewModel.cs
802
C#
// <copyright file="DSP_Frames.cs" company="QutEcoacoustics"> // All code in this file and all associated files are the copyright and property of the QUT Ecoacoustics Research Group (formerly MQUTeR, and formerly QUT Bioacoustics Research Group). // </copyright> namespace AudioAnalysisTools.DSP { using System; using System.Collections.Generic; using TowseyLibrary; using WavTools; // using MathNet.Numerics;using MathNet.Numerics.Transformations; /// <summary> /// digital signal processing methods /// </summary> public static class DSP_Frames { public const double Pi = Math.PI; public class EnvelopeAndFft { public int SampleRate { get; set; } public double Epsilon { get; set; } public TimeSpan Duration { get; set; } public double MinSignalValue { get; set; } public double MaxSignalValue { get; set; } /// <summary> /// Gets or sets the fraction of high energy signal frames PRIOR to noise removal. /// This value is used only when doing noise removal. If the value exceeds SNR.FractionalBoundForMode, /// then Lamel's noise removal algorithm may not work well. /// </summary> public double FractionOfHighEnergyFrames { get; set; } public int FrameCount { get; set; } public double[] Envelope { get; set; } public double[] FrameEnergy { get; set; } public double[] FrameDecibels { get; set; } public double[,] AmplitudeSpectrogram { get; set; } public double WindowPower { get; set; } public double[] Average { get; set; } public int NyquistFreq { get; set; } public double FreqBinWidth { get; set; } public int NyquistBin { get; set; } public int HighAmplitudeCount { get; set; } public int ClipCount { get; set; } } public static int FrameStep(int windowSize, double windowOverlap) { int step = (int)(windowSize * (1 - windowOverlap)); return step; } public static int[,] FrameStartEnds(int dataLength, int frameSize, double windowOverlap) { int frameStep = (int)(frameSize * (1 - windowOverlap)); return FrameStartEnds(dataLength, frameSize, frameStep); } /// <summary> /// Returns the start and end index of all frames in a long audio signal /// </summary> public static int[,] FrameStartEnds(int dataLength, int frameSize, int frameStep) { if (frameStep < 1) { throw new ArgumentException("Frame Step must be at least 1"); } if (frameStep > frameSize) { throw new ArgumentException("Frame Step must be <=" + frameSize); } int overlap = frameSize - frameStep; int framecount = (dataLength - overlap) / frameStep; // this truncates residual samples if (framecount < 2) { throw new ArgumentException("Signal must produce at least two frames!"); } // In the matrix "frames", col 0 = start; col 1 = end int offset = 0; int[,] frames = new int[framecount, 2]; for (int i = 0; i < framecount; i++) { frames[i, 0] = offset; // start of frame frames[i, 1] = offset + frameSize - 1; // end of frame offset += frameStep; } return frames; } /// <summary> /// Returns the signal broken into frames /// This method is not called because the only reason to break a signal into frames is to do fft on the frames. /// </summary> public static double[,] Frames(double[] data, int[,] startEnds) { // window size = location of first frame end + 1 int windowSize = startEnds[0, 1] + 1; int framecount = startEnds.GetLength(0); double[,] frames = new double[framecount, windowSize]; for (int i = 0; i < framecount; i++) { for (int j = 0; j < windowSize; j++) { frames[i, j] = data[startEnds[i, 0] + j]; } } return frames; } public static EnvelopeAndFft ExtractEnvelopeAndFfts(AudioRecording recording, int frameSize, double overlap, string windowName = null) { int frameStep = (int)(frameSize * (1 - overlap)); return ExtractEnvelopeAndAmplSpectrogram(recording.WavReader.Samples, recording.SampleRate, recording.Epsilon, frameSize, frameStep, windowName); } public static EnvelopeAndFft ExtractEnvelopeAndFfts(AudioRecording recording, int frameSize, int frameStep) { string windowName = FFT.KeyHammingWindow; return ExtractEnvelopeAndAmplSpectrogram(recording.WavReader.Samples, recording.SampleRate, recording.Epsilon, frameSize, frameStep, windowName); } public static EnvelopeAndFft ExtractEnvelopeAndAmplSpectrogram(double[] signal, int sampleRate, double epsilon, int frameSize, double overlap) { int frameStep = (int)(frameSize * (1 - overlap)); string windowName = FFT.KeyHammingWindow; return ExtractEnvelopeAndAmplSpectrogram(signal, sampleRate, epsilon, frameSize, frameStep, windowName); } /// <summary> /// Returns the following 18 values encapsulated in class EnvelopeAndFft /// 1) the minimum and maximum signal values /// 2) the average of absolute amplitudes for each frame /// 3) the signal envelope as vector. i.e. the maximum of absolute amplitudes for each frame. /// 4) vector of frame energies /// 5) the high amplitdue and clipping counts /// 6) the signal amplitude spectrogram /// 7) the power of the FFT Window, i.e. sum of squared window values. /// 8) the nyquist /// 9) the width of freq bin in Hz /// 10) the byquist bin ID /// AND OTHERS /// The returned info is used by Sonogram classes to draw sonograms and by Spectral Indices classes to calculate Spectral indices. /// Less than half the info is used to draw sonograms but it is difficult to disentangle calculation of all the info without /// reverting back to the old days when we used two classes and making sure they remain in synch. /// </summary> public static EnvelopeAndFft ExtractEnvelopeAndAmplSpectrogram( double[] signal, int sampleRate, double epsilon, int frameSize, int frameStep, string windowName = null) { // SIGNAL PRE-EMPHASIS helps with speech signals // Do not use this for enviromental audio //if (config.DoPreemphasis) //{ // signal = DSP_Filters.PreEmphasis(signal, 0.96); //} int[,] frameIDs = FrameStartEnds(signal.Length, frameSize, frameStep); if (frameIDs == null) { throw new NullReferenceException("Thrown in EnvelopeAndFft.ExtractEnvelopeAndAmplSpectrogram(): int matrix, frameIDs, cannot be null."); } int frameCount = frameIDs.GetLength(0); // set up the FFT parameters if (windowName == null) { windowName = FFT.KeyHammingWindow; } FFT.WindowFunc w = FFT.GetWindowFunction(windowName); var fft = new FFT(frameSize, w); // init class which calculates the MATLAB compatible .NET FFT double[,] spectrogram = new double[frameCount, fft.CoeffCount]; // init amplitude sonogram double minSignalValue = double.MaxValue; double maxSignalValue = double.MinValue; double[] average = new double[frameCount]; double[] envelope = new double[frameCount]; double[] frameEnergy = new double[frameCount]; double[] frameDecibels = new double[frameCount]; // for all frames for (int i = 0; i < frameCount; i++) { int start = i * frameStep; int end = start + frameSize; // get average and envelope double frameSum = signal[start]; double total = Math.Abs(signal[start]); double maxValue = total; double energy = 0; for (int x = start + 1; x < end; x++) { if (signal[x] > maxSignalValue) { maxSignalValue = signal[x]; } if (signal[x] < minSignalValue) { minSignalValue = signal[x]; } frameSum += signal[x]; // Get absolute signal average in current frame double absValue = Math.Abs(signal[x]); total += absValue; if (absValue > maxValue) { maxValue = absValue; } energy += signal[x] * signal[x]; } double frameDc = frameSum / frameSize; average[i] = total / frameSize; envelope[i] = maxValue; frameEnergy[i] = energy / frameSize; frameDecibels[i] = 10 * Math.Log10(frameEnergy[i]); // remove DC value from signal values double[] signalMinusAv = new double[frameSize]; for (int j = 0; j < frameSize; j++) { signalMinusAv[j] = signal[start + j] - frameDc; } // generate the spectra of FFT AMPLITUDES - NOTE: f[0]=DC; f[64]=Nyquist var f1 = fft.InvokeDotNetFFT(signalMinusAv); // Previous alternative call to do the FFT and return amplitude spectrum //f1 = fft.Invoke(window); // Smooth spectrum to reduce variance // In the early days (pre-2010), we used to smooth the spectra to reduce sonogram variance. This is statistically correct thing to do. // Later, we stopped this for standard sonograms but kept it for calculating acoustic indices. // As of 28 March 2017, we are merging the two codes and keeping spectrum smoothing. // Will need to check the effect on spectrograms. int smoothingWindow = 3; f1 = DataTools.filterMovingAverage(f1, smoothingWindow); // transfer amplitude spectrum to spectrogram matrix for (int j = 0; j < fft.CoeffCount; j++) { spectrogram[i, j] = f1[j]; } } // end frames // Remove the DC column ie column zero from amplitude spectrogram. double[,] amplSpectrogram = MatrixTools.Submatrix(spectrogram, 0, 1, spectrogram.GetLength(0) - 1, spectrogram.GetLength(1) - 1); // check the envelope for clipping. Accept a clip if two consecutive frames have max value = 1,0 Clipping.GetClippingCount(signal, envelope, frameStep, epsilon, out int highAmplitudeCount, out int clipCount); // get SNR data var snrdata = new SNR(signal, frameIDs); return new EnvelopeAndFft { // The following data is required when constructing sonograms Duration = TimeSpan.FromSeconds((double)signal.Length / sampleRate), Epsilon = epsilon, SampleRate = sampleRate, FrameCount = frameCount, FractionOfHighEnergyFrames = snrdata.FractionOfHighEnergyFrames, WindowPower = fft.WindowPower, AmplitudeSpectrogram = amplSpectrogram, // The below 11 variables are only used when calculating spectral and summary indices // energy level information ClipCount = clipCount, HighAmplitudeCount = highAmplitudeCount, MinSignalValue = minSignalValue, MaxSignalValue = maxSignalValue, // envelope info Average = average, Envelope = envelope, FrameEnergy = frameEnergy, FrameDecibels = frameDecibels, // freq scale info NyquistFreq = sampleRate / 2, NyquistBin = amplSpectrogram.GetLength(1) - 1, FreqBinWidth = sampleRate / (double)amplSpectrogram.GetLength(1) / 2, }; } /* * BELOW ARE THE TWO CLASSES ONCE USED TO MAKE SPECTROGRAMS for Sonograms and for Spectral INdices. Have merged to codes in method above. * In fact they only differed in smoothing of the spectra. See note in above method. public static double[,] MakeAmplitudeSpectrogram(double[] signal, int[,] frames, FFT.WindowFunc w, out double power) { // cycle through the frames for (int i = 0; i < frameCount; i++) { int start = i * frameStep; int end = start + frameSize; // get average and envelope double frameDc = signal[start]; double total = Math.Abs(signal[start]); double maxValue = total; double energy = 0; for (int x = start + 1; x < end; x++) { if (signal[x] > maxSignalValue) { maxSignalValue = signal[x]; } if (signal[x] < minSignalValue) { minSignalValue = signal[x]; } frameDc += signal[x]; // Get absolute signal average in current frame double absValue = Math.Abs(signal[x]); total += absValue; if (absValue > maxValue) { maxValue = absValue; } energy += (signal[x] * signal[x]); } frameDc /= frameSize; average[i] = total / frameSize; envelope[i] = maxValue; frameEnergy[i] = energy / frameSize; // remove DC value from signal values double[] signalMinusAv = new double[frameSize]; for (int j = 0; j < frameSize; j++) { signalMinusAv[j] = signal[start + j] - frameDc; } // generate the spectra of FFT AMPLITUDES - NOTE: f[0]=DC; f[64]=Nyquist var f1 = fft.InvokeDotNetFFT(signalMinusAv); ////f1 = fft.InvokeDotNetFFT(DataTools.GetRow(frames, i)); //returns fft amplitude spectrum ////f1 = fft.Invoke(DataTools.GetRow(frames, i)); //returns fft amplitude spectrum // smooth spectrum to reduce variance f1 = DataTools.filterMovingAverage(f1, 3); // transfer amplitude spectrum to spectrogram matrix for (int j = 0; j < fft.CoeffCount; j++) { spectrogram[i, j] = f1[j]; } } // end frames } public static double[,] MakeAmplitudeSpectrogram(double[] signal, int[,] frames, FFT.WindowFunc w, out double power) { int frameCount = frames.GetLength(0); int frameSize = frames[0, 1] + 1; // init FFT class which calculates the MATLAB compatible .NET FFT var fft = new FFT(frameSize, w, true); power = fft.WindowPower; //store for later use when calculating dB double[,] amplitudeSonogram = new double[frameCount, fft.CoeffCount]; //init amplitude sonogram var window = new double[frameSize]; // foreach frame or time step for (int i = 0; i < frameCount; i++) { //set up the window containing signal for (int j = 0; j < frameSize; j++) { window[j] = signal[frames[i, 0] + j]; } var f1 = fft.InvokeDotNetFFT(window); // Previous alternative call to do the FFT and return amplitude spectrum //f1 = fft.Invoke(window); // In the early days, we used to smooth the spectra to reduce sonogram variance. This is theoretically correct. // Stopped this for standard sonograms but kept it for calculating indices. // We are merging the two codes on 28March2017 cnad keeping the smoothing. // Will need to check the effect on spectrograms. int smoothingWindow = 3; f1 = DataTools.filterMovingAverage(f1, smoothingWindow); // transfer amplitude spectrum to a matrix for (int j = 0; j < fft.CoeffCount; j++) { amplitudeSonogram[i, j] = f1[j]; } } //end of all frames return amplitudeSonogram; } /// <summary> /// Does same as the method above but returns values for octave scale spectrograms. /// </summary> public static EnvelopeAndFft ExtractEnvelopeAndFftForOctaveScale(double[] signal, int sampleRate, double epsilon, int frameSize, int frameStep) { int[,] frameIDs = DSP_Frames.FrameStartEnds(signal.Length, frameSize, frameStep); if (frameIDs == null) return null; int frameCount = frameIDs.GetLength(0); double[] average = new double[frameCount]; double[] envelope = new double[frameCount]; double[] frameEnergy = new double[frameCount]; // set up the FFT parameters FFT.WindowFunc w = FFT.GetWindowFunction(FFT.Key_HammingWindow); var fft = new FFT(frameSize, w, true); // init class which calculates the MATLAB compatible .NET FFT double[,] spectrogram = new double[frameCount, fft.CoeffCount]; // init amplitude sonogram double minSignalValue = double.MaxValue; double maxSignalValue = double.MinValue; // cycle through the frames for (int i = 0; i < frameCount; i++) { int start = i * frameStep; int end = start + frameSize; // get average and envelope double frameDC = signal[start]; double total = Math.Abs(signal[start]); double maxValue = total; double energy = 0; for (int x = start + 1; x < end; x++) { if (signal[x] > maxSignalValue) maxSignalValue = signal[x]; if (signal[x] < minSignalValue) minSignalValue = signal[x]; frameDC += signal[x]; double absValue = Math.Abs(signal[x]); total += absValue; // go through current frame to get signal (absolute) average if (absValue > maxValue) maxValue = absValue; energy += (signal[x] * signal[x]); } frameDC /= frameSize; average[i] = total / frameSize; envelope[i] = maxValue; frameEnergy[i] = energy / frameSize; // remove DC value from signal values double[] signalMinusAv = new double[frameSize]; for (int j = 0; j < frameSize; j++) signalMinusAv[j] = signal[start + j] - frameDC; // generate the spectra of FFT AMPLITUDES - NOTE: f[0]=DC; f[64]=Nyquist var f1 = fft.InvokeDotNetFFT(signalMinusAv); // the fft ////f1 = fft.InvokeDotNetFFT(DataTools.GetRow(frames, i)); //returns fft amplitude spectrum ////f1 = fft.Invoke(DataTools.GetRow(frames, i)); //returns fft amplitude spectrum f1 = DataTools.filterMovingAverage(f1, 3); //smooth spectrum to reduce variance for (int j = 0; j < fft.CoeffCount; j++) //foreach freq bin spectrogram[i, j] = f1[j]; //transfer amplitude } // end frames // check the envelope for clipping. Accept a clip if two consecutive frames have max value = 1,0 int maxAmplitudeCount, clipCount; Clipping.GetClippingCount(signal, envelope, frameStep, epsilon, out maxAmplitudeCount, out clipCount); // Remove the DC column ie column zero from amplitude spectrogram. double[,] amplSpectrogram = MatrixTools.Submatrix(spectrogram, 0, 1, spectrogram.GetLength(0) - 1, spectrogram.GetLength(1) - 1); int nyquistFreq = sampleRate / 2; double binWidth = nyquistFreq / (double)amplSpectrogram.GetLength(1); int nyquistBin = amplSpectrogram.GetLength(1) - 1; return new EnvelopeAndFft { MinSignalValue = minSignalValue, MaxSignalValue = maxSignalValue, Average = average, Envelope = envelope, FrameEnergy = frameEnergy, MaxAmplitudeCount = maxAmplitudeCount, ClipCount = clipCount, AmplitudeSpectrogram = amplSpectrogram, WindowPower = fft.WindowPower, NyquistFreq = nyquistFreq, FreqBinWidth = binWidth, NyquistBin = nyquistBin }; } */ public static Tuple<double[], double[], double[], double[], double[]> ExtractEnvelopeAndZeroCrossings(double[] signal, int sr, int windowSize, double overlap) { int length = signal.Length; int frameOffset = (int)(windowSize * (1 - overlap)); int frameCount = (length - windowSize + frameOffset) / frameOffset; double[] average = new double[frameCount]; double[] envelope = new double[frameCount]; // count of zero crossings double[] zeroCrossings = new double[frameCount]; // sample count between zero crossings double[] zcPeriod = new double[frameCount]; double[] sdPeriod = new double[frameCount]; // standard deviation of sample count between zc. for (int i = 0; i < frameCount; i++) { List<int> periodList = new List<int>(); int start = i * frameOffset; int end = start + windowSize; //get average and envelope double maxValue = -double.MaxValue; double total = signal[start]; for (int x = start + 1; x < end; x++) { total += signal[x]; // go through current frame to get signal average/DC double absValue = Math.Abs(signal[x]); if (absValue > maxValue) { maxValue = absValue; } } average[i] = total / windowSize; envelope[i] = maxValue; //remove the average from signal double[] signalMinusAv = new double[windowSize]; for (int j = 0; j < windowSize; j++) { signalMinusAv[j] = signal[start + j] - average[i]; } //get zero crossings and periods int zeroCrossingCount = 0; int prevLocation = 0; double prevValue = signalMinusAv[0]; // go through current frame for (int j = 1; j < windowSize; j++) { //double absValue = Math.Abs(signalMinusAv[j]); // if zero crossing if (signalMinusAv[j] * prevValue < 0.0) { if (zeroCrossingCount > 0) { periodList.Add(j - prevLocation); // do not want to accumulate counts prior to first ZC. } zeroCrossingCount++; // count zero crossings prevLocation = j; prevValue = signalMinusAv[j]; } } // end current frame zeroCrossings[i] = zeroCrossingCount; int[] periods = periodList.ToArray(); double av; double sd; NormalDist.AverageAndSD(periods, out av, out sd); zcPeriod[i] = av; sdPeriod[i] = sd; } return Tuple.Create(average, envelope, zeroCrossings, zcPeriod, sdPeriod); } public static int[] ConvertZeroCrossings2Hz(double[] zeroCrossings, int frameWidth, int sampleRate) { int length = zeroCrossings.Length; var freq = new int[length]; for (int i = 0; i < length; i++) { freq[i] = (int)(zeroCrossings[i] * sampleRate / 2 / frameWidth); } return freq; } public static double[] ConvertSamples2Milliseconds(double[] sampleCounts, int sampleRate) { var tValues = new double[sampleCounts.Length]; for (int i = 0; i < sampleCounts.Length; i++) { tValues[i] = sampleCounts[i] * 1000 / sampleRate; } return tValues; } /// <summary> /// returns the min and max values in each frame. Signal values range from -1 to +1. /// </summary> public static void SignalEnvelope(double[,] frames, out double[] minAmp, out double[] maxAmp) { int frameCount = frames.GetLength(0); int n = frames.GetLength(1); minAmp = new double[frameCount]; maxAmp = new double[frameCount]; for (int i = 0; i < frameCount; i++) { double min = double.MaxValue; double max = -double.MaxValue; // foreach sample in frame for (int j = 0; j < n; j++) { if (min > frames[i, j]) { min = frames[i, j]; } else if (max < frames[i, j]) { max = frames[i, j]; } } minAmp[i] = min; maxAmp[i] = max; } } /// <summary> /// counts the zero crossings in each frame /// This info is used for determing the begin and end points for vocalisations. /// </summary> public static int[] ZeroCrossings(double[,] frames) { int frameCount = frames.GetLength(0); int n = frames.GetLength(1); int[] zc = new int[frameCount]; for (int i = 0; i < frameCount; i++) { int count = 0; for (int j = 1; j < n; j++) { count += Math.Abs(Math.Sign(frames[i, j]) - Math.Sign(frames[i, j - 1])); } zc[i] = count / 2; } return zc; } public static void DisplaySignal(double[] sig) { double[] newSig = DataTools.normalise(sig); foreach (double value in newSig) { int count = (int)(value * 50); for (int i = 0; i < count; i++) { LoggedConsole.Write("="); } LoggedConsole.WriteLine("="); } } public static void DisplaySignal(double[] sig, bool showIndex) { double[] newSig = DataTools.normalise(sig); for (int n = 0; n < sig.Length; n++) { if (showIndex) { LoggedConsole.Write(n.ToString("D3") + "|"); } int count = (int)(newSig[n] * 50); for (int i = 0; i < count; i++) { LoggedConsole.Write("="); } LoggedConsole.WriteLine("="); } } }//end class DSP }
40.35605
184
0.521299
[ "Apache-2.0" ]
stewartmacdonald/audio-analysis
src/AudioAnalysisTools/DSP/DSP_Frames.cs
29,018
C#
using Abp.Domain.Entities; using Abp.Domain.Repositories; using Abp.EntityFrameworkCore; using Abp.EntityFrameworkCore.Repositories; namespace Vertical.EntityFrameworkCore.Repositories { /// <summary> /// Base class for custom repositories of the application. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <typeparam name="TPrimaryKey">Primary key type of the entity</typeparam> public abstract class VerticalZeroRepositoryBase<TEntity, TPrimaryKey> : EfCoreRepositoryBase<VerticalZeroDbContext, TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> { protected VerticalZeroRepositoryBase(IDbContextProvider<VerticalZeroDbContext> dbContextProvider) : base(dbContextProvider) { } // Add your common methods for all repositories } /// <summary> /// Base class for custom repositories of the application. /// This is a shortcut of <see cref="VerticalZeroRepositoryBase{TEntity,TPrimaryKey}"/> for <see cref="int"/> primary key. /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> public abstract class VerticalSharedModuleRepositoryBase<TEntity> : VerticalZeroRepositoryBase<TEntity, int>, IRepository<TEntity> where TEntity : class, IEntity<int> { protected VerticalSharedModuleRepositoryBase(IDbContextProvider<VerticalZeroDbContext> dbContextProvider) : base(dbContextProvider) { } // Do not add any method here, add to the class above (since this inherits it)!!! } }
39.95
142
0.710263
[ "MIT" ]
Networked-Community/Vertical
aspnet-core/src/Vertical.Zero/EntityFrameworkCore/Repositories/VerticalZeroRepositoryBase.cs
1,600
C#
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Security.Permissions; namespace MSMQ.Messaging { /// <include file='..\..\doc\MessagingDescriptionAttribute.uex' path='docs/doc[@for="MessagingDescriptionAttribute"]/*' /> /// <devdoc> /// DescriptionAttribute marks a property, event, or extender with a /// description. Visual designers can display this description when referencing /// the member. /// </devdoc> [AttributeUsage(AttributeTargets.All)] [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")] public class MessagingDescriptionAttribute : DescriptionAttribute { private bool replaced = false; /// <include file='..\..\doc\MessagingDescriptionAttribute.uex' path='docs/doc[@for="MessagingDescriptionAttribute.MessagingDescriptionAttribute"]/*' /> /// <devdoc> /// Constructs a new sys description. /// </devdoc> public MessagingDescriptionAttribute(string description) : base(description) { } /// <include file='..\..\doc\MessagingDescriptionAttribute.uex' path='docs/doc[@for="MessagingDescriptionAttribute.Description"]/*' /> /// <devdoc> /// Retrieves the description text. /// </devdoc> public override string Description { [HostProtection(SharedState = true)] // DescriptionAttribute uses SharedState=true. We should not change base's behavior get { if (!replaced) { replaced = true; DescriptionValue = Res.GetString(base.Description); } return base.Description; } } } }
33.574074
160
0.615003
[ "MIT" ]
kwende/MSMQ.Messaging
src/Messaging/MessagingDescriptionAttribute.cs
1,813
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FreeCourse.Web.Models.Orders { public class OrderItemCreateInput { public string ProductId { get; set; } public string ProductName { get; set; } public string PictureUrl { get; set; } public Decimal Price { get; set; } } }
25
47
0.674667
[ "MIT" ]
ardansisman/MicroserviceWorkshop
Frontends/FreeCourse.Web/Models/Orders/OrderItemCreateInput.cs
377
C#
using System; using System.Collections.Generic; using System.Text; using System.Reflection; /// <summary> /// This class has a dictionary property that will return the name of the field and the object associated with it. It uses reflection to get the name and object. /// </summary> namespace simple_sia_library.Classes.Helper { public class PropertyReflector { public Dictionary<string, object> ReturnValue {get; set;} private string name; private object inputed_object; public PropertyReflector(object subject) { Type reflect = subject.GetType(); PropertyInfo[] ListAll = (PropertyInfo[])reflect.GetRuntimeProperties(); foreach (PropertyInfo pi in ListAll) { name = pi.Name; inputed_object = pi.GetValue(pi, null); ReturnValue.Add(name, inputed_object); } } } }
33.357143
162
0.637045
[ "MIT" ]
kiljoy001/simple_sia
Sia Library/Classes/Helper/PropertyReflector.cs
936
C#
using System; using System.IO; namespace GVFS.Common.NamedPipes { public class BrokenPipeException : Exception { public BrokenPipeException(string message, IOException innerException) : base(message, innerException) { } } }
20.5
79
0.627178
[ "MIT" ]
50Wliu/VFSForGit
GVFS/GVFS.Common/NamedPipes/BrokenPipeException.cs
289
C#
using System; namespace Actuarial.Shared.Domain { public class Person { public string Name { get; set; } public DateTime BirthDate { get; set; } public Gender Gender { get; set; } } }
20
47
0.604545
[ "MIT" ]
nielskeizer/Actuarial
src/Actuarial/Shared/Domain/Person.cs
220
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //+---------------------------------------------------------------------------- // // Microsoft Windows // File: ISponsor.cool // // Contents: Interface for Sponsors // // History: 1/5/00 pdejong Created // //+---------------------------------------------------------------------------- namespace System.Runtime.Remoting.Lifetime { using System; using System.Security.Permissions; /// <include file='doc\ISponsor.uex' path='docs/doc[@for="ISponsor"]/*' /> public interface ISponsor { /// <include file='doc\ISponsor.uex' path='docs/doc[@for="ISponsor.Renewal"]/*' /> [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)] TimeSpan Renewal(ILease lease); } }
29.633333
111
0.509561
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/clr/bcl/system/runtime/remoting/isponsor.cs
889
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-email-2018-07-26.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.PinpointEmail.Model; namespace Amazon.PinpointEmail { /// <summary> /// Interface for accessing PinpointEmail /// /// Amazon Pinpoint Email Service /// <para> /// Welcome to the <i>Amazon Pinpoint Email API Reference</i>. This guide provides information /// about the Amazon Pinpoint Email API (version 1.0), including supported operations, /// data types, parameters, and schemas. /// </para> /// /// <para> /// <a href="https://aws.amazon.com/pinpoint">Amazon Pinpoint</a> is an AWS service that /// you can use to engage with your customers across multiple messaging channels. You /// can use Amazon Pinpoint to send email, SMS text messages, voice messages, and push /// notifications. The Amazon Pinpoint Email API provides programmatic access to options /// that are unique to the email channel and supplement the options provided by the Amazon /// Pinpoint API. /// </para> /// /// <para> /// If you're new to Amazon Pinpoint, you might find it helpful to also review the <a /// href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/welcome.html">Amazon /// Pinpoint Developer Guide</a>. The <i>Amazon Pinpoint Developer Guide</i> provides /// tutorials, code samples, and procedures that demonstrate how to use Amazon Pinpoint /// features programmatically and how to integrate Amazon Pinpoint functionality into /// mobile apps and other types of applications. The guide also provides information about /// key topics such as Amazon Pinpoint integration with other AWS services and the limits /// that apply to using the service. /// </para> /// /// <para> /// The Amazon Pinpoint Email API is available in several AWS Regions and it provides /// an endpoint for each of these Regions. For a list of all the Regions and endpoints /// where the API is currently available, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html#pinpoint_region">AWS /// Service Endpoints</a> in the <i>Amazon Web Services General Reference</i>. To learn /// more about AWS Regions, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande-manage.html">Managing /// AWS Regions</a> in the <i>Amazon Web Services General Reference</i>. /// </para> /// /// <para> /// In each Region, AWS maintains multiple Availability Zones. These Availability Zones /// are physically isolated from each other, but are united by private, low-latency, high-throughput, /// and highly redundant network connections. These Availability Zones enable us to provide /// very high levels of availability and redundancy, while also minimizing latency. To /// learn more about the number of Availability Zones that are available in each Region, /// see <a href="http://aws.amazon.com/about-aws/global-infrastructure/">AWS Global Infrastructure</a>. /// </para> /// </summary> public partial interface IAmazonPinpointEmail : IAmazonService, IDisposable { #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Paginators for the service /// </summary> IPinpointEmailPaginatorFactory Paginators { get; } #endif #region CreateConfigurationSet /// <summary> /// Create a configuration set. <i>Configuration sets</i> are groups of rules that you /// can apply to the emails you send using Amazon Pinpoint. You apply a configuration /// set to an email by including a reference to the configuration set in the headers of /// the email. When you apply a configuration set to an email, all of the rules in that /// configuration set are applied to the email. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateConfigurationSet service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateConfigurationSet service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AlreadyExistsException"> /// The resource specified in your request already exists. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/CreateConfigurationSet">REST API Reference for CreateConfigurationSet Operation</seealso> Task<CreateConfigurationSetResponse> CreateConfigurationSetAsync(CreateConfigurationSetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateConfigurationSetEventDestination /// <summary> /// Create an event destination. In Amazon Pinpoint, <i>events</i> include message sends, /// deliveries, opens, clicks, bounces, and complaints. <i>Event destinations</i> are /// places that you can send information about these events to. For example, you can send /// event data to Amazon SNS to receive notifications when you receive bounces or complaints, /// or you can use Amazon Kinesis Data Firehose to stream data to Amazon S3 for long-term /// storage. /// /// /// <para> /// A single configuration set can include more than one event destination. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateConfigurationSetEventDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateConfigurationSetEventDestination service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AlreadyExistsException"> /// The resource specified in your request already exists. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/CreateConfigurationSetEventDestination">REST API Reference for CreateConfigurationSetEventDestination Operation</seealso> Task<CreateConfigurationSetEventDestinationResponse> CreateConfigurationSetEventDestinationAsync(CreateConfigurationSetEventDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateDedicatedIpPool /// <summary> /// Create a new pool of dedicated IP addresses. A pool can include one or more dedicated /// IP addresses that are associated with your Amazon Pinpoint account. You can associate /// a pool with a configuration set. When you send an email that uses that configuration /// set, Amazon Pinpoint sends it using only the IP addresses in the associated pool. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDedicatedIpPool service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateDedicatedIpPool service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AlreadyExistsException"> /// The resource specified in your request already exists. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/CreateDedicatedIpPool">REST API Reference for CreateDedicatedIpPool Operation</seealso> Task<CreateDedicatedIpPoolResponse> CreateDedicatedIpPoolAsync(CreateDedicatedIpPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateDeliverabilityTestReport /// <summary> /// Create a new predictive inbox placement test. Predictive inbox placement tests can /// help you predict how your messages will be handled by various email providers around /// the world. When you perform a predictive inbox placement test, you provide a sample /// message that contains the content that you plan to send to your customers. Amazon /// Pinpoint then sends that message to special email addresses spread across several /// major email providers. After about 24 hours, the test is complete, and you can use /// the <code>GetDeliverabilityTestReport</code> operation to view the results of the /// test. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDeliverabilityTestReport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateDeliverabilityTestReport service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AccountSuspendedException"> /// The message can't be sent because the account's ability to send email has been permanently /// restricted. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.MailFromDomainNotVerifiedException"> /// The message can't be sent because the sending domain isn't verified. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.MessageRejectedException"> /// The message can't be sent because it contains invalid content. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.SendingPausedException"> /// The message can't be sent because the account's ability to send email is currently /// paused. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/CreateDeliverabilityTestReport">REST API Reference for CreateDeliverabilityTestReport Operation</seealso> Task<CreateDeliverabilityTestReportResponse> CreateDeliverabilityTestReportAsync(CreateDeliverabilityTestReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateEmailIdentity /// <summary> /// Verifies an email identity for use with Amazon Pinpoint. In Amazon Pinpoint, an identity /// is an email address or domain that you use when you send email. Before you can use /// an identity to send email with Amazon Pinpoint, you first have to verify it. By verifying /// an address, you demonstrate that you're the owner of the address, and that you've /// given Amazon Pinpoint permission to send email from the address. /// /// /// <para> /// When you verify an email address, Amazon Pinpoint sends an email to the address. Your /// email address is verified as soon as you follow the link in the verification email. /// /// </para> /// /// <para> /// When you verify a domain, this operation provides a set of DKIM tokens, which you /// can convert into CNAME tokens. You add these CNAME tokens to the DNS configuration /// for your domain. Your domain is verified when Amazon Pinpoint detects these records /// in the DNS configuration for your domain. It usually takes around 72 hours to complete /// the domain verification process. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateEmailIdentity service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateEmailIdentity service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/CreateEmailIdentity">REST API Reference for CreateEmailIdentity Operation</seealso> Task<CreateEmailIdentityResponse> CreateEmailIdentityAsync(CreateEmailIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteConfigurationSet /// <summary> /// Delete an existing configuration set. /// /// /// <para> /// In Amazon Pinpoint, <i>configuration sets</i> are groups of rules that you can apply /// to the emails you send. You apply a configuration set to an email by including a reference /// to the configuration set in the headers of the email. When you apply a configuration /// set to an email, all of the rules in that configuration set are applied to the email. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationSet service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteConfigurationSet service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/DeleteConfigurationSet">REST API Reference for DeleteConfigurationSet Operation</seealso> Task<DeleteConfigurationSetResponse> DeleteConfigurationSetAsync(DeleteConfigurationSetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteConfigurationSetEventDestination /// <summary> /// Delete an event destination. /// /// /// <para> /// In Amazon Pinpoint, <i>events</i> include message sends, deliveries, opens, clicks, /// bounces, and complaints. <i>Event destinations</i> are places that you can send information /// about these events to. For example, you can send event data to Amazon SNS to receive /// notifications when you receive bounces or complaints, or you can use Amazon Kinesis /// Data Firehose to stream data to Amazon S3 for long-term storage. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConfigurationSetEventDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteConfigurationSetEventDestination service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/DeleteConfigurationSetEventDestination">REST API Reference for DeleteConfigurationSetEventDestination Operation</seealso> Task<DeleteConfigurationSetEventDestinationResponse> DeleteConfigurationSetEventDestinationAsync(DeleteConfigurationSetEventDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteDedicatedIpPool /// <summary> /// Delete a dedicated IP pool. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDedicatedIpPool service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteDedicatedIpPool service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/DeleteDedicatedIpPool">REST API Reference for DeleteDedicatedIpPool Operation</seealso> Task<DeleteDedicatedIpPoolResponse> DeleteDedicatedIpPoolAsync(DeleteDedicatedIpPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteEmailIdentity /// <summary> /// Deletes an email identity that you previously verified for use with Amazon Pinpoint. /// An identity can be either an email address or a domain name. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteEmailIdentity service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteEmailIdentity service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/DeleteEmailIdentity">REST API Reference for DeleteEmailIdentity Operation</seealso> Task<DeleteEmailIdentityResponse> DeleteEmailIdentityAsync(DeleteEmailIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetAccount /// <summary> /// Obtain information about the email-sending status and capabilities of your Amazon /// Pinpoint account in the current AWS Region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAccount service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetAccount service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetAccount">REST API Reference for GetAccount Operation</seealso> Task<GetAccountResponse> GetAccountAsync(GetAccountRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetBlacklistReports /// <summary> /// Retrieve a list of the blacklists that your dedicated IP addresses appear on. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBlacklistReports service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetBlacklistReports service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetBlacklistReports">REST API Reference for GetBlacklistReports Operation</seealso> Task<GetBlacklistReportsResponse> GetBlacklistReportsAsync(GetBlacklistReportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetConfigurationSet /// <summary> /// Get information about an existing configuration set, including the dedicated IP pool /// that it's associated with, whether or not it's enabled for sending email, and more. /// /// /// <para> /// In Amazon Pinpoint, <i>configuration sets</i> are groups of rules that you can apply /// to the emails you send. You apply a configuration set to an email by including a reference /// to the configuration set in the headers of the email. When you apply a configuration /// set to an email, all of the rules in that configuration set are applied to the email. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetConfigurationSet service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetConfigurationSet service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetConfigurationSet">REST API Reference for GetConfigurationSet Operation</seealso> Task<GetConfigurationSetResponse> GetConfigurationSetAsync(GetConfigurationSetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetConfigurationSetEventDestinations /// <summary> /// Retrieve a list of event destinations that are associated with a configuration set. /// /// /// <para> /// In Amazon Pinpoint, <i>events</i> include message sends, deliveries, opens, clicks, /// bounces, and complaints. <i>Event destinations</i> are places that you can send information /// about these events to. For example, you can send event data to Amazon SNS to receive /// notifications when you receive bounces or complaints, or you can use Amazon Kinesis /// Data Firehose to stream data to Amazon S3 for long-term storage. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetConfigurationSetEventDestinations service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetConfigurationSetEventDestinations service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetConfigurationSetEventDestinations">REST API Reference for GetConfigurationSetEventDestinations Operation</seealso> Task<GetConfigurationSetEventDestinationsResponse> GetConfigurationSetEventDestinationsAsync(GetConfigurationSetEventDestinationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDedicatedIp /// <summary> /// Get information about a dedicated IP address, including the name of the dedicated /// IP pool that it's associated with, as well information about the automatic warm-up /// process for the address. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDedicatedIp service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDedicatedIp service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDedicatedIp">REST API Reference for GetDedicatedIp Operation</seealso> Task<GetDedicatedIpResponse> GetDedicatedIpAsync(GetDedicatedIpRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDedicatedIps /// <summary> /// List the dedicated IP addresses that are associated with your Amazon Pinpoint account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDedicatedIps service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDedicatedIps service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDedicatedIps">REST API Reference for GetDedicatedIps Operation</seealso> Task<GetDedicatedIpsResponse> GetDedicatedIpsAsync(GetDedicatedIpsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDeliverabilityDashboardOptions /// <summary> /// Retrieve information about the status of the Deliverability dashboard for your Amazon /// Pinpoint account. When the Deliverability dashboard is enabled, you gain access to /// reputation, deliverability, and other metrics for the domains that you use to send /// email using Amazon Pinpoint. You also gain the ability to perform predictive inbox /// placement tests. /// /// /// <para> /// When you use the Deliverability dashboard, you pay a monthly subscription charge, /// in addition to any other fees that you accrue by using Amazon Pinpoint. For more information /// about the features and cost of a Deliverability dashboard subscription, see <a href="http://aws.amazon.com/pinpoint/pricing/">Amazon /// Pinpoint Pricing</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDeliverabilityDashboardOptions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDeliverabilityDashboardOptions service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDeliverabilityDashboardOptions">REST API Reference for GetDeliverabilityDashboardOptions Operation</seealso> Task<GetDeliverabilityDashboardOptionsResponse> GetDeliverabilityDashboardOptionsAsync(GetDeliverabilityDashboardOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDeliverabilityTestReport /// <summary> /// Retrieve the results of a predictive inbox placement test. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDeliverabilityTestReport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDeliverabilityTestReport service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDeliverabilityTestReport">REST API Reference for GetDeliverabilityTestReport Operation</seealso> Task<GetDeliverabilityTestReportResponse> GetDeliverabilityTestReportAsync(GetDeliverabilityTestReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDomainDeliverabilityCampaign /// <summary> /// Retrieve all the deliverability data for a specific campaign. This data is available /// for a campaign only if the campaign sent email by using a domain that the Deliverability /// dashboard is enabled for (<code>PutDeliverabilityDashboardOption</code> operation). /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDomainDeliverabilityCampaign service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDomainDeliverabilityCampaign service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDomainDeliverabilityCampaign">REST API Reference for GetDomainDeliverabilityCampaign Operation</seealso> Task<GetDomainDeliverabilityCampaignResponse> GetDomainDeliverabilityCampaignAsync(GetDomainDeliverabilityCampaignRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDomainStatisticsReport /// <summary> /// Retrieve inbox placement and engagement rates for the domains that you use to send /// email. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDomainStatisticsReport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDomainStatisticsReport service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetDomainStatisticsReport">REST API Reference for GetDomainStatisticsReport Operation</seealso> Task<GetDomainStatisticsReportResponse> GetDomainStatisticsReportAsync(GetDomainStatisticsReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEmailIdentity /// <summary> /// Provides information about a specific identity associated with your Amazon Pinpoint /// account, including the identity's verification status, its DKIM authentication status, /// and its custom Mail-From settings. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetEmailIdentity service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetEmailIdentity service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/GetEmailIdentity">REST API Reference for GetEmailIdentity Operation</seealso> Task<GetEmailIdentityResponse> GetEmailIdentityAsync(GetEmailIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListConfigurationSets /// <summary> /// List all of the configuration sets associated with your Amazon Pinpoint account in /// the current region. /// /// /// <para> /// In Amazon Pinpoint, <i>configuration sets</i> are groups of rules that you can apply /// to the emails you send. You apply a configuration set to an email by including a reference /// to the configuration set in the headers of the email. When you apply a configuration /// set to an email, all of the rules in that configuration set are applied to the email. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListConfigurationSets service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListConfigurationSets service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListConfigurationSets">REST API Reference for ListConfigurationSets Operation</seealso> Task<ListConfigurationSetsResponse> ListConfigurationSetsAsync(ListConfigurationSetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDedicatedIpPools /// <summary> /// List all of the dedicated IP pools that exist in your Amazon Pinpoint account in the /// current AWS Region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDedicatedIpPools service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDedicatedIpPools service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListDedicatedIpPools">REST API Reference for ListDedicatedIpPools Operation</seealso> Task<ListDedicatedIpPoolsResponse> ListDedicatedIpPoolsAsync(ListDedicatedIpPoolsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDeliverabilityTestReports /// <summary> /// Show a list of the predictive inbox placement tests that you've performed, regardless /// of their statuses. For predictive inbox placement tests that are complete, you can /// use the <code>GetDeliverabilityTestReport</code> operation to view the results. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDeliverabilityTestReports service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDeliverabilityTestReports service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListDeliverabilityTestReports">REST API Reference for ListDeliverabilityTestReports Operation</seealso> Task<ListDeliverabilityTestReportsResponse> ListDeliverabilityTestReportsAsync(ListDeliverabilityTestReportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDomainDeliverabilityCampaigns /// <summary> /// Retrieve deliverability data for all the campaigns that used a specific domain to /// send email during a specified time range. This data is available for a domain only /// if you enabled the Deliverability dashboard (<code>PutDeliverabilityDashboardOption</code> /// operation) for the domain. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDomainDeliverabilityCampaigns service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDomainDeliverabilityCampaigns service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListDomainDeliverabilityCampaigns">REST API Reference for ListDomainDeliverabilityCampaigns Operation</seealso> Task<ListDomainDeliverabilityCampaignsResponse> ListDomainDeliverabilityCampaignsAsync(ListDomainDeliverabilityCampaignsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListEmailIdentities /// <summary> /// Returns a list of all of the email identities that are associated with your Amazon /// Pinpoint account. An identity can be either an email address or a domain. This operation /// returns identities that are verified as well as those that aren't. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListEmailIdentities service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListEmailIdentities service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListEmailIdentities">REST API Reference for ListEmailIdentities Operation</seealso> Task<ListEmailIdentitiesResponse> ListEmailIdentitiesAsync(ListEmailIdentitiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTagsForResource /// <summary> /// Retrieve a list of the tags (keys and values) that are associated with a specified /// resource. A <i>tag</i> is a label that you optionally define and associate with a /// resource in Amazon Pinpoint. Each tag consists of a required <i>tag key</i> and an /// optional associated <i>tag value</i>. A tag key is a general label that acts as a /// category for more specific tag values. A tag value acts as a descriptor within a tag /// key. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsForResource service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutAccountDedicatedIpWarmupAttributes /// <summary> /// Enable or disable the automatic warm-up feature for dedicated IP addresses. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutAccountDedicatedIpWarmupAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutAccountDedicatedIpWarmupAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutAccountDedicatedIpWarmupAttributes">REST API Reference for PutAccountDedicatedIpWarmupAttributes Operation</seealso> Task<PutAccountDedicatedIpWarmupAttributesResponse> PutAccountDedicatedIpWarmupAttributesAsync(PutAccountDedicatedIpWarmupAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutAccountSendingAttributes /// <summary> /// Enable or disable the ability of your account to send email. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutAccountSendingAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutAccountSendingAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutAccountSendingAttributes">REST API Reference for PutAccountSendingAttributes Operation</seealso> Task<PutAccountSendingAttributesResponse> PutAccountSendingAttributesAsync(PutAccountSendingAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutConfigurationSetDeliveryOptions /// <summary> /// Associate a configuration set with a dedicated IP pool. You can use dedicated IP pools /// to create groups of dedicated IP addresses for sending specific types of email. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationSetDeliveryOptions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutConfigurationSetDeliveryOptions service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutConfigurationSetDeliveryOptions">REST API Reference for PutConfigurationSetDeliveryOptions Operation</seealso> Task<PutConfigurationSetDeliveryOptionsResponse> PutConfigurationSetDeliveryOptionsAsync(PutConfigurationSetDeliveryOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutConfigurationSetReputationOptions /// <summary> /// Enable or disable collection of reputation metrics for emails that you send using /// a particular configuration set in a specific AWS Region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationSetReputationOptions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutConfigurationSetReputationOptions service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutConfigurationSetReputationOptions">REST API Reference for PutConfigurationSetReputationOptions Operation</seealso> Task<PutConfigurationSetReputationOptionsResponse> PutConfigurationSetReputationOptionsAsync(PutConfigurationSetReputationOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutConfigurationSetSendingOptions /// <summary> /// Enable or disable email sending for messages that use a particular configuration set /// in a specific AWS Region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationSetSendingOptions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutConfigurationSetSendingOptions service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutConfigurationSetSendingOptions">REST API Reference for PutConfigurationSetSendingOptions Operation</seealso> Task<PutConfigurationSetSendingOptionsResponse> PutConfigurationSetSendingOptionsAsync(PutConfigurationSetSendingOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutConfigurationSetTrackingOptions /// <summary> /// Specify a custom domain to use for open and click tracking elements in email that /// you send using Amazon Pinpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutConfigurationSetTrackingOptions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutConfigurationSetTrackingOptions service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutConfigurationSetTrackingOptions">REST API Reference for PutConfigurationSetTrackingOptions Operation</seealso> Task<PutConfigurationSetTrackingOptionsResponse> PutConfigurationSetTrackingOptionsAsync(PutConfigurationSetTrackingOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDedicatedIpInPool /// <summary> /// Move a dedicated IP address to an existing dedicated IP pool. /// /// <note> /// <para> /// The dedicated IP address that you specify must already exist, and must be associated /// with your Amazon Pinpoint account. /// </para> /// /// <para> /// The dedicated IP pool you specify must already exist. You can create a new pool by /// using the <code>CreateDedicatedIpPool</code> operation. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutDedicatedIpInPool service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutDedicatedIpInPool service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutDedicatedIpInPool">REST API Reference for PutDedicatedIpInPool Operation</seealso> Task<PutDedicatedIpInPoolResponse> PutDedicatedIpInPoolAsync(PutDedicatedIpInPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDedicatedIpWarmupAttributes /// <summary> /// /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutDedicatedIpWarmupAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutDedicatedIpWarmupAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutDedicatedIpWarmupAttributes">REST API Reference for PutDedicatedIpWarmupAttributes Operation</seealso> Task<PutDedicatedIpWarmupAttributesResponse> PutDedicatedIpWarmupAttributesAsync(PutDedicatedIpWarmupAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDeliverabilityDashboardOption /// <summary> /// Enable or disable the Deliverability dashboard for your Amazon Pinpoint account. When /// you enable the Deliverability dashboard, you gain access to reputation, deliverability, /// and other metrics for the domains that you use to send email using Amazon Pinpoint. /// You also gain the ability to perform predictive inbox placement tests. /// /// /// <para> /// When you use the Deliverability dashboard, you pay a monthly subscription charge, /// in addition to any other fees that you accrue by using Amazon Pinpoint. For more information /// about the features and cost of a Deliverability dashboard subscription, see <a href="http://aws.amazon.com/pinpoint/pricing/">Amazon /// Pinpoint Pricing</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutDeliverabilityDashboardOption service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutDeliverabilityDashboardOption service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AlreadyExistsException"> /// The resource specified in your request already exists. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutDeliverabilityDashboardOption">REST API Reference for PutDeliverabilityDashboardOption Operation</seealso> Task<PutDeliverabilityDashboardOptionResponse> PutDeliverabilityDashboardOptionAsync(PutDeliverabilityDashboardOptionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutEmailIdentityDkimAttributes /// <summary> /// Used to enable or disable DKIM authentication for an email identity. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutEmailIdentityDkimAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutEmailIdentityDkimAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutEmailIdentityDkimAttributes">REST API Reference for PutEmailIdentityDkimAttributes Operation</seealso> Task<PutEmailIdentityDkimAttributesResponse> PutEmailIdentityDkimAttributesAsync(PutEmailIdentityDkimAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutEmailIdentityFeedbackAttributes /// <summary> /// Used to enable or disable feedback forwarding for an identity. This setting determines /// what happens when an identity is used to send an email that results in a bounce or /// complaint event. /// /// /// <para> /// When you enable feedback forwarding, Amazon Pinpoint sends you email notifications /// when bounce or complaint events occur. Amazon Pinpoint sends this notification to /// the address that you specified in the Return-Path header of the original email. /// </para> /// /// <para> /// When you disable feedback forwarding, Amazon Pinpoint sends notifications through /// other mechanisms, such as by notifying an Amazon SNS topic. You're required to have /// a method of tracking bounces and complaints. If you haven't set up another mechanism /// for receiving bounce or complaint notifications, Amazon Pinpoint sends an email notification /// when these events occur (even if this setting is disabled). /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutEmailIdentityFeedbackAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutEmailIdentityFeedbackAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutEmailIdentityFeedbackAttributes">REST API Reference for PutEmailIdentityFeedbackAttributes Operation</seealso> Task<PutEmailIdentityFeedbackAttributesResponse> PutEmailIdentityFeedbackAttributesAsync(PutEmailIdentityFeedbackAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutEmailIdentityMailFromAttributes /// <summary> /// Used to enable or disable the custom Mail-From domain configuration for an email identity. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutEmailIdentityMailFromAttributes service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutEmailIdentityMailFromAttributes service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/PutEmailIdentityMailFromAttributes">REST API Reference for PutEmailIdentityMailFromAttributes Operation</seealso> Task<PutEmailIdentityMailFromAttributesResponse> PutEmailIdentityMailFromAttributesAsync(PutEmailIdentityMailFromAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendEmail /// <summary> /// Sends an email message. You can use the Amazon Pinpoint Email API to send two types /// of messages: /// /// <ul> <li> /// <para> /// <b>Simple</b> – A standard email message. When you create this type of message, you /// specify the sender, the recipient, and the message body, and Amazon Pinpoint assembles /// the message for you. /// </para> /// </li> <li> /// <para> /// <b>Raw</b> – A raw, MIME-formatted email message. When you send this type of email, /// you have to specify all of the message headers, as well as the message body. You can /// use this message type to send messages that contain attachments. The message that /// you specify has to be a valid MIME message. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the SendEmail service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the SendEmail service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.AccountSuspendedException"> /// The message can't be sent because the account's ability to send email has been permanently /// restricted. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.LimitExceededException"> /// There are too many instances of the specified resource type. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.MailFromDomainNotVerifiedException"> /// The message can't be sent because the sending domain isn't verified. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.MessageRejectedException"> /// The message can't be sent because it contains invalid content. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.SendingPausedException"> /// The message can't be sent because the account's ability to send email is currently /// paused. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/SendEmail">REST API Reference for SendEmail Operation</seealso> Task<SendEmailResponse> SendEmailAsync(SendEmailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TagResource /// <summary> /// Add one or more tags (keys and values) to a specified resource. A <i>tag</i> is a /// label that you optionally define and associate with a resource in Amazon Pinpoint. /// Tags can help you categorize and manage resources in different ways, such as by purpose, /// owner, environment, or other criteria. A resource can have as many as 50 tags. /// /// /// <para> /// Each tag consists of a required <i>tag key</i> and an associated <i>tag value</i>, /// both of which you define. A tag key is a general label that acts as a category for /// more specific tag values. A tag value acts as a descriptor within a tag key. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/TagResource">REST API Reference for TagResource Operation</seealso> Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UntagResource /// <summary> /// Remove one or more tags (keys and values) from a specified resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.ConcurrentModificationException"> /// The resource is being modified by another operation or thread. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/UntagResource">REST API Reference for UntagResource Operation</seealso> Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateConfigurationSetEventDestination /// <summary> /// Update the configuration of an event destination for a configuration set. /// /// /// <para> /// In Amazon Pinpoint, <i>events</i> include message sends, deliveries, opens, clicks, /// bounces, and complaints. <i>Event destinations</i> are places that you can send information /// about these events to. For example, you can send event data to Amazon SNS to receive /// notifications when you receive bounces or complaints, or you can use Amazon Kinesis /// Data Firehose to stream data to Amazon S3 for long-term storage. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateConfigurationSetEventDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateConfigurationSetEventDestination service method, as returned by PinpointEmail.</returns> /// <exception cref="Amazon.PinpointEmail.Model.BadRequestException"> /// The input you provided is invalid. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.NotFoundException"> /// The resource you attempted to access doesn't exist. /// </exception> /// <exception cref="Amazon.PinpointEmail.Model.TooManyRequestsException"> /// Too many requests have been made to the operation. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-email-2018-07-26/UpdateConfigurationSetEventDestination">REST API Reference for UpdateConfigurationSetEventDestination Operation</seealso> Task<UpdateConfigurationSetEventDestinationResponse> UpdateConfigurationSetEventDestinationAsync(UpdateConfigurationSetEventDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
57.679892
243
0.679189
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/PinpointEmail/Generated/_netstandard/IAmazonPinpointEmail.cs
85,783
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using BookClub.Models; using Microsoft.AspNetCore.Identity; namespace BookClub { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFrameworkMySql() .AddDbContext<BookClubContext>(options => options .UseMySql(Configuration["ConnectionStrings:DefaultConnection"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<BookClubContext>() .AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 0; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredUniqueChars = 0; }); } public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseDeveloperExceptionPage(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run(async (context) => { await context.Response.WriteAsync("Something went wrong!"); }); } } }
28.923077
73
0.680851
[ "Unlicense", "MIT" ]
KristaRutz/Week-12-Advanced-Databases-and-Authentication-Project
BookClub/Startup.cs
1,880
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.Oci.LoadBalancer.Inputs { public sealed class LoadBalancerIpAddressDetailReservedIpArgs : Pulumi.ResourceArgs { /// <summary> /// Ocid of the pre-created public IP. That should be attahed to this load balancer. /// </summary> [Input("id")] public Input<string>? Id { get; set; } public LoadBalancerIpAddressDetailReservedIpArgs() { } } }
28.769231
92
0.676471
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/LoadBalancer/Inputs/LoadBalancerIpAddressDetailReservedIpArgs.cs
748
C#
namespace CarsVelingrad.ViewModels { using System; using System.Collections.Generic; using System.Text; public class VehicleViewModel { public int Id { get; set; } public string Brand { get; set; } public decimal Price { get; set; } public string AdvertDate { get; set; } public int? Run { get; set; } public string Model { get; set; } public string City { get; set; } public string Color { get; set; } public string Engine { get; set; } public int VehicleTypeId { get; set; } public int ExtrasPackageId { get; set; } public List<string> Tags { get; set; } } }
19.857143
48
0.57554
[ "MIT" ]
Kalin1603/CarsVelingrad
CarsVelingrad/CarsVelingrad.ViewModels/VehicleViewModel.cs
697
C#
using System; namespace CarSalesman { public class Engine { public string Model { get; set; } public int Power { get; set; } public string Displacement { get; set; } public string Efficiency { get; set; } public Engine(string model, int power, string displacement = "n/a", string efficiency = "n/a") { Model = model; Power = power; Displacement = displacement; Efficiency = efficiency; } } }
24.333333
102
0.551859
[ "MIT" ]
bobo4aces/04.SoftUni-CSharpFundamentals
02. CSharp OOP Basics - 01. Defining Classes/Exercises/DefiningClassesExercises/10. Car Salesman/Engine.cs
513
C#
namespace Stealer { using System; public class StartUp { static void Main(string[] args) { var spy = new Spy(); var fieldsInfo = spy.StealFieldInfo("Hacker", "username", "password"); Console.WriteLine(fieldsInfo); var accessModifiersInfo = spy.AnalyzeAcessModifiers("Hacker"); Console.WriteLine(accessModifiersInfo); } } }
24.611111
83
0.555305
[ "MIT" ]
q2kPetrov/SoftUni
C# OOP/06_Reflection/Demo/1. Stealer/StartUp.cs
445
C#
namespace DedupEngine { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using VideoDedupShared.IVideoFileExtension; using VideoDedupShared.TimeSpanExtension; using IDedupEngineSettings = VideoDedupShared.IDedupEngineSettings; using IFolderSettings = VideoDedupShared.IFolderSettings; using OperationType = VideoDedupShared.OperationType; using ProgressStyle = VideoDedupShared.ProgressStyle; using ComparisonResult = VideoDedupShared.ComparisonResult; public class DedupEngine : IDisposable { private static readonly string LogCheckingFile = "Checking: {0} - Duration: {1}"; private static readonly string LogCompareFile = " against: {0}"; private static readonly string LogDeletedFile = "File deleted: {0}"; private static readonly string LogNewFile = "File created: {0}"; private string AppDataFolder { get; } private bool disposedValue; // For IDisposable private object DedupLock { get; } = new object { }; private Task DedupTask { get; set; } = null; private CancellationTokenSource CancelSource { get; set; } = new CancellationTokenSource { }; private FileSystemWatcher FileWatcher { get; } = new FileSystemWatcher { }; // ConcurrentDictionary is used as a hash set private ConcurrentDictionary<VideoFile, byte> NewFiles { get; set; } private ConcurrentDictionary<VideoFile, byte> DeletedFiles { get; set; } private EngineState CurrentState { get; set; } public event EventHandler<StoppedEventArgs> Stopped; protected virtual void OnStopped() => Stopped?.Invoke(this, new StoppedEventArgs { }); public event EventHandler<DuplicateFoundEventArgs> DuplicateFound; protected virtual void OnDuplicateFound( VideoFile file1, VideoFile file2) => DuplicateFound?.Invoke(this, new DuplicateFoundEventArgs { File1 = file1, File2 = file2, BasePath = CurrentState.Settings.BasePath, }); public event EventHandler<OperationUpdateEventArgs> OperationUpdate; private DateTime operationStartTime = DateTime.MinValue; protected virtual void OnOperationUpdate(OperationType type, int counter, int maxCount) => OperationUpdate?.Invoke(this, new OperationUpdateEventArgs { Type = type, Counter = counter, MaxCount = maxCount, Style = ProgressStyle.Continuous, StartTime = operationStartTime, }); protected virtual void OnOperationUpdate(OperationType type, ProgressStyle style) => OperationUpdate?.Invoke(this, new OperationUpdateEventArgs { Type = type, Counter = 0, MaxCount = 0, Style = style, StartTime = operationStartTime, }); public event EventHandler<LoggedEventArgs> Logged; protected virtual void OnLogged(string message) => Logged?.Invoke(this, new LoggedEventArgs { Message = message, }); public DedupEngine(string appDataFolder) { if (string.IsNullOrWhiteSpace(appDataFolder)) { throw new ArgumentException($"'{nameof(appDataFolder)}' cannot" + $"be null or whitespace", nameof(appDataFolder)); } AppDataFolder = appDataFolder; FileWatcher.Changed += HandleFileWatcherChangedEvent; FileWatcher.Deleted += HandleFileWatcherDeletedEvent; FileWatcher.Error += HandleFileWatcherErrorEvent; FileWatcher.Renamed += HandleFileWatcherRenamedEvent; FileWatcher.Created += HandleFileWatcherCreatedEvent; } public DedupEngine(string appDataFolder, IDedupEngineSettings settings) : this(appDataFolder) => UpdateConfiguration(settings); public void UpdateConfiguration(IDedupEngineSettings settings) { if (settings is null) { throw new ArgumentNullException(nameof(settings)); } Stop(); CurrentState = new EngineState(settings, AppDataFolder); } public void Start() { if (CurrentState.Settings == null) { throw new InvalidOperationException("Unable to start. " + "No configuration set."); } if (!Directory.Exists(CurrentState.Settings.BasePath)) { throw new InvalidOperationException("Unable to start. " + "Base path is not valid."); } if (DedupTask != null && !DedupTask.IsCompleted) { return; } FileWatcher.Path = CurrentState.Settings.BasePath; FileWatcher.IncludeSubdirectories = CurrentState.Settings.Recursive; FileWatcher.EnableRaisingEvents = CurrentState.Settings.MonitorChanges; if (NewFiles != null) { foreach (var kvp in NewFiles) { kvp.Key.Dispose(); } } NewFiles = new ConcurrentDictionary<VideoFile, byte> { }; if (DeletedFiles != null) { foreach (var kvp in DeletedFiles) { kvp.Key.Dispose(); } } DeletedFiles = new ConcurrentDictionary<VideoFile, byte> { }; lock (DedupLock) { DedupTask?.Dispose(); CancelSource = new CancellationTokenSource(); DedupTask = Task.Factory.StartNew( ProcessFolder, CancelSource.Token); } } public void Stop() { FileWatcher.EnableRaisingEvents = false; if (DedupTask == null || DedupTask.IsCompleted) { return; } CancelSource.Cancel(); try { DedupTask?.Wait(); } catch (AggregateException exc) { exc.Handle(x => x is OperationCanceledException); } CancelSource?.Dispose(); OnStopped(); } private void StartProcessingChanges() { lock (DedupLock) { // If the task is still running, // it will check for new files on it's own. if (!DedupTask.IsCompleted) { return; } DedupTask = Task.Factory.StartNew( ProcessChanges, CancelSource.Token); } } private void HandleFileWatcherDeletedEvent(object sender, FileSystemEventArgs e) { OnLogged($"{nameof(HandleFileWatcherDeletedEvent)} - {e.FullPath}"); HandleDeletedFileEvent(e.FullPath); } private void HandleFileWatcherChangedEvent(object sender, FileSystemEventArgs e) { OnLogged($"{nameof(HandleFileWatcherChangedEvent)} - {e.FullPath}"); HandleNewFileEvent(e.FullPath); } private void HandleFileWatcherCreatedEvent(object sender, FileSystemEventArgs e) { OnLogged($"{nameof(HandleFileWatcherCreatedEvent)} - {e.FullPath}"); HandleNewFileEvent(e.FullPath); } private void HandleFileWatcherRenamedEvent(object sender, RenamedEventArgs e) { OnLogged($"{nameof(HandleFileWatcherRenamedEvent)} - {e.FullPath} - {e.OldFullPath}"); HandleDeletedFileEvent(e.OldFullPath); HandleNewFileEvent(e.FullPath); } private void HandleFileWatcherErrorEvent(object sender, ErrorEventArgs e) => OnLogged("FileWatcher crashed! Unable to continue monitoring the source folder."); private bool IsFilePathRelevant(string filePath, IFolderSettings settings) { if (!filePath.StartsWith(settings.BasePath)) { OnLogged($"File not in source folder: {filePath}"); return false; } foreach (var excludedPath in settings.ExcludedDirectories) { if (filePath.StartsWith(excludedPath)) { OnLogged($"File is in excluded directory: {filePath}"); return false; } } var extension = Path.GetExtension(filePath); if (!settings.FileExtensions.Contains(extension)) { OnLogged($"File doesn't have proper file extension: {filePath}"); return false; } return true; } private void HandleDeletedFileEvent(string filePath) { if (!IsFilePathRelevant(filePath, CurrentState.Settings)) { return; } _ = DeletedFiles.TryAdd(new VideoFile(filePath), 0); OnLogged(string.Format(LogDeletedFile, filePath)); StartProcessingChanges(); } private void HandleNewFileEvent(string filePath) { if (!IsFilePathRelevant(filePath, CurrentState.Settings)) { return; } _ = NewFiles.TryAdd(new VideoFile(filePath), 0); OnLogged(string.Format(LogNewFile, filePath)); StartProcessingChanges(); } private static IEnumerable<string> GetAllAccessibleFilesIn( string rootDirectory, IEnumerable<string> excludedDirectories = null, bool recursive = true, string searchPattern = "*.*") { if (Path.GetFileName(rootDirectory) == "$RECYCLE.BIN") { return new List<string> { }; } IEnumerable<string> files = new List<string> { }; if (excludedDirectories == null) { excludedDirectories = new List<string> { }; } try { files = files.Concat(Directory.EnumerateFiles(rootDirectory, searchPattern, SearchOption.TopDirectoryOnly)); if (recursive) { foreach (var directory in Directory .GetDirectories(rootDirectory) .Where(d => !excludedDirectories.Contains(d, StringComparer.InvariantCultureIgnoreCase))) { files = files.Concat(GetAllAccessibleFilesIn(directory, excludedDirectories, recursive, searchPattern)); } } } catch (UnauthorizedAccessException) { // Don't do anything if we cannot access a file. } return files; } private IEnumerable<VideoFile> GetVideoFileList( IFolderSettings folderSettings) { operationStartTime = DateTime.Now; OnOperationUpdate(OperationType.Searching, ProgressStyle.Marquee); // Get all video files in source path. var foundFiles = GetAllAccessibleFilesIn( folderSettings.BasePath, folderSettings.ExcludedDirectories, folderSettings.Recursive) .Where(f => folderSettings.FileExtensions.Contains( Path.GetExtension(f), StringComparer.InvariantCultureIgnoreCase)) .Select(f => new VideoFile(f)) .ToList(); if (CurrentState.VideoFiles == null) { return foundFiles; } foreach (var file in foundFiles.Except(CurrentState.VideoFiles)) { NewFiles.TryAdd(file, 0); } foreach (var file in CurrentState.VideoFiles.Except(foundFiles)) { DeletedFiles.TryAdd(file, 0); } return CurrentState.VideoFiles; } private void PreloadFiles( IEnumerable<VideoFile> videoFiles, CancellationToken cancelToken) { var counter = 0; operationStartTime = DateTime.Now; OnOperationUpdate( OperationType.LoadingMedia, counter, videoFiles.Count()); foreach (var f in videoFiles) { OnOperationUpdate(OperationType.LoadingMedia, ++counter, videoFiles.Count()); // For now we only preload the duration // since the size is only rarely used // in the comparison dialog. No need // to preload it. _ = f.Duration; //var size = f.FileSize; if (cancelToken.IsCancellationRequested) { break; } } } private void FindDuplicates(EngineState state, CancellationToken cancelToken) { operationStartTime = DateTime.Now; OnOperationUpdate( OperationType.Comparing, 0, state.VideoFiles.Count()); var timer = Stopwatch.StartNew(); state.VideoFiles = state.VideoFiles .OrderBy(f => f.Duration) .ToList(); for (/*We continue at the current index*/; CurrentState.CurrentIndex < state.VideoFiles.Count() - 1; CurrentState.CurrentIndex++) { if (cancelToken.IsCancellationRequested) { return; } var file = state.VideoFiles[CurrentState.CurrentIndex]; OnLogged(string.Format(LogCheckingFile, file.FilePath, file.Duration.ToPrettyString())); OnOperationUpdate(OperationType.Comparing, CurrentState.CurrentIndex + 1, state.VideoFiles.Count()); foreach (var other in state.VideoFiles .Skip(CurrentState.CurrentIndex + 1) .TakeWhile(other => file.IsDurationEqual(other, state.Settings))) { if (cancelToken.IsCancellationRequested) { return; } OnLogged(string.Format(LogCompareFile, other.FilePath)); try { var comparer = new VideoComparer { LeftVideoFile = file, RightVideoFile = other, Settings = state.Settings, }; if (comparer.Compare(cancelToken) == ComparisonResult.Duplicate) { OnLogged($"Found duplicate of {file.FilePath} and " + $"{other.FilePath}"); OnDuplicateFound(file, other); } } catch (AggregateException exc) when (exc.InnerException is MpvLib.MpvException) { OnLogged(exc.InnerException.Message); } } CurrentState.SaveState(); file.DisposeImages(); } // To make sure we don't do all the work again // when we load the state next time. // Maybe we should track that separately though. CurrentState.CurrentIndex = int.MaxValue; CurrentState.SaveState(); timer.Stop(); Debug.Print($"Dedup took {timer.ElapsedMilliseconds} ms"); OnOperationUpdate(OperationType.Comparing, state.VideoFiles.Count(), state.VideoFiles.Count()); } private void FindDuplicatesOf( IEnumerable<VideoFile> videoFiles, VideoFile refFile, CancellationToken cancelToken) { OnLogged(string.Format(LogCheckingFile, refFile.FilePath, refFile.Duration.ToPrettyString())); foreach (var file in videoFiles .Where(f => f != refFile) .Where(f => f.IsDurationEqual(refFile, CurrentState.Settings))) { if (cancelToken.IsCancellationRequested) { return; } OnLogged(string.Format(LogCompareFile, file.FilePath)); try { var comparer = new VideoComparer { LeftVideoFile = file, RightVideoFile = refFile, Settings = CurrentState.Settings, }; if (comparer.Compare(cancelToken) == ComparisonResult.Duplicate) { OnLogged($"Found duplicate of {refFile.FilePath} and" + $" {file.FilePath}"); OnDuplicateFound(refFile, file); } } catch (AggregateException exc) when (exc.InnerException is MpvLib.MpvException) { OnLogged(exc.InnerException.Message); } } } private void ProcessChangesIfAny() { lock (DedupLock) { if (NewFiles.Any() || DeletedFiles.Any()) { DedupTask = Task.Factory.StartNew( ProcessChanges, CancelSource.Token); return; } if (!CurrentState.Settings.MonitorChanges) { operationStartTime = DateTime.MinValue; OnOperationUpdate( OperationType.Completed, ProgressStyle.NoProgress); OnLogged("Finished comparison."); return; } operationStartTime = DateTime.Now; OnOperationUpdate( OperationType.Monitoring, ProgressStyle.Marquee); OnLogged("Monitoring for file changes..."); return; } } private void ProcessFolder() { var cancelToken = CancelSource.Token; var files = GetVideoFileList(CurrentState.Settings); cancelToken.ThrowIfCancellationRequested(); // Cancellable preload of files PreloadFiles(files, cancelToken); if (cancelToken.IsCancellationRequested) { CurrentState.VideoFiles = files.ToList(); CurrentState.SaveState(); cancelToken.ThrowIfCancellationRequested(); } // Remove invalid files CurrentState.VideoFiles = files .Where(f => f.Duration != TimeSpan.Zero) .ToList(); CurrentState.SaveState(); cancelToken.ThrowIfCancellationRequested(); FindDuplicates(CurrentState, cancelToken); // Cleanup in case of cancel foreach (var file in CurrentState.VideoFiles) { file.DisposeImages(); } cancelToken.ThrowIfCancellationRequested(); ProcessChangesIfAny(); } private void ProcessChanges() { var cancelToken = CancelSource.Token; while (DeletedFiles.Any()) { var deletedFile = DeletedFiles.First().Key; _ = DeletedFiles.TryRemove(deletedFile, out var _); if (CurrentState.VideoFiles.Remove(deletedFile)) { CurrentState.SaveState(); OnLogged($"Removed file: {deletedFile.FilePath}"); } else { OnLogged($"Deleted file not in VideoFile-List: " + $"{deletedFile.FilePath}"); } cancelToken.ThrowIfCancellationRequested(); } operationStartTime = DateTime.Now; OnOperationUpdate(OperationType.Comparing, 0, NewFiles.Count()); // We need to count for the ProgressUpdate since we shrink // the Queue on every iteration. var filesProcessed = 1; while (NewFiles.Any()) { var newFile = NewFiles.First().Key; _ = NewFiles.TryRemove(newFile, out var _); OnOperationUpdate(OperationType.Comparing, filesProcessed, filesProcessed + NewFiles.Count()); filesProcessed++; if (!newFile.WaitForFileAccess(cancelToken)) { OnLogged($"Unable to access new file: {newFile.FileName}"); cancelToken.ThrowIfCancellationRequested(); continue; } cancelToken.ThrowIfCancellationRequested(); if (newFile.Duration == TimeSpan.Zero) { OnLogged($"New file has no duration: {newFile.FilePath}"); continue; } cancelToken.ThrowIfCancellationRequested(); if (!CurrentState.VideoFiles.Contains(newFile)) { OnLogged($"New file added to VideoFile-List: {newFile.FilePath}"); CurrentState.VideoFiles.Add(newFile); } else { OnLogged($"New file already in VideoFile-List: {newFile.FilePath}"); continue; } cancelToken.ThrowIfCancellationRequested(); FindDuplicatesOf(CurrentState.VideoFiles, newFile, cancelToken); CurrentState.SaveState(); // Cleanup in case of cancel foreach (var file in CurrentState.VideoFiles) { file.DisposeImages(); } cancelToken.ThrowIfCancellationRequested(); } ProcessChangesIfAny(); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { CancelSource.Cancel(); try { DedupTask?.Wait(); } catch (AggregateException exc) { exc.Handle(x => x is OperationCanceledException); } CancelSource?.Dispose(); DedupTask?.Dispose(); FileWatcher?.Dispose(); // TODO: dispose managed state (managed objects) } disposedValue = true; } } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } } }
34.981349
98
0.509187
[ "MIT" ]
balQu/VideoDedup
DedupEngine/DedupEngine.cs
24,382
C#
using System.Collections.Generic; using Litmus.Core.ProjectAggregate; namespace Litmus.Web.Endpoints.ProjectEndpoints { public class ProjectListResponse { public List<ProjectRecord> Projects { get; set; } = new(); } }
22.727273
67
0.692
[ "MIT" ]
daneelshof/litmus
src/Litmus.Web/Endpoints/ProjectEndpoints/List.ProjectListResponse.cs
252
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace MyAnimeListSharp.Core { /// <summary> /// Class representing AnimeSearch result /// </summary> /// <remarks>http://stackoverflow.com/a/608181/4035</remarks> [Serializable, XmlRoot("anime")] public class AnimeSearchResponse : ISearchResponse<AnimeEntry> { [XmlElement("entry")] public List<AnimeEntry> Entries { get; set; } = new List<AnimeEntry>(); } }
28.882353
79
0.678208
[ "MIT" ]
dance2die/Project.MyAnimeList
Project.MyAnimeList/Project.MyAnimeList/Core/AnimeSearchResponse.cs
491
C#
 public static class IntExtensions { /// <summary> /// /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool HasFlag (this int a, int b) { return (a & b) == b; } /// <summary> /// /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static int AddFlag (this int a, int b) { return a |= b; } /// <summary> /// /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static int RemoveFlag (this int a, int b) { return a &= ~b; } }
25.185185
75
0.492647
[ "MIT" ]
Canpea55/UnitySourceMovement
Modified fragsurf/Extensions/IntExtensions.cs
682
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("MinecraftServerConnect")] [assembly: AssemblyDescription("Quick and safe connection to a Minecraft server.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MinecraftServerConnect")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("886c0101-1f15-4945-8968-20cea89553ab")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.459459
84
0.75411
[ "MIT" ]
robolivable/MinecraftServerConnect
MinecraftServerConnect/Properties/AssemblyInfo.cs
1,463
C#
namespace Tailspin.AnswerAnalysisService.Commands { using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Tailspin.Web.Survey.Shared.Helpers; using Tailspin.Web.Survey.Shared.QueueMessages; using Tailspin.Web.Survey.Shared.Stores; public class UpdatingSurveyResultsSummaryCommand : IBatchCommand<SurveyAnswerStoredMessage> { private readonly IDictionary<string, TenantSurveyProcessingInfo> tenantSurveyProcessingInfoCache; private readonly ISurveyAnswerStore surveyAnswerStore; private readonly ISurveyAnswersSummaryStore surveyAnswersSummaryStore; public UpdatingSurveyResultsSummaryCommand(IDictionary<string, TenantSurveyProcessingInfo> processingInfoCache, ISurveyAnswerStore surveyAnswerStore, ISurveyAnswersSummaryStore surveyAnswersSummaryStore) { this.tenantSurveyProcessingInfoCache = processingInfoCache; this.surveyAnswerStore = surveyAnswerStore; this.surveyAnswersSummaryStore = surveyAnswersSummaryStore; } public void PreRun() { this.tenantSurveyProcessingInfoCache.Clear(); } public bool Run(SurveyAnswerStoredMessage message) { RunAsync(message).Wait(); return false; // won't remove the message from the queue } public void PostRun() { PostRunAsync().Wait(); } private async Task RunAsync(SurveyAnswerStoredMessage message) { if (!message.AppendedToAnswers) { await this.surveyAnswerStore.AppendSurveyAnswerIdToAnswersListAsync( message.TenantId, message.SurveySlugName, message.SurveyAnswerBlobId); message.AppendedToAnswers = true; await message.UpdateQueueMessageAsync().ConfigureAwait(false); } var surveyAnswer = await this.surveyAnswerStore.GetSurveyAnswerAsync( message.TenantId, message.SurveySlugName, message.SurveyAnswerBlobId); var keyInCache = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", message.TenantId, message.SurveySlugName); TenantSurveyProcessingInfo surveyInfo; if (!this.tenantSurveyProcessingInfoCache.ContainsKey(keyInCache)) { surveyInfo = new TenantSurveyProcessingInfo(message.TenantId, message.SurveySlugName); this.tenantSurveyProcessingInfoCache[keyInCache] = surveyInfo; } else { surveyInfo = this.tenantSurveyProcessingInfoCache[keyInCache]; } surveyInfo.AnswersSummary.AddNewAnswer(surveyAnswer); surveyInfo.AnswersMessages.Add(message); } private async Task PostRunAsync() { foreach (var surveyInfo in this.tenantSurveyProcessingInfoCache.Values) { try { await this.surveyAnswersSummaryStore.MergeSurveyAnswersSummaryAsync(surveyInfo.AnswersSummary); foreach (var message in surveyInfo.AnswersMessages) { try { await message.DeleteQueueMessageAsync().ConfigureAwait(false); } catch (Exception e) { TraceHelper.TraceWarning("Error deleting message for '{0-1}': {2}", message.TenantId, message.SurveySlugName, e.Message); } } } catch (Exception e) { // do nothing - will leave the messages in the queue for reprocessing TraceHelper.TraceWarning(e.Message); } } } } }
38.700935
211
0.585124
[ "MIT" ]
msajidirfan/cloud-services-to-service-fabric
servicefabric/Tailspin/Tailspin.AnswerAnalysisService/Commands/UpdatingSurveyResultsSummaryCommand.cs
4,143
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the servicecatalog-2015-12-10.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.ServiceCatalog.Model { /// <summary> /// Container for the parameters to the EnableAWSOrganizationsAccess operation. /// Enable portfolio sharing feature through AWS Organizations. This API will allow Service /// Catalog to receive updates on your organization in order to sync your shares with /// the current structure. This API can only be called by the master account in the organization. /// /// /// <para> /// By calling this API Service Catalog will make a call to organizations:EnableAWSServiceAccess /// on your behalf so that your shares can be in sync with any changes in your AWS Organizations /// structure. /// </para> /// /// <para> /// Note that a delegated administrator is not authorized to invoke <code>EnableAWSOrganizationsAccess</code>. /// </para> /// </summary> public partial class EnableAWSOrganizationsAccessRequest : AmazonServiceCatalogRequest { } }
35.942308
114
0.720706
[ "Apache-2.0" ]
atpyatt/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/EnableAWSOrganizationsAccessRequest.cs
1,869
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ViewWrapperCodeGenerator.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.888889
150
0.585887
[ "MIT" ]
Zegeger/Decal
ZChatSystem/ZChatSystem/VirindiView/ViewWrapperCodeGenerator/ViewWrapperCodeGenerator/Properties/Settings.Designer.cs
1,079
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using Shiny.BluetoothLE; namespace Shiny.Testing.BluetoothLE { public class TestGattService : IGattService { public TestGattService(IPeripheral peripheral, string uuid) { this.Peripheral = peripheral; this.Uuid = uuid; } public IPeripheral Peripheral { get; } public string Uuid { get; } public List<IGattCharacteristic> Characteristics { get; set; } = new List<IGattCharacteristic>(); public IObservable<IList<IGattCharacteristic>> GetCharacteristics() => this.Characteristics .Cast<IList<IGattCharacteristic>>() .ToObservable(); public IObservable<IGattCharacteristic?> GetKnownCharacteristic(string characteristicUuid, bool throwIfNotFound = false) => Observable.Return( this.Characteristics .FirstOrDefault( x => x.Uuid.Equals(characteristicUuid) ) ) .Do(ch => { if (throwIfNotFound && ch == null) throw new ArgumentException($"Characteristic not found - {this.Uuid}/{characteristicUuid}"); }); } }
30.837209
131
0.592006
[ "MIT" ]
Codelisk/shiny
src/Shiny.Testing/BluetoothLE/TestGattService.cs
1,328
C#
using Stl.Serialization.Internal; namespace Stl.Serialization; [DataContract] public readonly struct ExceptionInfo : IEquatable<ExceptionInfo> { private static readonly Type[] ExceptionCtorArgumentTypes1 = { typeof(string), typeof(Exception) }; private static readonly Type[] ExceptionCtorArgumentTypes2 = { typeof(string) }; public static ExceptionInfo None { get; } = default; public static Func<ExceptionInfo, Exception?> ToExceptionConverter { get; set; } = DefaultToExceptionConverter; private readonly string _message; [DataMember(Order = 0)] public TypeRef TypeRef { get; } [DataMember(Order = 1)] public string Message => _message ?? ""; [IgnoreDataMember] public bool IsNone => TypeRef.AssemblyQualifiedName.IsEmpty; [JsonConstructor, Newtonsoft.Json.JsonConstructor] public ExceptionInfo(TypeRef typeRef, string? message) { TypeRef = typeRef; _message = message ?? ""; } public ExceptionInfo(Exception? exception) { if (exception == null) { TypeRef = default; _message = ""; } else { TypeRef = exception.GetType(); _message = exception.Message; } } public void Deconstruct(out TypeRef typeRef, out string message) { typeRef = TypeRef; message = Message; } public override string ToString() => IsNone ? $"{GetType().Name}()" : $"{GetType().Name}({TypeRef}, {JsonFormatter.Format(Message)})"; public Exception? ToException() { if (IsNone) return null; try { return ToExceptionConverter.Invoke(this) ?? Errors.RemoteException(this); } catch (Exception) { return Errors.RemoteException(this); } } // Conversion public static implicit operator ExceptionInfo(Exception exception) => new(exception); private static Exception? DefaultToExceptionConverter(ExceptionInfo exceptionInfo) { var type = exceptionInfo.TypeRef.Resolve(); if (!typeof(Exception).IsAssignableFrom(type)) return null; var ctor = type.GetConstructor(ExceptionCtorArgumentTypes1); if (ctor != null) { try { return (Exception) type.CreateInstance(exceptionInfo.Message, (Exception?) null); } catch { // Intended } } ctor = type.GetConstructor(ExceptionCtorArgumentTypes2); if (ctor == null) return null; var parameter = ctor.GetParameters().SingleOrDefault(); if (!StringComparer.Ordinal.Equals("message", parameter?.Name ?? "")) return null; return (Exception) type.CreateInstance(exceptionInfo.Message); } // Equality public bool Equals(ExceptionInfo other) => TypeRef.Equals(other.TypeRef) && StringComparer.Ordinal.Equals(Message, other.Message); public override bool Equals(object? obj) => obj is ExceptionInfo other && Equals(other); public override int GetHashCode() => HashCode.Combine(TypeRef, StringComparer.Ordinal.GetHashCode(Message)); public static bool operator ==(ExceptionInfo left, ExceptionInfo right) => left.Equals(right); public static bool operator !=(ExceptionInfo left, ExceptionInfo right) => !left.Equals(right); }
31.072072
115
0.627428
[ "MIT" ]
servicetitan/Stl
src/Stl/Serialization/ExceptionInfo.cs
3,449
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 ("TowerDefense")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("TowerDefense")] [assembly: AssemblyCopyright ("Copyright © 2015")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid ("79f7a241-20ad-4486-9bbe-dc7b7c748bcc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion ("1.0.0.0")] [assembly: AssemblyFileVersion ("1.0.0.0")]
38.081081
84
0.738822
[ "BSD-3-Clause" ]
splitandthechro/nginz
src/Games/TowerDefense/Properties/AssemblyInfo.cs
1,412
C#