content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CompactMPC { public class IdMapping<T> { private const int DefaultInitialCapacity = 4; private T _defaultValue; private T[] _values; public IdMapping() : this(default(T), DefaultInitialCapacity) { } public IdMapping(T defaultValue) : this(defaultValue, DefaultInitialCapacity) { } public IdMapping(T defaultValue, int initialCapacity) { _defaultValue = defaultValue; _values = new T[initialCapacity]; for (int i = 0; i < _values.Length; ++i) _values[i] = defaultValue; } public T this[int id] { get { if (id < 0) throw new ArgumentOutOfRangeException(nameof(id)); if (id < _values.Length) return _values[id]; return _defaultValue; } set { if (id < 0) throw new ArgumentOutOfRangeException(nameof(id)); int currentLength = _values.Length; int requiredLength = id + 1; if(requiredLength > currentLength) { int newLength = currentLength; while (newLength < requiredLength) newLength = 2 * newLength; Array.Resize(ref _values, newLength); for (int i = currentLength; i < newLength; ++i) _values[i] = _defaultValue; } _values[id] = value; } } } }
27.323077
70
0.494932
[ "MIT" ]
lumip/CompactMPC
CompactMPC/IdMapping.cs
1,778
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Assimp { public unsafe readonly struct PfnFileFlushProc : IDisposable { private readonly void* _handle; public delegate* unmanaged[Cdecl]<File*, void> Handle => (delegate* unmanaged[Cdecl]<File*, void>) _handle; public PfnFileFlushProc ( delegate* unmanaged[Cdecl]<File*, void> ptr ) => _handle = ptr; public PfnFileFlushProc ( FileFlushProc proc ) => _handle = (void*) SilkMarshal.DelegateToPtr(proc); public static PfnFileFlushProc From(FileFlushProc proc) => new PfnFileFlushProc(proc); public void Dispose() => SilkMarshal.Free((nint) _handle); public static implicit operator nint(PfnFileFlushProc pfn) => (nint) pfn.Handle; public static explicit operator PfnFileFlushProc(nint pfn) => new PfnFileFlushProc((delegate* unmanaged[Cdecl]<File*, void>) pfn); public static implicit operator PfnFileFlushProc(FileFlushProc proc) => new PfnFileFlushProc(proc); public static explicit operator FileFlushProc(PfnFileFlushProc pfn) => SilkMarshal.PtrToDelegate<FileFlushProc>(pfn); public static implicit operator delegate* unmanaged[Cdecl]<File*, void>(PfnFileFlushProc pfn) => pfn.Handle; public static implicit operator PfnFileFlushProc(delegate* unmanaged[Cdecl]<File*, void> ptr) => new PfnFileFlushProc(ptr); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void FileFlushProc(File* arg0); }
36.62963
131
0.706269
[ "MIT" ]
Ar37-rs/Silk.NET
src/Assimp/Silk.NET.Assimp/Structs/PfnFileFlushProc.gen.cs
1,978
C#
using PipeShot.Libraries.Helper; using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace PipeShot { /// <summary> /// Interaction logic for NotificationWindow.xaml /// </summary> public partial class NotificationWindow : IDisposable { /// <summary> /// Is a Notification currently shown /// </summary> public static bool IsShown { get; private set; } public static readonly Action ActionTroubleshoot = delegate { Process.Start(Path.Combine(ConfigHelper.InstallDir, "PipeShot.UI.exe"), "troubleshooting"); }; public enum NotificationType { Progress, Success, Error } public const int ShowDuration = 3500; private readonly double _left; private readonly TaskCompletionSource<bool> _task = new TaskCompletionSource<bool>(); private bool _autoHide; public NotificationWindow(string text, NotificationType type, bool autoHide, Action onClick) { InitializeComponent(); _left = SystemParameters.WorkArea.Left + SystemParameters.WorkArea.Width; double top = SystemParameters.WorkArea.Top + SystemParameters.WorkArea.Height; Left = _left; Top = top - Height - 10; _autoHide = autoHide; ContentLabel.Text = text; switch (type) { case NotificationType.Error: ErrorIcon.Visibility = Visibility.Visible; break; case NotificationType.Progress: ProgressBar.Visibility = Visibility.Visible; break; case NotificationType.Success: SuccessIcon.Visibility = Visibility.Visible; break; } if (onClick != null) { NotificationContent.Cursor = Cursors.Hand; NotificationContent.MouseDown += delegate { try { onClick.Invoke(); } catch { // ignored } FadeOut(); }; } } ~NotificationWindow() { Dispose(); } public NotificationWindow(string text, NotificationType type, bool autoHide) : this(text, type, autoHide, null) { } private async void Window_Loaded(object sender, RoutedEventArgs e) { IsShown = true; FadeIn(); if (_autoHide) { await Task.Delay(ShowDuration); FadeOut(); } } public Task ShowAsync() { _autoHide = true; Show(); return _task.Task; } public new void Close() { FadeOut(); } //Open Animation private void FadeIn() { this.Animate(OpacityProperty, 0, 1, 200); this.Animate(LeftProperty, _left, _left - Width - 10, 150); } //Close Animation private async void FadeOut() { try { this.Animate(OpacityProperty, 1, 0, 100); await this.AnimateAsync(LeftProperty, Left, _left, 100); _task.TrySetResult(true); base.Close(); } catch { // Invalid Operation, Task Canceled, Wrong Thread... } finally { IsShown = false; } } private void Window_Close(object sender, MouseButtonEventArgs e) { FadeOut(); } private void Window_MouseEnter(object sender, MouseEventArgs e) { BtnClose.BeginAnimation(OpacityProperty, Animations.FadeIn); } private void Window_MouseLeave(object sender, MouseEventArgs e) { BtnClose.BeginAnimation(OpacityProperty, Animations.FadeOut); } private void Close_MouseEnter(object sender, MouseEventArgs e) { CloseIcon.BeginAnimation(OpacityProperty, Animations.FadeIn); } private void Close_MouseLeave(object sender, MouseEventArgs e) { CloseIcon.BeginAnimation(OpacityProperty, Animations.FadeOut); } public void Dispose() { try { Close(); } catch { // ignored } } } }
30.020134
123
0.544377
[ "MIT" ]
PipeRift/Pipeshot
PipeShot/NotificationWindow.xaml.cs
4,475
C#
using Razorpay.Api; using System; using System.Collections.Generic; namespace RazorpaySampleApp { public partial class Charge : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string paymentId = Request.Form["razorpay_payment_id"]; Dictionary<string, object> input = new Dictionary<string, object>(); input.Add("amount", 100); // this amount should be same as transaction amount string key = "<Enter your Api Key here>"; string secret = "<Enter your Api Secret here>"; RazorpayClient client = new RazorpayClient(key, secret); Dictionary<string, string> attributes = new Dictionary<string, string>(); attributes.Add("razorpay_payment_id", paymentId); attributes.Add("razorpay_order_id", Request.Form["razorpay_order_id"]); attributes.Add("razorpay_signature", Request.Form["razorpay_signature"]); Utils.verifyPaymentSignature(attributes); // please use the below code to refund the payment // Refund refund = new Razorpay.Api.Payment((string) paymentId).Refund(); Console.WriteLine(paymentId); } } }
34.5
89
0.643317
[ "MIT" ]
Soubhagya03/Emandate
net40/Charge.aspx.cs
1,244
C#
using TSDMMusicdotNet.Commands; using TSDMMusicdotNet.Models; using System.Collections.ObjectModel; using System; using TSDMMusicdotNet.Helpers; using System.Text.RegularExpressions; namespace TSDMMusicdotNet.ViewModels { public class MainWindowsViewModel : ModelsBase { public ObservableCollection<DownloadLinkItem> DownloadLinkCollection { get; set; } private string _outBody = ""; public string OutBody { get { return _outBody; } set { _outBody = value; this.RaisePropertyChanged("OutBody"); } } private string _certificationLink = ""; public string CertificationLink { get { return _certificationLink; } set { _certificationLink = value; this.RaisePropertyChanged("CertificationLink"); } } private string _moraLink = ""; public string MoraLink { get { return _moraLink; } set { _moraLink = value; this.RaisePropertyChanged("MoraLink"); } } private string _outTitle = ""; public string OutTitle { get { return _outTitle; } set { _outTitle = value; this.RaisePropertyChanged("OutTitle"); } } private string _nowWorking = ""; public string NowWorking { get { return _nowWorking; } set { _nowWorking = value; this.RaisePropertyChanged("NowWorking"); } } private int _nowProgress = 0; public int NowProgress { get { return _nowProgress; } set { _nowProgress = value; this.RaisePropertyChanged("NowProgress"); } } public DelegateCommand ClearCommand { get; set; } public DelegateCommand CreateCommand { get; set; } private string _template = ""; public MainWindowsViewModel() { _template = MainWindowsCommands.ReadTemplate(); DownloadLinkCollection = new ObservableCollection<DownloadLinkItem>(MainWindowsCommands.GetDownloadLinkCollection()); MoraLink = ""; CertificationLink = ""; OutBody = ""; OutTitle = ""; ClearCommand = new DelegateCommand(); CreateCommand = new DelegateCommand(); ClearCommand.ExecuteCommand += new Action<object>(_clearPage); CreateCommand.ExecuteCommand += new Action<object>(_create); } private void _clearPage(object obj) { MoraLink = ""; CertificationLink = ""; OutBody = ""; OutTitle = ""; for (int i = 0; i < DownloadLinkCollection.Count; i++) { DownloadLinkCollection[i].DownloadLink = ""; } } private async void _create(object obj) { bool isgoodlink = LinksCheck(); if (isgoodlink) { UpdateProgress("连接mora...", 0); string packagelink = await MoraHelper.GetMoraPackageLinkAsync(MoraLink); UpdateProgress("读取信息...", 1); MoraJsonObjectModel moraJsonObject = await MoraHelper.GetMoraJsonObjectAsync(packagelink); UpdateProgress("生成主题...", 2); OutputModel output = new OutputModel(moraJsonObject, DownloadLinkCollection, CertificationLink, MoraLink); OutTitle = output.OutputTitle(); OutBody = output.OutputBody(_template); UpdateProgress("完成生成", 3); } else { System.Windows.Forms.MessageBox.Show("mora链接错误!"); } } private void UpdateProgress(string working,int progress) { this.NowWorking = working; this.NowProgress = progress; } private bool LinksCheck() { bool result = false; if (Regex.IsMatch(MoraLink, "http://mora.jp/package/(.*?)/(.*?)/") || Regex.IsMatch(MoraLink, "http://mora.jp/package/(.*?)/(.*?)/(.*?)")) { result = true; } return result; } } }
32.65493
151
0.505068
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SofiaXu/TSDMMusicdotNet
TSDMMusicdotNet/ViewModels/MainWindowsViewModel.cs
4,677
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TextrudeInteractive.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TextrudeInteractive.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to &lt;!DOCTYPE html&gt; ///&lt;html&gt; ///&lt;head&gt; /// &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html;charset=utf-8&quot;&gt; /// /// &lt;style type=&quot;text/css&quot;&gt; /// html, /// body { /// height: 100%; /// margin: 0; /// overflow: hidden; /// } /// /// #container { /// width: 100%; /// height: 100%; /// } /// &lt;/style&gt; ///&lt;/head&gt; ///&lt;body&gt; /// &lt;div id=&quot;container&quot; /&gt; /// /// &lt;script src=&quot;vs/loader.js&quot;&gt;&lt;/script&gt; /// &lt;script&gt; /// require.config({ paths: { &apos;vs&apos;: &apos;vs&apos; } [rest of string was truncated]&quot;;. /// </summary> internal static string monaco { get { return ResourceManager.GetString("monaco", resourceCulture); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] monaco_editor_0_22_3 { get { object obj = ResourceManager.GetObject("monaco_editor_0_22_3", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized string similar to /*--------------------------------------------------------------------------------------------- /// * Copyright (c) Microsoft Corporation. All rights reserved. /// * Licensed under the MIT License. See License.txt in the project root for license information. /// *--------------------------------------------------------------------------------------------*/ ///define(&apos;vs/basic-languages/scriban/scriban&apos;,[&quot;require&quot;, &quot;exports&quot;], function (require, exports) { /// &quot;use strict&quot;; /// Object.defineProperty(exports, &quot;__ [rest of string was truncated]&quot;;. /// </summary> internal static string scriban { get { return ResourceManager.GetString("scriban", resourceCulture); } } } }
43.286885
185
0.532854
[ "MIT" ]
NeilMacMullen/Textrude
TextrudeInteractive/Properties/Resources.Designer.cs
5,283
C#
namespace ARExample { public partial class SolarSistemView { public SolarSistemView() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); ArScene.RunSession?.Invoke(); } protected override void OnDisappearing() { base.OnDisappearing(); ArScene.PauseSession?.Invoke(); } private void btSolarSistem_Clicked(System.Object sender, System.EventArgs e) { ArScene.DrawSolarSystem?.Invoke(); } } }
21.75
84
0.546798
[ "MIT" ]
jorgediegocrespo/XamarinAR
ARExample/ARExample/SolarSystemView.xaml.cs
611
C#
namespace P04.Recharge { public class Employee : Worker, ISleeper { public Employee(string id) : base(id) { } public void Sleep() { // sleep... } } }
15.466667
45
0.435345
[ "MIT" ]
AntoniyaIvanova/SoftUni
C#/C# Advanced/C# OOP/06. SOLID/Solid - Lab/P04.Recharge/Employee.cs
234
C#
using System.Linq; namespace WebChat.Application.API.Common.Identity { public static class IdentityResultExtensions { public static IdentityResult ToApplicationResult(this Microsoft.AspNetCore.Identity.IdentityResult result) { return result.Succeeded ? IdentityResult.Success() : IdentityResult.Failure(result.Errors.Select(e => e.Description)); } } }
30.857143
114
0.671296
[ "Apache-2.0" ]
liannoi/web-chat
src/Layers/Application/Application.API/Common/Identity/IdentityResultExtensions.cs
432
C#
using System; namespace ISIT420COVIDFinalTiffanyValentina.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.243902
130
0.536245
[ "MIT" ]
Drakenshiinx/ISIT420COVIDFinalTiffanyValentina
ISIT420COVIDFinalTiffanyValentinaSolution/ISIT420COVIDFinalTiffanyValentina/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,076
C#
using System; namespace VsTranslator { public class GuidList { public const string PackageGuidString = "08a874bc-f0d4-40bc-8bbf-a1f2e30f92e5"; public static readonly Guid CommandSet = new Guid("86da4c7a-599c-42e2-af95-ee1b4d587545"); public const string OutputWindow = "4b805c0f-d131-4cb5-bf1c-23cde4626d23"; public const string TranslateOptions = "13F26042-A1A3-4933-9FDC-2DBF7396DD10"; } }
29.333333
98
0.718182
[ "MIT" ]
HiroHsu/VsTranslator
Codes/VsTranslator/GuidList.cs
442
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Quantum.Client.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// An Error response. /// </summary> [JsonTransformation] public partial class RestError { /// <summary> /// Initializes a new instance of the RestError class. /// </summary> public RestError() { CustomInit(); } /// <summary> /// Initializes a new instance of the RestError class. /// </summary> /// <param name="code">An identifier for the error. Codes are invariant /// and are intended to be consumed programmatically.</param> /// <param name="message">A message describing the error, intended to /// be suitable for displaying in a user interface.</param> public RestError(string code = default(string), string message = default(string)) { Code = code; Message = message; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets an identifier for the error. Codes are invariant and /// are intended to be consumed programmatically. /// </summary> [JsonProperty(PropertyName = "error.code")] public string Code { get; set; } /// <summary> /// Gets or sets a message describing the error, intended to be /// suitable for displaying in a user interface. /// </summary> [JsonProperty(PropertyName = "error.message")] public string Message { get; set; } } }
32.208955
90
0.609361
[ "MIT" ]
filipw/qsharp-runtime
src/Azure/Azure.Quantum.Client/generated/Models/RestError.cs
2,158
C#
namespace ExcelCamAddIn { partial class WinFormsCameraControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnTakePicture = new System.Windows.Forms.Button(); this.imgVideo = new System.Windows.Forms.PictureBox(); this.groupBoxCommands = new System.Windows.Forms.GroupBox(); this.btnSettings = new System.Windows.Forms.Button(); this.btnResolution = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.imgVideo)).BeginInit(); this.groupBoxCommands.SuspendLayout(); this.SuspendLayout(); // // btnTakePicture // this.btnTakePicture.Location = new System.Drawing.Point(3, 19); this.btnTakePicture.Name = "btnTakePicture"; this.btnTakePicture.Size = new System.Drawing.Size(275, 23); this.btnTakePicture.TabIndex = 1; this.btnTakePicture.Text = "Take picture"; this.btnTakePicture.UseVisualStyleBackColor = true; this.btnTakePicture.Click += new System.EventHandler(this.btnTakePicture_Click); // // imgVideo // this.imgVideo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.imgVideo.Location = new System.Drawing.Point(0, 0); this.imgVideo.Name = "imgVideo"; this.imgVideo.Size = new System.Drawing.Size(449, 326); this.imgVideo.TabIndex = 2; this.imgVideo.TabStop = false; // // groupBoxCommands // this.groupBoxCommands.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBoxCommands.Controls.Add(this.btnResolution); this.groupBoxCommands.Controls.Add(this.btnSettings); this.groupBoxCommands.Controls.Add(this.btnTakePicture); this.groupBoxCommands.Location = new System.Drawing.Point(0, 332); this.groupBoxCommands.Name = "groupBoxCommands"; this.groupBoxCommands.Size = new System.Drawing.Size(446, 51); this.groupBoxCommands.TabIndex = 3; this.groupBoxCommands.TabStop = false; this.groupBoxCommands.Text = "Commands"; // // btnSettings // this.btnSettings.Location = new System.Drawing.Point(365, 19); this.btnSettings.Name = "btnSettings"; this.btnSettings.Size = new System.Drawing.Size(75, 23); this.btnSettings.TabIndex = 2; this.btnSettings.Text = "Settings"; this.btnSettings.UseVisualStyleBackColor = true; this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click); // // btnResolution // this.btnResolution.Location = new System.Drawing.Point(284, 19); this.btnResolution.Name = "btnResolution"; this.btnResolution.Size = new System.Drawing.Size(75, 23); this.btnResolution.TabIndex = 3; this.btnResolution.Text = "Resolution"; this.btnResolution.UseVisualStyleBackColor = true; this.btnResolution.Click += new System.EventHandler(this.btnResolution_Click); // // WinFormsCameraControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.groupBoxCommands); this.Controls.Add(this.imgVideo); this.Name = "WinFormsCameraControl"; this.Size = new System.Drawing.Size(449, 386); this.Load += new System.EventHandler(this.WinFormsCameraControl_Load); ((System.ComponentModel.ISupportInitialize)(this.imgVideo)).EndInit(); this.groupBoxCommands.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnTakePicture; private System.Windows.Forms.PictureBox imgVideo; private System.Windows.Forms.GroupBox groupBoxCommands; private System.Windows.Forms.Button btnSettings; private System.Windows.Forms.Button btnResolution; } }
45.754237
165
0.610669
[ "MIT" ]
nemanja-popovic/ExcelAddInWithCamera
ExcelCamAddIn/WinFormsCameraControl.Designer.cs
5,401
C#
using UnityEngine; using System.Collections; public class UpLeftGuiPlacementCalculator : AbstractGuiPlacementCalculator { protected override Rect placement() { float left = HORIZONTAL_BORDER_OFFSET; float top = VERTICAL_BORDER_OFFSET; return new Rect(left, top, size.x, size.y); } }
21
74
0.782313
[ "Apache-2.0" ]
alvarogzp/nextation
Assets/Scripts/Gui/Renderer/Placement/Calculator/Impl/UpLeftGuiPlacementCalculator.cs
294
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // The TypeCode enum represents the type code of an object. To obtain the // TypeCode for a given object, use the Value.GetTypeCode() method. The // TypeCode.Empty value represents a null object reference. The TypeCode.Object // value represents an object that doesn't implement the IConvertible interface. The // TypeCode.DBNull value represents the database null, which is distinct and // different from a null reference. The other type codes represent values that // use the given simple type encoding. // // Note that when an object has a given TypeCode, there is no guarantee that // the object is an instance of the corresponding System.XXX value class. For // example, an object with the type code TypeCode.Int32 might actually be an // instance of a nullable 32-bit integer type (with a value that isn't the // database null). // // There are no type codes for "Missing", "Error", "IDispatch", and "IUnknown". // These types of values are instead represented as classes. When the type code // of an object is TypeCode.Object, a further instance-of check can be used to // determine if the object is one of these values. namespace System { public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } }
47.510638
84
0.635916
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Private.CoreLib/src/System/TypeCode.cs
2,233
C#
using System.Threading; using System.Threading.Tasks; using Atlassian.Bitbucket.UI.ViewModels; using Atlassian.Bitbucket.UI.Views; using GitCredentialManager; using GitCredentialManager.UI; namespace Atlassian.Bitbucket.UI.Commands { public class OAuthCommandImpl : OAuthCommand { public OAuthCommandImpl(ICommandContext context) : base(context) { } protected override Task ShowAsync(OAuthViewModel viewModel, CancellationToken ct) { return Gui.ShowDialogWindow(viewModel, () => new OAuthView(), GetParentHandle()); } } }
29
93
0.734483
[ "MIT" ]
1Bax/git-credential-manager
src/windows/Atlassian.Bitbucket.UI.Windows/Commands/OAuthCommandImpl.cs
580
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace Website.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
22.8125
66
0.745205
[ "MIT" ]
jusbuc2k/dotnet_mod_auth_pubtkt
src/Website/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs
367
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.SignalR.Client.Internal; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.SignalR.Client { /// <summary> /// A connection used to invoke hub methods on a SignalR Server. /// </summary> /// <remarks> /// A <see cref="HubConnection"/> should be created using <see cref="HubConnectionBuilder"/>. /// Before hub methods can be invoked the connection must be started using <see cref="StartAsync"/>. /// Clean up a connection using <see cref="StopAsync"/> or <see cref="DisposeAsync"/>. /// </remarks> public partial class HubConnection : IAsyncDisposable { /// <summary> /// The default timeout which specifies how long to wait for a message before closing the connection. Default is 30 seconds. /// </summary> public static readonly TimeSpan DefaultServerTimeout = TimeSpan.FromSeconds(30); // Server ping rate is 15 sec, this is 2 times that. /// <summary> /// The default timeout which specifies how long to wait for the handshake to respond before closing the connection. Default is 15 seconds. /// </summary> public static readonly TimeSpan DefaultHandshakeTimeout = TimeSpan.FromSeconds(15); /// <summary> /// The default interval that the client will send keep alive messages to let the server know to not close the connection. Default is 15 second interval. /// </summary> public static readonly TimeSpan DefaultKeepAliveInterval = TimeSpan.FromSeconds(15); // The receive loop has a single reader and single writer at a time so optimize the channel for that private static readonly UnboundedChannelOptions _receiveLoopOptions = new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }; private static readonly MethodInfo _sendStreamItemsMethod = typeof(HubConnection).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name.Equals(nameof(SendStreamItems))); private static readonly MethodInfo _sendIAsyncStreamItemsMethod = typeof(HubConnection).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name.Equals(nameof(SendIAsyncEnumerableStreamItems))); // Persistent across all connections private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; private readonly ConnectionLogScope _logScope; private readonly IHubProtocol _protocol; private readonly IServiceProvider _serviceProvider; private readonly IConnectionFactory _connectionFactory; private readonly IRetryPolicy? _reconnectPolicy; private readonly EndPoint _endPoint; private readonly ConcurrentDictionary<string, InvocationHandlerList> _handlers = new ConcurrentDictionary<string, InvocationHandlerList>(StringComparer.Ordinal); // Holds all mutable state other than user-defined handlers and settable properties. private readonly ReconnectingConnectionState _state; private bool _disposed; /// <summary> /// Occurs when the connection is closed. The connection could be closed due to an error or due to either the server or client intentionally /// closing the connection without error. /// </summary> /// <remarks> /// If this event was triggered from a connection error, the <see cref="Exception"/> that occurred will be passed in as the /// sole argument to this handler. If this event was triggered intentionally by either the client or server, then /// the argument will be <see langword="null"/>. /// </remarks> /// <example> /// The following example attaches a handler to the <see cref="Closed"/> event, and checks the provided argument to determine /// if there was an error: /// /// <code> /// connection.Closed += (exception) => /// { /// if (exception == null) /// { /// Console.WriteLine("Connection closed without error."); /// } /// else /// { /// Console.WriteLine($"Connection closed due to an error: {exception}"); /// } /// }; /// </code> /// </example> public event Func<Exception?, Task>? Closed; /// <summary> /// Occurs when the <see cref="HubConnection"/> starts reconnecting after losing its underlying connection. /// </summary> /// <remarks> /// The <see cref="Exception"/> that occurred will be passed in as the sole argument to this handler. /// </remarks> /// <example> /// The following example attaches a handler to the <see cref="Reconnecting"/> event, and checks the provided argument to log the error. /// /// <code> /// connection.Reconnecting += (exception) => /// { /// Console.WriteLine($"Connection started reconnecting due to an error: {exception}"); /// }; /// </code> /// </example> public event Func<Exception?, Task>? Reconnecting; /// <summary> /// Occurs when the <see cref="HubConnection"/> successfully reconnects after losing its underlying connection. /// </summary> /// <remarks> /// The <see cref="string"/> parameter will be the <see cref="HubConnection"/>'s new ConnectionId or null if negotiation was skipped. /// </remarks> /// <example> /// The following example attaches a handler to the <see cref="Reconnected"/> event, and checks the provided argument to log the ConnectionId. /// /// <code> /// connection.Reconnected += (connectionId) => /// { /// Console.WriteLine($"Connection successfully reconnected. The ConnectionId is now: {connectionId}"); /// }; /// </code> /// </example> public event Func<string?, Task>? Reconnected; // internal for testing purposes internal TimeSpan TickRate { get; set; } = TimeSpan.FromSeconds(1); /// <summary> /// Gets or sets the server timeout interval for the connection. /// </summary> /// <remarks> /// The client times out if it hasn't heard from the server for `this` long. /// </remarks> public TimeSpan ServerTimeout { get; set; } = DefaultServerTimeout; /// <summary> /// Gets or sets the interval at which the client sends ping messages. /// </summary> /// <remarks> /// Sending any message resets the timer to the start of the interval. /// </remarks> public TimeSpan KeepAliveInterval { get; set; } = DefaultKeepAliveInterval; /// <summary> /// Gets or sets the timeout for the initial handshake. /// </summary> public TimeSpan HandshakeTimeout { get; set; } = DefaultHandshakeTimeout; /// <summary> /// Gets the connection's current Id. This value will be cleared when the connection is stopped and will have a new value every time the connection is (re)established. /// This value will be null if the negotiation step is skipped via HttpConnectionOptions or if the WebSockets transport is explicitly specified because the /// client skips negotiation in that case as well. /// </summary> public string? ConnectionId => _state.CurrentConnectionStateUnsynchronized?.Connection.ConnectionId; /// <summary> /// Indicates the state of the <see cref="HubConnection"/> to the server. /// </summary> public HubConnectionState State => _state.OverallState; /// <summary> /// Initializes a new instance of the <see cref="HubConnection"/> class. /// </summary> /// <param name="connectionFactory">The <see cref="IConnectionFactory" /> used to create a connection each time <see cref="StartAsync" /> is called.</param> /// <param name="protocol">The <see cref="IHubProtocol" /> used by the connection.</param> /// <param name="endPoint">The <see cref="EndPoint"/> to connect to.</param> /// <param name="serviceProvider">An <see cref="IServiceProvider"/> containing the services provided to this <see cref="HubConnection"/> instance.</param> /// <param name="loggerFactory">The logger factory.</param> /// <param name="reconnectPolicy"> /// The <see cref="IRetryPolicy"/> that controls the timing and number of reconnect attempts. /// The <see cref="HubConnection"/> will not reconnect if the <paramref name="reconnectPolicy"/> is null. /// </param> /// <remarks> /// The <see cref="IServiceProvider"/> used to initialize the connection will be disposed when the connection is disposed. /// </remarks> public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, EndPoint endPoint, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IRetryPolicy reconnectPolicy) : this(connectionFactory, protocol, endPoint, serviceProvider, loggerFactory) { _reconnectPolicy = reconnectPolicy; } /// <summary> /// Initializes a new instance of the <see cref="HubConnection"/> class. /// </summary> /// <param name="connectionFactory">The <see cref="IConnectionFactory" /> used to create a connection each time <see cref="StartAsync" /> is called.</param> /// <param name="protocol">The <see cref="IHubProtocol" /> used by the connection.</param> /// <param name="endPoint">The <see cref="EndPoint"/> to connect to.</param> /// <param name="serviceProvider">An <see cref="IServiceProvider"/> containing the services provided to this <see cref="HubConnection"/> instance.</param> /// <param name="loggerFactory">The logger factory.</param> /// <remarks> /// The <see cref="IServiceProvider"/> used to initialize the connection will be disposed when the connection is disposed. /// </remarks> public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, EndPoint endPoint, IServiceProvider serviceProvider, ILoggerFactory loggerFactory) { _connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory)); _protocol = protocol ?? throw new ArgumentNullException(nameof(protocol)); _endPoint = endPoint ?? throw new ArgumentNullException(nameof(endPoint)); _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; _logger = _loggerFactory.CreateLogger<HubConnection>(); _state = new ReconnectingConnectionState(_logger); _logScope = new ConnectionLogScope(); } /// <summary> /// Starts a connection to the server. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous start.</returns> public virtual async Task StartAsync(CancellationToken cancellationToken = default) { CheckDisposed(); using (_logger.BeginScope(_logScope)) { await StartAsyncInner(cancellationToken).ForceAsync(); } } private async Task StartAsyncInner(CancellationToken cancellationToken = default) { await _state.WaitConnectionLockAsync(token: cancellationToken); try { if (!_state.TryChangeState(HubConnectionState.Disconnected, HubConnectionState.Connecting)) { throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started if it is not in the {nameof(HubConnectionState.Disconnected)} state."); } // The StopCts is canceled at the start of StopAsync should be reset every time the connection finishes stopping. // If this token is currently canceled, it means that StartAsync was called while StopAsync was still running. if (_state.StopCts.Token.IsCancellationRequested) { throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started while {nameof(StopAsync)} is running."); } using (CreateLinkedToken(cancellationToken, _state.StopCts.Token, out var linkedToken)) { await StartAsyncCore(linkedToken); } _state.ChangeState(HubConnectionState.Connecting, HubConnectionState.Connected); } catch { if (_state.TryChangeState(HubConnectionState.Connecting, HubConnectionState.Disconnected)) { _state.StopCts = new CancellationTokenSource(); } throw; } finally { _state.ReleaseConnectionLock(); } } /// <summary> /// Stops a connection to the server. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous stop.</returns> public virtual async Task StopAsync(CancellationToken cancellationToken = default) { CheckDisposed(); using (_logger.BeginScope(_logScope)) { await StopAsyncCore(disposing: false).ForceAsync(); } } // Current plan for IAsyncDisposable is that DisposeAsync will NOT take a CancellationToken // https://github.com/dotnet/csharplang/blob/195efa07806284d7b57550e7447dc8bd39c156bf/proposals/async-streams.md#iasyncdisposable /// <summary> /// Disposes the <see cref="HubConnection"/>. /// </summary> /// <returns>A <see cref="ValueTask"/> that represents the asynchronous dispose.</returns> public virtual async ValueTask DisposeAsync() { if (!_disposed) { using (_logger.BeginScope(_logScope)) { await StopAsyncCore(disposing: true).ForceAsync(); } } } // If the registered callback blocks it can cause the client to stop receiving messages. If you need to block, get off the current thread first. /// <summary> /// Registers a handler that will be invoked when the hub method with the specified method name is invoked. /// </summary> /// <param name="methodName">The name of the hub method to define.</param> /// <param name="parameterTypes">The parameters types expected by the hub method.</param> /// <param name="handler">The handler that will be raised when the hub method is invoked.</param> /// <param name="state">A state object that will be passed to the handler.</param> /// <returns>A subscription that can be disposed to unsubscribe from the hub method.</returns> /// <remarks> /// This is a low level method for registering a handler. Using an <see cref="HubConnectionExtensions"/> <c>On</c> extension method is recommended. /// </remarks> public virtual IDisposable On(string methodName, Type[] parameterTypes, Func<object?[], object, Task> handler, object state) { Log.RegisteringHandler(_logger, methodName); CheckDisposed(); // It's OK to be disposed while registering a callback, we'll just never call the callback anyway (as with all the callbacks registered before disposal). var invocationHandler = new InvocationHandler(parameterTypes, handler, state); var invocationList = _handlers.AddOrUpdate(methodName, _ => new InvocationHandlerList(invocationHandler), (_, invocations) => { lock (invocations) { invocations.Add(invocationHandler); } return invocations; }); return new Subscription(invocationHandler, invocationList); } /// <summary> /// Removes all handlers associated with the method with the specified method name. /// </summary> /// <param name="methodName">The name of the hub method from which handlers are being removed</param> public virtual void Remove(string methodName) { CheckDisposed(); Log.RemovingHandlers(_logger, methodName); _handlers.TryRemove(methodName, out _); } /// <summary> /// Invokes a streaming hub method on the server using the specified method name, return type and arguments. /// </summary> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="returnType">The return type of the server method.</param> /// <param name="args">The arguments used to invoke the server method.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns> /// A <see cref="Task{TResult}"/> that represents the asynchronous invoke. /// The <see cref="Task{TResult}.Result"/> property returns a <see cref="ChannelReader{T}"/> for the streamed hub method values. /// </returns> /// <remarks> /// This is a low level method for invoking a streaming hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>StreamAsChannelAsync</c> extension method is recommended. /// </remarks> public virtual async Task<ChannelReader<object?>> StreamAsChannelCoreAsync(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken = default) { using (_logger.BeginScope(_logScope)) { return await StreamAsChannelCoreAsyncCore(methodName, returnType, args, cancellationToken).ForceAsync(); } } /// <summary> /// Invokes a hub method on the server using the specified method name, return type and arguments. /// </summary> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="returnType">The return type of the server method.</param> /// <param name="args">The arguments used to invoke the server method.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns> /// A <see cref="Task{TResult}"/> that represents the asynchronous invoke. /// The <see cref="Task{TResult}.Result"/> property returns an <see cref="object"/> for the hub method return value. /// </returns> /// <remarks> /// This is a low level method for invoking a hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>InvokeAsync</c> extension method is recommended. /// </remarks> public virtual async Task<object?> InvokeCoreAsync(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken = default) { using (_logger.BeginScope(_logScope)) { return await InvokeCoreAsyncCore(methodName, returnType, args, cancellationToken).ForceAsync(); } } /// <summary> /// Invokes a hub method on the server using the specified method name and arguments. /// Does not wait for a response from the receiver. /// </summary> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="args">The arguments used to invoke the server method.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous invoke.</returns> /// <remarks> /// This is a low level method for invoking a hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>SendAsync</c> extension method is recommended. /// </remarks> public virtual async Task SendCoreAsync(string methodName, object?[] args, CancellationToken cancellationToken = default) { using (_logger.BeginScope(_logScope)) { await SendCoreAsyncCore(methodName, args, cancellationToken).ForceAsync(); } } private async Task StartAsyncCore(CancellationToken cancellationToken) { _state.AssertInConnectionLock(); SafeAssert(_state.CurrentConnectionStateUnsynchronized == null, "We already have a connection!"); cancellationToken.ThrowIfCancellationRequested(); CheckDisposed(); Log.Starting(_logger); // Start the connection var connection = await _connectionFactory.ConnectAsync(_endPoint, cancellationToken); var startingConnectionState = new ConnectionState(connection, this); // From here on, if an error occurs we need to shut down the connection because // we still own it. try { Log.HubProtocol(_logger, _protocol.Name, _protocol.Version); await HandshakeAsync(startingConnectionState, cancellationToken); } catch (Exception ex) { Log.ErrorStartingConnection(_logger, ex); // Can't have any invocations to cancel, we're in the lock. await CloseAsync(startingConnectionState.Connection); throw; } // Set this at the end to avoid setting internal state until the connection is real _state.CurrentConnectionStateUnsynchronized = startingConnectionState; // Tell the server we intend to ping. // Old clients never ping, and shouldn't be timed out, so ping to tell the server that we should be timed out if we stop. // StartAsyncCore is invoked and awaited by StartAsyncInner and ReconnectAsync with the connection lock still acquired. if (!(connection.Features.Get<IConnectionInherentKeepAliveFeature>()?.HasInherentKeepAlive ?? false)) { await SendHubMessage(startingConnectionState, PingMessage.Instance, cancellationToken); } startingConnectionState.ReceiveTask = ReceiveLoop(startingConnectionState); Log.Started(_logger); } private static ValueTask CloseAsync(ConnectionContext connection) { return connection.DisposeAsync(); } // This method does both Dispose and Start, the 'disposing' flag indicates which. // The behaviors are nearly identical, except that the _disposed flag is set in the lock // if we're disposing. private async Task StopAsyncCore(bool disposing) { // StartAsync acquires the connection lock for the duration of the handshake. // ReconnectAsync also acquires the connection lock for reconnect attempts and handshakes. // Cancel the StopCts without acquiring the lock so we can short-circuit it. _state.StopCts.Cancel(); // Potentially wait for StartAsync to finish, and block a new StartAsync from // starting until we've finished stopping. await _state.WaitConnectionLockAsync(token: default); // Ensure that ReconnectingState.ReconnectTask is not accessed outside of the lock. var reconnectTask = _state.ReconnectTask; if (reconnectTask.Status != TaskStatus.RanToCompletion) { // Let the current reconnect attempts finish if necessary without the lock. // Otherwise, ReconnectAsync will stall forever acquiring the lock. // It should never throw, even if the reconnect attempts fail. // The StopCts should prevent the HubConnection from restarting until it is reset. _state.ReleaseConnectionLock(); await reconnectTask; await _state.WaitConnectionLockAsync(token: default); } ConnectionState? connectionState; try { if (disposing && _disposed) { // DisposeAsync should be idempotent. return; } CheckDisposed(); connectionState = _state.CurrentConnectionStateUnsynchronized; // Set the stopping flag so that any invocations after this get a useful error message instead of // silently failing or throwing an error about the pipe being completed. if (connectionState != null) { connectionState.Stopping = true; } else { // Reset StopCts if there isn't an active connection so that the next StartAsync wont immediately fail due to the token being canceled _state.StopCts = new CancellationTokenSource(); } if (disposing) { // Must set this before calling DisposeAsync because the service provider has a reference to the HubConnection and will try to dispose it again _disposed = true; if (_serviceProvider is IAsyncDisposable asyncDispose) { await asyncDispose.DisposeAsync(); } else { (_serviceProvider as IDisposable)?.Dispose(); } } } finally { _state.ReleaseConnectionLock(); } // Now stop the connection we captured if (connectionState != null) { await connectionState.StopAsync(); } } /// <summary> /// Invokes a streaming hub method on the server using the specified method name, return type and arguments. /// </summary> /// <typeparam name="TResult">The return type of the streaming server method.</typeparam> /// <param name="methodName">The name of the server method to invoke.</param> /// <param name="args">The arguments used to invoke the server method.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns> /// A <see cref="IAsyncEnumerable{TResult}"/> that represents the stream. /// </returns> public virtual IAsyncEnumerable<TResult> StreamAsyncCore<TResult>(string methodName, object?[] args, CancellationToken cancellationToken = default) { var cts = cancellationToken.CanBeCanceled ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken) : new CancellationTokenSource(); var stream = CastIAsyncEnumerable<TResult>(methodName, args, cts); var cancelableStream = AsyncEnumerableAdapters.MakeCancelableTypedAsyncEnumerable(stream, cts); return cancelableStream; } private async IAsyncEnumerable<T> CastIAsyncEnumerable<T>(string methodName, object?[] args, CancellationTokenSource cts) { var reader = await StreamAsChannelCoreAsync(methodName, typeof(T), args, cts.Token); while (await reader.WaitToReadAsync(cts.Token)) { while (reader.TryRead(out var item)) { yield return (T)item!; } } } private async Task<ChannelReader<object?>> StreamAsChannelCoreAsyncCore(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken) { async Task OnStreamCanceled(InvocationRequest irq) { // We need to take the connection lock in order to ensure we a) have a connection and b) are the only one accessing the write end of the pipe. await _state.WaitConnectionLockAsync(token: default); try { if (_state.CurrentConnectionStateUnsynchronized != null) { Log.SendingCancellation(_logger, irq.InvocationId); // Fire and forget, if it fails that means we aren't connected anymore. _ = SendHubMessage(_state.CurrentConnectionStateUnsynchronized, new CancelInvocationMessage(irq.InvocationId), irq.CancellationToken); } else { Log.UnableToSendCancellation(_logger, irq.InvocationId); } } finally { _state.ReleaseConnectionLock(); } // Cancel the invocation irq.Dispose(); } var readers = default(Dictionary<string, object>); CheckDisposed(); var connectionState = await _state.WaitForActiveConnectionAsync(nameof(StreamAsChannelCoreAsync), token: cancellationToken); ChannelReader<object?> channel; try { CheckDisposed(); cancellationToken.ThrowIfCancellationRequested(); readers = PackageStreamingParams(connectionState, ref args, out var streamIds); // I just want an excuse to use 'irq' as a variable name... var irq = InvocationRequest.Stream(cancellationToken, returnType, connectionState.GetNextId(), _loggerFactory, this, out channel); await InvokeStreamCore(connectionState, methodName, irq, args, streamIds?.ToArray(), cancellationToken); if (cancellationToken.CanBeCanceled) { cancellationToken.Register(state => _ = OnStreamCanceled((InvocationRequest)state!), irq); } LaunchStreams(connectionState, readers, cancellationToken); } finally { _state.ReleaseConnectionLock(); } return channel; } private Dictionary<string, object>? PackageStreamingParams(ConnectionState connectionState, ref object?[] args, out List<string>? streamIds) { Dictionary<string, object>? readers = null; streamIds = null; var newArgsCount = args.Length; const int MaxStackSize = 256; Span<bool> isStreaming = args.Length <= MaxStackSize ? stackalloc bool[MaxStackSize].Slice(0, args.Length) : new bool[args.Length]; for (var i = 0; i < args.Length; i++) { var arg = args[i]; if (arg is not null && ReflectionHelper.IsStreamingType(arg.GetType())) { isStreaming[i] = true; newArgsCount--; if (readers is null) { readers = new Dictionary<string, object>(); } if (streamIds is null) { streamIds = new List<string>(); } var id = connectionState.GetNextId(); readers[id] = arg; streamIds.Add(id); Log.StartingStream(_logger, id); } } if (newArgsCount == args.Length) { return null; } var newArgs = newArgsCount > 0 ? new object?[newArgsCount] : Array.Empty<object?>(); int newArgsIndex = 0; for (var i = 0; i < args.Length; i++) { if (!isStreaming[i]) { newArgs[newArgsIndex] = args[i]; newArgsIndex++; } } args = newArgs; return readers; } private void LaunchStreams(ConnectionState connectionState, Dictionary<string, object>? readers, CancellationToken cancellationToken) { if (readers == null) { // if there were no streaming parameters then readers is never initialized return; } _state.AssertInConnectionLock(); // It's safe to access connectionState.UploadStreamToken as we still have the connection lock var cts = CancellationTokenSource.CreateLinkedTokenSource(connectionState.UploadStreamToken, cancellationToken); foreach (var kvp in readers) { var reader = kvp.Value; // For each stream that needs to be sent, run a "send items" task in the background. // This reads from the channel, attaches streamId, and sends to server. // A single background thread here quickly gets messy. if (ReflectionHelper.IsIAsyncEnumerable(reader.GetType())) { _ = _sendIAsyncStreamItemsMethod .MakeGenericMethod(reader.GetType().GetInterface("IAsyncEnumerable`1")!.GetGenericArguments()) .Invoke(this, new object[] { connectionState, kvp.Key.ToString(), reader, cts }); continue; } _ = _sendStreamItemsMethod .MakeGenericMethod(reader.GetType().GetGenericArguments()) .Invoke(this, new object[] { connectionState, kvp.Key.ToString(), reader, cts }); } } // this is called via reflection using the `_sendStreamItems` field private Task SendStreamItems<T>(ConnectionState connectionState, string streamId, ChannelReader<T> reader, CancellationTokenSource tokenSource) { async Task ReadChannelStream() { while (await reader.WaitToReadAsync(tokenSource.Token)) { while (!tokenSource.Token.IsCancellationRequested && reader.TryRead(out var item)) { await SendWithLock(connectionState, new StreamItemMessage(streamId, item), tokenSource.Token); Log.SendingStreamItem(_logger, streamId); } } } return CommonStreaming(connectionState, streamId, ReadChannelStream); } // this is called via reflection using the `_sendIAsyncStreamItemsMethod` field private Task SendIAsyncEnumerableStreamItems<T>(ConnectionState connectionState, string streamId, IAsyncEnumerable<T> stream, CancellationTokenSource tokenSource) { async Task ReadAsyncEnumerableStream() { var streamValues = AsyncEnumerableAdapters.MakeCancelableTypedAsyncEnumerable(stream, tokenSource); await foreach (var streamValue in streamValues) { await SendWithLock(connectionState, new StreamItemMessage(streamId, streamValue), tokenSource.Token); Log.SendingStreamItem(_logger, streamId); } } return CommonStreaming(connectionState, streamId, ReadAsyncEnumerableStream); } private async Task CommonStreaming(ConnectionState connectionState, string streamId, Func<Task> createAndConsumeStream) { Log.StartingStream(_logger, streamId); string? responseError = null; try { await createAndConsumeStream(); } catch (OperationCanceledException) { Log.CancelingStream(_logger, streamId); responseError = "Stream canceled by client."; } catch (Exception ex) { Log.ErroredStream(_logger, streamId, ex); responseError = $"Stream errored by client: '{ex}'"; } Log.CompletingStream(_logger, streamId); // Don't use cancellation token here // this is triggered by a cancellation token to tell the server that the client is done streaming await SendWithLock(connectionState, CompletionMessage.WithError(streamId, responseError), cancellationToken: default); } private async Task<object?> InvokeCoreAsyncCore(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken) { var readers = default(Dictionary<string, object>); CheckDisposed(); var connectionState = await _state.WaitForActiveConnectionAsync(nameof(InvokeCoreAsync), token: cancellationToken); Task<object?> invocationTask; try { CheckDisposed(); readers = PackageStreamingParams(connectionState, ref args, out var streamIds); var irq = InvocationRequest.Invoke(cancellationToken, returnType, connectionState.GetNextId(), _loggerFactory, this, out invocationTask); await InvokeCore(connectionState, methodName, irq, args, streamIds?.ToArray(), cancellationToken); LaunchStreams(connectionState, readers, cancellationToken); } finally { _state.ReleaseConnectionLock(); } // Wait for this outside the lock, because it won't complete until the server responds return await invocationTask; } private async Task InvokeCore(ConnectionState connectionState, string methodName, InvocationRequest irq, object?[] args, string[]? streams, CancellationToken cancellationToken) { Log.PreparingBlockingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName!, args.Length); // Client invocations are always blocking var invocationMessage = new InvocationMessage(irq.InvocationId, methodName, args, streams); Log.RegisteringInvocation(_logger, irq.InvocationId); connectionState.AddInvocation(irq); // Trace the full invocation Log.IssuingInvocation(_logger, irq.InvocationId, irq.ResultType.FullName!, methodName, args); try { await SendHubMessage(connectionState, invocationMessage, cancellationToken); } catch (Exception ex) { Log.FailedToSendInvocation(_logger, irq.InvocationId, ex); connectionState.TryRemoveInvocation(irq.InvocationId, out _); irq.Fail(ex); } } private async Task InvokeStreamCore(ConnectionState connectionState, string methodName, InvocationRequest irq, object?[] args, string[]? streams, CancellationToken cancellationToken) { _state.AssertConnectionValid(); Log.PreparingStreamingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName!, args.Length); var invocationMessage = new StreamInvocationMessage(irq.InvocationId, methodName, args, streams); Log.RegisteringInvocation(_logger, irq.InvocationId); connectionState.AddInvocation(irq); // Trace the full invocation Log.IssuingInvocation(_logger, irq.InvocationId, irq.ResultType.FullName!, methodName, args); try { await SendHubMessage(connectionState, invocationMessage, cancellationToken); } catch (Exception ex) { Log.FailedToSendInvocation(_logger, irq.InvocationId, ex); connectionState.TryRemoveInvocation(irq.InvocationId, out _); irq.Fail(ex); } } private async Task SendHubMessage(ConnectionState connectionState, HubMessage hubMessage, CancellationToken cancellationToken = default) { _state.AssertConnectionValid(); _protocol.WriteMessage(hubMessage, connectionState.Connection.Transport.Output); Log.SendingMessage(_logger, hubMessage); #pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods // REVIEW: If a token is passed in and is canceled during FlushAsync it seems to break .Complete()... await connectionState.Connection.Transport.Output.FlushAsync(); #pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods Log.MessageSent(_logger, hubMessage); // We've sent a message, so don't ping for a while connectionState.ResetSendPing(); } private async Task SendCoreAsyncCore(string methodName, object?[] args, CancellationToken cancellationToken) { var readers = default(Dictionary<string, object>); CheckDisposed(); var connectionState = await _state.WaitForActiveConnectionAsync(nameof(SendCoreAsync), token: cancellationToken); try { CheckDisposed(); readers = PackageStreamingParams(connectionState, ref args, out var streamIds); Log.PreparingNonBlockingInvocation(_logger, methodName, args.Length); var invocationMessage = new InvocationMessage(null, methodName, args, streamIds?.ToArray()); await SendHubMessage(connectionState, invocationMessage, cancellationToken); LaunchStreams(connectionState, readers, cancellationToken); } finally { _state.ReleaseConnectionLock(); } } private async Task SendWithLock(ConnectionState expectedConnectionState, HubMessage message, CancellationToken cancellationToken, [CallerMemberName] string callerName = "") { CheckDisposed(); var connectionState = await _state.WaitForActiveConnectionAsync(callerName, token: cancellationToken); try { CheckDisposed(); SafeAssert(ReferenceEquals(expectedConnectionState, connectionState), "The connection state changed unexpectedly!"); await SendHubMessage(connectionState, message, cancellationToken); } finally { _state.ReleaseConnectionLock(); } } private async Task<CloseMessage?> ProcessMessagesAsync(HubMessage message, ConnectionState connectionState, ChannelWriter<InvocationMessage> invocationMessageWriter) { Log.ResettingKeepAliveTimer(_logger); connectionState.ResetTimeout(); InvocationRequest? irq; switch (message) { case InvocationBindingFailureMessage bindingFailure: // The server can't receive a response, so we just drop the message and log // REVIEW: Is this the right approach? Log.ArgumentBindingFailure(_logger, bindingFailure.InvocationId, bindingFailure.Target, bindingFailure.BindingFailure.SourceException); break; case InvocationMessage invocation: Log.ReceivedInvocation(_logger, invocation.InvocationId, invocation.Target, invocation.Arguments); await invocationMessageWriter.WriteAsync(invocation); break; case CompletionMessage completion: if (!connectionState.TryRemoveInvocation(completion.InvocationId!, out irq)) { Log.DroppedCompletionMessage(_logger, completion.InvocationId!); break; } DispatchInvocationCompletion(completion, irq); irq.Dispose(); break; case StreamItemMessage streamItem: // if there's no open StreamInvocation with the given id, then complete with an error if (!connectionState.TryGetInvocation(streamItem.InvocationId!, out irq)) { Log.DroppedStreamMessage(_logger, streamItem.InvocationId!); break; } await DispatchInvocationStreamItemAsync(streamItem, irq); break; case CloseMessage close: if (string.IsNullOrEmpty(close.Error)) { Log.ReceivedClose(_logger); } else { Log.ReceivedCloseWithError(_logger, close.Error); } return close; case PingMessage _: Log.ReceivedPing(_logger); // timeout is reset above, on receiving any message break; default: throw new InvalidOperationException($"Unexpected message type: {message.GetType().FullName}"); } return null; } private async Task DispatchInvocationAsync(InvocationMessage invocation) { // Find the handler if (!_handlers.TryGetValue(invocation.Target, out var invocationHandlerList)) { Log.MissingHandler(_logger, invocation.Target); return; } // Grabbing the current handlers var copiedHandlers = invocationHandlerList.GetHandlers(); foreach (var handler in copiedHandlers) { try { await handler.InvokeAsync(invocation.Arguments); } catch (Exception ex) { Log.ErrorInvokingClientSideMethod(_logger, invocation.Target, ex); } } } private async Task DispatchInvocationStreamItemAsync(StreamItemMessage streamItem, InvocationRequest irq) { Log.ReceivedStreamItem(_logger, irq.InvocationId); if (irq.CancellationToken.IsCancellationRequested) { Log.CancelingStreamItem(_logger, irq.InvocationId); } else if (!await irq.StreamItem(streamItem.Item)) { Log.ReceivedStreamItemAfterClose(_logger, irq.InvocationId); } } private void DispatchInvocationCompletion(CompletionMessage completion, InvocationRequest irq) { Log.ReceivedInvocationCompletion(_logger, irq.InvocationId); if (irq.CancellationToken.IsCancellationRequested) { Log.CancelingInvocationCompletion(_logger, irq.InvocationId); } else { irq.Complete(completion); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(HubConnection)); } } private async Task HandshakeAsync(ConnectionState startingConnectionState, CancellationToken cancellationToken) { // Send the Handshake request Log.SendingHubHandshake(_logger); var handshakeRequest = new HandshakeRequestMessage(_protocol.Name, _protocol.Version); HandshakeProtocol.WriteRequestMessage(handshakeRequest, startingConnectionState.Connection.Transport.Output); var sendHandshakeResult = await startingConnectionState.Connection.Transport.Output.FlushAsync(CancellationToken.None); if (sendHandshakeResult.IsCompleted) { // The other side disconnected var ex = new IOException("The server disconnected before the handshake could be started."); Log.ErrorReceivingHandshakeResponse(_logger, ex); throw ex; } var input = startingConnectionState.Connection.Transport.Input; using var handshakeCts = new CancellationTokenSource(HandshakeTimeout); try { // cancellationToken already contains _state.StopCts.Token, so we don't have to link it again using (CreateLinkedToken(cancellationToken, handshakeCts.Token, out var linkedToken)) { while (true) { var result = await input.ReadAsync(linkedToken); var buffer = result.Buffer; var consumed = buffer.Start; var examined = buffer.End; try { // Read first message out of the incoming data if (!buffer.IsEmpty) { if (HandshakeProtocol.TryParseResponseMessage(ref buffer, out var message)) { // Adjust consumed and examined to point to the end of the handshake // response, this handles the case where invocations are sent in the same payload // as the negotiate response. consumed = buffer.Start; examined = consumed; if (message.Error != null) { Log.HandshakeServerError(_logger, message.Error); throw new HubException( $"Unable to complete handshake with the server due to an error: {message.Error}"); } Log.HandshakeComplete(_logger); break; } } if (result.IsCompleted) { // Not enough data, and we won't be getting any more data. throw new InvalidOperationException( "The server disconnected before sending a handshake response"); } } finally { input.AdvanceTo(consumed, examined); } } } } catch (HubException) { // This was already logged as a HandshakeServerError throw; } catch (InvalidDataException ex) { Log.ErrorInvalidHandshakeResponse(_logger, ex); throw; } catch (OperationCanceledException ex) { if (handshakeCts.IsCancellationRequested) { Log.ErrorHandshakeTimedOut(_logger, HandshakeTimeout, ex); } else { Log.ErrorHandshakeCanceled(_logger, ex); } throw; } catch (Exception ex) { Log.ErrorReceivingHandshakeResponse(_logger, ex); throw; } } private async Task ReceiveLoop(ConnectionState connectionState) { // We hold a local capture of the connection state because StopAsync may dump out the current one. // We'll be locking any time we want to check back in to the "active" connection state. _state.AssertInConnectionLock(); Log.ReceiveLoopStarting(_logger); // Performs periodic tasks -- here sending pings and checking timeout // Disposed with `timer.Stop()` in the finally block below var timer = new TimerAwaitable(TickRate, TickRate); var timerTask = connectionState.TimerLoop(timer); var uploadStreamSource = new CancellationTokenSource(); connectionState.UploadStreamToken = uploadStreamSource.Token; var invocationMessageChannel = Channel.CreateUnbounded<InvocationMessage>(_receiveLoopOptions); // We can't safely wait for this task when closing without introducing deadlock potential when calling StopAsync in a .On method connectionState.InvocationMessageReceiveTask = StartProcessingInvocationMessages(invocationMessageChannel.Reader); async Task StartProcessingInvocationMessages(ChannelReader<InvocationMessage> invocationMessageChannelReader) { while (await invocationMessageChannelReader.WaitToReadAsync()) { while (invocationMessageChannelReader.TryRead(out var invocationMessage)) { await DispatchInvocationAsync(invocationMessage); } } } var input = connectionState.Connection.Transport.Input; try { while (true) { var result = await input.ReadAsync(); var buffer = result.Buffer; try { if (result.IsCanceled) { // We were canceled. Possibly because we were stopped gracefully break; } else if (!buffer.IsEmpty) { Log.ProcessingMessage(_logger, buffer.Length); CloseMessage? closeMessage = null; while (_protocol.TryParseMessage(ref buffer, connectionState, out var message)) { // We have data, process it closeMessage = await ProcessMessagesAsync(message, connectionState, invocationMessageChannel.Writer); if (closeMessage != null) { // Closing because we got a close frame, possibly with an error in it. if (closeMessage.Error != null) { connectionState.CloseException = new HubException($"The server closed the connection with the following error: {closeMessage.Error}"); } // Stopping being true indicates the client shouldn't try to reconnect even if automatic reconnects are enabled. if (!closeMessage.AllowReconnect) { connectionState.Stopping = true; } break; } } // If we're closing stop everything if (closeMessage != null) { break; } } if (result.IsCompleted) { if (!buffer.IsEmpty) { throw new InvalidDataException("Connection terminated while reading a message."); } break; } } finally { // The buffer was sliced up to where it was consumed, so we can just advance to the start. // We mark examined as `buffer.End` so that if we didn't receive a full frame, we'll wait for more data // before yielding the read again. input.AdvanceTo(buffer.Start, buffer.End); } } } catch (Exception ex) { Log.ServerDisconnectedWithError(_logger, ex); connectionState.CloseException = ex; } finally { invocationMessageChannel.Writer.TryComplete(); timer.Stop(); await timerTask; uploadStreamSource.Cancel(); await HandleConnectionClose(connectionState); } } // Internal for testing internal Task RunTimerActions() { // Don't bother acquiring the connection lock. This is only called from tests. return _state.CurrentConnectionStateUnsynchronized!.RunTimerActions(); } // Internal for testing internal void OnServerTimeout() { // Don't bother acquiring the connection lock. This is only called from tests. _state.CurrentConnectionStateUnsynchronized!.OnServerTimeout(); } private async Task HandleConnectionClose(ConnectionState connectionState) { // Clear the connectionState field await _state.WaitConnectionLockAsync(token: default); try { SafeAssert(ReferenceEquals(_state.CurrentConnectionStateUnsynchronized, connectionState), "Someone other than ReceiveLoop cleared the connection state!"); _state.CurrentConnectionStateUnsynchronized = null; // Dispose the connection await CloseAsync(connectionState.Connection); // Cancel any outstanding invocations within the connection lock connectionState.CancelOutstandingInvocations(connectionState.CloseException); if (connectionState.Stopping || _reconnectPolicy == null) { if (connectionState.CloseException != null) { Log.ShutdownWithError(_logger, connectionState.CloseException); } else { Log.ShutdownConnection(_logger); } _state.ChangeState(HubConnectionState.Connected, HubConnectionState.Disconnected); CompleteClose(connectionState.CloseException); } else { _state.ReconnectTask = ReconnectAsync(connectionState.CloseException); } } finally { _state.ReleaseConnectionLock(); } } private void CompleteClose(Exception? closeException) { _state.AssertInConnectionLock(); _state.StopCts = new CancellationTokenSource(); RunCloseEvent(closeException); } private void RunCloseEvent(Exception? closeException) { var closed = Closed; async Task RunClosedEventAsync() { // Dispatch to the thread pool before we invoke the user callback await AwaitableThreadPool.Yield(); try { Log.InvokingClosedEventHandler(_logger); await closed.Invoke(closeException); } catch (Exception ex) { Log.ErrorDuringClosedEvent(_logger, ex); } } // There is no need to start a new task if there is no Closed event registered if (closed != null) { // Fire-and-forget the closed event _ = RunClosedEventAsync(); } } private async Task ReconnectAsync(Exception? closeException) { var previousReconnectAttempts = 0; var reconnectStartTime = DateTime.UtcNow; var retryReason = closeException; var nextRetryDelay = GetNextRetryDelay(previousReconnectAttempts, TimeSpan.Zero, retryReason); // We still have the connection lock from the caller, HandleConnectionClose. _state.AssertInConnectionLock(); if (nextRetryDelay == null) { Log.FirstReconnectRetryDelayNull(_logger); _state.ChangeState(HubConnectionState.Connected, HubConnectionState.Disconnected); CompleteClose(closeException); return; } _state.ChangeState(HubConnectionState.Connected, HubConnectionState.Reconnecting); if (closeException != null) { Log.ReconnectingWithError(_logger, closeException); } else { Log.Reconnecting(_logger); } RunReconnectingEvent(closeException); while (nextRetryDelay != null) { Log.AwaitingReconnectRetryDelay(_logger, previousReconnectAttempts + 1, nextRetryDelay.Value); try { await Task.Delay(nextRetryDelay.Value, _state.StopCts.Token); } catch (OperationCanceledException ex) { Log.ReconnectingStoppedDuringRetryDelay(_logger); await _state.WaitConnectionLockAsync(token: default); try { _state.ChangeState(HubConnectionState.Reconnecting, HubConnectionState.Disconnected); CompleteClose(GetOperationCanceledException("Connection stopped during reconnect delay. Done reconnecting.", ex, _state.StopCts.Token)); } finally { _state.ReleaseConnectionLock(); } return; } await _state.WaitConnectionLockAsync(token: default); try { SafeAssert(ReferenceEquals(_state.CurrentConnectionStateUnsynchronized, null), "Someone other than Reconnect set the connection state!"); await StartAsyncCore(_state.StopCts.Token); Log.Reconnected(_logger, previousReconnectAttempts, DateTime.UtcNow - reconnectStartTime); _state.ChangeState(HubConnectionState.Reconnecting, HubConnectionState.Connected); RunReconnectedEvent(); return; } catch (Exception ex) { retryReason = ex; Log.ReconnectAttemptFailed(_logger, ex); if (_state.StopCts.IsCancellationRequested) { Log.ReconnectingStoppedDuringReconnectAttempt(_logger); _state.ChangeState(HubConnectionState.Reconnecting, HubConnectionState.Disconnected); CompleteClose(GetOperationCanceledException("Connection stopped during reconnect attempt. Done reconnecting.", ex, _state.StopCts.Token)); return; } previousReconnectAttempts++; } finally { _state.ReleaseConnectionLock(); } nextRetryDelay = GetNextRetryDelay(previousReconnectAttempts, DateTime.UtcNow - reconnectStartTime, retryReason); } await _state.WaitConnectionLockAsync(token: default); try { SafeAssert(ReferenceEquals(_state.CurrentConnectionStateUnsynchronized, null), "Someone other than Reconnect set the connection state!"); var elapsedTime = DateTime.UtcNow - reconnectStartTime; Log.ReconnectAttemptsExhausted(_logger, previousReconnectAttempts, elapsedTime); _state.ChangeState(HubConnectionState.Reconnecting, HubConnectionState.Disconnected); var message = $"Reconnect retries have been exhausted after {previousReconnectAttempts} failed attempts and {elapsedTime} elapsed. Disconnecting."; CompleteClose(new OperationCanceledException(message)); } finally { _state.ReleaseConnectionLock(); } } private TimeSpan? GetNextRetryDelay(long previousRetryCount, TimeSpan elapsedTime, Exception? retryReason) { try { return _reconnectPolicy!.NextRetryDelay(new RetryContext { PreviousRetryCount = previousRetryCount, ElapsedTime = elapsedTime, RetryReason = retryReason, }); } catch (Exception ex) { Log.ErrorDuringNextRetryDelay(_logger, ex); return null; } } private OperationCanceledException GetOperationCanceledException(string message, Exception innerException, CancellationToken cancellationToken) { #if NETSTANDARD2_1 || NETCOREAPP return new OperationCanceledException(message, innerException, _state.StopCts.Token); #else return new OperationCanceledException(message, innerException); #endif } private void RunReconnectingEvent(Exception? closeException) { var reconnecting = Reconnecting; async Task RunReconnectingEventAsync() { // Dispatch to the thread pool before we invoke the user callback await AwaitableThreadPool.Yield(); try { await reconnecting.Invoke(closeException); } catch (Exception ex) { Log.ErrorDuringReconnectingEvent(_logger, ex); } } // There is no need to start a new task if there is no Reconnecting event registered if (reconnecting != null) { // Fire-and-forget the closed event _ = RunReconnectingEventAsync(); } } private void RunReconnectedEvent() { var reconnected = Reconnected; async Task RunReconnectedEventAsync() { // Dispatch to the thread pool before we invoke the user callback await AwaitableThreadPool.Yield(); try { await reconnected.Invoke(ConnectionId); } catch (Exception ex) { Log.ErrorDuringReconnectedEvent(_logger, ex); } } // There is no need to start a new task if there is no Reconnected event registered if (reconnected != null) { // Fire-and-forget the reconnected event _ = RunReconnectedEventAsync(); } } private static IDisposable? CreateLinkedToken(CancellationToken token1, CancellationToken token2, out CancellationToken linkedToken) { if (!token1.CanBeCanceled) { linkedToken = token2; return null; } else if (!token2.CanBeCanceled) { linkedToken = token1; return null; } else { var cts = CancellationTokenSource.CreateLinkedTokenSource(token1, token2); linkedToken = cts.Token; return cts; } } // Debug.Assert plays havoc with Unit Tests. But I want something that I can "assert" only in Debug builds. [Conditional("DEBUG")] private static void SafeAssert(bool condition, string message, [CallerMemberName] string? memberName = null, [CallerFilePath] string? fileName = null, [CallerLineNumber] int lineNumber = 0) { if (!condition) { throw new Exception($"Assertion failed in {memberName}, at {fileName}:{lineNumber}: {message}"); } } private class Subscription : IDisposable { private readonly InvocationHandler _handler; private readonly InvocationHandlerList _handlerList; public Subscription(InvocationHandler handler, InvocationHandlerList handlerList) { _handler = handler; _handlerList = handlerList; } public void Dispose() { _handlerList.Remove(_handler); } } private class InvocationHandlerList { private readonly List<InvocationHandler> _invocationHandlers; // A lazy cached copy of the handlers that doesn't change for thread safety. // Adding or removing a handler sets this to null. private InvocationHandler[]? _copiedHandlers; internal InvocationHandlerList(InvocationHandler handler) { _invocationHandlers = new List<InvocationHandler>() { handler }; } internal InvocationHandler[] GetHandlers() { var handlers = _copiedHandlers; if (handlers == null) { lock (_invocationHandlers) { // Check if the handlers are set, if not we'll copy them over. if (_copiedHandlers == null) { _copiedHandlers = _invocationHandlers.ToArray(); } handlers = _copiedHandlers; } } return handlers; } internal void Add(InvocationHandler handler) { lock (_invocationHandlers) { _invocationHandlers.Add(handler); _copiedHandlers = null; } } internal void Remove(InvocationHandler handler) { lock (_invocationHandlers) { if (_invocationHandlers.Remove(handler)) { _copiedHandlers = null; } } } } private readonly struct InvocationHandler { public Type[] ParameterTypes { get; } private readonly Func<object?[], object, Task> _callback; private readonly object _state; public InvocationHandler(Type[] parameterTypes, Func<object?[], object, Task> callback, object state) { _callback = callback; ParameterTypes = parameterTypes; _state = state; } public Task InvokeAsync(object?[] parameters) { return _callback(parameters, _state); } } private class ConnectionState : IInvocationBinder { private readonly HubConnection _hubConnection; private readonly ILogger _logger; private readonly bool _hasInherentKeepAlive; private readonly object _lock = new object(); private readonly Dictionary<string, InvocationRequest> _pendingCalls = new Dictionary<string, InvocationRequest>(StringComparer.Ordinal); private TaskCompletionSource<object?>? _stopTcs; private volatile bool _stopping; private int _nextInvocationId; private long _nextActivationServerTimeout; private long _nextActivationSendPing; public ConnectionContext Connection { get; } public Task? ReceiveTask { get; set; } public Exception? CloseException { get; set; } public CancellationToken UploadStreamToken { get; set; } // We store this task so we can view it in a dump file, but never await it public Task? InvocationMessageReceiveTask { get; set; } // Indicates the connection is stopping AND the client should NOT attempt to reconnect even if automatic reconnects are enabled. // This means either HubConnection.DisposeAsync/StopAsync was called OR a CloseMessage with AllowReconnects set to false was received. public bool Stopping { get => _stopping; set => _stopping = value; } public ConnectionState(ConnectionContext connection, HubConnection hubConnection) { Connection = connection; _hubConnection = hubConnection; _hubConnection._logScope.ConnectionId = connection.ConnectionId; _logger = _hubConnection._logger; _hasInherentKeepAlive = connection.Features.Get<IConnectionInherentKeepAliveFeature>()?.HasInherentKeepAlive ?? false; } public string GetNextId() => (++_nextInvocationId).ToString(CultureInfo.InvariantCulture); public void AddInvocation(InvocationRequest irq) { lock (_lock) { if (_pendingCalls.ContainsKey(irq.InvocationId)) { Log.InvocationAlreadyInUse(_logger, irq.InvocationId); throw new InvalidOperationException($"Invocation ID '{irq.InvocationId}' is already in use."); } else { _pendingCalls.Add(irq.InvocationId, irq); } } } public bool TryGetInvocation(string invocationId, [NotNullWhen(true)] out InvocationRequest? irq) { lock (_lock) { return _pendingCalls.TryGetValue(invocationId, out irq); } } public bool TryRemoveInvocation(string invocationId, [NotNullWhen(true)] out InvocationRequest? irq) { lock (_lock) { if (_pendingCalls.TryGetValue(invocationId, out irq)) { _pendingCalls.Remove(invocationId); return true; } else { return false; } } } public void CancelOutstandingInvocations(Exception? exception) { Log.CancelingOutstandingInvocations(_logger); lock (_lock) { foreach (var outstandingCall in _pendingCalls.Values) { Log.RemovingInvocation(_logger, outstandingCall.InvocationId); if (exception != null) { outstandingCall.Fail(exception); } outstandingCall.Dispose(); } _pendingCalls.Clear(); } } public Task StopAsync() { // We want multiple StopAsync calls on the same connection state // to wait for the same "stop" to complete. lock (_lock) { if (_stopTcs != null) { return _stopTcs.Task; } else { _stopTcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); return StopAsyncCore(); } } } private async Task StopAsyncCore() { Log.Stopping(_logger); // Complete our write pipe, which should cause everything to shut down Log.TerminatingReceiveLoop(_logger); Connection.Transport.Input.CancelPendingRead(); // Wait ServerTimeout for the server or transport to shut down. Log.WaitingForReceiveLoopToTerminate(_logger); await (ReceiveTask ?? Task.CompletedTask); Log.Stopped(_logger); _hubConnection._logScope.ConnectionId = null; _stopTcs!.TrySetResult(null); } public async Task TimerLoop(TimerAwaitable timer) { // initialize the timers timer.Start(); ResetTimeout(); ResetSendPing(); using (timer) { // await returns True until `timer.Stop()` is called in the `finally` block of `ReceiveLoop` while (await timer) { await RunTimerActions(); } } } public void ResetSendPing() { Volatile.Write(ref _nextActivationSendPing, (DateTime.UtcNow + _hubConnection.KeepAliveInterval).Ticks); } public void ResetTimeout() { Volatile.Write(ref _nextActivationServerTimeout, (DateTime.UtcNow + _hubConnection.ServerTimeout).Ticks); } // Internal for testing internal async Task RunTimerActions() { if (_hasInherentKeepAlive) { return; } if (DateTime.UtcNow.Ticks > Volatile.Read(ref _nextActivationServerTimeout)) { OnServerTimeout(); } if (DateTime.UtcNow.Ticks > Volatile.Read(ref _nextActivationSendPing) && !Stopping) { if (!_hubConnection._state.TryAcquireConnectionLock()) { Log.UnableToAcquireConnectionLockForPing(_logger); return; } Log.AcquiredConnectionLockForPing(_logger); try { if (_hubConnection._state.CurrentConnectionStateUnsynchronized != null) { SafeAssert(ReferenceEquals(_hubConnection._state.CurrentConnectionStateUnsynchronized, this), "Something reset the connection state before the timer loop completed!"); await _hubConnection.SendHubMessage(this, PingMessage.Instance); } } finally { _hubConnection._state.ReleaseConnectionLock(); } } } // Internal for testing internal void OnServerTimeout() { CloseException = new TimeoutException( $"Server timeout ({_hubConnection.ServerTimeout.TotalMilliseconds:0.00}ms) elapsed without receiving a message from the server."); Connection.Transport.Input.CancelPendingRead(); } Type IInvocationBinder.GetReturnType(string invocationId) { if (!TryGetInvocation(invocationId, out var irq)) { Log.ReceivedUnexpectedResponse(_logger, invocationId); throw new KeyNotFoundException($"No invocation with id '{invocationId}' could be found."); } return irq.ResultType; } Type IInvocationBinder.GetStreamItemType(string invocationId) { // previously, streaming was only server->client, and used GetReturnType for StreamItems // literally the same code as the above method if (!TryGetInvocation(invocationId, out var irq)) { Log.ReceivedUnexpectedResponse(_logger, invocationId); throw new KeyNotFoundException($"No invocation with id '{invocationId}' could be found."); } return irq.ResultType; } IReadOnlyList<Type> IInvocationBinder.GetParameterTypes(string methodName) { if (!_hubConnection._handlers.TryGetValue(methodName, out var invocationHandlerList)) { Log.MissingHandler(_logger, methodName); return Type.EmptyTypes; } // We use the parameter types of the first handler var handlers = invocationHandlerList.GetHandlers(); if (handlers.Length > 0) { return handlers[0].ParameterTypes; } throw new InvalidOperationException($"There are no callbacks registered for the method '{methodName}'"); } } private class ReconnectingConnectionState { // This lock protects the connection state. private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1, 1); private readonly ILogger _logger; public ReconnectingConnectionState(ILogger logger) { _logger = logger; StopCts = new CancellationTokenSource(); ReconnectTask = Task.CompletedTask; } public ConnectionState? CurrentConnectionStateUnsynchronized { get; set; } public HubConnectionState OverallState { get; private set; } public CancellationTokenSource StopCts { get; set; } = new CancellationTokenSource(); public Task ReconnectTask { get; set; } = Task.CompletedTask; public void ChangeState(HubConnectionState expectedState, HubConnectionState newState) { if (!TryChangeState(expectedState, newState)) { Log.StateTransitionFailed(_logger, expectedState, newState, OverallState); throw new InvalidOperationException($"The HubConnection failed to transition from the '{expectedState}' state to the '{newState}' state because it was actually in the '{OverallState}' state."); } } public bool TryChangeState(HubConnectionState expectedState, HubConnectionState newState) { AssertInConnectionLock(); Log.AttemptingStateTransition(_logger, expectedState, newState); if (OverallState != expectedState) { return false; } OverallState = newState; return true; } [Conditional("DEBUG")] public void AssertInConnectionLock([CallerMemberName] string? memberName = null, [CallerFilePath] string? fileName = null, [CallerLineNumber] int lineNumber = 0) => SafeAssert(_connectionLock.CurrentCount == 0, "We're not in the Connection Lock!", memberName, fileName, lineNumber); [Conditional("DEBUG")] public void AssertConnectionValid([CallerMemberName] string? memberName = null, [CallerFilePath] string? fileName = null, [CallerLineNumber] int lineNumber = 0) { AssertInConnectionLock(memberName, fileName, lineNumber); SafeAssert(CurrentConnectionStateUnsynchronized != null, "We don't have a connection!", memberName, fileName, lineNumber); } public Task WaitConnectionLockAsync(CancellationToken token, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0) { Log.WaitingOnConnectionLock(_logger, memberName, filePath, lineNumber); return _connectionLock.WaitAsync(token); } public bool TryAcquireConnectionLock() { if (OperatingSystem.IsBrowser()) { return _connectionLock.WaitAsync(0).Result; } return _connectionLock.Wait(0); } // Don't call this method in a try/finally that releases the lock since we're also potentially releasing the connection lock here. public async Task<ConnectionState> WaitForActiveConnectionAsync(string methodName, CancellationToken token, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0) { await WaitConnectionLockAsync(token, methodName); if (CurrentConnectionStateUnsynchronized == null || CurrentConnectionStateUnsynchronized.Stopping) { ReleaseConnectionLock(methodName); throw new InvalidOperationException($"The '{methodName}' method cannot be called if the connection is not active"); } return CurrentConnectionStateUnsynchronized; } public void ReleaseConnectionLock([CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0) { Log.ReleasingConnectionLock(_logger, memberName, filePath, lineNumber); _connectionLock.Release(); } } } }
43.543886
294
0.569173
[ "MIT" ]
48355746/AspNetCore
src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs
88,307
C#
using System; using LumiSoft.Net; namespace LumiSoft.Net.IMAP.Server { /// <summary> /// Provides data for the AuthUser event for POP3_Server and SMTP_Server. /// </summary> public class AuthUser_EventArgs { private IMAP_Session m_pSession = null; private string m_UserName = ""; private string m_PasswData = ""; private string m_Data = ""; private AuthType m_AuthType; private bool m_Validated = false; private string m_ReturnData = ""; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to IMAP session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(IMAP_Session session,string userName,string passwData,string data,AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = passwData; m_Data = data; m_AuthType = authType; } #region Properties Implementation /// <summary> /// Gets reference to smtp session. /// </summary> public IMAP_Session Session { get{ return m_pSession; } } /// <summary> /// User name. /// </summary> public string UserName { get{ return m_UserName; } } /// <summary> /// Password data. eg. for AUTH=PLAIN it's password and for AUTH=APOP it's md5HexHash. /// </summary> public string PasswData { get{ return m_PasswData; } } /// <summary> /// Authentication specific data(as tag). /// </summary> public string AuthData { get{ return m_Data; } } /// <summary> /// Authentication type. /// </summary> public AuthType AuthType { get{ return m_AuthType; } } /// <summary> /// Gets or sets if user is valid. /// </summary> public bool Validated { get{ return m_Validated; } set{ m_Validated = value; } } /// <summary> /// Gets or sets authentication data what must be returned for connected client. /// </summary> public string ReturnData { get{ return m_ReturnData; } set{ m_ReturnData = value; } } #endregion } }
22
112
0.640374
[ "Apache-2.0" ]
jeske/StepsDB-alpha
ThirdParty/LumiSoft/Net/Net/IMAP/Server/AuthUser_EventArgs.cs
2,244
C#
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Reflection; using Behaviac.Design.Attributes; using Behaviac.Design.Data; using Behaviac.Design.Network; using Behaviac.Design.Nodes; namespace Behaviac.Design { public partial class ParametersPanel : UserControl { class RowControl { private string _name; public string Name { get { return this._name; } set { this._name = value; } } private System.Windows.Forms.Label _nameLabel; public System.Windows.Forms.Label NameLabel { get { return _nameLabel; } set { _nameLabel = value; } } private System.Windows.Forms.Label _typeLabel; public System.Windows.Forms.Label TypeLabel { get { return _typeLabel; } set { _typeLabel = value; } } private DesignerPropertyEditor _valueEditor; public DesignerPropertyEditor ValueEditor { get { return _valueEditor; } set { _valueEditor = value; } } } private List<RowControl> _rowControls = new List<RowControl>(); private AgentType _agentType = null; private string _agentFullname = string.Empty; public ParametersPanel() { InitializeComponent(); columnStyles = tableLayoutPanel.ColumnStyles; } public void InspectObject(AgentType agentType, string agentFullname) { _agentType = agentType; _agentFullname = agentFullname; preLayout(); deleteAllRowControls(); if (agentType != null) { IList<PropertyDef> properties = agentType.GetProperties(); foreach (PropertyDef p in properties) { if (!p.IsArrayElement) { addRowControl(p); } } } postLayout(); } public bool SetProperty(BehaviorNode behavior, string valueName, string valueStr) { DesignerPropertyEditor propertyEditor = getPropertyEditor(valueName); if (propertyEditor == null && behavior != null) { Node root = behavior as Node; foreach (PropertyDef p in root.LocalVars) { if (!p.IsArrayElement && p.BasicName == valueName) { propertyEditor = addRowControl(p); break; } } } if (propertyEditor == null) { return false; } VariableDef var = propertyEditor.GetVariable(); if (var.Value.ToString().ToLower() != valueStr.ToLower()) { Plugin.InvokeTypeParser(null, var.ValueType, valueStr, (object value) => var.Value = value, null); propertyEditor.ValueWasnotAssigned(); propertyEditor.SetVariable(var, null); propertyEditor.ValueWasAssigned(); return true; } return false; } public void SetProperty(FrameStatePool.PlanningState nodeState, string agentFullName) { Debug.Check(nodeState != null); //iterate all the properties for (int i = 0; i < _rowControls.Count; ++i) { RowControl rc = _rowControls[i]; object v = GetPropertyValue(nodeState, agentFullName, rc.Name); if (v != null) { SetProperty(null, rc.Name, v.ToString()); } } } private static object GetPropertyValue(FrameStatePool.PlanningState nodeState, string agentFullName, string propertyName) { FrameStatePool.PlanningState ns = nodeState; bool bOk = ns._agents.ContainsKey(agentFullName) && ns._agents[agentFullName].ContainsKey(propertyName); //if the current node has no value, to look for it in the parent's object v = null; while (!bOk) { ns = ns._parent; if (ns == null) { break; } bOk = ns._agents.ContainsKey(agentFullName) && ns._agents[agentFullName].ContainsKey(propertyName); } if (bOk) { Debug.Check(ns._agents[agentFullName].ContainsKey(propertyName)); v = ns._agents[agentFullName][propertyName]; } return v; } private void preLayout() { this.tableLayoutPanel.SuspendLayout(); this.SuspendLayout(); } private void postLayout() { this.tableLayoutPanel.ResumeLayout(); this.tableLayoutPanel.PerformLayout(); this.ResumeLayout(); this.PerformLayout(); columnStyles = tableLayoutPanel.ColumnStyles; } private DesignerPropertyEditor getPropertyEditor(string propertyName) { for (int i = 0; i < _rowControls.Count; ++i) { if (_rowControls[i].Name == propertyName) { return _rowControls[i].ValueEditor; } } return null; } private int getRowIndex(DesignerPropertyEditor valueEditor) { for (int i = 0; i < _rowControls.Count; ++i) { if (_rowControls[i].ValueEditor == valueEditor) { return i; } } return -1; } private DesignerPropertyEditor createPropertyEditor(PropertyDef property) { Type type = property.Type; Type editorType = Plugin.InvokeEditorType(type); Debug.Check(editorType != null); DesignerPropertyEditor editor = (DesignerPropertyEditor)editorType.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, new object[0]); editor.TabStop = false; editor.Dock = System.Windows.Forms.DockStyle.Fill; editor.Margin = new System.Windows.Forms.Padding(0); editor.ValueWasChanged += new DesignerPropertyEditor.ValueChanged(editor_ValueWasChanged); VariableDef var = new VariableDef(Plugin.DefaultValue(type)); editor.SetVariable(var, null); editor.ValueWasAssigned(); return editor; } private DesignerPropertyEditor addRowControl(PropertyDef property) { this.tableLayoutPanel.RowCount++; this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); int rowIndex = _rowControls.Count + 1; RowControl rowControl = new RowControl(); _rowControls.Add(rowControl); rowControl.Name = property.BasicName; rowControl.NameLabel = new System.Windows.Forms.Label(); rowControl.NameLabel.Dock = System.Windows.Forms.DockStyle.Fill; rowControl.NameLabel.Margin = new System.Windows.Forms.Padding(0); rowControl.NameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; rowControl.NameLabel.Text = property.DisplayName; this.tableLayoutPanel.Controls.Add(rowControl.NameLabel, 0, rowIndex); rowControl.TypeLabel = new System.Windows.Forms.Label(); rowControl.TypeLabel.Dock = System.Windows.Forms.DockStyle.Fill; rowControl.TypeLabel.Margin = new System.Windows.Forms.Padding(0); rowControl.TypeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; rowControl.TypeLabel.Text = Plugin.GetNativeTypeName(property.Type); this.tableLayoutPanel.Controls.Add(rowControl.TypeLabel, 1, rowIndex); rowControl.ValueEditor = createPropertyEditor(property); rowControl.ValueEditor.Dock = System.Windows.Forms.DockStyle.Fill; rowControl.ValueEditor.Margin = new System.Windows.Forms.Padding(0); this.tableLayoutPanel.Controls.Add(rowControl.ValueEditor, 2, rowIndex); return rowControl.ValueEditor; } private void deleteAllRowControls() { for (int rowIndex = _rowControls.Count - 1; rowIndex >= 0; --rowIndex) { RowControl rowControl = _rowControls[rowIndex]; _rowControls.RemoveAt(rowIndex); this.tableLayoutPanel.RowStyles.RemoveAt(rowIndex); this.tableLayoutPanel.Controls.Remove(rowControl.NameLabel); this.tableLayoutPanel.Controls.Remove(rowControl.TypeLabel); if (rowControl.ValueEditor != null) { this.tableLayoutPanel.Controls.Remove(rowControl.ValueEditor); } } this.tableLayoutPanel.RowCount = 1; } private void editor_ValueWasChanged(object sender, DesignerPropertyInfo property) { if (string.IsNullOrEmpty(_agentFullname)) { return; } int index = getRowIndex(sender as DesignerPropertyEditor); if (index > -1) { RowControl row = _rowControls[index]; VariableDef var = row.ValueEditor.GetVariable(); if (var != null && var.Value != null) { string value = var.Value.ToString(); if (!string.IsNullOrEmpty(value)) { string valueType = row.TypeLabel.Text; string valueName = row.Name; if (AgentDataPool.CurrentFrame > -1) { AgentDataPool.AddValue(_agentFullname, valueName, AgentDataPool.CurrentFrame, value); } NetworkManager.Instance.SendProperty(_agentFullname, valueType, valueName, value); } } } } private void lostAnyFocus() { this.Enabled = false; this.Enabled = true; } private void ParametersPanel_Click(object sender, EventArgs e) { lostAnyFocus(); } private void tableLayoutPanel_Click(object sender, EventArgs e) { lostAnyFocus(); } TableLayoutColumnStyleCollection columnStyles; bool resizing = false; int colindex = -1; private void tableLayoutPanel_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { columnStyles = tableLayoutPanel.ColumnStyles; resizing = true; } } private void tableLayoutPanel_MouseMove(object sender, MouseEventArgs e) { List<float> widthes = new List<float>(); if (columnStyles.Count > 0 && columnStyles[0].SizeType == SizeType.Absolute) { for (int i = 0; i < columnStyles.Count; i++) { widthes.Add(columnStyles[i].Width); } } else { widthes.Add(nameLabel.Width); widthes.Add(typeLabel.Width); widthes.Add(valueLabel.Width); } if (!resizing) { float width = 0; for (int i = 0; i < widthes.Count; i++) { width += widthes[i]; if (e.X > width - 5 && e.X < width + 5) { colindex = i; tableLayoutPanel.Cursor = Cursors.VSplit; break; } else { colindex = -1; tableLayoutPanel.Cursor = Cursors.Default; } } } if (resizing && (colindex > -1)) { if (colindex > -1) { float width = e.X; for (int i = 0; i < colindex; i++) { width -= widthes[i]; } if (width > 100) { tableLayoutPanel.SuspendLayout(); this.SuspendLayout(); columnStyles[colindex].SizeType = SizeType.Absolute; columnStyles[colindex].Width = width; tableLayoutPanel.ResumeLayout(); this.ResumeLayout(); } } } } private void tableLayoutPanel_MouseUp(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { resizing = false; tableLayoutPanel.Cursor = Cursors.Default; } } private void tableLayoutPanel_MouseLeave(object sender, EventArgs e) { resizing = false; tableLayoutPanel.Cursor = Cursors.Default; } } }
32.088421
162
0.509644
[ "MIT" ]
3-Delta/Unity-UI
Tools/AI/Behaviac/BehaviacDesigner/ParametersPanel.cs
15,244
C#
using ConsensusCore.Domain.BaseClasses; using ConsensusCore.Domain.Interfaces; using ConsensusCore.Domain.RPCs; using ConsensusCore.Domain.Utility; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsensusCore.Node.Services.Data.Components { public class WriteCache { public IOperationCacheRepository _operationCacheRepository; public ILogger<WriteCache> _logger; public int OperationsInQueue { get { return _operationCacheRepository.CountOperationsInQueue(); } } public int OperationsInTransit { get { return _operationCacheRepository.CountOperationsInTransit(); } } public object queueLock = new object(); ConcurrentQueue<ShardWriteOperation> operations = new ConcurrentQueue<ShardWriteOperation>(); //In-memory queue public List<ShardWriteOperation> OperationQueue { get; set; } = new List<ShardWriteOperation>(); public Dictionary<string, ShardWriteOperation> TransitQueue { get; set; } = new Dictionary<string, ShardWriteOperation>(); private readonly bool _persistToDisk; public WriteCache(IOperationCacheRepository transactionCacheRepository, ILogger<WriteCache> logger, bool persistToDisk = true) { _operationCacheRepository = transactionCacheRepository; _logger = logger; _persistToDisk = persistToDisk; //Load persistent queue into memory if (_persistToDisk) { _logger.LogDebug("Loading transactions to queue..."); OperationQueue = _operationCacheRepository.GetOperationQueueAsync().GetAwaiter().GetResult().ToList(); TransitQueue = _operationCacheRepository.GetTransitQueueAsync().GetAwaiter().GetResult().ToList().ToDictionary(swo => swo.Id, swo => swo); } else { _logger.LogWarning("Queue has been set to transient mode. Queue data will not be persisted to disk"); } } public async Task<bool> EnqueueOperationAsync(ShardWriteOperation transaction) { lock (queueLock) { OperationQueue.Add(transaction); } if (_persistToDisk) return await _operationCacheRepository.EnqueueOperationAsync(transaction); return true; } public async Task<ShardWriteOperation> DequeueOperation() { lock (queueLock) { var operationQueueResult = OperationQueue.Take(1); if (operationQueueResult.Count() > 0) { var operation = operationQueueResult.First(); TransitQueue.TryAdd(operation.Id, SystemExtension.Clone(operation)); OperationQueue.Remove(operation); if (_persistToDisk) { _operationCacheRepository.AddOperationToTransitAsync(operation).GetAwaiter().GetResult(); _operationCacheRepository.DeleteOperationFromQueueAsync(operation).GetAwaiter().GetResult(); } return operation; } return null; } } public async Task<bool> CompleteOperation(string transactionId) { lock (queueLock) { TransitQueue.Remove(transactionId); } if (_persistToDisk) { return await _operationCacheRepository.DeleteOperationFromTransitAsync(transactionId); } return true; } public bool IsOperationComplete(string transactionId) { lock (queueLock) { var isOperationInQueue = OperationQueue.Find(oq => oq.Id == transactionId) != null; return (!TransitQueue.ContainsKey(transactionId) && !isOperationInQueue); } } } }
40.343137
154
0.621142
[ "MIT" ]
xucito/consensus-core
ConsensusCore.Node/Services/Data/Components/WriteCache.cs
4,117
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("Odd Even Sum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Odd Even Sum")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("840269ed-8cce-47cd-8675-fa4ba61812b7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.756757
84
0.742305
[ "MIT" ]
delian1986/C-SoftUni-repo
Programming Basics/05.Cycles (For Loops)/ForLoops/Odd Even Sum/Properties/AssemblyInfo.cs
1,400
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary>Application stack major version.</summary> [System.ComponentModel.TypeConverter(typeof(StackMajorVersionTypeConverter))] public partial class StackMajorVersion { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMajorVersion" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersion" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersion DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new StackMajorVersion(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMajorVersion" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersion" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersion DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new StackMajorVersion(content); } /// <summary> /// Creates a new instance of <see cref="StackMajorVersion" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="StackMajorVersion" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersion FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMajorVersion" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal StackMajorVersion(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("DisplayVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).DisplayVersion = (string) content.GetValueForProperty("DisplayVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).DisplayVersion, global::System.Convert.ToString); } if (content.Contains("RuntimeVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).RuntimeVersion = (string) content.GetValueForProperty("RuntimeVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).RuntimeVersion, global::System.Convert.ToString); } if (content.Contains("IsDefault")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDefault = (bool?) content.GetValueForProperty("IsDefault",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDefault, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("MinorVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).MinorVersion = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMinorVersion[]) content.GetValueForProperty("MinorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).MinorVersion, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMinorVersion>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMinorVersionTypeConverter.ConvertFrom)); } if (content.Contains("ApplicationInsight")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).ApplicationInsight = (bool?) content.GetValueForProperty("ApplicationInsight",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).ApplicationInsight, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsPreview")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsPreview = (bool?) content.GetValueForProperty("IsPreview",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsPreview, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsDeprecated")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDeprecated = (bool?) content.GetValueForProperty("IsDeprecated",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDeprecated, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsHidden")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsHidden = (bool?) content.GetValueForProperty("IsHidden",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsHidden, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMajorVersion" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal StackMajorVersion(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("DisplayVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).DisplayVersion = (string) content.GetValueForProperty("DisplayVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).DisplayVersion, global::System.Convert.ToString); } if (content.Contains("RuntimeVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).RuntimeVersion = (string) content.GetValueForProperty("RuntimeVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).RuntimeVersion, global::System.Convert.ToString); } if (content.Contains("IsDefault")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDefault = (bool?) content.GetValueForProperty("IsDefault",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDefault, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("MinorVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).MinorVersion = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMinorVersion[]) content.GetValueForProperty("MinorVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).MinorVersion, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMinorVersion>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.StackMinorVersionTypeConverter.ConvertFrom)); } if (content.Contains("ApplicationInsight")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).ApplicationInsight = (bool?) content.GetValueForProperty("ApplicationInsight",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).ApplicationInsight, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsPreview")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsPreview = (bool?) content.GetValueForProperty("IsPreview",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsPreview, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsDeprecated")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDeprecated = (bool?) content.GetValueForProperty("IsDeprecated",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsDeprecated, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } if (content.Contains("IsHidden")) { ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsHidden = (bool?) content.GetValueForProperty("IsHidden",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStackMajorVersionInternal)this).IsHidden, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Application stack major version. [System.ComponentModel.TypeConverter(typeof(StackMajorVersionTypeConverter))] public partial interface IStackMajorVersion { } }
76.838384
617
0.702971
[ "MIT" ]
AlanFlorance/azure-powershell
src/Functions/generated/api/Models/Api20190801/StackMajorVersion.PowerShell.cs
15,017
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Auth_test.Models; namespace Auth_test.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
21.868421
112
0.595668
[ "MIT" ]
AnnaFrank17/iTra17
Auth_test/Auth_test/Controllers/HomeController.cs
833
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Dolittle.Security; using Machine.Specifications; using Moq; using It = Machine.Specifications.It; namespace Dolittle.Security.Specs.for_SecurityTarget { [Subject(typeof(SecurityTarget))] public class when_checking_can_authorize_with_no_securables_that_can_authorize { static Mock<ISecurable> securable_that_cannot_authorize; static Mock<ISecurable> another_securable_that_cannot_authorize; static SecurityTarget target; static bool can_authorize; Establish context = () => { securable_that_cannot_authorize = new Mock<ISecurable>(); securable_that_cannot_authorize.Setup(s => s.CanAuthorize(Moq.It.IsAny<object>())).Returns(false); another_securable_that_cannot_authorize = new Mock<ISecurable>(); another_securable_that_cannot_authorize.Setup(s => s.CanAuthorize(Moq.It.IsAny<object>())).Returns(false); target = new SecurityTarget(string.Empty); target.AddSecurable(securable_that_cannot_authorize.Object); target.AddSecurable(another_securable_that_cannot_authorize.Object); }; Because of = () => can_authorize = target.CanAuthorize(new object()); It should_not_be_authorizable = () => can_authorize.ShouldBeFalse(); } }
43.911765
122
0.703282
[ "MIT" ]
dolittle-fundamentals/DotNET.Fundamentals
Specifications/Security/for_SecurityTarget/when_checking_can_authorize_with_no_securables_that_can_authorize.cs
1,495
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// ListPolicyVersions Request Marshaller /// </summary> public class ListPolicyVersionsRequestMarshaller : IMarshaller<IRequest, ListPolicyVersionsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListPolicyVersionsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListPolicyVersionsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT"); request.HttpMethod = "GET"; string uriResourcePath = "/policies/{policyName}/version"; if (!publicRequest.IsSetPolicyName()) throw new AmazonIoTException("Request object does not have required field PolicyName set"); uriResourcePath = uriResourcePath.Replace("{policyName}", StringUtils.FromStringWithSlashEncoding(publicRequest.PolicyName)); request.ResourcePath = uriResourcePath; return request; } private static ListPolicyVersionsRequestMarshaller _instance = new ListPolicyVersionsRequestMarshaller(); internal static ListPolicyVersionsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListPolicyVersionsRequestMarshaller Instance { get { return _instance; } } } }
34.816092
151
0.664576
[ "Apache-2.0" ]
DalavanCloud/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/ListPolicyVersionsRequestMarshaller.cs
3,029
C#
namespace AdventOfCode.Levels._02; public record Command(Movement Movement, int Value);
29.333333
52
0.829545
[ "MIT" ]
KoTLiK/AdventOfCode
AdventOfCode.2021/Levels/02/Command.cs
88
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils; using DiscUtils.BootConfig; using DiscUtils.Common; using DiscUtils.Ntfs; using DiscUtils.Partitions; using DiscUtils.Registry; using DiscUtils.Streams; namespace OSClone { class Program : ProgramBase { // Shared to avoid continual re-allocation of a large buffer private static byte[] _copyBuffer = new byte[10 * 1024 * 1024]; private static string[] _excludedFiles = new string[] { @"\PAGEFILE.SYS", @"\HIBERFIL.SYS", @"\SYSTEM VOLUME INFORMATION" }; private CommandLineParameter _sourceFile; private CommandLineParameter _destFile; private CommandLineSwitch _labelSwitch; private Dictionary<long, string> _uniqueFiles = new Dictionary<long,string>(); static void Main(string[] args) { Program program = new Program(); program.Run(args); } protected override StandardSwitches DefineCommandLine(CommandLineParser parser) { _sourceFile = FileOrUriParameter("in_file", "The disk image containing the Operating System image to be cloned.", false); _destFile = FileOrUriParameter("out_file", "The path to the output disk image.", false); _labelSwitch = new CommandLineSwitch("l", "label", "name", "The volume label for the NTFS file system created."); parser.AddParameter(_sourceFile); parser.AddParameter(_destFile); parser.AddSwitch(_labelSwitch); return StandardSwitches.OutputFormatAndAdapterType | StandardSwitches.UserAndPassword | StandardSwitches.DiskSize; } protected override void DoRun() { if (DiskSize <= 0) { DisplayHelp(); return; } using (VirtualDisk sourceDisk = VirtualDisk.OpenDisk(_sourceFile.Value, FileAccess.Read, UserName, Password)) using (VirtualDisk destDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _destFile.Value, DiskParameters, UserName, Password)) { if (destDisk is DiscUtils.Vhd.Disk) { ((DiscUtils.Vhd.Disk)destDisk).AutoCommitFooter = false; } // Copy the MBR from the source disk, and invent a new signature for this new disk destDisk.SetMasterBootRecord(sourceDisk.GetMasterBootRecord()); destDisk.Signature = new Random().Next(); SparseStream sourcePartStream = SparseStream.FromStream(sourceDisk.Partitions[0].Open(), Ownership.None); NtfsFileSystem sourceNtfs = new NtfsFileSystem(sourcePartStream); // Copy the OS boot code into memory, so we can apply it when formatting the new disk byte[] bootCode; using (Stream bootStream = sourceNtfs.OpenFile("$Boot", FileMode.Open, FileAccess.Read)) { bootCode = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < bootCode.Length) { totalRead += bootStream.Read(bootCode, totalRead, bootCode.Length - totalRead); } } // Partition the new disk with a single NTFS partition BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs); VolumeManager volMgr = new VolumeManager(destDisk); string label = _labelSwitch.IsPresent ? _labelSwitch.Value : sourceNtfs.VolumeLabel; using (NtfsFileSystem destNtfs = NtfsFileSystem.Format(volMgr.GetLogicalVolumes()[0], label, bootCode)) { destNtfs.SetSecurity(@"\", sourceNtfs.GetSecurity(@"\")); destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled; sourceNtfs.NtfsOptions.HideHiddenFiles = false; sourceNtfs.NtfsOptions.HideSystemFiles = false; CopyFiles(sourceNtfs, destNtfs, @"\", true); if (destNtfs.FileExists(@"\boot\BCD")) { // Force all boot entries in the BCD to point to the newly created NTFS partition - does _not_ cope with // complex multi-volume / multi-boot scenarios at all. using (Stream bcdStream = destNtfs.OpenFile(@"\boot\BCD", FileMode.Open, FileAccess.ReadWrite)) { using (RegistryHive hive = new RegistryHive(bcdStream)) { Store store = new Store(hive.Root); foreach (var obj in store.Objects) { foreach (var elem in obj.Elements) { if (elem.Format == DiscUtils.BootConfig.ElementFormat.Device) { elem.Value = DiscUtils.BootConfig.ElementValue.ForDevice(elem.Value.ParentObject, volMgr.GetPhysicalVolumes()[0]); } } } } } } } } } private void CopyFiles(NtfsFileSystem sourceNtfs, NtfsFileSystem destNtfs, string path, bool subs) { if (subs) { foreach (var dir in sourceNtfs.GetDirectories(path)) { if (!IsExcluded(dir)) { int hardLinksRemaining = sourceNtfs.GetHardLinkCount(dir) - 1; bool newDir = false; long sourceFileId = sourceNtfs.GetFileId(dir); string refPath; if (_uniqueFiles.TryGetValue(sourceFileId, out refPath)) { // If this is another name for a known dir, recreate the hard link destNtfs.CreateHardLink(refPath, dir); } else { destNtfs.CreateDirectory(dir); newDir = true; FileAttributes fileAttrs = sourceNtfs.GetAttributes(dir); if ((fileAttrs & FileAttributes.ReparsePoint) != 0) { destNtfs.SetReparsePoint(dir, sourceNtfs.GetReparsePoint(dir)); } destNtfs.SetAttributes(dir, fileAttrs); destNtfs.SetSecurity(dir, sourceNtfs.GetSecurity(dir)); } // File may have a short name string shortName = sourceNtfs.GetShortName(dir); if (!string.IsNullOrEmpty(shortName) && shortName != dir) { destNtfs.SetShortName(dir, shortName); --hardLinksRemaining; } if (newDir) { if (hardLinksRemaining > 0) { _uniqueFiles[sourceFileId] = dir; } CopyFiles(sourceNtfs, destNtfs, dir, subs); } // Set standard information last (includes modification timestamps) destNtfs.SetFileStandardInformation(dir, sourceNtfs.GetFileStandardInformation(dir)); } } } foreach (var file in sourceNtfs.GetFiles(path)) { Console.WriteLine(file); int hardLinksRemaining = sourceNtfs.GetHardLinkCount(file) - 1; long sourceFileId = sourceNtfs.GetFileId(file); string refPath; if (_uniqueFiles.TryGetValue(sourceFileId, out refPath)) { // If this is another name for a known file, recreate the hard link destNtfs.CreateHardLink(refPath, file); } else { CopyFile(sourceNtfs, destNtfs, file); if (hardLinksRemaining > 0) { _uniqueFiles[sourceFileId] = file; } } // File may have a short name string shortName = sourceNtfs.GetShortName(file); if (!string.IsNullOrEmpty(shortName) && shortName != file) { destNtfs.SetShortName(file, shortName); } } } private void CopyFile(NtfsFileSystem sourceNtfs, NtfsFileSystem destNtfs, string path) { if (IsExcluded(path)) { return; } using (Stream s = sourceNtfs.OpenFile(path, FileMode.Open, FileAccess.Read)) using (Stream d = destNtfs.OpenFile(path, FileMode.Create, FileAccess.ReadWrite)) { d.SetLength(s.Length); int numRead = s.Read(_copyBuffer, 0, _copyBuffer.Length); while (numRead > 0) { d.Write(_copyBuffer, 0, numRead); numRead = s.Read(_copyBuffer, 0, _copyBuffer.Length); } } destNtfs.SetSecurity(path, sourceNtfs.GetSecurity(path)); destNtfs.SetFileStandardInformation(path, sourceNtfs.GetFileStandardInformation(path)); } private static bool IsExcluded(string path) { string pathUpper = path.ToUpperInvariant(); for (int i = 0; i < _excludedFiles.Length; ++i) { if (pathUpper == _excludedFiles[i]) { return true; } } return false; } } }
41.593525
158
0.529274
[ "MIT" ]
AssafTzurEl/DiscUtils
Utilities/OSClone/Program.cs
11,563
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion namespace Stimulsoft.Base.Json { /// <summary> /// Specifies float format handling options when writing special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/> with <see cref="JsonWriter"/>. /// </summary> public enum FloatFormatHandling { /// <summary> /// Write special floating point values as strings in JSON, e.g. "NaN", "Infinity", "-Infinity". /// </summary> String = 0, /// <summary> /// Write special floating point values as symbols in JSON, e.g. NaN, Infinity, -Infinity. /// Note that this will produce non-valid JSON. /// </summary> Symbol = 1, /// <summary> /// Write special floating point values as the property's default value in JSON, e.g. 0.0 for a <see cref="System.Double"/> property, null for a <see cref="System.Nullable{Double}"/> property. /// </summary> DefaultValue = 2 } }
44.1
200
0.689342
[ "MIT" ]
stimulsoft/Stimulsoft.Controls.Net
Stimulsoft.Base/Json/IO/FloatFormatHandling.cs
2,207
C#
using System; using System.Collections.Generic; using Alphaleonis.Win32.Filesystem; using System.Linq; using System.Text; using System.Threading.Tasks; using SCG.Data; using SCG.Commands; using System.Windows; using System.Windows.Input; using System.Text.RegularExpressions; using SCG.Data.View; using System.Windows.Media.Imaging; using Ookii.Dialogs.Wpf; using SCG.Interfaces; using SCG.Core; using System.Diagnostics; namespace SCG { public static class FileCommands { private static LoadCommands loadCommands; private static SaveCommands saveCommands; public static LoadCommands Load => loadCommands; public static SaveCommands Save => saveCommands; public static string AppDirectory = ""; public static string EnsureExtension(string filePath, string extension) { if(!FileExtensionFound(filePath, extension)) { return Path.ChangeExtension(filePath, extension); } return filePath; } public static string ReadFile(string filePath) { var contents = ""; try { if (File.Exists(filePath)) { using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4096, false)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(stream)) { contents = sr.ReadToEnd(); } } } else { Log.Here().Warning("File \"{0}\" does not exist.", filePath); } } catch (Exception e) { Log.Here().Error("Error reading file at {0} - {1}", filePath, e.ToString()); } return contents; } public static bool RenameFile(string filePath, string nextFilePath) { try { if (File.Exists(filePath)) { var result = File.Copy(filePath, nextFilePath, CopyOptions.FailIfExists); if(!result.IsCanceled && result.IsFile) { Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(filePath, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); Log.Here().Activity($"Renamed \"{filePath}\" to \"{nextFilePath}\"."); return true; } } else { Log.Here().Warning("File \"{0}\" does not exist.", filePath); } } catch (Exception e) { Log.Here().Error("Error reading file at {0} - {1}", filePath, e.ToString()); } return false; } public static async Task<string> ReadFileAsync(string filePath) { using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4096, true)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(stream)) { string contents = await sr.ReadToEndAsync(); return contents; } } } public static bool WriteToFile(string filePath, string contents, bool supressLogMessage = true) { try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write, 4096, false)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(stream)) { sw.WriteLine(contents); if (!supressLogMessage) Log.Here().Activity("Saved file: {0}", filePath); } } return true; } catch (Exception e) { Log.Here().Error("Error saving file at {0} - {1}", filePath, e.ToString()); return false; } } public static async Task<bool> WriteToFileAsync(string filePath, string contents, bool supressLogMessage = true) { try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write, 4096, true)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(stream)) { await sw.WriteLineAsync(contents); if (!supressLogMessage) Log.Here().Activity("Saved file: {0}", filePath); } } return true; } catch (Exception e) { Log.Here().Error("Error saving file at {0} - {1}", filePath, e.ToString()); return false; } } public static bool CreateFile(string filePath) { try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); FileInfo file = new FileInfo(filePath); file.Create(); Log.Here().Activity("Created file: {0}", filePath); return true; } catch (Exception e) { Log.Here().Error("Error creating file at {0} - {1}", filePath, e.ToString()); return false; } } public static void OpenConfirmationDialog(Window ParentWindow, string WindowTitle, string MainInstruction, string Content, Action<bool> TaskAction) { if(TaskDialog.OSSupportsTaskDialogs) { using (TaskDialog dialog = new TaskDialog()) { dialog.CenterParent = true; dialog.WindowTitle = WindowTitle; dialog.MainInstruction = MainInstruction; dialog.Content = Content; //dialog.ExpandedInformation = ""; //dialog.Footer = "Task Dialogs support footers and can even include <a href=\"http://www.ookii.org\">hyperlinks</a>."; dialog.FooterIcon = TaskDialogIcon.Information; //dialog.EnableHyperlinks = true; TaskDialogButton okButton = new TaskDialogButton(ButtonType.Ok); TaskDialogButton cancelButton = new TaskDialogButton(ButtonType.Cancel); dialog.Buttons.Add(okButton); dialog.Buttons.Add(cancelButton); //dialog.HyperlinkClicked += new EventHandler<HyperlinkClickedEventArgs>(TaskDialog_HyperLinkClicked); TaskDialogButton button = dialog.ShowDialog(ParentWindow); if (button.ButtonType == ButtonType.Ok || button.ButtonType == ButtonType.Yes) { TaskAction?.Invoke(true); } else { TaskAction?.Invoke(false); } } } } public static bool ModuleSettingsExist { get { return AppController.Main.CurrentModule != null && AppController.Main.CurrentModule.ModuleData != null && AppController.Main.CurrentModule.ModuleData.ModuleSettings != null; } } public static void OpenBackupFolder(IProjectData projectData) { if (ModuleSettingsExist) { string directory = Path.Combine(Path.GetFullPath(AppController.Main.CurrentModule.ModuleData.ModuleSettings.BackupRootDirectory), projectData.ProjectName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } Process.Start(directory); } } public static void OpenGitFolder(IProjectData projectData) { if (ModuleSettingsExist) { string directory = Path.Combine(Path.GetFullPath(AppController.Main.CurrentModule.ModuleData.ModuleSettings.GitRootDirectory), projectData.ProjectName); if (Directory.Exists(directory)) { Process.Start(directory); } else { Process.Start(Path.GetFullPath(AppController.Main.CurrentModule.ModuleData.ModuleSettings.GitRootDirectory)); } } } /* public static bool IsPathValid(String pathString) { Uri pathUri; Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri); return isValidUri && pathUri != null && pathUri.IsLoopback; } */ public static bool IsValidPath(string path) { if (String.IsNullOrWhiteSpace(path)) return false; if (PathIsRelative(path)) return true; if (path.Length < 3) return false; string validLongPathPrefix = @"\\?\"; path = path.Replace(validLongPathPrefix, ""); Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$"); if (!driveCheck.IsMatch(path.Substring(0, 3))) { return false; } var x1 = (path.Substring(3, path.Length - 3)); string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());; strTheseAreInvalidFileNameChars += @":?*"; Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]"); if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3))) { return false; } var driveLetterWithColonAndSlash = Path.GetPathRoot(path); if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash)) { return false; } return true; } public static bool IsValidFilePath(string path) { if (String.IsNullOrWhiteSpace(path)) return false; //check the path: if (Path.GetInvalidPathChars().Any(x => path.Contains(x))) return false; //check the filename (if one can be isolated out): string fileName = Path.GetFileName(path); if (Path.GetInvalidFileNameChars().Any(x => fileName.Contains(x))) return false; return true; } //private static Regex directoryRegex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$"); public static bool IsValidDirectoryPath(string path) { if (String.IsNullOrWhiteSpace(path)) return false; //check the path: if (Path.GetInvalidPathChars().Any(x => path.Contains(x))) return false; if(path[path.Length - 1] != '\\') return false; return true; //return directoryRegex.IsMatch(path); } public static bool PathIsRelative(string path) { try { Uri result; return Uri.TryCreate(path, UriKind.Relative, out result); } catch (Exception) { } return false; } public static bool IsValidImage(string filename) { if (String.IsNullOrWhiteSpace(filename) || !File.Exists(filename)) return false; return Helpers.Image.CheckImageType(filename) != Util.HelperUtil.ImageType.None; } public static bool FileExtensionFound(string fPath, params string[] extensions) { if (extensions.Length > 1) { Array.Sort(extensions, StringComparer.OrdinalIgnoreCase); int result = Array.BinarySearch(extensions, Path.GetExtension(fPath), StringComparer.OrdinalIgnoreCase); //Log.Here().Activity($"Binary search: {fPath} [{string.Join(",", extensions)}] = {result}"); return result > -1; } else if (extensions.Length == 1) { return extensions[0].Equals(Path.GetExtension(fPath), StringComparison.OrdinalIgnoreCase); } return false; } public static bool FileExists(string path) { if(PathIsRelative(path)) { return File.Exists(Path.ResolveRelativePath(AppDirectory, path)); } else { return File.Exists(path); } } public static bool DirectoryExists(string path) { if (PathIsRelative(path)) { return Directory.Exists(Path.ResolveRelativePath(AppDirectory, path)); } else { return Directory.Exists(path); } } public static void Init() { AppDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); loadCommands = new LoadCommands(); saveCommands = new SaveCommands(); } /* public static void SetData(MainAppData AppData) { loadCommands.SetData(AppData); saveCommands.SetData(AppData); } */ } }
27.464824
177
0.684841
[ "MIT" ]
LaughingLeader/SourceControlGenerator
SourceControlGenerator/Core/FileCommands.cs
10,933
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PlotViewBase.Events.cs" company="OxyPlot"> // Copyright (c) 2020 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using OxyPlot.XF.Skia.Effects; namespace OxyPlot.XF.Skia { /// <summary> /// Base class for WPF PlotView implementations. /// </summary> public abstract partial class PlotViewBase { /// <summary> /// The touch points of the previous touch event. /// </summary> private ScreenPoint[] previousTouchPoints; private void AddTouchEffect() { var touchEffect = new MyTouchEffect(); touchEffect.TouchAction += TouchEffect_TouchAction; this.Effects.Add(touchEffect); } private void TouchEffect_TouchAction(object sender, TouchActionEventArgs e) { switch (e.Type) { case TouchActionType.Pressed: OnTouchDownEvent(e); break; case TouchActionType.Moved: OnTouchMoveEvent(e); break; case TouchActionType.Released: OnTouchUpEvent(e); break; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Handles touch down events. /// </summary> /// <param name="e">The motion event arguments.</param> /// <returns><c>true</c> if the event was handled.</returns> private bool OnTouchDownEvent(TouchActionEventArgs e) { var args = ToTouchEventArgs(e, Scale); var handled = this.ActualController.HandleTouchStarted(this, args); this.previousTouchPoints = GetTouchPoints(e, Scale); return handled; } /// <summary> /// Handles touch move events. /// </summary> /// <param name="e">The motion event arguments.</param> /// <returns><c>true</c> if the event was handled.</returns> private bool OnTouchMoveEvent(TouchActionEventArgs e) { var currentTouchPoints = GetTouchPoints(e, Scale); var args = new XamarinOxyTouchEventArgs(currentTouchPoints, this.previousTouchPoints); var handled = this.ActualController.HandleTouchDelta(this, args); this.previousTouchPoints = currentTouchPoints; return handled; } /// <summary> /// Handles touch released events. /// </summary> /// <param name="e">The motion event arguments.</param> /// <returns><c>true</c> if the event was handled.</returns> private bool OnTouchUpEvent(TouchActionEventArgs e) { return this.ActualController.HandleTouchCompleted(this, ToTouchEventArgs(e, Scale)); } /// <summary> /// Converts an <see cref="TouchActionEventArgs" /> to a <see cref="OxyTouchEventArgs" />. /// </summary> /// <param name="e">The event arguments.</param> /// <param name = "scale">The resolution scale factor.</param> /// <returns>The converted event arguments.</returns> public static OxyTouchEventArgs ToTouchEventArgs(TouchActionEventArgs e, double scale) { return new XamarinOxyTouchEventArgs { Position = new ScreenPoint(e.Location.X / scale, e.Location.Y / scale), DeltaTranslation = new ScreenVector(0, 0), DeltaScale = new ScreenVector(1, 1), PointerCount = e.Locations.Length }; } /// <summary> /// Gets the touch points from the specified <see cref="TouchActionEventArgs" /> argument. /// </summary> /// <param name="e">The event arguments.</param> /// <param name = "scale">The resolution scale factor.</param> /// <returns>The touch points.</returns> public static ScreenPoint[] GetTouchPoints(TouchActionEventArgs e, double scale) { var result = new ScreenPoint[e.Locations.Length]; for (int i = 0; i < e.Locations.Length; i++) { result[i] = new ScreenPoint(e.Locations[i].X / scale, e.Locations[i].Y / scale); } return result; } } }
38.470588
120
0.538663
[ "MIT" ]
iniceice88/OxyPlot.Xamarin.Forms.Skia
Source/OxyPlot.Xamarin.Forms.Skia/PlotViewBase.Events.cs
4,580
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.KeyManagementService.Model { ///<summary> /// KeyManagementService exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class CloudHsmClusterInvalidConfigurationException : AmazonKeyManagementServiceException { /// <summary> /// Constructs a new CloudHsmClusterInvalidConfigurationException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public CloudHsmClusterInvalidConfigurationException(string message) : base(message) {} /// <summary> /// Construct instance of CloudHsmClusterInvalidConfigurationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public CloudHsmClusterInvalidConfigurationException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of CloudHsmClusterInvalidConfigurationException /// </summary> /// <param name="innerException"></param> public CloudHsmClusterInvalidConfigurationException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of CloudHsmClusterInvalidConfigurationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public CloudHsmClusterInvalidConfigurationException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of CloudHsmClusterInvalidConfigurationException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public CloudHsmClusterInvalidConfigurationException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the CloudHsmClusterInvalidConfigurationException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected CloudHsmClusterInvalidConfigurationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
45.896907
186
0.671159
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/CloudHsmClusterInvalidConfigurationException.cs
4,452
C#
using MathNet.Numerics.LinearAlgebra; using System; namespace PID_Tuner { /* public class Transfer { public double[] CooficientsX { get; set; } = new double[] { 1 }; public double[] CooficientsY { get; set; } = new double[] { }; private History<double> histX; private History<double> histY; public double Cycle(double input) { double accum = 0; //k=0 => -1 in time for (int k = 0; k < CooficientsY.Length; k++) accum += CooficientsY[k] * histY[k]; for (int k = 0; k < CooficientsX.Length; k++) accum += CooficientsX[k] * histX[k]; histX.Add(input); histY.Add(accum); return accum; } public void Reset() { histX = new History<double>(CooficientsX.Length); histY = new History<double>(CooficientsY.Length); } public static Transfer GenerateEstimate(double[] hInSamples, double[] hOutSamples, int numerators, int denumerators) { int num = numerators; int den = denumerators; int samples = 6; samples = hInSamples.Length - Math.Max(num, den); Matrix<double> F = Matrix<double>.Build.Dense(samples, num + den); //first sample is most actual sample. Vector<double> yShort = Vector<double>.Build.Dense(samples); for (int y = 0; y < F.RowCount; y++) { for (int x = 0; x < F.ColumnCount; x++) { int ind = F.RowCount - y + x - (x < num ? 0 : num); F[y, x] = (x < num ? hOutSamples[ind] : hInSamples[ind]); } yShort[y] = hOutSamples[samples - y - 1]; } Matrix<double> Ft = F.Transpose(); Matrix<double> F1 = Ft * F; Matrix<double> F2 = F1.PseudoInverse(); Vector<double> V1 = Ft * yShort; Vector<double> c = F2 * V1; Transfer t = new Transfer(); t.CooficientsY = c.SubVector(0, num).ToArray(); t.CooficientsX = c.SubVector(num, den).ToArray(); return t; } public override string ToString() { string s = "a=["; foreach(double c in CooficientsY) s += c.ToString("0.000000") + ", "; s = s.Substring(0, s.Length -2) + "]\r\nb=["; foreach (double c in CooficientsX) s += c.ToString("0.000000") + ", "; s = s.Substring(0, s.Length - 2) + "]\r\n"; return s; } } */ }
27.292929
124
0.483346
[ "MIT" ]
vanBassum/PID_Tuner
PID_Tuner/PID_Tuner/Filters/Transfer.cs
2,704
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.ComponentModel; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.Numerics; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { /// <summary> /// Encapsulates a GDI+ drawing surface. /// </summary> public sealed partial class Graphics : MarshalByRefObject, IDisposable, IDeviceContext { /// <summary> /// Handle to native DC - obtained from the GDI+ graphics object. We need to cache it to implement /// IDeviceContext interface. /// </summary> private IntPtr _nativeHdc; public delegate bool DrawImageAbort(IntPtr callbackdata); /// <summary> /// Callback for EnumerateMetafile methods. /// This method can then call Metafile.PlayRecord to play the record that was just enumerated. /// </summary> /// <param name="recordType">if >= MinRecordType, it's an EMF+ record</param> /// <param name="flags">always 0 for EMF records</param> /// <param name="dataSize">size of the data, or 0 if no data</param> /// <param name="data">pointer to the data, or NULL if no data (UINT32 aligned)</param> /// <param name="callbackData">pointer to callbackData, if any</param> /// <returns>False to abort enumerating, true to continue.</returns> public delegate bool EnumerateMetafileProc( EmfPlusRecordType recordType, int flags, int dataSize, IntPtr data, PlayRecordCallback callbackData); /// <summary> /// Handle to native GDI+ graphics object. This object is created on demand. /// </summary> internal IntPtr NativeGraphics { get; private set; } public Region Clip { get { var region = new Region(); int status = Gdip.GdipGetClip(new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion)); Gdip.CheckStatus(status); return region; } set => SetClip(value, CombineMode.Replace); } public RectangleF ClipBounds { get { Gdip.CheckStatus(Gdip.GdipGetClipBounds(new HandleRef(this, NativeGraphics), out RectangleF rect)); return rect; } } /// <summary> /// Gets or sets the <see cref='Drawing2D.CompositingMode'/> associated with this <see cref='Graphics'/>. /// </summary> public CompositingMode CompositingMode { get { Gdip.CheckStatus(Gdip.GdipGetCompositingMode(new HandleRef(this, NativeGraphics), out CompositingMode mode)); return mode; } set { if (value < CompositingMode.SourceOver || value > CompositingMode.SourceCopy) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CompositingMode)); Gdip.CheckStatus(Gdip.GdipSetCompositingMode(new HandleRef(this, NativeGraphics), value)); } } public CompositingQuality CompositingQuality { get { Gdip.CheckStatus(Gdip.GdipGetCompositingQuality(new HandleRef(this, NativeGraphics), out CompositingQuality cq)); return cq; } set { if (value < CompositingQuality.Invalid || value > CompositingQuality.AssumeLinear) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CompositingQuality)); Gdip.CheckStatus(Gdip.GdipSetCompositingQuality(new HandleRef(this, NativeGraphics), value)); } } public float DpiX { get { Gdip.CheckStatus(Gdip.GdipGetDpiX(new HandleRef(this, NativeGraphics), out float dpi)); return dpi; } } public float DpiY { get { Gdip.CheckStatus(Gdip.GdipGetDpiY(new HandleRef(this, NativeGraphics), out float dpi)); return dpi; } } /// <summary> /// Gets or sets the interpolation mode associated with this Graphics. /// </summary> public InterpolationMode InterpolationMode { get { Gdip.CheckStatus(Gdip.GdipGetInterpolationMode(new HandleRef(this, NativeGraphics), out InterpolationMode mode)); return mode; } set { if (value < InterpolationMode.Invalid || value > InterpolationMode.HighQualityBicubic) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(InterpolationMode)); // GDI+ interprets the value of InterpolationMode and sets a value accordingly. // Libgdiplus does not, so do this manually here. switch (value) { case InterpolationMode.Default: case InterpolationMode.Low: value = InterpolationMode.Bilinear; break; case InterpolationMode.High: value = InterpolationMode.HighQualityBicubic; break; case InterpolationMode.Invalid: throw new ArgumentException(SR.GdiplusInvalidParameter); default: break; } Gdip.CheckStatus(Gdip.GdipSetInterpolationMode(new HandleRef(this, NativeGraphics), value)); } } public bool IsClipEmpty { get { Gdip.CheckStatus(Gdip.GdipIsClipEmpty(new HandleRef(this, NativeGraphics), out bool isEmpty)); return isEmpty; } } public bool IsVisibleClipEmpty { get { Gdip.CheckStatus(Gdip.GdipIsVisibleClipEmpty(new HandleRef(this, NativeGraphics), out bool isEmpty)); return isEmpty; } } public float PageScale { get { Gdip.CheckStatus(Gdip.GdipGetPageScale(new HandleRef(this, NativeGraphics), out float scale)); return scale; } set { // Libgdiplus doesn't perform argument validation, so do this here for compatability. if (value <= 0 || value > 1000000032) throw new ArgumentException(SR.GdiplusInvalidParameter); Gdip.CheckStatus(Gdip.GdipSetPageScale(new HandleRef(this, NativeGraphics), value)); } } public GraphicsUnit PageUnit { get { Gdip.CheckStatus(Gdip.GdipGetPageUnit(new HandleRef(this, NativeGraphics), out GraphicsUnit unit)); return unit; } set { if (value < GraphicsUnit.World || value > GraphicsUnit.Millimeter) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(GraphicsUnit)); // GDI+ doesn't allow GraphicsUnit.World as a valid value for PageUnit. // Libgdiplus doesn't perform argument validation, so do this here. if (value == GraphicsUnit.World) throw new ArgumentException(SR.GdiplusInvalidParameter); Gdip.CheckStatus(Gdip.GdipSetPageUnit(new HandleRef(this, NativeGraphics), value)); } } public PixelOffsetMode PixelOffsetMode { get { Gdip.CheckStatus(Gdip.GdipGetPixelOffsetMode(new HandleRef(this, NativeGraphics), out PixelOffsetMode mode)); return mode; } set { if (value < PixelOffsetMode.Invalid || value > PixelOffsetMode.Half) throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PixelOffsetMode)); // GDI+ doesn't allow PixelOffsetMode.Invalid as a valid value for PixelOffsetMode. // Libgdiplus doesn't perform argument validation, so do this here. if (value == PixelOffsetMode.Invalid) throw new ArgumentException(SR.GdiplusInvalidParameter); Gdip.CheckStatus(Gdip.GdipSetPixelOffsetMode(new HandleRef(this, NativeGraphics), value)); } } public Point RenderingOrigin { get { Gdip.CheckStatus(Gdip.GdipGetRenderingOrigin(new HandleRef(this, NativeGraphics), out int x, out int y)); return new Point(x, y); } set { Gdip.CheckStatus(Gdip.GdipSetRenderingOrigin(new HandleRef(this, NativeGraphics), value.X, value.Y)); } } public SmoothingMode SmoothingMode { get { Gdip.CheckStatus(Gdip.GdipGetSmoothingMode(new HandleRef(this, NativeGraphics), out SmoothingMode mode)); return mode; } set { if (value < SmoothingMode.Invalid || value > SmoothingMode.AntiAlias) throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(SmoothingMode)); // GDI+ interprets the value of SmoothingMode and sets a value accordingly. // Libgdiplus does not, so do this manually here. switch (value) { case SmoothingMode.Default: case SmoothingMode.HighSpeed: value = SmoothingMode.None; break; case SmoothingMode.HighQuality: value = SmoothingMode.AntiAlias; break; case SmoothingMode.Invalid: throw new ArgumentException(SR.GdiplusInvalidParameter); default: break; } Gdip.CheckStatus(Gdip.GdipSetSmoothingMode(new HandleRef(this, NativeGraphics), value)); } } public int TextContrast { get { Gdip.CheckStatus(Gdip.GdipGetTextContrast(new HandleRef(this, NativeGraphics), out int textContrast)); return textContrast; } set { Gdip.CheckStatus(Gdip.GdipSetTextContrast(new HandleRef(this, NativeGraphics), value)); } } /// <summary> /// Gets or sets the rendering mode for text associated with this <see cref='Graphics'/>. /// </summary> public TextRenderingHint TextRenderingHint { get { Gdip.CheckStatus(Gdip.GdipGetTextRenderingHint(new HandleRef(this, NativeGraphics), out TextRenderingHint hint)); return hint; } set { if (value < TextRenderingHint.SystemDefault || value > TextRenderingHint.ClearTypeGridFit) throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(TextRenderingHint)); Gdip.CheckStatus(Gdip.GdipSetTextRenderingHint(new HandleRef(this, NativeGraphics), value)); } } /// <summary> /// Gets or sets the world transform for this <see cref='Graphics'/>. /// </summary> public Matrix Transform { get { var matrix = new Matrix(); Gdip.CheckStatus(Gdip.GdipGetWorldTransform( new HandleRef(this, NativeGraphics), new HandleRef(matrix, matrix.NativeMatrix))); return matrix; } set { Gdip.CheckStatus(Gdip.GdipSetWorldTransform( new HandleRef(this, NativeGraphics), new HandleRef(value, value.NativeMatrix))); } } /// <summary> /// Gets or sets the world transform elements for this <see cref="Graphics"/>. /// </summary> /// <remarks> /// This is a more performant alternative to <see cref="Transform"/> that does not need disposal. /// </remarks> public unsafe Matrix3x2 TransformElements { get { Gdip.CheckStatus(Gdip.GdipCreateMatrix(out IntPtr nativeMatrix)); try { Gdip.CheckStatus(Gdip.GdipGetWorldTransform( new HandleRef(this, NativeGraphics), new HandleRef(null, nativeMatrix))); Matrix3x2 matrix = default; Gdip.CheckStatus(Gdip.GdipGetMatrixElements(new HandleRef(null, nativeMatrix), (float*)&matrix)); return matrix; } finally { if (nativeMatrix != IntPtr.Zero) { Gdip.GdipDeleteMatrix(new HandleRef(null, nativeMatrix)); } } } set { IntPtr nativeMatrix = Matrix.CreateNativeHandle(value); try { Gdip.CheckStatus(Gdip.GdipSetWorldTransform( new HandleRef(this, NativeGraphics), new HandleRef(null, nativeMatrix))); } finally { if (nativeMatrix != IntPtr.Zero) { Gdip.GdipDeleteMatrix(new HandleRef(null, nativeMatrix)); } } } } public IntPtr GetHdc() { IntPtr hdc = IntPtr.Zero; Gdip.CheckStatus(Gdip.GdipGetDC(new HandleRef(this, NativeGraphics), out hdc)); _nativeHdc = hdc; // need to cache the hdc to be able to release with a call to IDeviceContext.ReleaseHdc(). return _nativeHdc; } [EditorBrowsable(EditorBrowsableState.Advanced)] public void ReleaseHdc(IntPtr hdc) => ReleaseHdcInternal(hdc); public void ReleaseHdc() => ReleaseHdcInternal(_nativeHdc); /// <summary> /// Forces immediate execution of all operations currently on the stack. /// </summary> public void Flush() => Flush(FlushIntention.Flush); /// <summary> /// Forces execution of all operations currently on the stack. /// </summary> public void Flush(FlushIntention intention) { Gdip.CheckStatus(Gdip.GdipFlush(new HandleRef(this, NativeGraphics), intention)); FlushCore(); } public void SetClip(Graphics g) => SetClip(g, CombineMode.Replace); public void SetClip(Graphics g, CombineMode combineMode) { if (g == null) throw new ArgumentNullException(nameof(g)); Gdip.CheckStatus(Gdip.GdipSetClipGraphics( new HandleRef(this, NativeGraphics), new HandleRef(g, g.NativeGraphics), combineMode)); } public void SetClip(Rectangle rect) => SetClip(rect, CombineMode.Replace); public void SetClip(Rectangle rect, CombineMode combineMode) { Gdip.CheckStatus(Gdip.GdipSetClipRectI( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, combineMode)); } public void SetClip(RectangleF rect) => SetClip(rect, CombineMode.Replace); public void SetClip(RectangleF rect, CombineMode combineMode) { Gdip.CheckStatus(Gdip.GdipSetClipRect( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, combineMode)); } public void SetClip(GraphicsPath path) => SetClip(path, CombineMode.Replace); public void SetClip(GraphicsPath path, CombineMode combineMode) { if (path == null) throw new ArgumentNullException(nameof(path)); Gdip.CheckStatus(Gdip.GdipSetClipPath( new HandleRef(this, NativeGraphics), new HandleRef(path, path._nativePath), combineMode)); } public void SetClip(Region region, CombineMode combineMode) { if (region == null) throw new ArgumentNullException(nameof(region)); Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), combineMode)); } public void IntersectClip(Rectangle rect) { Gdip.CheckStatus(Gdip.GdipSetClipRectI( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Intersect)); } public void IntersectClip(RectangleF rect) { Gdip.CheckStatus(Gdip.GdipSetClipRect( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Intersect)); } public void IntersectClip(Region region) { if (region == null) throw new ArgumentNullException(nameof(region)); Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), CombineMode.Intersect)); } public void ExcludeClip(Rectangle rect) { Gdip.CheckStatus(Gdip.GdipSetClipRectI( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Exclude)); } public void ExcludeClip(Region region) { if (region == null) throw new ArgumentNullException(nameof(region)); Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), CombineMode.Exclude)); } public void ResetClip() { Gdip.CheckStatus(Gdip.GdipResetClip(new HandleRef(this, NativeGraphics))); } public void TranslateClip(float dx, float dy) { Gdip.CheckStatus(Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy)); } public void TranslateClip(int dx, int dy) { Gdip.CheckStatus(Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy)); } public bool IsVisible(int x, int y) => IsVisible(new Point(x, y)); public bool IsVisible(Point point) { Gdip.CheckStatus(Gdip.GdipIsVisiblePointI( new HandleRef(this, NativeGraphics), point.X, point.Y, out bool isVisible)); return isVisible; } public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y)); public bool IsVisible(PointF point) { Gdip.CheckStatus(Gdip.GdipIsVisiblePoint( new HandleRef(this, NativeGraphics), point.X, point.Y, out bool isVisible)); return isVisible; } public bool IsVisible(int x, int y, int width, int height) { return IsVisible(new Rectangle(x, y, width, height)); } public bool IsVisible(Rectangle rect) { Gdip.CheckStatus(Gdip.GdipIsVisibleRectI( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, out bool isVisible)); return isVisible; } public bool IsVisible(float x, float y, float width, float height) { return IsVisible(new RectangleF(x, y, width, height)); } public bool IsVisible(RectangleF rect) { Gdip.CheckStatus(Gdip.GdipIsVisibleRect( new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, out bool isVisible)); return isVisible; } /// <summary> /// Resets the world transform to identity. /// </summary> public void ResetTransform() { Gdip.CheckStatus(Gdip.GdipResetWorldTransform(new HandleRef(this, NativeGraphics))); } /// <summary> /// Multiplies the <see cref='Matrix'/> that represents the world transform and <paramref name="matrix"/>. /// </summary> public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); /// <summary> /// Multiplies the <see cref='Matrix'/> that represents the world transform and <paramref name="matrix"/>. /// </summary> public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. if (matrix.NativeMatrix == IntPtr.Zero) return; Gdip.CheckStatus(Gdip.GdipMultiplyWorldTransform( new HandleRef(this, NativeGraphics), new HandleRef(matrix, matrix.NativeMatrix), order)); } public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend); public void TranslateTransform(float dx, float dy, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipTranslateWorldTransform(new HandleRef(this, NativeGraphics), dx, dy, order)); } public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend); public void ScaleTransform(float sx, float sy, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipScaleWorldTransform(new HandleRef(this, NativeGraphics), sx, sy, order)); } public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend); public void RotateTransform(float angle, MatrixOrder order) { Gdip.CheckStatus(Gdip.GdipRotateWorldTransform(new HandleRef(this, NativeGraphics), angle, order)); } /// <summary> /// Draws an arc from the specified ellipse. /// </summary> public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawArc( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Draws an arc from the specified ellipse. /// </summary> public void DrawArc(Pen pen, RectangleF rect, float startAngle, float sweepAngle) { DrawArc(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } /// <summary> /// Draws an arc from the specified ellipse. /// </summary> public void DrawArc(Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawArcI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Draws an arc from the specified ellipse. /// </summary> public void DrawArc(Pen pen, Rectangle rect, float startAngle, float sweepAngle) { DrawArc(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } /// <summary> /// Draws a cubic bezier curve defined by four ordered pairs that represent points. /// </summary> public void DrawBezier(Pen pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawBezier( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2, x3, y3, x4, y4)); } /// <summary> /// Draws a cubic bezier curve defined by four points. /// </summary> public void DrawBezier(Pen pen, PointF pt1, PointF pt2, PointF pt3, PointF pt4) { DrawBezier(pen, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); } /// <summary> /// Draws a cubic bezier curve defined by four points. /// </summary> public void DrawBezier(Pen pen, Point pt1, Point pt2, Point pt3, Point pt4) { DrawBezier(pen, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); } /// <summary> /// Draws the outline of a rectangle specified by <paramref name="rect"/>. /// </summary> public void DrawRectangle(Pen pen, Rectangle rect) { DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Draws the outline of the specified rectangle. /// </summary> public void DrawRectangle(Pen pen, float x, float y, float width, float height) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawRectangle( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); } /// <summary> /// Draws the outline of the specified rectangle. /// </summary> public void DrawRectangle(Pen pen, int x, int y, int width, int height) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawRectangleI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); } /// <summary> /// Draws the outlines of a series of rectangles. /// </summary> public unsafe void DrawRectangles(Pen pen, RectangleF[] rects) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (RectangleF* r = rects) { CheckErrorStatus(Gdip.GdipDrawRectangles( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), r, rects.Length)); } } /// <summary> /// Draws the outlines of a series of rectangles. /// </summary> public unsafe void DrawRectangles(Pen pen, Rectangle[] rects) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (Rectangle* r = rects) { CheckErrorStatus(Gdip.GdipDrawRectanglesI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), r, rects.Length)); } } /// <summary> /// Draws the outline of an ellipse defined by a bounding rectangle. /// </summary> public void DrawEllipse(Pen pen, RectangleF rect) { DrawEllipse(pen, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Draws the outline of an ellipse defined by a bounding rectangle. /// </summary> public void DrawEllipse(Pen pen, float x, float y, float width, float height) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawEllipse( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); } /// <summary> /// Draws the outline of an ellipse specified by a bounding rectangle. /// </summary> public void DrawEllipse(Pen pen, Rectangle rect) { DrawEllipse(pen, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Draws the outline of an ellipse defined by a bounding rectangle. /// </summary> public void DrawEllipse(Pen pen, int x, int y, int width, int height) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawEllipseI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); } /// <summary> /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// </summary> public void DrawPie(Pen pen, RectangleF rect, float startAngle, float sweepAngle) { DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } /// <summary> /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// </summary> public void DrawPie(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawPie( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// </summary> public void DrawPie(Pen pen, Rectangle rect, float startAngle, float sweepAngle) { DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } /// <summary> /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// </summary> public void DrawPie(Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawPieI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Draws the outline of a polygon defined by an array of points. /// </summary> public unsafe void DrawPolygon(Pen pen, PointF[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawPolygon( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws the outline of a polygon defined by an array of points. /// </summary> public unsafe void DrawPolygon(Pen pen, Point[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawPolygonI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws the lines and curves defined by a <see cref='GraphicsPath'/>. /// </summary> public void DrawPath(Pen pen, GraphicsPath path) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (path == null) throw new ArgumentNullException(nameof(path)); CheckErrorStatus(Gdip.GdipDrawPath( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(path, path._nativePath))); } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, PointF[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, PointF[] points, float tension) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve2( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, tension)); } } public void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfSegments) { DrawCurve(pen, points, offset, numberOfSegments, 0.5f); } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfSegments, float tension) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve3( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, offset, numberOfSegments, tension)); } } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, Point[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurveI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, Point[] points, float tension) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve2I( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, tension)); } } /// <summary> /// Draws a curve defined by an array of points. /// </summary> public unsafe void DrawCurve(Pen pen, Point[] points, int offset, int numberOfSegments, float tension) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve3I( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, offset, numberOfSegments, tension)); } } /// <summary> /// Draws a closed curve defined by an array of points. /// </summary> public unsafe void DrawClosedCurve(Pen pen, PointF[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws a closed curve defined by an array of points. /// </summary> public unsafe void DrawClosedCurve(Pen pen, PointF[] points, float tension, FillMode fillmode) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve2( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, tension)); } } /// <summary> /// Draws a closed curve defined by an array of points. /// </summary> public unsafe void DrawClosedCurve(Pen pen, Point[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurveI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws a closed curve defined by an array of points. /// </summary> public unsafe void DrawClosedCurve(Pen pen, Point[] points, float tension, FillMode fillmode) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve2I( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length, tension)); } } /// <summary> /// Fills the entire drawing surface with the specified color. /// </summary> public void Clear(Color color) { Gdip.CheckStatus(Gdip.GdipGraphicsClear(new HandleRef(this, NativeGraphics), color.ToArgb())); } /// <summary> /// Fills the interior of a rectangle with a <see cref='Brush'/>. /// </summary> public void FillRectangle(Brush brush, RectangleF rect) { FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Fills the interior of a rectangle with a <see cref='Brush'/>. /// </summary> public void FillRectangle(Brush brush, float x, float y, float width, float height) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillRectangle( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height)); } /// <summary> /// Fills the interior of a rectangle with a <see cref='Brush'/>. /// </summary> public void FillRectangle(Brush brush, Rectangle rect) { FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Fills the interior of a rectangle with a <see cref='Brush'/>. /// </summary> public void FillRectangle(Brush brush, int x, int y, int width, int height) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillRectangleI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height)); } /// <summary> /// Fills the interiors of a series of rectangles with a <see cref='Brush'/>. /// </summary> public unsafe void FillRectangles(Brush brush, RectangleF[] rects) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (RectangleF* r = rects) { CheckErrorStatus(Gdip.GdipFillRectangles( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), r, rects.Length)); } } /// <summary> /// Fills the interiors of a series of rectangles with a <see cref='Brush'/>. /// </summary> public unsafe void FillRectangles(Brush brush, Rectangle[] rects) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (Rectangle* r = rects) { CheckErrorStatus(Gdip.GdipFillRectanglesI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), r, rects.Length)); } } /// <summary> /// Fills the interior of a polygon defined by an array of points. /// </summary> public void FillPolygon(Brush brush, PointF[] points) { FillPolygon(brush, points, FillMode.Alternate); } /// <summary> /// Fills the interior of a polygon defined by an array of points. /// </summary> public unsafe void FillPolygon(Brush brush, PointF[] points, FillMode fillMode) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillPolygon( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length, fillMode)); } } /// <summary> /// Fills the interior of a polygon defined by an array of points. /// </summary> public void FillPolygon(Brush brush, Point[] points) { FillPolygon(brush, points, FillMode.Alternate); } /// <summary> /// Fills the interior of a polygon defined by an array of points. /// </summary> public unsafe void FillPolygon(Brush brush, Point[] points, FillMode fillMode) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillPolygonI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length, fillMode)); } } /// <summary> /// Fills the interior of an ellipse defined by a bounding rectangle. /// </summary> public void FillEllipse(Brush brush, RectangleF rect) { FillEllipse(brush, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Fills the interior of an ellipse defined by a bounding rectangle. /// </summary> public void FillEllipse(Brush brush, float x, float y, float width, float height) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillEllipse( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height)); } /// <summary> /// Fills the interior of an ellipse defined by a bounding rectangle. /// </summary> public void FillEllipse(Brush brush, Rectangle rect) { FillEllipse(brush, rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Fills the interior of an ellipse defined by a bounding rectangle. /// </summary> public void FillEllipse(Brush brush, int x, int y, int width, int height) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillEllipseI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height)); } /// <summary> /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// </summary> public void FillPie(Brush brush, Rectangle rect, float startAngle, float sweepAngle) { FillPie(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } /// <summary> /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// </summary> public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillPie( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// </summary> public void FillPie(Brush brush, int x, int y, int width, int height, int startAngle, int sweepAngle) { if (brush == null) throw new ArgumentNullException(nameof(brush)); CheckErrorStatus(Gdip.GdipFillPieI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height, startAngle, sweepAngle)); } /// <summary> /// Fills the interior a closed curve defined by an array of points. /// </summary> public unsafe void FillClosedCurve(Brush brush, PointF[] points) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length)); } } /// <summary> /// Fills the interior of a closed curve defined by an array of points. /// </summary> public void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode) { FillClosedCurve(brush, points, fillmode, 0.5f); } public unsafe void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode, float tension) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve2( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length, tension, fillmode)); } } /// <summary> /// Fills the interior a closed curve defined by an array of points. /// </summary> public unsafe void FillClosedCurve(Brush brush, Point[] points) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurveI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length)); } } public void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode) { FillClosedCurve(brush, points, fillmode, 0.5f); } public unsafe void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode, float tension) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve2I( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), p, points.Length, tension, fillmode)); } } /// <summary> /// Draws a string with the specified font. /// </summary> public void DrawString(string? s, Font font, Brush brush, float x, float y) { DrawString(s, font, brush, new RectangleF(x, y, 0, 0), null); } public void DrawString(string? s, Font font, Brush brush, PointF point) { DrawString(s, font, brush, new RectangleF(point.X, point.Y, 0, 0), null); } public void DrawString(string? s, Font font, Brush brush, float x, float y, StringFormat? format) { DrawString(s, font, brush, new RectangleF(x, y, 0, 0), format); } public void DrawString(string? s, Font font, Brush brush, PointF point, StringFormat? format) { DrawString(s, font, brush, new RectangleF(point.X, point.Y, 0, 0), format); } public void DrawString(string? s, Font font, Brush brush, RectangleF layoutRectangle) { DrawString(s, font, brush, layoutRectangle, null); } public void DrawString(string? s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat? format) { if (brush == null) throw new ArgumentNullException(nameof(brush)); if (string.IsNullOrEmpty(s)) return; if (font == null) throw new ArgumentNullException(nameof(font)); CheckErrorStatus(Gdip.GdipDrawString( new HandleRef(this, NativeGraphics), s, s.Length, new HandleRef(font, font.NativeFont), ref layoutRectangle, new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero), new HandleRef(brush, brush.NativeBrush))); } public SizeF MeasureString( string? text, Font font, SizeF layoutArea, StringFormat? stringFormat, out int charactersFitted, out int linesFilled) { if (string.IsNullOrEmpty(text)) { charactersFitted = 0; linesFilled = 0; return SizeF.Empty; } if (font == null) throw new ArgumentNullException(nameof(font)); RectangleF layout = new RectangleF(0, 0, layoutArea.Width, layoutArea.Height); RectangleF boundingBox = default; Gdip.CheckStatus(Gdip.GdipMeasureString( new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref layout, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), ref boundingBox, out charactersFitted, out linesFilled)); return boundingBox.Size; } public SizeF MeasureString(string? text, Font font, PointF origin, StringFormat? stringFormat) { if (string.IsNullOrEmpty(text)) return SizeF.Empty; if (font == null) throw new ArgumentNullException(nameof(font)); RectangleF layout = new RectangleF(origin.X, origin.Y, 0, 0); RectangleF boundingBox = default; Gdip.CheckStatus(Gdip.GdipMeasureString( new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref layout, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), ref boundingBox, out int a, out int b)); return boundingBox.Size; } public SizeF MeasureString(string? text, Font font, SizeF layoutArea) => MeasureString(text, font, layoutArea, null); public SizeF MeasureString(string? text, Font font, SizeF layoutArea, StringFormat? stringFormat) { if (string.IsNullOrEmpty(text)) return SizeF.Empty; if (font == null) throw new ArgumentNullException(nameof(font)); RectangleF layout = new RectangleF(0, 0, layoutArea.Width, layoutArea.Height); RectangleF boundingBox = default; Gdip.CheckStatus(Gdip.GdipMeasureString( new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref layout, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), ref boundingBox, out int a, out int b)); return boundingBox.Size; } public SizeF MeasureString(string? text, Font font) { return MeasureString(text, font, new SizeF(0, 0)); } public SizeF MeasureString(string? text, Font font, int width) { return MeasureString(text, font, new SizeF(width, 999999)); } public SizeF MeasureString(string? text, Font font, int width, StringFormat? format) { return MeasureString(text, font, new SizeF(width, 999999), format); } public Region[] MeasureCharacterRanges(string? text, Font font, RectangleF layoutRect, StringFormat? stringFormat) { if (string.IsNullOrEmpty(text)) return Array.Empty<Region>(); if (font == null) throw new ArgumentNullException(nameof(font)); Gdip.CheckStatus(Gdip.GdipGetStringFormatMeasurableCharacterRangeCount( new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), out int count)); IntPtr[] gpRegions = new IntPtr[count]; Region[] regions = new Region[count]; for (int f = 0; f < count; f++) { regions[f] = new Region(); gpRegions[f] = regions[f].NativeRegion; } Gdip.CheckStatus(Gdip.GdipMeasureCharacterRanges( new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref layoutRect, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), count, gpRegions)); return regions; } /// <summary> /// Draws the specified image at the specified location. /// </summary> public void DrawImage(Image image, PointF point) { DrawImage(image, point.X, point.Y); } public void DrawImage(Image image, float x, float y) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImage( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, RectangleF rect) { DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height); } public void DrawImage(Image image, float x, float y, float width, float height) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y, width, height); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, Point point) { DrawImage(image, point.X, point.Y); } public void DrawImage(Image image, int x, int y) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, Rectangle rect) { DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height); } public void DrawImage(Image image, int x, int y, int width, int height) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y, width, height); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImageUnscaled(Image image, Point point) { DrawImage(image, point.X, point.Y); } public void DrawImageUnscaled(Image image, int x, int y) { DrawImage(image, x, y); } public void DrawImageUnscaled(Image image, Rectangle rect) { DrawImage(image, rect.X, rect.Y); } public void DrawImageUnscaled(Image image, int x, int y, int width, int height) { DrawImage(image, x, y); } public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) { if (image == null) throw new ArgumentNullException(nameof(image)); int width = Math.Min(rect.Width, image.Width); int height = Math.Min(rect.Height, image.Height); // We could put centering logic here too for the case when the image // is smaller than the rect. DrawImage(image, rect, 0, 0, width, height, GraphicsUnit.Pixel); } // Affine or perspective blt // destPoints.Length = 3: rect => parallelogram // destPoints[0] <=> top-left corner of the source rectangle // destPoints[1] <=> top-right corner // destPoints[2] <=> bottom-left corner // destPoints.Length = 4: rect => quad // destPoints[3] <=> bottom-right corner // // @notes Perspective blt only works for bitmap images. public unsafe void DrawImage(Image image, PointF[] destPoints) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); if (image == null) throw new ArgumentNullException(nameof(image)); int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); fixed (PointF* p = destPoints) { int status = Gdip.GdipDrawImagePoints( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), p, count); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } } public unsafe void DrawImage(Image image, Point[] destPoints) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); if (image == null) throw new ArgumentNullException(nameof(image)); int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); fixed (Point* p = destPoints) { int status = Gdip.GdipDrawImagePointsI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), p, count); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } } public void DrawImage(Image image, float x, float y, RectangleF srcRect, GraphicsUnit srcUnit) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImagePointRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, (int)srcUnit); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, int x, int y, Rectangle srcRect, GraphicsUnit srcUnit) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImagePointRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, (int)srcUnit); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRectRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), destRect.X, destRect.Y, destRect.Width, destRect.Height, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit, NativeMethods.NullHandleRef, null, NativeMethods.NullHandleRef); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRectRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), destRect.X, destRect.Y, destRect.Width, destRect.Height, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit, NativeMethods.NullHandleRef, null, NativeMethods.NullHandleRef); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public unsafe void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); if (image == null) throw new ArgumentNullException(nameof(image)); int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); fixed (PointF* p = destPoints) { int status = Gdip.GdipDrawImagePointsRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), p, destPoints.Length, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit, NativeMethods.NullHandleRef, null, NativeMethods.NullHandleRef); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } } public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) { DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, null, 0); } public void DrawImage( Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback) { DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, callback, 0); } public unsafe void DrawImage( Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback, int callbackData) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); if (image == null) throw new ArgumentNullException(nameof(image)); int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); fixed (PointF* p = destPoints) { int status = Gdip.GdipDrawImagePointsRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), p, destPoints.Length, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit, new HandleRef(imageAttr, imageAttr?.nativeImageAttributes ?? IntPtr.Zero), callback, new HandleRef(null, (IntPtr)callbackData)); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } } public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit) { DrawImage(image, destPoints, srcRect, srcUnit, null, null, 0); } public void DrawImage( Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) { DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, null, 0); } public void DrawImage( Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback) { DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, callback, 0); } public unsafe void DrawImage( Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback, int callbackData) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); if (image == null) throw new ArgumentNullException(nameof(image)); int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); fixed (Point* p = destPoints) { int status = Gdip.GdipDrawImagePointsRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), p, destPoints.Length, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit, new HandleRef(imageAttr, imageAttr?.nativeImageAttributes ?? IntPtr.Zero), callback, new HandleRef(null, (IntPtr)callbackData)); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } } public void DrawImage( Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, null); } public void DrawImage( Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttrs) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttrs, null); } public void DrawImage( Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttrs, DrawImageAbort? callback) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttrs, callback, IntPtr.Zero); } public void DrawImage( Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttrs, DrawImageAbort? callback, IntPtr callbackData) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRectRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), destRect.X, destRect.Y, destRect.Width, destRect.Height, srcX, srcY, srcWidth, srcHeight, srcUnit, new HandleRef(imageAttrs, imageAttrs?.nativeImageAttributes ?? IntPtr.Zero), callback, new HandleRef(null, callbackData)); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } public void DrawImage( Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, null); } public void DrawImage( Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttr) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttr, null); } public void DrawImage( Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback) { DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttr, callback, IntPtr.Zero); } public void DrawImage( Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes? imageAttrs, DrawImageAbort? callback, IntPtr callbackData) { if (image == null) throw new ArgumentNullException(nameof(image)); int status = Gdip.GdipDrawImageRectRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), destRect.X, destRect.Y, destRect.Width, destRect.Height, srcX, srcY, srcWidth, srcHeight, srcUnit, new HandleRef(imageAttrs, imageAttrs?.nativeImageAttributes ?? IntPtr.Zero), callback, new HandleRef(null, callbackData)); IgnoreMetafileErrors(image, ref status); CheckErrorStatus(status); } /// <summary> /// Draws a line connecting the two specified points. /// </summary> public void DrawLine(Pen pen, PointF pt1, PointF pt2) { DrawLine(pen, pt1.X, pt1.Y, pt2.X, pt2.Y); } /// <summary> /// Draws a series of line segments that connect an array of points. /// </summary> public unsafe void DrawLines(Pen pen, PointF[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawLines( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// Draws a line connecting the two specified points. /// </summary> public void DrawLine(Pen pen, int x1, int y1, int x2, int y2) { if (pen == null) throw new ArgumentNullException(nameof(pen)); CheckErrorStatus(Gdip.GdipDrawLineI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2)); } /// <summary> /// Draws a line connecting the two specified points. /// </summary> public void DrawLine(Pen pen, Point pt1, Point pt2) { DrawLine(pen, pt1.X, pt1.Y, pt2.X, pt2.Y); } /// <summary> /// Draws a series of line segments that connect an array of points. /// </summary> public unsafe void DrawLines(Pen pen, Point[] points) { if (pen == null) throw new ArgumentNullException(nameof(pen)); if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawLinesI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), p, points.Length)); } } /// <summary> /// CopyPixels will perform a gdi "bitblt" operation to the source from the destination with the given size. /// </summary> public void CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize) { CopyFromScreen(upperLeftSource.X, upperLeftSource.Y, upperLeftDestination.X, upperLeftDestination.Y, blockRegionSize); } /// <summary> /// CopyPixels will perform a gdi "bitblt" operation to the source from the destination with the given size. /// </summary> public void CopyFromScreen(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize) { CopyFromScreen(sourceX, sourceY, destinationX, destinationY, blockRegionSize, CopyPixelOperation.SourceCopy); } /// <summary> /// CopyPixels will perform a gdi "bitblt" operation to the source from the destination with the given size /// and specified raster operation. /// </summary> public void CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize, CopyPixelOperation copyPixelOperation) { CopyFromScreen(upperLeftSource.X, upperLeftSource.Y, upperLeftDestination.X, upperLeftDestination.Y, blockRegionSize, copyPixelOperation); } public void EnumerateMetafile(Metafile metafile, PointF destPoint, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoint, callback, IntPtr.Zero); } public void EnumerateMetafile(Metafile metafile, PointF destPoint, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoint, callback, callbackData, null); } public void EnumerateMetafile(Metafile metafile, Point destPoint, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoint, callback, IntPtr.Zero); } public void EnumerateMetafile(Metafile metafile, Point destPoint, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoint, callback, callbackData, null); } public void EnumerateMetafile(Metafile metafile, RectangleF destRect, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destRect, callback, IntPtr.Zero); } public void EnumerateMetafile(Metafile metafile, RectangleF destRect, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destRect, callback, callbackData, null); } public void EnumerateMetafile(Metafile metafile, Rectangle destRect, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destRect, callback, IntPtr.Zero); } public void EnumerateMetafile(Metafile metafile, Rectangle destRect, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destRect, callback, callbackData, null); } public void EnumerateMetafile(Metafile metafile, PointF[] destPoints, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, PointF[] destPoints, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero, null); } public void EnumerateMetafile(Metafile metafile, Point[] destPoints, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero); } public void EnumerateMetafile(Metafile metafile, Point[] destPoints, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoints, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, PointF destPoint, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, PointF destPoint, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, Point destPoint, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, Point destPoint, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, callbackData, null); } public void EnumerateMetafile( Metafile metafile, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback) { EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, IntPtr.Zero); } public void EnumerateMetafile( Metafile metafile, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, EnumerateMetafileProc callback, IntPtr callbackData) { EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, callbackData, null); } public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, PointF[] pts) { if (pts == null) throw new ArgumentNullException(nameof(pts)); fixed (PointF* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformPoints( new HandleRef(this, NativeGraphics), (int)destSpace, (int)srcSpace, p, pts.Length)); } } public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, Point[] pts) { if (pts == null) throw new ArgumentNullException(nameof(pts)); fixed (Point* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformPointsI( new HandleRef(this, NativeGraphics), (int)destSpace, (int)srcSpace, p, pts.Length)); } } /// <summary> /// GDI+ will return a 'generic error' when we attempt to draw an Emf /// image with width/height == 1. Here, we will hack around this by /// resetting the errorstatus. Note that we don't do simple arg checking /// for height || width == 1 here because transforms can be applied to /// the Graphics object making it difficult to identify this scenario. /// </summary> private void IgnoreMetafileErrors(Image image, ref int errorStatus) { if (errorStatus != Gdip.Ok && image.RawFormat.Equals(ImageFormat.Emf)) errorStatus = Gdip.Ok; } /// <summary> /// Creates a Region class only if the native region is not infinite. /// </summary> internal Region? GetRegionIfNotInfinite() { Gdip.CheckStatus(Gdip.GdipCreateRegion(out IntPtr regionHandle)); try { Gdip.GdipGetClip(new HandleRef(this, NativeGraphics), new HandleRef(null, regionHandle)); Gdip.CheckStatus(Gdip.GdipIsInfiniteRegion( new HandleRef(null, regionHandle), new HandleRef(this, NativeGraphics), out int isInfinite)); if (isInfinite != 0) { // Infinite return null; } Region region = new Region(regionHandle); regionHandle = IntPtr.Zero; return region; } finally { if (regionHandle != IntPtr.Zero) { Gdip.GdipDeleteRegion(new HandleRef(null, regionHandle)); } } } } }
36.259289
150
0.547021
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs
90,757
C#
using System.Transactions; using CoreDdd.Domain.Events; using CoreDdd.Domain.Repositories; using CoreDdd.Nhibernate.UnitOfWorks; using CoreDdd.TestHelpers.DomainEvents; using CoreDdd.UnitOfWorks; using CoreIoC; using IntegrationTestsShared.TestEntities; using IntegrationTestsShared.TransactionScopes; using NUnit.Framework; using Shouldly; namespace CoreDdd.Rebus.UnitOfWork.Tests.RebusTransactionScopeUnitOfWorks { [TestFixture] public class when_saving_entity_within_rebus_transaction_scope_unit_of_work { private VolatileResourceManager _volatileResourceManager; private IRepository<TestEntityWithDomainEvent> _entityRepository; private TestEntityWithDomainEvent _entity; private TestDomainEvent _raisedDomainEvent; private FakeMessageContext _fakeMessageContext; private (TransactionScope transactionScope, IUnitOfWork unitOfWork) _transactionScopeUnitOfWork; [SetUp] public void Context() { var domainEventHandlerFactory = new FakeDomainEventHandlerFactory(domainEvent => _raisedDomainEvent = (TestDomainEvent)domainEvent); DomainEvents.Initialize(domainEventHandlerFactory); _volatileResourceManager = new VolatileResourceManager(); var unitOfWorkFactory = IoC.Resolve<IUnitOfWorkFactory>(); RebusTransactionScopeUnitOfWork.Initialize( unitOfWorkFactory: unitOfWorkFactory, isolationLevel: IsolationLevel.ReadCommitted, transactionScopeEnlistmentAction: transactionScope => _volatileResourceManager.EnlistIntoTransactionScope(transactionScope) ); _fakeMessageContext = new FakeMessageContext(); _transactionScopeUnitOfWork = RebusTransactionScopeUnitOfWork.Create(_fakeMessageContext); _simulateApplicationTransaction(); RebusTransactionScopeUnitOfWork.Commit(_fakeMessageContext, _transactionScopeUnitOfWork); RebusTransactionScopeUnitOfWork.Cleanup(_fakeMessageContext, _transactionScopeUnitOfWork); } private void _simulateApplicationTransaction() { _entityRepository = IoC.Resolve<IRepository<TestEntityWithDomainEvent>>(); _entity = new TestEntityWithDomainEvent(); _entity.BehaviouralMethodWithRaisingDomainEvent(); _entityRepository.Save(_entity); _volatileResourceManager.SetMemberValue(23); } [Test] public void entity_is_persisted_and_can_be_fetched_after_the_transaction_commit() { _entity.ShouldNotBeNull(); var unitOfWork = IoC.Resolve<NhibernateUnitOfWork>(); unitOfWork.BeginTransaction(); _entityRepository = IoC.Resolve<IRepository<TestEntityWithDomainEvent>>(); _entity = _entityRepository.Get(_entity.Id); _entity.ShouldNotBeNull(); unitOfWork.Rollback(); } [Test] public void volatile_resource_manager_value_is_set_after_transaction_scope_commit() { _volatileResourceManager.MemberValue.ShouldBe(23); } [Test] public void domain_event_is_handled() { _raisedDomainEvent.ShouldNotBeNull(); } } }
37.157303
144
0.715754
[ "MIT" ]
Buthrakaur/coreddd
src/CoreDdd.Rebus.UnitOfWork.Tests/RebusTransactionScopeUnitOfWorks/when_saving_entity_within_rebus_transaction_scope_unit_of_work.cs
3,309
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Model { /// <summary> /// Lock-in of the securitized derivative. /// </summary> [DataContract(Name = "inline_response_200_6_instrument_lockIn")] public partial class InlineResponse2006InstrumentLockIn : IEquatable<InlineResponse2006InstrumentLockIn>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2006InstrumentLockIn" /> class. /// </summary> /// <param name="observation">observation.</param> /// <param name="value">Value of the lock-in..</param> /// <param name="distance">distance.</param> /// <param name="cashFlow">Cash flow amount..</param> public InlineResponse2006InstrumentLockIn(InlineResponse2006InstrumentKnockOutObservation observation = default(InlineResponse2006InstrumentKnockOutObservation), decimal value = default(decimal), InlineResponse2006InstrumentLockInDistance distance = default(InlineResponse2006InstrumentLockInDistance), decimal cashFlow = default(decimal)) { this.Observation = observation; this.Value = value; this.Distance = distance; this.CashFlow = cashFlow; } /// <summary> /// Gets or Sets Observation /// </summary> [DataMember(Name = "observation", EmitDefaultValue = false)] public InlineResponse2006InstrumentKnockOutObservation Observation { get; set; } /// <summary> /// Value of the lock-in. /// </summary> /// <value>Value of the lock-in.</value> [DataMember(Name = "value", EmitDefaultValue = false)] public decimal Value { get; set; } /// <summary> /// Gets or Sets Distance /// </summary> [DataMember(Name = "distance", EmitDefaultValue = false)] public InlineResponse2006InstrumentLockInDistance Distance { get; set; } /// <summary> /// Cash flow amount. /// </summary> /// <value>Cash flow amount.</value> [DataMember(Name = "cashFlow", EmitDefaultValue = false)] public decimal CashFlow { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponse2006InstrumentLockIn {\n"); sb.Append(" Observation: ").Append(Observation).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" Distance: ").Append(Distance).Append("\n"); sb.Append(" CashFlow: ").Append(CashFlow).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as InlineResponse2006InstrumentLockIn); } /// <summary> /// Returns true if InlineResponse2006InstrumentLockIn instances are equal /// </summary> /// <param name="input">Instance of InlineResponse2006InstrumentLockIn to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse2006InstrumentLockIn input) { if (input == null) { return false; } return ( this.Observation == input.Observation || (this.Observation != null && this.Observation.Equals(input.Observation)) ) && ( this.Value == input.Value || this.Value.Equals(input.Value) ) && ( this.Distance == input.Distance || (this.Distance != null && this.Distance.Equals(input.Distance)) ) && ( this.CashFlow == input.CashFlow || this.CashFlow.Equals(input.CashFlow) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Observation != null) { hashCode = (hashCode * 59) + this.Observation.GetHashCode(); } hashCode = (hashCode * 59) + this.Value.GetHashCode(); if (this.Distance != null) { hashCode = (hashCode * 59) + this.Distance.GetHashCode(); } hashCode = (hashCode * 59) + this.CashFlow.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
37.841808
347
0.584951
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/SecuritizedDerivativesAPIforDigitalPortals/v2/src/FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals/Model/InlineResponse2006InstrumentLockIn.cs
6,698
C#
//----------------------------------------------------------------------- // <copyright company="Sherlock"> // Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0. // </copyright> //----------------------------------------------------------------------- using System; using System.Runtime.Serialization; using Sherlock.Shared.Core.Properties; namespace Sherlock.Shared.Core.Reporting { /// <summary> /// An exception thrown when a user tries add a message to a test section that has not /// been initialized. /// </summary> [Serializable] public sealed class CannotAddMessageToUninitializedTestSectionException : Exception { /// <summary> /// Initializes a new instance of the <see cref="CannotAddMessageToUninitializedTestSectionException"/> class. /// </summary> public CannotAddMessageToUninitializedTestSectionException() : this(Resources.Exceptions_Messages_CannotAddMessageToUninitializedTestSection) { } /// <summary> /// Initializes a new instance of the <see cref="CannotAddMessageToUninitializedTestSectionException"/> class. /// </summary> /// <param name="message">The message.</param> public CannotAddMessageToUninitializedTestSectionException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="CannotAddMessageToUninitializedTestSectionException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> public CannotAddMessageToUninitializedTestSectionException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="CannotAddMessageToUninitializedTestSectionException"/> class. /// </summary> /// <param name="info"> /// The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data /// about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information /// about the source or destination. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="info"/> parameter is null. /// </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException"> /// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). /// </exception> private CannotAddMessageToUninitializedTestSectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
42
117
0.62585
[ "Apache-2.0" ]
pvandervelde/Sherlock
src/shared.core/Reporting/CannotAddMessageToUninitializedTestSectionException.cs
2,942
C#
#region Copyright Preamble // // Copyright @ 2019 NCode Group // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using GreenPipes; using MassTransit.Scoping; using MassTransit.Transports.InMemory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; namespace MassTransit.Extensions.Hosting.Tests { /// <summary /> public class InMemoryHostBuilderTests { /// <summary /> public InMemoryHostBuilderTests(ITestOutputHelper output) { _output = output ?? throw new ArgumentNullException(nameof(output)); } private readonly ITestOutputHelper _output; private async Task UseServiceScope(bool useServiceScope) { _output.WriteLine($"UseServiceScope: {useServiceScope}"); const string connectionName = "connection-name-test"; const string queueName = "queue-name-test"; var message = new ExampleMessage { CorrelationId = Guid.NewGuid(), StringData = "FooBar", DateTimeOffsetData = DateTimeOffset.Now, }; var services = new ServiceCollection(); services.AddSingleton(_output); services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Trace); builder.AddXUnit(_output); }); var inlineFilterWasCalled = false; var exceptions = new List<ExceptionDispatchInfo>(); services.AddMassTransit(busBuilder => { busBuilder.UseInMemory(connectionName, hostBuilder => { hostBuilder.AddConfigurator(configurator => { configurator.UseInlineFilter(async (context, next) => { var inputAddress = context.ReceiveContext.InputAddress; var messageTypes = string.Join(",", context.SupportedMessageTypes); _output.WriteLine($"UseExecute: InputAddress={inputAddress}; MessageTypes={messageTypes}"); try { await next.Send(context).ConfigureAwait(false); } catch (Exception exception) { exceptions.Add(ExceptionDispatchInfo.Capture(exception)); throw; } }); }); hostBuilder.UseHostAccessor(); if (useServiceScope) hostBuilder.UseServiceScope(); hostBuilder.AddConfigurator((host, busFactory, serviceProviderBuilder) => { busFactory.UseInlineFilter(async (context, next) => { var hasPayloadInline = context.TryGetPayload<IServiceProvider>(out var serviceProviderInline); Assert.Equal(useServiceScope, hasPayloadInline); if (useServiceScope) { Assert.True(hasPayloadInline); Assert.NotNull(serviceProviderInline); Assert.NotSame(serviceProviderBuilder, serviceProviderInline); } else { Assert.False(hasPayloadInline); Assert.Null(serviceProviderInline); } var consumerServiceProvider = serviceProviderInline ?? serviceProviderBuilder; var consumerScopeProvider = consumerServiceProvider.GetRequiredService<IConsumerScopeProvider>(); using (var scope = consumerScopeProvider.GetScope(context)) { var hasPayloadScope = scope.Context.TryGetPayload<IServiceProvider>(out var serviceProviderScope); Assert.True(hasPayloadScope); if (useServiceScope) { Assert.Same(consumerServiceProvider, serviceProviderScope); } else { Assert.NotSame(consumerServiceProvider, serviceProviderScope); } await next.Send(scope.Context).ConfigureAwait(false); inlineFilterWasCalled = true; } }); }); hostBuilder.AddReceiveEndpoint(queueName, endpoint => { endpoint.AddConsumer<ExampleConsumer>(consumerConfigurator => { consumerConfigurator.Message<IExampleMessage>(messageConfigurator => { messageConfigurator.UseExecute(context => { Assert.Equal(message.CorrelationId, context.Message.CorrelationId); Assert.Equal(message.StringData, context.Message.StringData); Assert.Equal(message.DateTimeOffsetData, context.Message.DateTimeOffsetData); }); }); }); }); }); }); using (var serviceProvider = services.BuildServiceProvider()) { var busManager = serviceProvider.GetRequiredService<IBusManager>(); await busManager.StartAsync(CancellationToken.None).ConfigureAwait(false); await Task.Yield(); var hostAccessor = serviceProvider.GetRequiredService<IHostAccessor>(); var inMemoryHost = hostAccessor.GetHost<IInMemoryHost>(connectionName); var bus = busManager.GetBus(connectionName); var sendAddress = new Uri(inMemoryHost.Address, queueName); var sendEndpoint = await bus.GetSendEndpoint(sendAddress).ConfigureAwait(false); await sendEndpoint.Send<IExampleMessage>(message).ConfigureAwait(false); await Task.Delay(500).ConfigureAwait(false); await busManager.StopAsync(CancellationToken.None).ConfigureAwait(false); } exceptions.ForEach(ex => ex.Throw()); Assert.True(inlineFilterWasCalled); } /// <summary /> [Fact] public void AddReceiveEndpoint_GivenConfigurator_ThenValid() { var services = new ServiceCollection(); const string connectionName = "connection-name-test"; var baseAddress = new Uri("rabbitmq://localhost"); var inMemoryHostBuilder = new InMemoryHostBuilder(services, connectionName, baseAddress); var endpointConfiguratorWasCalled = false; inMemoryHostBuilder.AddReceiveEndpoint("queue-name-test", (IInMemoryReceiveEndpointBuilder builder) => { Assert.Same(services, builder.Services); builder.AddConfigurator((host, endpointConfigurator, serviceProvider) => { endpointConfiguratorWasCalled = true; Assert.Equal(baseAddress, host.Address); }); }); using (var serviceProvider = services.BuildServiceProvider()) { var busControl = inMemoryHostBuilder.Create(serviceProvider); Assert.NotNull(busControl); Assert.True(endpointConfiguratorWasCalled); } } /// <summary /> [Fact] public void Create_ThenValid() { var services = new ServiceCollection(); const string connectionName = "connection-name-test"; var baseAddress = new Uri("rabbitmq://localhost"); var inMemoryHostBuilder = new InMemoryHostBuilder(services, connectionName, baseAddress); Assert.Same(services, inMemoryHostBuilder.Services); Assert.Equal(connectionName, inMemoryHostBuilder.ConnectionName); Assert.Contains(services, item => item.Lifetime == ServiceLifetime.Singleton && item.ServiceType == typeof(IBusHostFactory) && item.ImplementationInstance == inMemoryHostBuilder); inMemoryHostBuilder.UseHostAccessor(); using (var serviceProvider = services.BuildServiceProvider()) { var hostAccessor = serviceProvider.GetRequiredService<IHostAccessor>(); var inMemoryHostBefore = hostAccessor.GetHost<IInMemoryHost>(connectionName); Assert.Null(inMemoryHostBefore); var busControl = inMemoryHostBuilder.Create(serviceProvider); Assert.NotNull(busControl); var inMemoryHostAfter = hostAccessor.GetHost<IInMemoryHost>(connectionName); Assert.NotNull(inMemoryHostAfter); Assert.Equal(baseAddress, inMemoryHostAfter.Address); } } /// <summary /> [Fact] public async Task UseServiceScope_ThenValid() { await UseServiceScope(true).ConfigureAwait(false); _output.WriteLine(string.Empty); await UseServiceScope(false).ConfigureAwait(false); } } }
40.608365
130
0.543539
[ "ECL-2.0", "Apache-2.0" ]
NCodeGroup/MassTransit.Extensions.Hosting
MassTransit.Extensions.Hosting.Tests/InMemoryHostBuilderTests.cs
10,680
C#
using System; using Systems; using UniRx; using UnityEngine; using Utils; using Utils.Plugins; namespace SystemBase { public class GameComponent : MonoBehaviour, IGameComponent { public virtual IGameSystem System { get; set; } public void RegisterToGame() { IoC.Resolve<Game>().RegisterComponent(this); } protected void Start() { RegisterToGame(); OverwriteStart(); } protected virtual void OverwriteStart() { } public IObservable<TComponent> WaitOn<TComponent>(ReactiveProperty<TComponent> componentToWaitOnTo) where TComponent : GameComponent { return componentToWaitOnTo.WhereNotNull().Select(waitedComponent => waitedComponent); } public IDisposable WaitOn<TComponent>(ReactiveProperty<TComponent> componentToWaitOnTo, Action<TComponent> onNext) where TComponent : GameComponent { return componentToWaitOnTo .WhereNotNull() .Select(waitedComponent => waitedComponent) .Subscribe(onNext) .AddTo(this); } } public class SemanticGameComponent<TGameComponent> : GameComponent where TGameComponent : IGameComponent { public TGameComponent dependency; public TGameComponent Dependency { get => dependency != null ? dependency : GetComponent<TGameComponent>(); set => dependency = value; } } }
28.018182
122
0.621674
[ "Unlicense" ]
limered/SystemBase
Assets/SystemBase/GameComponent.cs
1,543
C#
using System; using System.Collections.Generic; using System.Linq; using Telerik.Core; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; namespace Telerik.UI.Xaml.Controls.Input.Calendar { internal class XamlMultiDayViewLayer : CalendarLayer { internal Canvas contentPanel; internal Canvas topHeader; internal bool shouldArrange; private const int DefaultTopLeftHeaderZIndex = 1000; private const int DefaultToptHeaderZIndex = 500; private const int DefaultLeftHeaderZIndex = 750; private const int DefaultTodaySlotZIndex = 200; private const int DefaultLineZIndex = 500; private const int DefaultCurrentTimeIndicatorZIndex = 750; private const int DefaultAppointmentZIndex = 1000; private ScrollViewer scrollViewer; private Canvas leftHeaderPanel; private Canvas topLeftHeaderPanel; private double leftOffset; private bool isPointerInsideScrollViewer; private int numberOfDaysToNavigateTo; private RadRect viewPortArea; private RadRect bufferedViewPortArea; private TextBlock measurementPresenter; private Border allDayTextBorder; private TextBlock allDayTextBlock; private Border currentTimeIndicatorBorder; private Border horizontalLowerGridLineBorder; private Border horizontaUpperGridLineBorder; private Border horizontaTopHeaderGridLineBorder; private Border verticalGridLineBorder; private Border todaySlotBorder; private Dictionary<CalendarTimeRulerItem, TextBlock> realizedTimerRulerItemsPresenters; private Dictionary<CalendarGridLine, Border> realizedTimerRulerLinePresenters; private Dictionary<Slot, SlotControl> realizedSlotPresenters; private Dictionary<Slot, SlotControl> visibleSlotPresenters; private Dictionary<CalendarAppointmentInfo, AppointmentControl> realizedAppointmentPresenters; private Dictionary<CalendarAppointmentInfo, AppointmentControl> visibleAppointmentPresenters; private Queue<TextBlock> recycledTimeRulerItems; private Queue<Border> recycledTimeRulerLines; private Queue<SlotControl> recycledSlots; private Queue<AppointmentControl> recycledAppointments; private Queue<SlotControl> fullyRecycledSlots; private Queue<AppointmentControl> fullyRecycledAppointments; private Point scrollMousePosition; private Storyboard offsetStoryboard; private DoubleAnimation offsetAnimation; private TranslateTransform translateTransform; private double prevHorizontalOffset; private double currHorizontalOffset; private bool isAnimationOngoing; public XamlMultiDayViewLayer() { this.scrollViewer = new ScrollViewer(); this.scrollViewer.HorizontalScrollMode = ScrollMode.Disabled; this.translateTransform = new TranslateTransform(); this.contentPanel = new Canvas(); this.contentPanel.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.System; this.contentPanel.RenderTransform = this.translateTransform; this.contentPanel.HorizontalAlignment = HorizontalAlignment.Left; this.contentPanel.VerticalAlignment = VerticalAlignment.Top; this.leftHeaderPanel = new Canvas(); this.leftHeaderPanel.ManipulationMode = ManipulationModes.None; Canvas.SetZIndex(this.leftHeaderPanel, DefaultLeftHeaderZIndex); this.topLeftHeaderPanel = new Canvas(); this.topLeftHeaderPanel.ManipulationMode = ManipulationModes.None; this.topLeftHeaderPanel.Background = MultiDayViewSettings.DefaultBackground; Canvas.SetZIndex(this.topLeftHeaderPanel, DefaultTopLeftHeaderZIndex); this.topHeader = new Canvas(); this.topHeader.Background = MultiDayViewSettings.DefaultBackground; this.topHeader.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.System; Canvas.SetZIndex(this.topHeader, DefaultToptHeaderZIndex); this.scrollViewer.Content = this.contentPanel; this.scrollViewer.TopHeader = this.topHeader; this.scrollViewer.LeftHeader = this.leftHeaderPanel; this.scrollViewer.TopLeftHeader = this.topLeftHeaderPanel; this.realizedTimerRulerItemsPresenters = new Dictionary<CalendarTimeRulerItem, TextBlock>(); this.realizedTimerRulerLinePresenters = new Dictionary<CalendarGridLine, Border>(); this.realizedSlotPresenters = new Dictionary<Slot, SlotControl>(); this.visibleSlotPresenters = new Dictionary<Slot, SlotControl>(); this.realizedAppointmentPresenters = new Dictionary<CalendarAppointmentInfo, AppointmentControl>(); this.visibleAppointmentPresenters = new Dictionary<CalendarAppointmentInfo, AppointmentControl>(); this.recycledTimeRulerItems = new Queue<TextBlock>(); this.recycledTimeRulerLines = new Queue<Border>(); this.recycledSlots = new Queue<SlotControl>(); this.fullyRecycledSlots = new Queue<SlotControl>(); this.recycledAppointments = new Queue<AppointmentControl>(); this.fullyRecycledAppointments = new Queue<AppointmentControl>(); this.CreateOffsetAnimation(); } protected internal override UIElement VisualElement { get { return this.scrollViewer; } } internal RadSize MeasureContent(object content) { this.EnsureMeasurementPresenter(); this.measurementPresenter.Text = content.ToString(); return XamlContentLayerHelper.MeasureVisual(this.measurementPresenter); } internal async void UpdateUI(bool shouldUpdateTopHeader = true) { if (this.shouldArrange) { this.ArrangeVisualElement(); this.shouldArrange = false; } this.viewPortArea = new RadRect(this.scrollViewer.HorizontalOffset, this.scrollViewer.VerticalOffset, this.scrollViewer.Width, this.scrollViewer.Height); double xOfsset = this.scrollViewer.HorizontalOffset + this.leftHeaderPanel.Width; this.bufferedViewPortArea = new RadRect(xOfsset, this.scrollViewer.VerticalOffset, this.leftOffset * 3, this.scrollViewer.Height); var calendar = this.Owner; CalendarModel model = calendar.Model; ElementCollection<CalendarTimeRulerItem> timeRulerItems = model.multiDayViewModel.timeRulerItems; ElementCollection<CalendarGridLine> timeRulerLines = model.multiDayViewModel.timerRulerLines; List<CalendarAppointmentInfo> appointmentInfos = model.multiDayViewModel.appointmentInfos; if (shouldUpdateTopHeader) { this.UpdateTimeRulerDecorations(model.multiDayViewModel, model.AreDayNamesVisible); this.UpdateTimeRulerAllDayText(model.multiDayViewModel.allDayLabelLayout); } this.UpdateTimeRulerItems(timeRulerItems); this.UpdateTimerRulerLines(timeRulerLines); this.UpdateAppointments(appointmentInfos); this.UpdateSlots(); this.UpdateTodaySlot(); this.UpdateCurrentTimeIndicator(); // If there is a pending Appointment that needs to be scrolled we are dispatching it. IAppointment pendingToScrollApp = calendar.pendingScrollToAppointment; if (pendingToScrollApp != null) { await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.ScrollAppointmentIntoView(pendingToScrollApp); calendar.pendingScrollToAppointment = null; }); } } internal void ScrollAppointmentIntoView(IAppointment appointment) { RadCalendar calendar = this.Owner; if (calendar != null) { CalendarMultiDayViewModel model = calendar.Model.multiDayViewModel; var appointmentInfos = model.appointmentInfos; if (appointmentInfos != null && appointmentInfos.Count > 0) { DateTime startDate = calendar.DisplayDate.Date; DateTime endDate = startDate.AddDays(calendar.MultiDayViewSettings.VisibleDays - 1); CalendarAppointmentInfo appointmentInfo = appointmentInfos.FirstOrDefault(a => a.childAppointment == appointment && startDate <= a.Date && endDate >= a.Date); if (appointmentInfo != null) { RadRect layoutSlot = appointmentInfo.layoutSlot; if (this.scrollViewer.VerticalOffset != layoutSlot.Y) { this.scrollViewer.ChangeView(0.0f, layoutSlot.Y, 1.0f); } } } } } internal void ScrollTimeRuler(TimeSpan time) { var calendar = this.Owner; if (calendar == null) { return; } var model = calendar.Model.multiDayViewModel; var timeRulerInfos = model.timeRulerItems; if (timeRulerInfos != null && timeRulerInfos.Count > 0) { var multiDayViewSettings = calendar.MultiDayViewSettings; var timeRuler = timeRulerInfos.FirstOrDefault(a => a.StartTime <= time && a.EndTime > time); if (timeRuler != null) { var heightCoeff = (time - timeRuler.StartTime).Ticks / (double)TimeSpan.FromHours(1).Ticks; var timeItemHeight = multiDayViewSettings.TimeLinesSpacing * heightCoeff; var offset = timeRuler.layoutSlot.Y + timeItemHeight + model.halfTextHeight; if (this.scrollViewer.VerticalOffset != offset) { this.scrollViewer.ChangeView(0.0f, offset, 1.0f); } } else { if (time > multiDayViewSettings.DayEndTime) { this.scrollViewer.ChangeView(0.0f, this.scrollViewer.ScrollableHeight, 1.0f); } else { this.scrollViewer.ChangeView(0.0f, 0.0f, 1.0f); } } } } internal void RecycleTimeRulerItems(ElementCollection<CalendarTimeRulerItem> timeRulerItems) { foreach (var item in timeRulerItems) { TextBlock visual; if (this.realizedTimerRulerItemsPresenters.TryGetValue(item, out visual)) { this.realizedTimerRulerItemsPresenters.Remove(item); this.recycledTimeRulerItems.Enqueue(visual); } } } internal void RecycleTimeRulerLines(ElementCollection<CalendarGridLine> timeRulerLines) { foreach (var line in timeRulerLines) { Border visual; if (this.realizedTimerRulerLinePresenters.TryGetValue(line, out visual)) { this.realizedTimerRulerLinePresenters.Remove(line); this.recycledTimeRulerLines.Enqueue(visual); } } } internal void RecycleModelSlots(IEnumerable<Slot> slots) { var multiDayViewModel = this.Owner.Model.multiDayViewModel; if (multiDayViewModel != null) { var specialSlots = multiDayViewModel.specialSlots; foreach (var slot in slots) { var slotsToRemove = specialSlots.Where(a => a.Key == slot).ToList(); for (int i = 0; i < slotsToRemove.Count; i++) { var slotToRemove = slotsToRemove[i]; SlotControl visual; if (this.realizedSlotPresenters.TryGetValue(slotToRemove.Value, out visual)) { this.RecycleSlotVisual(slotToRemove.Value, visual); } specialSlots.Remove(slotToRemove); } } } } internal void UpdateCurrentTimeIndicator() { CalendarModel model = this.Owner.Model; CalendarGridLine currentTimeIndicator = model.CurrentTimeIndicator; if (currentTimeIndicator != null) { if (this.viewPortArea.IntersectsWith(currentTimeIndicator.layoutSlot) && currentTimeIndicator.layoutSlot.IsSizeValid()) { if (this.currentTimeIndicatorBorder == null) { this.currentTimeIndicatorBorder = new Border(); this.AddVisualChild(this.currentTimeIndicatorBorder); Canvas.SetZIndex(this.currentTimeIndicatorBorder, XamlMultiDayViewLayer.DefaultCurrentTimeIndicatorZIndex); } else if (this.currentTimeIndicatorBorder.Visibility == Visibility.Collapsed) { this.currentTimeIndicatorBorder.Visibility = Visibility.Visible; Canvas.SetZIndex(this.currentTimeIndicatorBorder, XamlMultiDayViewLayer.DefaultCurrentTimeIndicatorZIndex); } MultiDayViewSettings settings = model.multiDayViewSettings; Style currentTimeIndicatorStyle = settings.CurrentTimeIndicatorStyle ?? settings.defaultCurrentTimeIndicatorStyle; if (currentTimeIndicatorStyle != null) { this.currentTimeIndicatorBorder.Style = currentTimeIndicatorStyle; } Canvas.SetLeft(this.currentTimeIndicatorBorder, -this.leftOffset); Canvas.SetTop(this.currentTimeIndicatorBorder, currentTimeIndicator.layoutSlot.Y); this.currentTimeIndicatorBorder.Width = currentTimeIndicator.layoutSlot.Width; } else if (this.currentTimeIndicatorBorder?.Visibility == Visibility.Visible) { this.currentTimeIndicatorBorder.Visibility = Visibility.Collapsed; this.currentTimeIndicatorBorder.ClearValue(Canvas.ZIndexProperty); this.currentTimeIndicatorBorder.ClearValue(Border.StyleProperty); } } } internal void UpdateSlots() { var calendar = this.Owner; if (calendar == null) { return; } var slots = calendar.Model.multiDayViewModel.specialSlots; if (slots == null) { return; } foreach (var slot in slots) { var specialSlot = slot.Value; SlotControl visual; if (this.realizedSlotPresenters.TryGetValue(specialSlot, out visual)) { this.visibleSlotPresenters.Add(specialSlot, visual); } } foreach (var slot in slots) { var specialSlot = slot.Value; SlotControl visual; this.visibleSlotPresenters.TryGetValue(specialSlot, out visual); if (!this.bufferedViewPortArea.IntersectsWith(specialSlot.layoutSlot)) { if (visual != null) { this.RecycleSlotVisual(specialSlot, visual); } continue; } if (visual != null) { XamlContentLayer.ArrangeUIElement(visual, specialSlot.layoutSlot, true); Canvas.SetLeft(visual, specialSlot.layoutSlot.X - this.leftOffset + this.leftHeaderPanel.Width); continue; } visual = this.GetDefaultSlotVisual(specialSlot); if (visual != null) { calendar.PrepareContainerForSpecialSlot(visual, specialSlot); XamlContentLayer.ArrangeUIElement(visual, specialSlot.layoutSlot, true); Canvas.SetLeft(visual, specialSlot.layoutSlot.X - this.leftOffset + this.leftHeaderPanel.Width); } } foreach (var visual in this.recycledSlots) { visual.Visibility = Visibility.Collapsed; visual.DataContext = null; this.fullyRecycledSlots.Enqueue(visual); } this.recycledSlots.Clear(); this.visibleSlotPresenters.Clear(); } internal void UpdateTodaySlot() { Slot todaySlot = this.Owner.Model.multiDayViewModel.todaySlot; if (todaySlot == null) { return; } if (this.todaySlotBorder == null) { this.todaySlotBorder = new Border(); this.contentPanel.Children.Add(this.todaySlotBorder); } else { this.todaySlotBorder.ClearValue(Border.VisibilityProperty); this.todaySlotBorder.ClearValue(Border.StyleProperty); this.todaySlotBorder.ClearValue(Canvas.ZIndexProperty); this.todaySlotBorder.ClearValue(Canvas.LeftProperty); } if (this.bufferedViewPortArea.IntersectsWith(todaySlot.layoutSlot)) { MultiDayViewSettings settings = this.Owner.MultiDayViewSettings; Style todaySlotStyle = settings.TodaySlotStyle ?? settings.defaulTodaySlotStyle; if (todaySlotStyle != null) { this.todaySlotBorder.Style = todaySlotStyle; } RadRect layoutSlot = todaySlot.layoutSlot; XamlMultiDayViewLayer.ArrangeUIElement(this.todaySlotBorder, layoutSlot, true); Canvas.SetZIndex(this.todaySlotBorder, XamlMultiDayViewLayer.DefaultTodaySlotZIndex); Canvas.SetLeft(this.todaySlotBorder, layoutSlot.X - this.leftOffset + this.leftHeaderPanel.Width); } else if (this.todaySlotBorder.Visibility == Visibility.Visible) { this.todaySlotBorder.Visibility = Visibility.Collapsed; } } internal void UpdateAppointments(List<CalendarAppointmentInfo> appointmentInfos) { if (appointmentInfos == null) { return; } foreach (var appointmentInfo in appointmentInfos) { AppointmentControl appControl; if (this.realizedAppointmentPresenters.TryGetValue(appointmentInfo, out appControl)) { this.visibleAppointmentPresenters.Add(appointmentInfo, appControl); } } RadCalendar calendar = this.Owner; foreach (var appointmentInfo in appointmentInfos) { AppointmentControl appointmentControl; this.visibleAppointmentPresenters.TryGetValue(appointmentInfo, out appointmentControl); if (!this.bufferedViewPortArea.IntersectsWith(appointmentInfo.layoutSlot)) { if (appointmentControl != null) { this.RecycleAppointmentVisual(appointmentInfo, appointmentControl); } continue; } if (appointmentControl != null) { RadRect layoutSlot = appointmentInfo.layoutSlot; layoutSlot.Width -= 3; XamlContentLayer.ArrangeUIElement(appointmentControl, layoutSlot, true); Canvas.SetZIndex(appointmentControl, XamlMultiDayViewLayer.DefaultAppointmentZIndex); Canvas.SetLeft(appointmentControl, layoutSlot.X - this.leftOffset + this.leftHeaderPanel.Width); continue; } appointmentControl = this.GetDefaultAppointmentVisual(appointmentInfo); if (appointmentControl != null) { RadRect layoutSlot = appointmentInfo.layoutSlot; layoutSlot.Width -= 3; appointmentControl.appointmentInfo = appointmentInfo; calendar.PrepareContainerForAppointment(appointmentControl, appointmentInfo); XamlContentLayer.ArrangeUIElement(appointmentControl, layoutSlot, true); Canvas.SetZIndex(appointmentControl, XamlMultiDayViewLayer.DefaultAppointmentZIndex); Canvas.SetLeft(appointmentControl, layoutSlot.X - this.leftOffset + this.leftHeaderPanel.Width); } } this.ClearAppointmentVisuals(this.recycledAppointments); this.recycledAppointments.Clear(); this.visibleAppointmentPresenters.Clear(); } internal void UpdateTimeRulerAllDayText(RadRect allDayLabelLayout) { if (allDayLabelLayout != RadRect.Empty) { if (this.allDayTextBlock == null && this.allDayTextBorder == null) { this.allDayTextBlock = new TextBlock(); this.allDayTextBorder = new Border(); this.allDayTextBorder.Child = this.allDayTextBlock; this.topLeftHeaderPanel.Children.Add(this.allDayTextBorder); } MultiDayViewSettings settings = this.Owner.MultiDayViewSettings; Style allDayAreaTextStyle = settings.AllDayAreaTextStyle ?? settings.defaultAllDayAreaTextStyle; if (allDayAreaTextStyle != null) { this.allDayTextBlock.Style = allDayAreaTextStyle; } else if (this.allDayTextBlock.Style != null) { this.allDayTextBlock.Style = null; } Style allDayAreaTextBorderStyle = settings.AllDayAreaTextBorderStyle; if (allDayAreaTextBorderStyle != null) { this.allDayTextBorder.Style = allDayAreaTextBorderStyle; } else if (this.allDayTextBorder.Style != null) { this.allDayTextBorder.Style = null; } if (this.allDayTextBlock.Text != null && !this.IsTextExplicitlySet(this.allDayTextBlock.Style)) { this.allDayTextBlock.Text = settings.AllDayAreaText; } if (this.allDayTextBlock.Visibility == Visibility.Collapsed) { this.allDayTextBlock.Visibility = Visibility.Visible; } XamlMultiDayViewLayer.ArrangeUIElement(this.allDayTextBorder, allDayLabelLayout, true); } else if (this.allDayTextBlock != null && this.allDayTextBlock.Visibility == Visibility.Visible) { this.allDayTextBlock.Visibility = Visibility.Collapsed; } } internal void UpdateTimeRulerDecorations(CalendarMultiDayViewModel model, bool areDayNamesVisible) { CalendarGridLine horizontalAllDayLowerLine = model.horizontalLowerAllDayAreaRulerGridLine; CalendarGridLine horizontalAllDayUpperLine = model.horizontalUpperAllDayAreaRulerGridLine; CalendarGridLine horizontalTopHeaderLine = model.horizontalTopHeaderRulerGridLine; CalendarGridLine verticalLine = model.verticalRulerGridLine; if (this.horizontalLowerGridLineBorder == null) { this.horizontalLowerGridLineBorder = new Border(); this.topLeftHeaderPanel.Children.Add(this.horizontalLowerGridLineBorder); } if (this.horizontaUpperGridLineBorder == null) { this.horizontaUpperGridLineBorder = new Border(); this.topLeftHeaderPanel.Children.Add(this.horizontaUpperGridLineBorder); } if (this.horizontaTopHeaderGridLineBorder == null) { this.horizontaTopHeaderGridLineBorder = new Border(); this.topLeftHeaderPanel.Children.Add(this.horizontaTopHeaderGridLineBorder); } if (areDayNamesVisible && this.horizontaTopHeaderGridLineBorder.Visibility == Visibility.Collapsed) { this.horizontaTopHeaderGridLineBorder.Visibility = Visibility.Visible; } else if (!areDayNamesVisible && this.horizontaTopHeaderGridLineBorder.Visibility == Visibility.Visible) { this.horizontaTopHeaderGridLineBorder.Visibility = Visibility.Collapsed; } if (this.verticalGridLineBorder == null) { this.verticalGridLineBorder = new Border(); this.topLeftHeaderPanel.Children.Add(this.verticalGridLineBorder); } if (horizontalAllDayUpperLine != null) { this.LayoutTopAllDayAreaHorizontalBorder(horizontalAllDayUpperLine); } if (horizontalAllDayLowerLine != null) { this.LayoutLowerAllDayAreaHorizontalBorder(horizontalAllDayLowerLine); } if (horizontalTopHeaderLine != null) { this.LayoutTopHeaderHorizontalBorder(horizontalTopHeaderLine); } if (verticalLine != null) { this.LayoutVerticalHeaderBorder(verticalLine); } } internal void ArrangeVisualElement() { RadCalendar calendar = this.Owner; Size availableCalendarViewSize = calendar.CalendarViewSize; CalendarMultiDayViewModel multiDayViewModel = calendar.Model.multiDayViewModel; double allDayAreaHeight = multiDayViewModel.totalAllDayAreaHeight; double timeRulerWidth = multiDayViewModel.timeRulerWidth; double totalWidth = (availableCalendarViewSize.Width - timeRulerWidth) * 2; this.leftOffset = totalWidth / 2 + timeRulerWidth - calendar.GridLinesThickness / 2; foreach (var topHeaderChild in this.topHeader.Children) { if (topHeaderChild.RenderTransform != this.translateTransform) { topHeaderChild.RenderTransform = this.translateTransform; } Canvas.SetLeft(topHeaderChild, -this.leftOffset); } Canvas.SetLeft(this.topHeader, -this.leftOffset); this.scrollViewer.Width = availableCalendarViewSize.Width; this.scrollViewer.Height = availableCalendarViewSize.Height; this.contentPanel.Width = totalWidth; double cellHeight = multiDayViewModel.dayViewLayoutSlot.Height / multiDayViewModel.SpecificColumnCount; double topOffset = Math.Abs(cellHeight + multiDayViewModel.dayViewLayoutSlot.Y + calendar.GridLinesThickness); this.topLeftHeaderPanel.Height = topOffset + allDayAreaHeight; this.topLeftHeaderPanel.Width = timeRulerWidth; this.topHeader.Height = topOffset + allDayAreaHeight; this.topHeader.Width = totalWidth + this.leftOffset; if (multiDayViewModel.timeRulerItems != null && multiDayViewModel.timeRulerItems.Count > 0) { RadRect lastItemSlot = multiDayViewModel.timeRulerItems[multiDayViewModel.timeRulerItems.Count - 1].layoutSlot; this.contentPanel.Height = lastItemSlot.Y + lastItemSlot.Height; this.contentPanel.Width = this.scrollViewer.Width; this.leftHeaderPanel.Height = lastItemSlot.Y + lastItemSlot.Height; this.leftHeaderPanel.Width = multiDayViewModel.timeRulerWidth; } this.UpdatePanelsBackground(calendar.MultiDayViewSettings.TimelineBackground); this.UpdateTopHeaderBackground(); } internal void UpdatePanelsBackground(Brush background) { Brush defaultCalendarBrush = this.Owner.Background ?? MultiDayViewSettings.DefaultBackground; if (this.contentPanel.Background != background) { if (background != null) { this.contentPanel.Background = background; this.leftHeaderPanel.Background = background; } else { this.contentPanel.Background = defaultCalendarBrush; this.leftHeaderPanel.Background = defaultCalendarBrush; } } else if (this.contentPanel.Background == null) { this.contentPanel.Background = defaultCalendarBrush; this.leftHeaderPanel.Background = defaultCalendarBrush; } } internal void ClearRealizedAppointmentVisuals() { this.ClearAppointmentVisuals(this.realizedAppointmentPresenters.Values); this.realizedAppointmentPresenters.Clear(); } internal void ClearRealizedSlotVisuals() { this.ClearSlotVisuals(this.realizedSlotPresenters.Values); this.realizedSlotPresenters.Clear(); } protected internal override void DetachUI(Panel parent) { base.DetachUI(parent); this.scrollViewer.ViewChanged -= this.OnScrollViewerViewChanged; this.scrollViewer.RemoveHandler(UIElement.PointerPressedEvent, new PointerEventHandler(this.OnScrollViewerPointerPressed)); this.scrollViewer.RemoveHandler(UIElement.PointerMovedEvent, new PointerEventHandler(this.OnScrollViewerPointerMoved)); this.scrollViewer.RemoveHandler(UIElement.PointerExitedEvent, new PointerEventHandler(this.OnScrollViewerPointerExitedEvent)); this.scrollViewer.RemoveHandler(UIElement.PointerEnteredEvent, new PointerEventHandler(this.OnScrollViewerPointerEnteredEvent)); this.scrollViewer.ManipulationCompleted -= this.OnScrollViewerManipulationCompleted; if (this.offsetStoryboard != null) { this.offsetStoryboard.Completed -= this.OnOffsetStoryboardCompleted; } } protected internal override void AttachUI(Panel parent) { base.AttachUI(parent); this.scrollViewer.ViewChanged += this.OnScrollViewerViewChanged; this.scrollViewer.AddHandler(UIElement.PointerPressedEvent, new PointerEventHandler(this.OnScrollViewerPointerPressed), true); this.scrollViewer.AddHandler(UIElement.PointerMovedEvent, new PointerEventHandler(this.OnScrollViewerPointerMoved), true); this.scrollViewer.AddHandler(UIElement.PointerExitedEvent, new PointerEventHandler(this.OnScrollViewerPointerExitedEvent), true); this.scrollViewer.AddHandler(UIElement.PointerEnteredEvent, new PointerEventHandler(this.OnScrollViewerPointerEnteredEvent), true); this.scrollViewer.ManipulationCompleted += this.OnScrollViewerManipulationCompleted; if (this.offsetStoryboard != null) { this.offsetStoryboard.Completed += this.OnOffsetStoryboardCompleted; } } protected internal override void AddVisualChild(UIElement child) { this.contentPanel.Children.Add(child); } protected internal override void RemoveVisualChild(UIElement child) { this.contentPanel.Children.Remove(child); } private void RecycleSlotVisual(Slot slot, SlotControl visual) { this.realizedSlotPresenters.Remove(slot); this.recycledSlots.Enqueue(visual); } private void RecycleAppointmentVisual(CalendarAppointmentInfo info, AppointmentControl visual) { this.realizedAppointmentPresenters.Remove(info); this.recycledAppointments.Enqueue(visual); } private void ClearAppointmentVisuals(IEnumerable<AppointmentControl> appointments) { foreach (var visual in appointments) { visual.Visibility = Visibility.Collapsed; this.fullyRecycledAppointments.Enqueue(visual); } } private void ClearSlotVisuals(IEnumerable<SlotControl> slots) { foreach (var visual in slots) { visual.Visibility = Visibility.Collapsed; this.fullyRecycledSlots.Enqueue(visual); } } private void LayoutVerticalHeaderBorder(CalendarGridLine verticalLine) { this.ApplyTimeRulerStyle(verticalLine, this.verticalGridLineBorder); if (!XamlDecorationLayer.IsStrokeBrushExplicitlySet(this.verticalGridLineBorder.Style)) { this.verticalGridLineBorder.BorderBrush = this.Owner.GridLinesBrush; } if (this.verticalGridLineBorder.BorderBrush != null && !XamlDecorationLayer.IsStrokeThicknessExplicitlySet(this.verticalGridLineBorder.Style)) { this.verticalGridLineBorder.BorderThickness = new Thickness(this.Owner.GridLinesThickness); } RadRect layoutSlot = verticalLine.layoutSlot; XamlMultiDayViewLayer.ArrangeUIElement(this.verticalGridLineBorder, layoutSlot, true); } private void LayoutTopHeaderHorizontalBorder(CalendarGridLine horizontalTopHeaderLine) { this.ApplyTimeRulerStyle(horizontalTopHeaderLine, this.horizontaTopHeaderGridLineBorder); if (!XamlDecorationLayer.IsStrokeBrushExplicitlySet(this.horizontaTopHeaderGridLineBorder.Style)) { this.horizontaTopHeaderGridLineBorder.BorderBrush = this.Owner.GridLinesBrush; } if (this.horizontaTopHeaderGridLineBorder.BorderBrush != null && !XamlDecorationLayer.IsStrokeThicknessExplicitlySet(this.horizontaTopHeaderGridLineBorder.Style)) { this.horizontaTopHeaderGridLineBorder.BorderThickness = new Thickness(this.Owner.GridLinesThickness); } RadRect layoutSlot = horizontalTopHeaderLine.layoutSlot; XamlMultiDayViewLayer.ArrangeUIElement(this.horizontaTopHeaderGridLineBorder, layoutSlot, true); } private void LayoutLowerAllDayAreaHorizontalBorder(CalendarGridLine horizontalAllDayLowerLine) { MultiDayViewSettings settings = this.Owner.MultiDayViewSettings; Style allDayAreaBorderStyle = settings.AllDayAreaBorderStyle ?? settings.defaultAllDayAreaBorderStyle; if (allDayAreaBorderStyle != null) { this.horizontalLowerGridLineBorder.Style = allDayAreaBorderStyle; } if (!XamlDecorationLayer.IsStrokeBrushExplicitlySet(this.horizontalLowerGridLineBorder.Style)) { this.horizontalLowerGridLineBorder.BorderBrush = this.Owner.GridLinesBrush; } if (this.horizontalLowerGridLineBorder.BorderBrush != null && !XamlDecorationLayer.IsStrokeThicknessExplicitlySet(this.horizontalLowerGridLineBorder.Style)) { this.horizontalLowerGridLineBorder.BorderThickness = new Thickness(this.Owner.GridLinesThickness); } RadRect layoutSlot = horizontalAllDayLowerLine.layoutSlot; layoutSlot.Height = this.horizontalLowerGridLineBorder.BorderThickness.Left; XamlMultiDayViewLayer.ArrangeUIElement(this.horizontalLowerGridLineBorder, layoutSlot, true); } private void LayoutTopAllDayAreaHorizontalBorder(CalendarGridLine horizontalAllDayUpperLine) { this.ApplyTimeRulerStyle(horizontalAllDayUpperLine, this.horizontaUpperGridLineBorder); if (!XamlDecorationLayer.IsStrokeBrushExplicitlySet(this.horizontaUpperGridLineBorder.Style)) { this.horizontaUpperGridLineBorder.BorderBrush = this.Owner.GridLinesBrush; } if (this.horizontaUpperGridLineBorder.BorderBrush != null && !XamlDecorationLayer.IsStrokeThicknessExplicitlySet(this.horizontaUpperGridLineBorder.Style)) { this.horizontaUpperGridLineBorder.BorderThickness = new Thickness(this.Owner.GridLinesThickness); } RadRect layoutSlot = horizontalAllDayUpperLine.layoutSlot; XamlMultiDayViewLayer.ArrangeUIElement(this.horizontaUpperGridLineBorder, layoutSlot, true); } private bool IsTextExplicitlySet(Style style) { if (style != null) { foreach (Setter setter in style.Setters) { if (setter.Property == TextBlock.TextProperty) { return true; } } } return false; } private void UpdateTimeRulerItems(ElementCollection<CalendarTimeRulerItem> timeRulerItems) { if (timeRulerItems == null) { return; } this.RecycleTimeRulerItems(timeRulerItems); for (int i = 0; i < timeRulerItems.Count; i++) { var item = timeRulerItems[i]; if (!this.viewPortArea.IntersectsWith(item.layoutSlot) || i == 0) { continue; } FrameworkElement element = this.GetDefaultTimeRulerItemVisual(item); if (element != null) { this.ApplyTimeRulerStyle(item, element); RadRect layoutSlot = item.layoutSlot; XamlContentLayer.ArrangeUIElement(element, layoutSlot, true); } } foreach (TextBlock item in this.recycledTimeRulerItems) { item.Visibility = Visibility.Collapsed; } } private void UpdateTimerRulerLines(ElementCollection<CalendarGridLine> timeRulerLines) { if (timeRulerLines == null) { return; } this.RecycleTimeRulerLines(timeRulerLines); foreach (var gridLine in timeRulerLines) { if (!this.viewPortArea.IntersectsWith(gridLine.layoutSlot)) { continue; } Border border = this.GetTimerRulerLine(gridLine); if (border != null) { this.ApplyTimeRulerStyle(gridLine, border); if (!XamlDecorationLayer.IsStrokeBrushExplicitlySet(border.Style)) { border.BorderBrush = this.Owner.GridLinesBrush; } if (border.BorderBrush != null && !XamlDecorationLayer.IsStrokeThicknessExplicitlySet(border.Style)) { border.BorderThickness = new Thickness(this.Owner.GridLinesThickness); } RadRect layoutSlot = gridLine.layoutSlot; XamlContentLayer.ArrangeUIElement(border, layoutSlot, true); Canvas.SetLeft(border, -this.leftOffset); Canvas.SetZIndex(border, XamlMultiDayViewLayer.DefaultLineZIndex); } } foreach (var recycledLine in this.recycledTimeRulerLines) { recycledLine.Visibility = Visibility.Collapsed; } } private void EnsureMeasurementPresenter() { if (this.measurementPresenter == null) { this.measurementPresenter = new TextBlock(); this.measurementPresenter.Margin = new Thickness(5, 0, 5, 0); this.measurementPresenter.Opacity = 0; this.measurementPresenter.IsHitTestVisible = false; } } private FrameworkElement GetDefaultTimeRulerItemVisual(CalendarTimeRulerItem timeRulerItem) { TextBlock visual; if (this.recycledTimeRulerItems.Count > 0) { visual = this.recycledTimeRulerItems.Dequeue(); visual.ClearValue(TextBlock.VisibilityProperty); visual.ClearValue(TextBlock.StyleProperty); } else { visual = this.CreateDefaultTimeRulerItemVisual(); } visual.Text = timeRulerItem.Label; this.realizedTimerRulerItemsPresenters.Add(timeRulerItem, visual); return visual; } private Border GetTimerRulerLine(CalendarGridLine line) { Border visual; if (this.recycledTimeRulerLines.Count > 0) { visual = this.recycledTimeRulerLines.Dequeue(); visual.ClearValue(Border.VisibilityProperty); visual.ClearValue(Border.StyleProperty); visual.ClearValue(Border.BorderThicknessProperty); visual.ClearValue(Canvas.ZIndexProperty); visual.ClearValue(Canvas.LeftProperty); } else { visual = this.CreateBorderVisual(); } this.realizedTimerRulerLinePresenters.Add(line, visual); return visual; } private SlotControl GetDefaultSlotVisual(Slot slot) { SlotControl visual; if (this.recycledSlots.Count > 0) { visual = this.recycledSlots.Dequeue(); } else if (this.fullyRecycledSlots.Count > 0) { visual = this.fullyRecycledSlots.Dequeue(); visual.ClearValue(SlotControl.VisibilityProperty); } else { visual = this.CreateSlotVisual(); } this.realizedSlotPresenters.Add(slot, visual); return visual; } private AppointmentControl GetDefaultAppointmentVisual(CalendarAppointmentInfo info) { AppointmentControl visual; if (this.recycledAppointments.Count > 0) { visual = this.recycledAppointments.Dequeue(); } else if (this.fullyRecycledAppointments.Count > 0) { visual = this.fullyRecycledAppointments.Dequeue(); visual.ClearValue(AppointmentControl.VisibilityProperty); } else { visual = this.CreateDefaultAppointmentVisual(); } this.realizedAppointmentPresenters.Add(info, visual); return visual; } private TextBlock CreateDefaultTimeRulerItemVisual() { TextBlock textBlock = new TextBlock(); textBlock.IsHitTestVisible = false; this.leftHeaderPanel.Children.Add(textBlock); return textBlock; } private Border CreateBorderVisual() { Border slot = new Border(); this.AddVisualChild(slot); return slot; } private AppointmentControl CreateDefaultAppointmentVisual() { AppointmentControl appointmentControl = new AppointmentControl(); appointmentControl.calendar = this.Owner; this.AddVisualChild(appointmentControl); return appointmentControl; } private SlotControl CreateSlotVisual() { SlotControl slot = new SlotControl(); this.AddVisualChild(slot); return slot; } private void OnScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { this.UpdateUI(false); } private void OnScrollViewerPointerPressed(object sender, PointerRoutedEventArgs e) { if (e.OriginalSource != this.topLeftHeaderPanel && e.OriginalSource != this.leftHeaderPanel && !this.isAnimationOngoing) { this.scrollMousePosition = e.GetCurrentPoint(this.scrollViewer).Position; this.prevHorizontalOffset = this.translateTransform.X; this.scrollViewer.CapturePointer(e.Pointer); } } private void OnScrollViewerPointerMoved(object sender, PointerRoutedEventArgs e) { if (!this.isAnimationOngoing && this.isPointerInsideScrollViewer && this.scrollViewer.PointerCaptures != null && this.scrollViewer.PointerCaptures.Count > 0) { this.currHorizontalOffset = this.prevHorizontalOffset + (this.scrollMousePosition.X - e.GetCurrentPoint(this.scrollViewer).Position.X); double viewPortWidth = this.scrollViewer.Width - this.leftHeaderPanel.Width; if (viewPortWidth > this.currHorizontalOffset && -viewPortWidth < this.currHorizontalOffset) { this.translateTransform.X = -this.currHorizontalOffset; } } } private void OnScrollViewerPointerExitedEvent(object sender, PointerRoutedEventArgs e) { if (!this.isAnimationOngoing && this.scrollViewer.PointerCaptures != null && this.scrollViewer.PointerCaptures.Count > 0) { this.isPointerInsideScrollViewer = false; } } private void OnScrollViewerPointerEnteredEvent(object sender, PointerRoutedEventArgs e) { this.isPointerInsideScrollViewer = true; } private void OnScrollViewerManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e) { if (!this.isAnimationOngoing) { this.scrollViewer.ReleasePointerCaptures(); RadCalendar calendar = this.Owner; double cellWidth = (this.scrollViewer.Width - this.leftHeaderPanel.Width) / calendar.Model.ColumnCount; double navigationWidth = (cellWidth * calendar.MultiDayViewSettings.NavigationStep) / 2; double currentPosition = this.translateTransform.X + this.currHorizontalOffset; this.numberOfDaysToNavigateTo = (int)Math.Round(this.currHorizontalOffset / cellWidth); if (this.currHorizontalOffset > 0) { if (navigationWidth < this.currHorizontalOffset) { double totalPassedWidth = this.numberOfDaysToNavigateTo * cellWidth; if (totalPassedWidth - this.currHorizontalOffset > 0) { currentPosition = -totalPassedWidth; } else { this.numberOfDaysToNavigateTo += 1; currentPosition = -cellWidth * this.numberOfDaysToNavigateTo; } } } else { if (navigationWidth < -this.currHorizontalOffset) { double totalPassedWidth = this.numberOfDaysToNavigateTo * cellWidth; if (totalPassedWidth - this.currHorizontalOffset < 0) { currentPosition = -totalPassedWidth; } else { this.numberOfDaysToNavigateTo -= 1; currentPosition = -cellWidth * this.numberOfDaysToNavigateTo; } } } this.offsetAnimation.From = this.translateTransform.X; this.offsetAnimation.To = currentPosition; this.currHorizontalOffset = currentPosition; this.isAnimationOngoing = true; this.offsetStoryboard.Begin(); } } private void CreateOffsetAnimation() { this.offsetStoryboard = new Storyboard(); this.offsetAnimation = new DoubleAnimation(); this.offsetAnimation.EnableDependentAnimation = true; this.offsetAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5)); ExponentialEase easing = new ExponentialEase(); easing.EasingMode = EasingMode.EaseInOut; this.offsetAnimation.EasingFunction = easing; this.offsetStoryboard.Children.Add(this.offsetAnimation); Storyboard.SetTarget(this.offsetStoryboard, this.translateTransform); Storyboard.SetTargetProperty(this.offsetStoryboard, nameof(this.translateTransform.X)); } private void OnOffsetStoryboardCompleted(object sender, object e) { this.offsetStoryboard.Stop(); this.isAnimationOngoing = false; if (Math.Round(this.currHorizontalOffset) != this.prevHorizontalOffset) { RadCalendar calendar = this.Owner; if (this.translateTransform.X < 0) { calendar.RaiseMoveToNextViewCommand(this.numberOfDaysToNavigateTo); } else { calendar.RaiseMoveToPreviousViewCommand(-this.numberOfDaysToNavigateTo); } } this.translateTransform.X = 0; } private void ApplyTimeRulerStyle(object item, FrameworkElement container) { MultiDayViewSettings settings = this.Owner.MultiDayViewSettings; CalendarTimeRulerItemStyleSelector itemStyleSelector = settings.TimeRulerItemStyleSelector ?? settings.defaultTimeRulerItemStyleSelector; if (itemStyleSelector != null) { var style = itemStyleSelector.SelectStyle(item, container); if (style != null) { container.Style = style; } } } private void UpdateTopHeaderBackground() { Brush defaultCalendarBrush = this.Owner.Background ?? MultiDayViewSettings.DefaultBackground; if (this.topHeader.Background != defaultCalendarBrush) { this.topHeader.Background = defaultCalendarBrush; } if (this.topLeftHeaderPanel.Background != defaultCalendarBrush) { this.topLeftHeaderPanel.Background = defaultCalendarBrush; } } } }
41.866452
178
0.600826
[ "Apache-2.0" ]
ChristianGutman/UI-For-UWP
Controls/Input/Input.UWP/Calendar/View/Layers/XamlMultiDayViewLayer.cs
52,042
C#
using System; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Mvc; namespace BasicSample.Requests { public class SampleRequest : IRequest<SampleResponse> { public int Id { get; set; } } public class SampleResponse { public string Name { get; set; } public DateTime Timestamp { get; set; } } public class SampleRequestHandler : IRequestHandler<SampleRequest, SampleResponse> { [HttpPost("SampleRequest")] public async Task<SampleResponse> Handle(SampleRequest request, CancellationToken cancellationToken) { await Task.Delay(200); return new SampleResponse { Name = "Kahbazi", Timestamp = DateTime.Now }; } } }
23.194444
108
0.617964
[ "MIT" ]
Kahbazi/MediatR.AspNetCore.Endpoints
samples/BasicSample/Requests/SampleRequest.cs
835
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace WpfLightToolkit.Interfaces { public interface IContentLoader { Task<object> LoadContentAsync(FrameworkElement parent, object oldContent, object newContent, CancellationToken cancellationToken); void OnSizeContentChanged(FrameworkElement parent, object content); } }
25.888889
138
0.791845
[ "MIT" ]
kfreezen/WpfLightToolkit
Sources/WpfLightToolkit/Interfaces/IContentLoader.cs
468
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Searcher { class SearcherControl : VisualElement { // Window constants. const string k_WindowTitleLabel = "windowTitleLabel"; const string k_WindowDetailsPanel = "windowDetailsVisualContainer"; const string k_WindowResultsScrollViewName = "windowResultsScrollView"; const string k_WindowSearchTextFieldName = "searchBox"; const string k_WindowAutoCompleteLabelName = "autoCompleteLabel"; const string k_WindowSearchIconName = "searchIcon"; const string k_WindowResizerName = "windowResizer"; const int k_TabCharacter = 9; Label m_AutoCompleteLabel; IEnumerable<SearcherItem> m_Results; List<SearcherItem> m_VisibleResults; HashSet<SearcherItem> m_ExpandedResults; Searcher m_Searcher; string m_SuggestedTerm; string m_Text = string.Empty; Action<SearcherItem> m_SelectionCallback; Action<Searcher.AnalyticsEvent> m_AnalyticsDataCallback; ListView m_ListView; TextField m_SearchTextField; VisualElement m_SearchTextInput; VisualElement m_DetailsPanel; internal Label TitleLabel { get; } internal VisualElement Resizer { get; } public SearcherControl() { // Load window template. var windowUxmlTemplate = Resources.Load<VisualTreeAsset>("SearcherWindow"); // Clone Window Template. var windowRootVisualElement = windowUxmlTemplate.CloneTree(); windowRootVisualElement.AddToClassList("content"); windowRootVisualElement.StretchToParentSize(); // Add Window VisualElement to window's RootVisualContainer Add(windowRootVisualElement); m_VisibleResults = new List<SearcherItem>(); m_ExpandedResults = new HashSet<SearcherItem>(); m_ListView = this.Q<ListView>(k_WindowResultsScrollViewName); if (m_ListView != null) { m_ListView.bindItem = Bind; m_ListView.RegisterCallback<KeyDownEvent>(OnResultsScrollViewKeyDown); #if UNITY_2020_1_OR_NEWER m_ListView.onItemsChosen += obj => m_SelectionCallback((SearcherItem)obj.FirstOrDefault()); m_ListView.onSelectionChange += selectedItems => m_Searcher.Adapter.OnSelectionChanged(selectedItems.OfType<SearcherItem>().ToList()); #else m_ListView.onItemChosen += obj => m_SelectionCallback((SearcherItem)obj); m_ListView.onSelectionChanged += selectedItems => m_Searcher.Adapter.OnSelectionChanged(selectedItems.OfType<SearcherItem>()); #endif m_ListView.focusable = true; m_ListView.tabIndex = 1; } m_DetailsPanel = this.Q(k_WindowDetailsPanel); TitleLabel = this.Q<Label>(k_WindowTitleLabel); m_SearchTextField = this.Q<TextField>(k_WindowSearchTextFieldName); if (m_SearchTextField != null) { m_SearchTextField.focusable = true; m_SearchTextField.RegisterCallback<InputEvent>(OnSearchTextFieldTextChanged); m_SearchTextInput = m_SearchTextField.Q(TextInputBaseField<string>.textInputUssName); m_SearchTextInput.RegisterCallback<KeyDownEvent>(OnSearchTextFieldKeyDown); } m_AutoCompleteLabel = this.Q<Label>(k_WindowAutoCompleteLabelName); Resizer = this.Q(k_WindowResizerName); RegisterCallback<AttachToPanelEvent>(OnEnterPanel); RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); // TODO: HACK - ListView's scroll view steals focus using the scheduler. EditorApplication.update += HackDueToListViewScrollViewStealingFocus; style.flexGrow = 1; } void HackDueToListViewScrollViewStealingFocus() { m_SearchTextInput?.Focus(); // ReSharper disable once DelegateSubtraction EditorApplication.update -= HackDueToListViewScrollViewStealingFocus; } void OnEnterPanel(AttachToPanelEvent e) { RegisterCallback<KeyDownEvent>(OnKeyDown); } void OnLeavePanel(DetachFromPanelEvent e) { UnregisterCallback<KeyDownEvent>(OnKeyDown); } void OnKeyDown(KeyDownEvent e) { if (e.keyCode == KeyCode.Escape) { CancelSearch(); } } void CancelSearch() { OnSearchTextFieldTextChanged(InputEvent.GetPooled(m_Text, string.Empty)); m_SelectionCallback(null); m_AnalyticsDataCallback?.Invoke(new Searcher.AnalyticsEvent(Searcher.AnalyticsEvent.EventType.Cancelled, m_SearchTextField.value)); } public void Setup(Searcher searcher, Action<SearcherItem> selectionCallback, Action<Searcher.AnalyticsEvent> analyticsDataCallback) { m_Searcher = searcher; m_SelectionCallback = selectionCallback; m_AnalyticsDataCallback = analyticsDataCallback; if (m_Searcher.Adapter.HasDetailsPanel) { m_Searcher.Adapter.InitDetailsPanel(m_DetailsPanel); m_DetailsPanel.RemoveFromClassList("hidden"); } else { m_DetailsPanel.AddToClassList("hidden"); } TitleLabel.text = m_Searcher.Adapter.Title; if (string.IsNullOrEmpty(TitleLabel.text)) { TitleLabel.parent.style.visibility = Visibility.Hidden; TitleLabel.parent.style.position = Position.Absolute; } Refresh(); } void Refresh() { var query = m_Text; m_Results = m_Searcher.Search(query); GenerateVisibleResults(); // The first item in the results is always the highest scored item. // We want to scroll to and select this item. var visibleIndex = -1; m_SuggestedTerm = string.Empty; var results = m_Results.ToList(); if (results.Any()) { var scrollToItem = results.First(); visibleIndex = m_VisibleResults.IndexOf(scrollToItem); var cursorIndex = m_SearchTextField.cursorIndex; if (query.Length > 0) { var strings = scrollToItem.Name.Split(' '); var wordStartIndex = cursorIndex == 0 ? 0 : query.LastIndexOf(' ', cursorIndex - 1) + 1; var word = query.Substring(wordStartIndex, cursorIndex - wordStartIndex); if (word.Length > 0) foreach (var t in strings) { if (t.StartsWith(word, StringComparison.OrdinalIgnoreCase)) { m_SuggestedTerm = t; break; } } } } m_ListView.itemsSource = m_VisibleResults; m_ListView.makeItem = m_Searcher.Adapter.MakeItem; m_ListView.Refresh(); SetSelectedElementInResultsList(visibleIndex); } void GenerateVisibleResults() { if (string.IsNullOrEmpty(m_Text)) { m_ExpandedResults.Clear(); RemoveChildrenFromResults(); return; } RegenerateVisibleResults(); ExpandAllParents(); } void ExpandAllParents() { m_ExpandedResults.Clear(); foreach (var item in m_VisibleResults) if (item.HasChildren) m_ExpandedResults.Add(item); } void RemoveChildrenFromResults() { m_VisibleResults.Clear(); var parents = new HashSet<SearcherItem>(); foreach (var item in m_Results.Where(i => !parents.Contains(i))) { var currentParent = item; while (true) { if (currentParent.Parent == null) { if (parents.Contains(currentParent)) break; parents.Add(currentParent); m_VisibleResults.Add(currentParent); break; } currentParent = currentParent.Parent; } } if (m_Searcher.SortComparison != null) m_VisibleResults.Sort(m_Searcher.SortComparison); } void RegenerateVisibleResults() { var idSet = new HashSet<SearcherItem>(); m_VisibleResults.Clear(); foreach (var item in m_Results.Where(item => !idSet.Contains(item))) { idSet.Add(item); m_VisibleResults.Add(item); var currentParent = item.Parent; while (currentParent != null) { if (!idSet.Contains(currentParent)) { idSet.Add(currentParent); m_VisibleResults.Add(currentParent); } currentParent = currentParent.Parent; } AddResultChildren(item, idSet); } var comparison = m_Searcher.SortComparison ?? ((i1, i2) => { var result = i1.Database.Id - i2.Database.Id; return result != 0 ? result : i1.Id - i2.Id; }); m_VisibleResults.Sort(comparison); } void AddResultChildren(SearcherItem item, ISet<SearcherItem> idSet) { if (!item.HasChildren) return; foreach (var child in item.Children) { if (!idSet.Contains(child)) { idSet.Add(child); m_VisibleResults.Add(child); } AddResultChildren(child, idSet); } } bool HasChildResult(SearcherItem item) { if (m_Results.Contains(item)) return true; foreach (var child in item.Children) { if (HasChildResult(child)) return true; } return false; } ItemExpanderState GetExpanderState(int index) { var item = m_VisibleResults[index]; foreach (var child in item.Children) { if (!m_VisibleResults.Contains(child) && !HasChildResult(child)) continue; return m_ExpandedResults.Contains(item) ? ItemExpanderState.Expanded : ItemExpanderState.Collapsed; } return ItemExpanderState.Hidden; } void Bind(VisualElement target, int index) { var item = m_VisibleResults[index]; var expanderState = GetExpanderState(index); var expander = m_Searcher.Adapter.Bind(target, item, expanderState, m_Text); expander.RegisterCallback<MouseDownEvent>(ExpandOrCollapse); } static void GetItemsToHide(SearcherItem parent, ref HashSet<SearcherItem> itemsToHide) { if (!parent.HasChildren) { itemsToHide.Add(parent); return; } foreach (var child in parent.Children) { itemsToHide.Add(child); GetItemsToHide(child, ref itemsToHide); } } void HideUnexpandedItems() { // Hide unexpanded children. var itemsToHide = new HashSet<SearcherItem>(); foreach (var item in m_VisibleResults) { if (m_ExpandedResults.Contains(item)) continue; if (!item.HasChildren) continue; if (itemsToHide.Contains(item)) continue; // We need to hide its children. GetItemsToHide(item, ref itemsToHide); } foreach (var item in itemsToHide) m_VisibleResults.Remove(item); } // ReSharper disable once UnusedMember.Local void RefreshListViewOn() { // TODO: Call ListView.Refresh() when it is fixed. // Need this workaround until then. // See: https://fogbugz.unity3d.com/f/cases/1027728/ // And: https://gitlab.internal.unity3d.com/upm-packages/editor/com.unity.searcher/issues/9 var scrollView = m_ListView.Q<ScrollView>(); var scroller = scrollView?.Q<Scroller>("VerticalScroller"); if (scroller == null) return; var oldValue = scroller.value; scroller.value = oldValue + 1.0f; scroller.value = oldValue - 1.0f; scroller.value = oldValue; } void Expand(SearcherItem item) { m_ExpandedResults.Add(item); RegenerateVisibleResults(); HideUnexpandedItems(); m_ListView.Refresh(); } void Collapse(SearcherItem item) { // if it's already collapsed or not collapsed if (!m_ExpandedResults.Remove(item)) { // this case applies for a left arrow key press if (item.Parent != null) SetSelectedElementInResultsList(m_VisibleResults.IndexOf(item.Parent)); // even if it's a root item and has no parents, do nothing more return; } RegenerateVisibleResults(); HideUnexpandedItems(); // TODO: understand what happened m_ListView.Refresh(); // RefreshListViewOn(); } void ExpandOrCollapse(MouseDownEvent evt) { if (!(evt.target is VisualElement expanderLabel)) return; VisualElement itemElement = expanderLabel.GetFirstAncestorOfType<TemplateContainer>(); if (!(itemElement?.userData is SearcherItem item) || !item.HasChildren || !expanderLabel.ClassListContains("Expanded") && !expanderLabel.ClassListContains("Collapsed")) return; if (!m_ExpandedResults.Contains(item)) Expand(item); else Collapse(item); evt.StopImmediatePropagation(); } void OnSearchTextFieldTextChanged(InputEvent inputEvent) { var text = inputEvent.newData; if (string.Equals(text, m_Text)) return; // This is necessary due to OnTextChanged(...) being called after user inputs that have no impact on the text. // Ex: Moving the caret. m_Text = text; // If backspace is pressed and no text remain, clear the suggestion label. if (string.IsNullOrEmpty(text)) { this.Q(k_WindowSearchIconName).RemoveFromClassList("Active"); // Display the unfiltered results list. Refresh(); m_AutoCompleteLabel.text = String.Empty; m_SuggestedTerm = String.Empty; SetSelectedElementInResultsList(0); return; } if (!this.Q(k_WindowSearchIconName).ClassListContains("Active")) this.Q(k_WindowSearchIconName).AddToClassList("Active"); Refresh(); // Calculate the start and end indexes of the word being modified (if any). var cursorIndex = m_SearchTextField.cursorIndex; // search toward the beginning of the string starting at the character before the cursor // +1 because we want the char after a space, or 0 if the search fails var wordStartIndex = cursorIndex == 0 ? 0 : (text.LastIndexOf(' ', cursorIndex - 1) + 1); // search toward the end of the string from the cursor index var wordEndIndex = text.IndexOf(' ', cursorIndex); if (wordEndIndex == -1) // no space found, assume end of string wordEndIndex = text.Length; // Clear the suggestion term if the caret is not within a word (both start and end indexes are equal, ex: (space)caret(space)) // or the user didn't append characters to a word at the end of the query. if (wordStartIndex == wordEndIndex || wordEndIndex < text.Length) { m_AutoCompleteLabel.text = string.Empty; m_SuggestedTerm = string.Empty; return; } var word = text.Substring(wordStartIndex, wordEndIndex - wordStartIndex); if (!string.IsNullOrEmpty(m_SuggestedTerm)) { var wordSuggestion = word + m_SuggestedTerm.Substring(word.Length, m_SuggestedTerm.Length - word.Length); text = text.Remove(wordStartIndex, word.Length); text = text.Insert(wordStartIndex, wordSuggestion); m_AutoCompleteLabel.text = text; } else { m_AutoCompleteLabel.text = String.Empty; } } void OnResultsScrollViewKeyDown(KeyDownEvent keyDownEvent) { switch (keyDownEvent.keyCode) { case KeyCode.UpArrow: case KeyCode.DownArrow: case KeyCode.Home: case KeyCode.End: case KeyCode.PageUp: case KeyCode.PageDown: return; default: SetSelectedElementInResultsList(keyDownEvent); break; } } void OnSearchTextFieldKeyDown(KeyDownEvent keyDownEvent) { // First, check if we cancelled the search. if (keyDownEvent.keyCode == KeyCode.Escape) { CancelSearch(); return; } // For some reason the KeyDown event is raised twice when entering a character. // As such, we ignore one of the duplicate event. // This workaround was recommended by the Editor team. The cause of the issue relates to how IMGUI works // and a fix was not in the works at the moment of this writing. if (keyDownEvent.character == k_TabCharacter) { // Prevent switching focus to another visual element. keyDownEvent.PreventDefault(); return; } // If Tab is pressed, complete the query with the suggested term. if (keyDownEvent.keyCode == KeyCode.Tab) { // Used to prevent the TAB input from executing it's default behavior. We're hijacking it for auto-completion. keyDownEvent.PreventDefault(); if (!string.IsNullOrEmpty(m_SuggestedTerm)) { SelectAndReplaceCurrentWord(); m_AutoCompleteLabel.text = string.Empty; // TODO: Revisit, we shouldn't need to do this here. m_Text = m_SearchTextField.text; Refresh(); m_SuggestedTerm = string.Empty; } } else { SetSelectedElementInResultsList(keyDownEvent); } } void SelectAndReplaceCurrentWord() { var s = m_SearchTextField.value; var lastWordIndex = s.LastIndexOf(' '); lastWordIndex++; var newText = s.Substring(0, lastWordIndex) + m_SuggestedTerm; // Wait for SelectRange api to reach trunk //#if UNITY_2018_3_OR_NEWER // m_SearchTextField.value = newText; // m_SearchTextField.SelectRange(m_SearchTextField.value.Length, m_SearchTextField.value.Length); //#else // HACK - relies on the textfield moving the caret when being assigned a value and skipping // all low surrogate characters var magicMoveCursorToEndString = new string('\uDC00', newText.Length); m_SearchTextField.value = magicMoveCursorToEndString; m_SearchTextField.value = newText; //#endif } void SetSelectedElementInResultsList(KeyDownEvent keyDownEvent) { if (m_ListView.childCount == 0) return; int index; switch (keyDownEvent.keyCode) { case KeyCode.Escape: m_SelectionCallback(null); m_AnalyticsDataCallback?.Invoke(new Searcher.AnalyticsEvent(Searcher.AnalyticsEvent.EventType.Cancelled, m_SearchTextField.value)); break; case KeyCode.Return: case KeyCode.KeypadEnter: if (m_ListView.selectedIndex != -1) { m_SelectionCallback((SearcherItem)m_ListView.selectedItem); m_AnalyticsDataCallback?.Invoke(new Searcher.AnalyticsEvent(Searcher.AnalyticsEvent.EventType.Picked, m_SearchTextField.value)); } else { m_SelectionCallback(null); m_AnalyticsDataCallback?.Invoke(new Searcher.AnalyticsEvent(Searcher.AnalyticsEvent.EventType.Cancelled, m_SearchTextField.value)); } break; case KeyCode.LeftArrow: index = m_ListView.selectedIndex; if (index >= 0 && index < m_ListView.itemsSource.Count) Collapse(m_ListView.selectedItem as SearcherItem); break; case KeyCode.RightArrow: index = m_ListView.selectedIndex; if (index >= 0 && index < m_ListView.itemsSource.Count) Expand(m_ListView.selectedItem as SearcherItem); break; case KeyCode.UpArrow: case KeyCode.DownArrow: case KeyCode.PageUp: case KeyCode.PageDown: index = m_ListView.selectedIndex; if (index >= 0 && index < m_ListView.itemsSource.Count) m_ListView.OnKeyDown(keyDownEvent); break; } } void SetSelectedElementInResultsList(int selectedIndex) { var newIndex = selectedIndex >= 0 && selectedIndex < m_VisibleResults.Count ? selectedIndex : -1; if (newIndex < 0) return; m_ListView.selectedIndex = newIndex; m_ListView.ScrollToItem(m_ListView.selectedIndex); } } }
35.568835
155
0.552507
[ "MIT" ]
BoxThatBeat/pirateCTF
SinkEm/Library/PackageCache/com.unity.searcher@4.0.9/Editor/Searcher/SearcherControl.cs
23,511
C#
using System; using CMS.Core; using CMS.Ecommerce; using CMS.Helpers; using CMS.UIControls; [Title("ProductPriceDetail.Title")] public partial class CMSModules_Ecommerce_CMSPages_ShoppingCartSKUPriceDetail : CMSLiveModalPage { protected void Page_Load(object sender, EventArgs e) { // Initialize product price detail ucSKUPriceDetail.CartItemGuid = QueryHelper.GetGuid("itemguid", Guid.Empty); ucSKUPriceDetail.ShoppingCart = Service.Resolve<IShoppingService>().GetCurrentShoppingCart(); btnClose.Text = GetString("General.Close"); btnClose.OnClientClick = "Close(); return false;"; } }
30.619048
101
0.74028
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/Ecommerce/CMSPages/ShoppingCartSKUPriceDetail.aspx.cs
645
C#
using System; using System.Collections.Generic; namespace ModernMembership.Authorization { public interface IUserRightsService { IEnumerable<ScopedRights> GetRights(Guid userId); } }
18.083333
65
0.705069
[ "Apache-2.0" ]
sapiens/ModernMembership
src/ModernMembership.Authorization/IUserRightsService.cs
219
C#
using System; using Newtonsoft.Json; namespace poi.Models { public class Healthcheck { public Healthcheck() { Message = "POI Service Healthcheck"; Status = "Jim is Healthy"; } [Newtonsoft.Json.JsonProperty(PropertyName = "message")] public string Message {get;set;} [Newtonsoft.Json.JsonProperty(PropertyName = "status")] public string Status { get; set; } } }
22.8
64
0.594298
[ "MIT" ]
OpenHackTeam11/TripViewer
apis/poi/web/Models/Healthcheck.cs
458
C#
//------------------------------------------------------------------------------ // <auto-generated /> // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ using System; #if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) using System.Runtime.Serialization; #endif namespace Datadog.Trace.Vendors.ProtoBuf { /// <summary> /// Indicates an error during serialization/deserialization of a proto stream. /// </summary> #if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) [Serializable] #endif internal class ProtoException : Exception { /// <summary>Creates a new ProtoException instance.</summary> public ProtoException() { } /// <summary>Creates a new ProtoException instance.</summary> public ProtoException(string message) : base(message) { } /// <summary>Creates a new ProtoException instance.</summary> public ProtoException(string message, Exception innerException) : base(message, innerException) { } #if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) /// <summary>Creates a new ProtoException instance.</summary> protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
37.828571
108
0.616314
[ "Apache-2.0" ]
Kielek/signalfx-dotnet-tracing
tracer/src/Datadog.Trace/Vendors/protobuf-net/ProtoException.cs
1,324
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DocumentDB.Latest { [Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:documentdb:getDatabaseAccountGremlinDatabase'.")] public static class GetDatabaseAccountGremlinDatabase { /// <summary> /// An Azure Cosmos DB Gremlin database. /// Latest API Version: 2016-03-31. /// </summary> public static Task<GetDatabaseAccountGremlinDatabaseResult> InvokeAsync(GetDatabaseAccountGremlinDatabaseArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetDatabaseAccountGremlinDatabaseResult>("azure-native:documentdb/latest:getDatabaseAccountGremlinDatabase", args ?? new GetDatabaseAccountGremlinDatabaseArgs(), options.WithVersion()); } public sealed class GetDatabaseAccountGremlinDatabaseArgs : Pulumi.InvokeArgs { /// <summary> /// Cosmos DB database account name. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// Cosmos DB database name. /// </summary> [Input("databaseName", required: true)] public string DatabaseName { get; set; } = null!; /// <summary> /// Name of an Azure resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetDatabaseAccountGremlinDatabaseArgs() { } } [OutputType] public sealed class GetDatabaseAccountGremlinDatabaseResult { /// <summary> /// A system generated property representing the resource etag required for optimistic concurrency control. /// </summary> public readonly string? Etag; /// <summary> /// The unique resource identifier of the database account. /// </summary> public readonly string Id; /// <summary> /// The location of the resource group to which the resource belongs. /// </summary> public readonly string? Location; /// <summary> /// The name of the database account. /// </summary> public readonly string Name; /// <summary> /// A system generated property. A unique identifier. /// </summary> public readonly string? Rid; /// <summary> /// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// A system generated property that denotes the last updated timestamp of the resource. /// </summary> public readonly object? Ts; /// <summary> /// The type of Azure resource. /// </summary> public readonly string Type; [OutputConstructor] private GetDatabaseAccountGremlinDatabaseResult( string? etag, string id, string? location, string name, string? rid, ImmutableDictionary<string, string>? tags, object? ts, string type) { Etag = etag; Id = id; Location = location; Name = name; Rid = rid; Tags = tags; Ts = ts; Type = type; } } }
36.8
509
0.623582
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DocumentDB/Latest/GetDatabaseAccountGremlinDatabase.cs
4,232
C#
using UnityEngine; using System.Collections; public class NextTutorial : MonoBehaviour { public Tutorial tutorial; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnPress(bool isPressed) { if(isPressed==true) { tutorial.Next(); } } }
13.913043
43
0.675
[ "Apache-2.0" ]
RutgersUniversityVirtualWorlds/FreshTherapyOffice
Assets/Assets RU/Scripts/NGUI/NextTutorial.cs
320
C#
using Kingmaker.Utility; using System.Collections.Generic; namespace TabletopTweaks.Config { public class Fixes : IUpdatableSettings { public bool NewSettingsOffByDefault = false; public SettingGroup BaseFixes = new SettingGroup(); public SettingGroup Aeon = new SettingGroup(); public SettingGroup Demon = new SettingGroup(); public SettingGroup Lich = new SettingGroup(); public SettingGroup Trickster = new SettingGroup(); public ClassGroup Alchemist = new ClassGroup(); public ClassGroup Arcanist = new ClassGroup(); public ClassGroup Barbarian = new ClassGroup(); public ClassGroup Bloodrager = new ClassGroup(); public ClassGroup Cavalier = new ClassGroup(); public ClassGroup Cleric = new ClassGroup(); public ClassGroup Fighter = new ClassGroup(); public ClassGroup Kineticist = new ClassGroup(); public ClassGroup Magus = new ClassGroup(); public ClassGroup Monk = new ClassGroup(); public ClassGroup Oracle = new ClassGroup(); public ClassGroup Paladin = new ClassGroup(); public ClassGroup Ranger = new ClassGroup(); public ClassGroup Rogue = new ClassGroup(); public ClassGroup Shaman = new ClassGroup(); public ClassGroup Slayer = new ClassGroup(); public ClassGroup Sorcerer = new ClassGroup(); public ClassGroup Warpriest = new ClassGroup(); public ClassGroup Witch = new ClassGroup(); public SettingGroup Hellknight = new SettingGroup(); public SettingGroup Loremaster = new SettingGroup(); public SettingGroup Spells = new SettingGroup(); public SettingGroup Bloodlines = new SettingGroup(); public SettingGroup Feats = new SettingGroup(); public SettingGroup MythicAbilities = new SettingGroup(); public SettingGroup MythicFeats = new SettingGroup(); public UnitGroup Units = new UnitGroup(); public CrusadeGroup Crusade = new CrusadeGroup(); public ItemGroup Items = new ItemGroup(); public void Init() { Alchemist.SetParents(); Arcanist.SetParents(); Barbarian.SetParents(); Bloodrager.SetParents(); Cavalier.SetParents(); Cleric.SetParents(); Fighter.SetParents(); Kineticist.SetParents(); Magus.SetParents(); Monk.SetParents(); Oracle.SetParents(); Paladin.SetParents(); Ranger.SetParents(); Rogue.SetParents(); Shaman.SetParents(); Slayer.SetParents(); Sorcerer.SetParents(); Warpriest.SetParents(); Witch.SetParents(); Units.SetParents(); Crusade.SetParents(); Items.SetParents(); } public void OverrideSettings(IUpdatableSettings userSettings) { var loadedSettings = userSettings as Fixes; NewSettingsOffByDefault = loadedSettings.NewSettingsOffByDefault; BaseFixes.LoadSettingGroup(loadedSettings.BaseFixes, NewSettingsOffByDefault); Aeon.LoadSettingGroup(loadedSettings.Aeon, NewSettingsOffByDefault); Demon.LoadSettingGroup(loadedSettings.Demon, NewSettingsOffByDefault); Lich.LoadSettingGroup(loadedSettings.Lich, NewSettingsOffByDefault); Trickster.LoadSettingGroup(loadedSettings.Trickster, NewSettingsOffByDefault); Alchemist.LoadClassGroup(loadedSettings.Alchemist, NewSettingsOffByDefault); Arcanist.LoadClassGroup(loadedSettings.Arcanist, NewSettingsOffByDefault); Barbarian.LoadClassGroup(loadedSettings.Barbarian, NewSettingsOffByDefault); Bloodrager.LoadClassGroup(loadedSettings.Bloodrager, NewSettingsOffByDefault); Cavalier.LoadClassGroup(loadedSettings.Cavalier, NewSettingsOffByDefault); Cleric.LoadClassGroup(loadedSettings.Cleric, NewSettingsOffByDefault); Fighter.LoadClassGroup(loadedSettings.Fighter, NewSettingsOffByDefault); Kineticist.LoadClassGroup(loadedSettings.Kineticist, NewSettingsOffByDefault); Magus.LoadClassGroup(loadedSettings.Magus, NewSettingsOffByDefault); Monk.LoadClassGroup(loadedSettings.Monk, NewSettingsOffByDefault); Oracle.LoadClassGroup(loadedSettings.Oracle, NewSettingsOffByDefault); Paladin.LoadClassGroup(loadedSettings.Paladin, NewSettingsOffByDefault); Ranger.LoadClassGroup(loadedSettings.Ranger, NewSettingsOffByDefault); Rogue.LoadClassGroup(loadedSettings.Rogue, NewSettingsOffByDefault); Shaman.LoadClassGroup(loadedSettings.Shaman, NewSettingsOffByDefault); Slayer.LoadClassGroup(loadedSettings.Slayer, NewSettingsOffByDefault); Sorcerer.LoadClassGroup(loadedSettings.Sorcerer, NewSettingsOffByDefault); Warpriest.LoadClassGroup(loadedSettings.Warpriest, NewSettingsOffByDefault); Witch.LoadClassGroup(loadedSettings.Witch, NewSettingsOffByDefault); Hellknight.LoadSettingGroup(loadedSettings.Hellknight, NewSettingsOffByDefault); Loremaster.LoadSettingGroup(loadedSettings.Loremaster, NewSettingsOffByDefault); Spells.LoadSettingGroup(loadedSettings.Spells, NewSettingsOffByDefault); Bloodlines.LoadSettingGroup(loadedSettings.Bloodlines, NewSettingsOffByDefault); Feats.LoadSettingGroup(loadedSettings.Feats, NewSettingsOffByDefault); MythicAbilities.LoadSettingGroup(loadedSettings.MythicAbilities, NewSettingsOffByDefault); MythicFeats.LoadSettingGroup(loadedSettings.MythicFeats, NewSettingsOffByDefault); Units.LoadUnitGroup(loadedSettings.Units, NewSettingsOffByDefault); Crusade.LoadCrusadeGroup(loadedSettings.Crusade, NewSettingsOffByDefault); Items.LoadItemGroup(loadedSettings.Items, NewSettingsOffByDefault); } public class ClassGroup : IDisableableGroup, ICollapseableGroup { private bool IsExpanded = true; public bool DisableAll = false; public bool GroupIsDisabled() => DisableAll; public void SetGroupDisabled(bool value) => DisableAll = value; public NestedSettingGroup Base; public SortedDictionary<string, NestedSettingGroup> Archetypes = new SortedDictionary<string, NestedSettingGroup>(); public ClassGroup() { Base = new NestedSettingGroup(this); } public void SetParents() { Base.Parent = this; Archetypes.ForEach(entry => entry.Value.Parent = this); } public void LoadClassGroup(ClassGroup group, bool frozen) { DisableAll = group.DisableAll; Base.LoadSettingGroup(group.Base, frozen); group.Archetypes.ForEach(entry => { if (Archetypes.ContainsKey(entry.Key)) { Archetypes[entry.Key].LoadSettingGroup(entry.Value, frozen); } }); } ref bool ICollapseableGroup.IsExpanded() { return ref IsExpanded; } public void SetExpanded(bool value) { IsExpanded = value; } } public class CrusadeGroup : IDisableableGroup, ICollapseableGroup { private bool IsExpanded = true; public bool DisableAll = false; public bool GroupIsDisabled() => DisableAll; public void SetGroupDisabled(bool value) => DisableAll = value; public NestedSettingGroup Buildings; public CrusadeGroup() { Buildings = new NestedSettingGroup(this); } public void SetParents() { Buildings.Parent = this; } public void LoadCrusadeGroup(CrusadeGroup group, bool frozen) { DisableAll = group.DisableAll; Buildings.LoadSettingGroup(group.Buildings, frozen); } ref bool ICollapseableGroup.IsExpanded() { return ref IsExpanded; } public void SetExpanded(bool value) { IsExpanded = value; } } public class ItemGroup : IDisableableGroup, ICollapseableGroup { private bool IsExpanded = true; public bool DisableAll = false; public bool GroupIsDisabled() => DisableAll; public void SetGroupDisabled(bool value) => DisableAll = value; public NestedSettingGroup Armor; public NestedSettingGroup Equipment; public NestedSettingGroup Weapons; public ItemGroup() { Armor = new NestedSettingGroup(this); Equipment = new NestedSettingGroup(this); Weapons = new NestedSettingGroup(this); } public void SetParents() { Armor.Parent = this; Equipment.Parent = this; Weapons.Parent = this; } public void LoadItemGroup(ItemGroup group, bool frozen) { DisableAll = group.DisableAll; Armor.LoadSettingGroup(group.Armor, frozen); Equipment.LoadSettingGroup(group.Equipment, frozen); Weapons.LoadSettingGroup(group.Weapons, frozen); } ref bool ICollapseableGroup.IsExpanded() { return ref IsExpanded; } public void SetExpanded(bool value) { IsExpanded = value; } } public class UnitGroup : IDisableableGroup, ICollapseableGroup { private bool IsExpanded = true; public bool DisableAll = false; public bool GroupIsDisabled() => DisableAll; public void SetGroupDisabled(bool value) => DisableAll = value; public NestedSettingGroup Companions; public NestedSettingGroup NPCs; public NestedSettingGroup Bosses; public NestedSettingGroup Enemies; public UnitGroup() { Companions = new NestedSettingGroup(this); NPCs = new NestedSettingGroup(this); Bosses = new NestedSettingGroup(this); Enemies = new NestedSettingGroup(this); } public void SetParents() { Companions.Parent = this; NPCs.Parent = this; Bosses.Parent = this; Enemies.Parent = this; } public void LoadUnitGroup(UnitGroup group, bool frozen) { DisableAll = group.DisableAll; Bosses.LoadSettingGroup(group.Bosses, frozen); Enemies.LoadSettingGroup(group.Enemies, frozen); Companions.LoadSettingGroup(group.Companions, frozen); NPCs.LoadSettingGroup(group.NPCs, frozen); } ref bool ICollapseableGroup.IsExpanded() { return ref IsExpanded; } public void SetExpanded(bool value) { IsExpanded = value; } } } }
43.657692
128
0.630341
[ "MIT" ]
1onepower/WrathMods-TabletopTweaks
TabletopTweaks/Config/Fixes.cs
11,353
C#
using System; using System.ComponentModel; using System.Windows.Forms; namespace Xinq { internal class QueryTextBox : TextBox { private const int WM_KEYDOWN = 0x100; private const int WM_CHAR = 0x102; private const int WM_CUT = 0x300; private const int WM_PASTE = 0x302; private const int WM_CLEAR = 0x303; public event CancelEventHandler TextChanging; protected override void WndProc(ref Message m) { var causesTextChange = false; Keys keyData; switch (m.Msg) { case WM_KEYDOWN: keyData = (Keys)((int)((long)m.WParam)) | ModifierKeys; if (keyData == Keys.Delete) causesTextChange = true; break; case WM_CHAR: keyData = (Keys)((int)((long)m.WParam)) | ModifierKeys; if (keyData != Keys.Escape) causesTextChange = true; break; case WM_CUT: case WM_PASTE: case WM_CLEAR: causesTextChange = true; break; } if (causesTextChange) { var e = new CancelEventArgs(false); if (TextChanging != null) TextChanging(this, e); if (e.Cancel) return; } base.WndProc(ref m); } } }
24.8
76
0.449132
[ "MIT" ]
Azure3bt/Xinq
Projects/Package/Sources/Xinq/QueryTextBox.cs
1,612
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Esprima; using Jint; using Jint.Native; using Jint.Runtime; using Microsoft.Extensions.Caching.Memory; using Squidex.Domain.Apps.Core.Contents; using Squidex.Domain.Apps.Core.Scripting.ContentWrapper; using Squidex.Domain.Apps.Core.Scripting.Internal; using Squidex.Infrastructure; using Squidex.Infrastructure.Json.Objects; using Squidex.Infrastructure.Validation; namespace Squidex.Domain.Apps.Core.Scripting { public sealed class JintScriptEngine : IScriptEngine { private readonly IJintExtension[] extensions; private readonly Parser parser; public TimeSpan Timeout { get; set; } = TimeSpan.FromMilliseconds(200); public TimeSpan ExecutionTimeout { get; set; } = TimeSpan.FromMilliseconds(4000); public JintScriptEngine(IMemoryCache memoryCache, IEnumerable<IJintExtension>? extensions = null) { parser = new Parser(memoryCache); this.extensions = extensions?.ToArray() ?? Array.Empty<IJintExtension>(); } public async Task<IJsonValue> ExecuteAsync(ScriptVars vars, string script, ScriptOptions options = default) { Guard.NotNull(vars, nameof(vars)); Guard.NotNullOrEmpty(script, nameof(script)); using (var cts = new CancellationTokenSource(ExecutionTimeout)) { var tcs = new TaskCompletionSource<IJsonValue>(); using (cts.Token.Register(() => tcs.TrySetCanceled())) { var context = CreateEngine(vars, options, cts.Token, tcs.TrySetException, true); context.Engine.SetValue("complete", new Action<JsValue?>(value => { tcs.TrySetResult(JsonMapper.Map(value)); })); Execute(context.Engine, script); if (!context.IsAsync) { tcs.TrySetResult(JsonMapper.Map(context.Engine.GetCompletionValue())); } return await tcs.Task; } } } public async Task<NamedContentData> TransformAsync(ScriptVars vars, string script, ScriptOptions options = default) { Guard.NotNull(vars, nameof(vars)); Guard.NotNullOrEmpty(script, nameof(script)); using (var cts = new CancellationTokenSource(ExecutionTimeout)) { var tcs = new TaskCompletionSource<NamedContentData>(); using (cts.Token.Register(() => tcs.TrySetCanceled())) { var context = CreateEngine(vars, options, cts.Token, tcs.TrySetException, true); context.Engine.SetValue("complete", new Action<JsValue?>(value => { tcs.TrySetResult(vars.Data!); })); context.Engine.SetValue("replace", new Action(() => { var dataInstance = context.Engine.GetValue("ctx").AsObject().Get("data"); if (dataInstance != null && dataInstance.IsObject() && dataInstance.AsObject() is ContentDataObject data) { if (!tcs.Task.IsCompleted) { if (data.TryUpdate(out var modified)) { tcs.TrySetResult(modified); } else { tcs.TrySetResult(vars.Data!); } } } })); Execute(context.Engine, script); if (!context.IsAsync) { tcs.TrySetResult(vars.Data!); } return await tcs.Task; } } } public IJsonValue Execute(ScriptVars vars, string script, ScriptOptions options = default) { Guard.NotNull(vars, nameof(vars)); Guard.NotNullOrEmpty(script, nameof(script)); var context = CreateEngine(vars, options); Execute(context.Engine, script); return JsonMapper.Map(context.Engine.GetCompletionValue()); } private ExecutionContext CreateEngine(ScriptVars vars, ScriptOptions options, CancellationToken cancellationToken = default, ExceptionHandler? exceptionHandler = null, bool async = false) { var engine = new Engine(options => { options.AddObjectConverter(DefaultConverter.Instance); options.SetReferencesResolver(NullPropagation.Instance); options.Strict(); options.TimeoutInterval(Timeout); }); if (options.CanDisallow) { engine.AddDisallow(); } if (options.CanReject) { engine.AddReject(); } foreach (var extension in extensions) { extension.Extend(engine); } var context = new ExecutionContext(engine, cancellationToken, exceptionHandler); context.AddVariables(vars, options); foreach (var extension in extensions) { extension.Extend(context, async); } return context; } private void Execute(Engine engine, string script) { try { var program = parser.Parse(script); engine.Execute(program); } catch (ArgumentException ex) { throw new ValidationException($"Failed to execute script with javascript syntax error: {ex.Message}", new ValidationError(ex.Message)); } catch (JavaScriptException ex) { throw new ValidationException($"Failed to execute script with javascript error: {ex.Message}", new ValidationError(ex.Message)); } catch (ParserException ex) { throw new ValidationException($"Failed to execute script with javascript error: {ex.Message}", new ValidationError(ex.Message)); } } } }
35.769231
195
0.519857
[ "MIT" ]
SpyRefused/chthonianex
backend/src/Squidex.Domain.Apps.Core.Operations/Scripting/JintScriptEngine.cs
6,978
C#
// // Author: // Aaron Bockover <abock@xamarin.com> // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Xamarin.Interactive.Protocol; using Xamarin.Interactive.Representations.Reflection; namespace Xamarin.Interactive.CodeAnalysis { [Serializable] sealed class Evaluation : IXipResponseMessage, IEvaluation { [NonSerialized] Compilation compilation; ICompilation IEvaluation.Compilation => compilation; public Compilation Compilation { set => compilation = value; } public Guid RequestId { get; set; } public CodeCellId CodeCellId { get; set; } public EvaluationPhase Phase { get; set; } public EvaluationResultHandling ResultHandling { get; set; } public object Result { get; set; } public ExceptionNode Exception { get; set; } public bool Interrupted { get; set; } public TimeSpan EvaluationDuration { get; set; } // CultureInfo is serializable, but it's very very heavy, and // does not cache (e.g. is not IObjectReference) so so we'll // just look up by LCID on the other side public int CultureLCID { get; set; } public int UICultureLCID { get; set; } public bool InitializedAgentIntegration { get; set; } public AssemblyDefinition [] LoadedAssemblies { get; set; } } }
35
69
0.662718
[ "MIT" ]
mono/workbooks
Agents/Xamarin.Interactive/CodeAnalysis/Evaluation.cs
1,435
C#
// <auto-generated /> using BookCave.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace BookCave.Migrations { [DbContext(typeof(DataContext))] partial class DataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.2-rtm-10011") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BookCave.Data.EntityModels.AccountImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<byte[]>("Img"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("AccountImages"); }); modelBuilder.Entity("BookCave.Data.EntityModels.Author", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Authors"); }); modelBuilder.Entity("BookCave.Data.EntityModels.Book", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Isbn"); b.Property<double>("Price"); b.Property<int>("PublisherId"); b.Property<int>("PublishingYear"); b.Property<string>("Title"); b.Property<string>("Type"); b.HasKey("Id"); b.ToTable("Books"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BookAuthorConnection", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AuthorId"); b.Property<int>("BookId"); b.HasKey("Id"); b.ToTable("BookAuthorConnections"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BookDetails", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<string>("Description"); b.Property<string>("Font"); b.Property<int>("Length"); b.Property<int>("PageCount"); b.HasKey("Id"); b.ToTable("BookDetails"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BookGenreConnection", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<int>("GenreId"); b.HasKey("Id"); b.ToTable("BookGenreConnections"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BookRating", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<double>("Rating"); b.HasKey("Id"); b.ToTable("BookRatings"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BookReview", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<double>("Rating"); b.Property<string>("Review"); b.Property<string>("Reviewer"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("BookReviews"); }); modelBuilder.Entity("BookCave.Data.EntityModels.BooksInOrder", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("OrderId"); b.Property<double>("Price"); b.Property<int>("Quantity"); b.Property<string>("Title"); b.HasKey("Id"); b.ToTable("BooksInOrder"); }); modelBuilder.Entity("BookCave.Data.EntityModels.CartItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<int>("Quantity"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("CartItems"); }); modelBuilder.Entity("BookCave.Data.EntityModels.CoverImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BookId"); b.Property<byte[]>("Img"); b.HasKey("Id"); b.ToTable("CoverImages"); }); modelBuilder.Entity("BookCave.Data.EntityModels.Genre", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Genres"); }); modelBuilder.Entity("BookCave.Data.EntityModels.Order", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("DateOfPurchase"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("Orders"); }); modelBuilder.Entity("BookCave.Data.EntityModels.OrderInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BillingCity"); b.Property<string>("BillingCounry"); b.Property<string>("BillingFirstName"); b.Property<int>("BillingHouseNumber"); b.Property<string>("BillingLastName"); b.Property<string>("BillingStreetName"); b.Property<string>("BillingZipCode"); b.Property<int>("OrderId"); b.Property<string>("PaymentCardNumber"); b.Property<string>("PaymentExpirationMonth"); b.Property<string>("PaymentExpirationYear"); b.Property<string>("PaymentFullName"); b.Property<string>("ShippingCity"); b.Property<string>("ShippingCountry"); b.Property<string>("ShippingFirstName"); b.Property<int>("ShippingHouseNumber"); b.Property<string>("ShippingLastName"); b.Property<string>("ShippingStreetName"); b.Property<string>("ShippingZipCode"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("OrderInfo"); }); modelBuilder.Entity("BookCave.Data.EntityModels.Publisher", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Publishers"); }); modelBuilder.Entity("BookCave.Data.EntityModels.ShippingBilling", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BillingCity"); b.Property<string>("BillingCounry"); b.Property<string>("BillingFirstName"); b.Property<int>("BillingHouseNumber"); b.Property<string>("BillingLastName"); b.Property<string>("BillingStreetName"); b.Property<string>("BillingZipCode"); b.Property<string>("ShippingCity"); b.Property<string>("ShippingCountry"); b.Property<string>("ShippingFirstName"); b.Property<int>("ShippingHouseNumber"); b.Property<string>("ShippingLastName"); b.Property<string>("ShippingStreetName"); b.Property<string>("ShippingZipCode"); b.Property<string>("UserId"); b.HasKey("Id"); b.ToTable("ShippingBillingInfo"); }); #pragma warning restore 612, 618 } } }
28.64759
117
0.449795
[ "MIT" ]
DStrik/BookCave
Migrations/DataContextModelSnapshot.cs
9,513
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Prism.Modularity; using Prism.Regions; namespace HelloWorldModule { public class HelloWorldModule : IModule { private readonly IRegionManager _regionManager; public HelloWorldModule(IRegionManager regionManager) { _regionManager = regionManager; } public void Initialize() { _regionManager.RegisterViewWithRegion("MainRegion", typeof(HelloWorldView)); } } }
22.153846
88
0.6875
[ "MIT" ]
gilfaer/PrismHelloWorld
PrismHelloWorld/HelloWorldModule/HelloWorldModule.cs
578
C#
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // // The Initial Developer of this Original Code is Ted Dunsford. Created 7/23/2009 9:33:11 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// TransverseMercator is a class allowing the transverse mercator transform as transcribed /// from the 4.6 version of the Proj4 library (pj_tmerc.c) /// </summary> public class Transform : ITransform { #region Private Variables /// <summary> /// Pi/2 /// </summary> protected const double HALF_PI = 1.5707963267948966; //= Math.PI/2; /// <summary> /// Math.Pi / 4 /// </summary> protected const double FORT_PI = 0.78539816339744833; //= Math.PI/4; /// <summary> /// 2 * Math.Pi /// </summary> protected const double TWO_PI = Math.PI * 2; /// <summary> /// 1E-10 /// </summary> protected const double EPS10 = 1E-10; /// <summary> /// Analytic Hk /// </summary> protected const int IS_ANAL_HK = 4; /// <summary> /// Analytic Conv /// </summary> protected const int IS_ANAL_CONV = 10; /// <summary> /// Analytic Xl Yl /// </summary> protected const int IS_ANAL_XL_YL = 1; /// <summary> /// Analytic Xp Yp /// </summary> protected const int IS_ANAL_XP_YP = 2; /// <summary> /// Radians to Degrees /// </summary> protected const double RAD_TO_DEG = 57.29577951308232; /// <summary> /// Degrees to Radians /// </summary> protected const double DEG_TO_RAD = .0174532925199432958; /// <summary> /// The integer index representing lambda values in arrays representing geodetic coordinates /// </summary> protected const int LAMBDA = 0; /// <summary> /// The integer index representing phi values in arrays representing geodetic coordinates /// </summary> protected const int PHI = 1; /// <summary> /// The integer index representing X values in arrays representing linear coordinates /// </summary> protected const int X = 0; /// <summary> /// The integer index representing Y values in arrays representing linear coordinates /// </summary> protected const int Y = 1; /// <summary> /// The integer index representing real values in arrays representing complex numbers /// </summary> protected const int R = 0; /// <summary> /// The integer index representing immaginary values in arrays representing complex numbers /// </summary> protected const int I = 1; private string _esriName; private string[] _proj4Aliases; private string _proj4Name; /// <summary> /// The major axis /// </summary> protected double A { get; set; } /// <summary> /// 1/a /// </summary> protected double Ra { get; set; } /// <summary> /// 1 - e^2; /// </summary> protected double OneEs { get; set; } /// <summary> /// 1/OneEs /// </summary> protected double ROneEs { get; set; } /// <summary> /// Eccentricity /// </summary> protected double E { get; set; } /// <summary> /// True if the spheroid is flattened /// </summary> protected bool IsElliptical { get; set; } /// <summary> /// Eccentricity Squared /// </summary> protected double Es { get; set; } // eccentricity squared /// <summary> /// Central Latitude /// </summary> protected double Phi0 { get; set; } // central latitude /// <summary> /// Central Longitude /// </summary> protected double Lam0 { get; set; } // central longitude /// <summary> /// False Easting /// </summary> protected double X0 { get; set; } // easting /// <summary> /// False Northing /// </summary> protected double Y0 { get; set; } // northing /// <summary> /// Scaling Factor /// </summary> protected double K0 { get; set; } // scaling factor /// <summary> /// Scaling to meter /// </summary> protected double ToMeter { get; set; } // cartesian scaling /// <summary> /// Scaling from meter /// </summary> protected double FromMeter { get; set; } // cartesian scaling from meter /// <summary> /// The B parameter, which should be consisten with the semi-minor axis /// </summary> protected double B { get; set; } /// <summary> /// For transforms that distinguish between polar, oblique and equitorial modes /// </summary> protected enum Modes { /// <summary> /// North Pole /// </summary> NorthPole = 0, /// <summary> /// South Pole /// </summary> SouthPole = 1, /// <summary> /// Equitorial /// </summary> Equitorial = 2, /// <summary> /// Oblique /// </summary> Oblique = 3 } #endregion #region Constructors #endregion #region Methods /// <summary> /// Initializes the parameters from the projection info /// </summary> /// <param name="projectionInfo">The projection information used to control this transform</param> public void Init(ProjectionInfo projectionInfo) { // Setup protected values common to all the projections that inherit from this projection Es = projectionInfo.GeographicInfo.Datum.Spheroid.EccentricitySquared(); if (projectionInfo.LatitudeOfOrigin != null) Phi0 = projectionInfo.Phi0; if (projectionInfo.CentralMeridian != null) Lam0 = projectionInfo.Lam0; if (projectionInfo.FalseEasting != null) X0 = projectionInfo.FalseEasting.Value; if (projectionInfo.FalseNorthing != null) Y0 = projectionInfo.FalseNorthing.Value; K0 = projectionInfo.ScaleFactor; A = projectionInfo.GeographicInfo.Datum.Spheroid.EquatorialRadius; B = projectionInfo.GeographicInfo.Datum.Spheroid.PolarRadius; E = projectionInfo.GeographicInfo.Datum.Spheroid.Eccentricity(); Ra = 1 / A; OneEs = 1 - Es; ROneEs = 1 / OneEs; //_datumParams = proj.GeographicInfo.Datum.ToWGS84; if (projectionInfo.Unit != null) { ToMeter = projectionInfo.Unit.Meters; FromMeter = 1 / projectionInfo.Unit.Meters; } else { ToMeter = 1; FromMeter = 1; } if (Es != 0) { IsElliptical = true; } OnInit(projectionInfo); } /// <summary> /// Transforms all the coordinates by cycling through them in a loop, /// transforming each one. Only the 0 and 1 values of each coordinate will be /// transformed, higher dimensional values will be copied. /// </summary> public void Forward(double[] lp, int startIndex, int numPoints) { double[] xy = new double[lp.Length]; OnForward(lp, xy, startIndex, numPoints); Array.Copy(xy, startIndex * 2, lp, startIndex * 2, numPoints * 2); } /// <summary> /// Transforms all the coordinates by cycling through them in a loop, /// transforming each one. Only the 0 and 1 values of each coordinate will be /// transformed, higher dimensional values will be copied. /// </summary> public void Inverse(double[] xy, int startIndex, int numPoints) { double[] lp = new double[xy.Length]; OnInverse(xy, lp, startIndex, numPoints); Array.Copy(lp, startIndex * 2, xy, startIndex * 2, numPoints * 2); } /// <summary> /// Special factor calculations for a factors calculation /// </summary> /// <param name="lp">lambda-phi</param> /// <param name="p">The projection</param> /// <param name="fac">The Factors</param> public void Special(double[] lp, ProjectionInfo p, Factors fac) { OnSpecial(lp, p, fac); } /// <summary> /// Uses an enumeration to generate a new instance of a known transform class /// </summary> /// <param name="value">The member of the KnownTransforms to instantiate</param> /// <returns>A new ITransform interface representing the specific transform</returns> public static ITransform FromKnownTransform(KnownTransform value) { string name = value.ToString(); foreach (ITransform transform in TransformManager.DefaultTransformManager.Transforms) { if (transform.Name == name) return transform.Copy(); } return null; } /// <summary> /// Allows for some custom code during a process method /// </summary> /// <param name="lp">lambda-phi</param> /// <param name="p">The projection coordinate system information</param> /// <param name="fac">The Factors</param> protected virtual void OnSpecial(double[] lp, ProjectionInfo p, Factors fac) { // some projections support this as part of a process routine, // this will not affect forward or inverse transforms } #endregion #region Properties /// <summary> /// Gets or sets the string name of this projection as it appears in .prj files and /// Esri wkt. This can also be several names separated by a semicolon. /// </summary> public string Name { get { return _esriName; } set { _esriName = value; } } /// <summary> /// Gets or sets the string name of this projection as it should appear in proj4 strings. /// This can also be several names deliminated by a semicolon. /// </summary> public string Proj4Name { get { return _proj4Name; } protected set { _proj4Name = value; } } /// <summary> /// Gets or sets a list of optional aliases that can be used in the place of the Proj4Name. /// This will only be used during reading, and will not be used during writing. /// </summary> public string[] Proj4Aliases { get { return _proj4Aliases; } protected set { _proj4Aliases = value; } } #endregion #region Protected methods /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected virtual void OnInit(ProjectionInfo projInfo) { } /// <summary> /// Transforms cartesian x, y to geodetic lambda, phi /// </summary> /// <param name="lp">in -> the lambda, phi coordinates</param> /// <param name="xy">out -> the cartesian x, y</param> /// <param name="startIndex">The zero based starting point index. If this is 1, for instance, reading will skip the x and y of the first point and start at the second point.</param> /// <param name="numPoints">The integer count of the pairs of xy values to consider.</param> protected virtual void OnForward(double[] lp, double[] xy, int startIndex, int numPoints) { } /// <summary> /// The inverse transform from linear units to geodetic units /// </summary> /// <param name="xy">The double values for the input x and y values stored in an array</param> /// <param name="lp">The double values for the output lambda and phi values stored in an array</param> /// <param name="startIndex">The zero based starting point index. If this is 1, for instance, reading will skip the x and y of the first point and start at the second point.</param> /// <param name="numPoints">The integer count of the pairs of xy values to consider</param> protected virtual void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints) { } #endregion #region ITransform Members /// <summary> /// /// </summary> /// <returns></returns> public object Clone() { return MemberwiseClone(); } #endregion } }
36.925187
190
0.555886
[ "Apache-2.0" ]
aardvark-community/unofficial.dotspatial.projections
src/Unofficial.DotSpatial.Projections/Transforms/Transform.cs
14,807
C#
using UnityEngine; using UnityEditor; using Object = UnityEngine.Object; using System.Collections.Generic; using System; using System.Reflection; [CustomPropertyDrawer(typeof(AssetPath.Attribute))] public class AssetPathDrawer : PropertyDrawer { // A helper warning label when the user puts the attribute above a non string type. private const string m_InvalidTypeLabel = "Attribute invalid for type "; private const float m_ButtonWidth = 80f; private static int s_PPtrHash = "s_PPtrHash".GetHashCode(); private string m_ActivePickerPropertyPath; private int m_PickerControlID = -1; private static GUIContent m_MissingAssetLabel = new GUIContent("Missing"); // A shared array of references to the objects we have loaded private IDictionary<string, Object> m_References; /// <summary> /// Invoked when unity creates our drawer. /// </summary> public AssetPathDrawer() { m_References = new Dictionary<string, Object>(); } /// <summary> /// Invoked when we want to try our property. /// </summary> /// <param name="position">The position we have allocated on screen</param> /// <param name="property">The field our attribute is over</param> /// <param name="label">The nice display label it has</param> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { property = GetProperty(property); if (property.propertyType != SerializedPropertyType.String) { // Create a rect for our label Rect labelPosition = position; // Set it's width labelPosition.width = EditorGUIUtility.labelWidth; // Draw it GUI.Label(labelPosition, label); // Create a rect for our content Rect contentPosition = position; // Move it over by the x contentPosition.x += labelPosition.width; // Shrink it in width since we moved it over contentPosition.width -= labelPosition.width; // Draw our content warning; EditorGUI.HelpBox(contentPosition, m_InvalidTypeLabel + this.fieldInfo.FieldType.Name, MessageType.Error); } else { HandleObjectReference(position, property, label); } } /// <summary> /// Due to the fact that ShowObjectPicker does not have a none generic version we /// have to use reflection to create and invoke it. /// </summary> /// <param name="type"></param> private void ShowObjectPicker(Type type, Rect position) { // Get the type Type classType = typeof(EditorGUIUtility); // Get the method MethodInfo showObjectPickerMethod = classType.GetMethod("ShowObjectPicker", BindingFlags.Public | BindingFlags.Static); // Make the generic version MethodInfo genericObjectPickerMethod = showObjectPickerMethod.MakeGenericMethod(type); // We have no starting target Object target = null; // We are not allowing scene objects bool allowSceneObjects = false; // An empty filter string searchFilter = string.Empty; // Make a control ID m_PickerControlID = GUIUtility.GetControlID(s_PPtrHash, FocusType.Passive, position); // Save our property path // Invoke it (We have to do this step since there is only a generic version for showing the asset picker. genericObjectPickerMethod.Invoke(null, new object[] { target, allowSceneObjects, searchFilter, m_PickerControlID }); } protected virtual SerializedProperty GetProperty(SerializedProperty rootProperty) { return rootProperty; } protected virtual Type ObjectType() { // Get our attribute AssetPath.Attribute attribute = this.attribute as AssetPath.Attribute; // Return back the type. return attribute.type; } private void HandleObjectReference(Rect position, SerializedProperty property, GUIContent label) { Type objectType = ObjectType(); // First get our value Object propertyValue = null; // Save our path string assetPath = property.stringValue; // Have a label to say it's missing //bool isMissing = false; // Check if we have a key if (m_References.ContainsKey(property.propertyPath)) { // Get the value. propertyValue = m_References[property.propertyPath]; } // Now if its null we try to load it if (propertyValue == null && !string.IsNullOrEmpty(assetPath)) { // Try to load our asset propertyValue = AssetDatabase.LoadAssetAtPath(assetPath, objectType); if (propertyValue == null) { //isMissing = true; } else { m_References[property.propertyPath] = propertyValue; } } EditorGUI.BeginChangeCheck(); { // Draw our object field. propertyValue = EditorGUI.ObjectField(position, label, propertyValue, objectType, false); } if (EditorGUI.EndChangeCheck()) { OnSelectionMade(propertyValue, property); } } protected virtual void OnSelectionMade(Object newSelection, SerializedProperty property) { string assetPath = string.Empty; if (newSelection != null) { // Get our path assetPath = AssetDatabase.GetAssetPath(newSelection); } // Save our value. m_References[property.propertyPath] = newSelection; // Save it back property.stringValue = assetPath; } }
35.472393
127
0.634383
[ "MIT" ]
ByronMayne/AssetPathAttribute
proj.unity/Assets/AssetPathAttribute/Editor/AssetPathDrawer.cs
5,784
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. namespace System.Data.Entity.TestModels.ExtraLazyLoading { using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data.Entity.Infrastructure; public class LazyBlogContext : DbContext { public LazyBlogContext() { Database.SetInitializer(new LazyBlogsContextInitializer()); Configuration.LazyLoadingEnabled = false; ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += (s, e) => new QueryableCollectionInitializer().InitializeCollections(this, e.Entity); } public DbSet<LazyPost> Posts { get; set; } public DbSet<LazyComment> Comments { get; set; } } public class LazyBlogsContextInitializer : DropCreateDatabaseIfModelChanges<LazyBlogContext> { protected override void Seed(LazyBlogContext context) { context.Posts.Add( new LazyPost { Id = 1, Title = "Lazy Unicorns", Comments = new List<LazyComment> { new LazyComment { Content = "Are enums supported?" }, new LazyComment { Content = "My unicorns are so lazy they fell asleep." }, new LazyComment { Content = "Is a unicorn without a horn just a horse?" }, } }); context.Posts.Add( new LazyPost { Id = 2, Title = "Sleepy Horses", Comments = new List<LazyComment> { new LazyComment { Content = "Are enums supported?" }, } }); } } public class LazyComment { public int Id { get; set; } public string Content { get; set; } public LazyPost Post { get; set; } } public class LazyPost { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public ICollection<LazyComment> Comments { get; set; } } }
38.178571
145
0.419083
[ "MIT" ]
dotnet/ef6tools
test/EntityFramework/FunctionalTests.ProviderAgnostic/TestModels/ExtraLazyLoading/LazyBlogContext.cs
3,209
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for HyperParameterTrainingJobDefinition Object /// </summary> public class HyperParameterTrainingJobDefinitionUnmarshaller : IUnmarshaller<HyperParameterTrainingJobDefinition, XmlUnmarshallerContext>, IUnmarshaller<HyperParameterTrainingJobDefinition, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> HyperParameterTrainingJobDefinition IUnmarshaller<HyperParameterTrainingJobDefinition, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public HyperParameterTrainingJobDefinition Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; HyperParameterTrainingJobDefinition unmarshalledObject = new HyperParameterTrainingJobDefinition(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("AlgorithmSpecification", targetDepth)) { var unmarshaller = HyperParameterAlgorithmSpecificationUnmarshaller.Instance; unmarshalledObject.AlgorithmSpecification = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EnableInterContainerTrafficEncryption", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.EnableInterContainerTrafficEncryption = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EnableNetworkIsolation", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.EnableNetworkIsolation = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InputDataConfig", targetDepth)) { var unmarshaller = new ListUnmarshaller<Channel, ChannelUnmarshaller>(ChannelUnmarshaller.Instance); unmarshalledObject.InputDataConfig = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OutputDataConfig", targetDepth)) { var unmarshaller = OutputDataConfigUnmarshaller.Instance; unmarshalledObject.OutputDataConfig = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ResourceConfig", targetDepth)) { var unmarshaller = ResourceConfigUnmarshaller.Instance; unmarshalledObject.ResourceConfig = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RoleArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.RoleArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StaticHyperParameters", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); unmarshalledObject.StaticHyperParameters = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StoppingCondition", targetDepth)) { var unmarshaller = StoppingConditionUnmarshaller.Instance; unmarshalledObject.StoppingCondition = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VpcConfig", targetDepth)) { var unmarshaller = VpcConfigUnmarshaller.Instance; unmarshalledObject.VpcConfig = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static HyperParameterTrainingJobDefinitionUnmarshaller _instance = new HyperParameterTrainingJobDefinitionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static HyperParameterTrainingJobDefinitionUnmarshaller Instance { get { return _instance; } } } }
43.452055
218
0.621847
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/HyperParameterTrainingJobDefinitionUnmarshaller.cs
6,344
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Client.Http.Serialization { using System; using System.Collections.Generic; using Microsoft.ServiceFabric.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Converter for <see cref="NodeDownEvent" />. /// </summary> internal class NodeDownEventConverter { /// <summary> /// Deserializes the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param> /// <returns>The object Value.</returns> internal static NodeDownEvent Deserialize(JsonReader reader) { return reader.Deserialize(GetFromJsonProperties); } /// <summary> /// Gets the object from Json properties. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param> /// <returns>The object Value.</returns> internal static NodeDownEvent GetFromJsonProperties(JsonReader reader) { var eventInstanceId = default(Guid?); var timeStamp = default(DateTime?); var hasCorrelatedEvents = default(bool?); var nodeName = default(NodeName); var nodeInstance = default(long?); var lastNodeUpAt = default(DateTime?); do { var propName = reader.ReadPropertyName(); if (string.Compare("EventInstanceId", propName, StringComparison.Ordinal) == 0) { eventInstanceId = reader.ReadValueAsGuid(); } else if (string.Compare("TimeStamp", propName, StringComparison.Ordinal) == 0) { timeStamp = reader.ReadValueAsDateTime(); } else if (string.Compare("HasCorrelatedEvents", propName, StringComparison.Ordinal) == 0) { hasCorrelatedEvents = reader.ReadValueAsBool(); } else if (string.Compare("NodeName", propName, StringComparison.Ordinal) == 0) { nodeName = NodeNameConverter.Deserialize(reader); } else if (string.Compare("NodeInstance", propName, StringComparison.Ordinal) == 0) { nodeInstance = reader.ReadValueAsLong(); } else if (string.Compare("LastNodeUpAt", propName, StringComparison.Ordinal) == 0) { lastNodeUpAt = reader.ReadValueAsDateTime(); } else { reader.SkipPropertyValue(); } } while (reader.TokenType != JsonToken.EndObject); return new NodeDownEvent( eventInstanceId: eventInstanceId, timeStamp: timeStamp, hasCorrelatedEvents: hasCorrelatedEvents, nodeName: nodeName, nodeInstance: nodeInstance, lastNodeUpAt: lastNodeUpAt); } /// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, NodeDownEvent obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.Kind.ToString(), "Kind", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.EventInstanceId, "EventInstanceId", JsonWriterExtensions.WriteGuidValue); writer.WriteProperty(obj.TimeStamp, "TimeStamp", JsonWriterExtensions.WriteDateTimeValue); writer.WriteProperty(obj.NodeName, "NodeName", NodeNameConverter.Serialize); writer.WriteProperty(obj.NodeInstance, "NodeInstance", JsonWriterExtensions.WriteLongValue); writer.WriteProperty(obj.LastNodeUpAt, "LastNodeUpAt", JsonWriterExtensions.WriteDateTimeValue); if (obj.HasCorrelatedEvents != null) { writer.WriteProperty(obj.HasCorrelatedEvents, "HasCorrelatedEvents", JsonWriterExtensions.WriteBoolValue); } writer.WriteEndObject(); } } }
44.418182
144
0.575727
[ "MIT" ]
OlegKarasik/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Client.Http/Serialization/NodeDownEventConverter.cs
4,886
C#
using UnityEngine; using ParadoxNotion.Design; using NodeCanvas.Framework; namespace FlowCanvas.Nodes { [Category("Events/Signals")] [Description("Check if a defined Signal has been invoked. Signals are similar to name-based events but are safer to changes and support multiple parameters.")] [HasRefreshButton, DropReferenceType(typeof(SignalDefinition))] [ExecutionPriority(100)] public class SignalCallback : RouterEventNode<Transform>, IDropedReferenceNode { [GatherPortsCallback] public BBParameter<SignalDefinition> _signalDefinition; private SignalDefinition signalDefinition { get { return _signalDefinition.value; } set { _signalDefinition.value = value; } } private FlowOutput onReceived; private Transform receiver; private Transform sender; private object[] args; public override string name { get { return base.name + string.Format(" [ <color=#DDDDDD>{0}</color> ]", signalDefinition != null ? signalDefinition.name : "NULL"); } } public void SetTarget(Object target) { signalDefinition = (SignalDefinition)target; GatherPorts(); } protected override void Subscribe(ParadoxNotion.Services.EventRouter router) { } protected override void UnSubscribe(ParadoxNotion.Services.EventRouter router) { } public override void OnPostGraphStarted() { base.OnPostGraphStarted(); if ( signalDefinition != null ) { signalDefinition.onInvoke -= OnInvoked; signalDefinition.onInvoke += OnInvoked; } } public override void OnGraphStoped() { base.OnGraphStoped(); if ( signalDefinition != null ) { signalDefinition.onInvoke -= OnInvoked; } } protected override void RegisterPorts() { onReceived = AddFlowOutput("Received"); AddValueOutput<Transform>("Receiver", () => receiver); AddValueOutput<Transform>("Sender", () => sender); if ( signalDefinition != null ) { for ( var _i = 0; _i < signalDefinition.parameters.Count; _i++ ) { var i = _i; var parameter = signalDefinition.parameters[i]; AddValueOutput(parameter.name, parameter.ID, parameter.type, () => args[i]); } } } void OnInvoked(Transform sender, Transform receiver, bool isGlobal, object[] args) { this.receiver = ResolveReceiver(receiver != null ? receiver.gameObject : null); if ( this.receiver != null || isGlobal ) { this.sender = sender; this.args = args; onReceived.Call(new Flow()); } } } }
36.556962
163
0.59903
[ "MIT" ]
puerts-tsc/startup
Assets/Plugins/ThirdParty/ParadoxNotion/FlowCanvas/Modules/FlowGraphs/Nodes/Events/Custom/SignalCallback.cs
2,890
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; #if WINDOWS_UWP using Xamarin.Forms.Platform.UWP; using XPlatform = Xamarin.Forms.Platform.UWP.Platform; #elif __WINDOWS__ using Xamarin.Forms.Platform.WinRT; using XPlatform = Xamarin.Forms.Platform.WinRT.Platform; #endif namespace Ao3TrackReader.Controls { public partial class LookupView : PaneView { public LookupView () { InitializeComponent (); } protected override void OnIsOnScreenChanging(bool newValue) { base.OnIsOnScreenChanging(newValue); if (newValue == false) WebViewHolder.Content = null; } public void View(Uri uri, string title) { Title.Text = title; IsOnScreen = true; WebViewHolder.Content = new WebView(); WebViewHolder.Content.Focus(); #if __WINDOWS__ var renderer = (WebViewRenderer) XPlatform.GetRenderer(WebViewHolder.Content); var requestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri); #if WINDOWS_UWP requestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15226"); renderer.Control.Settings.IsIndexedDBEnabled = false; renderer.Control.Settings.IsJavaScriptEnabled = true; #else requestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; WebView/2.0; rv:11.0; IEMobile/11.0) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537"); #endif renderer.Control.NavigateWithHttpRequestMessage(requestMessage); renderer.Control.Focus(Windows.UI.Xaml.FocusState.Programmatic); #else WebViewHolder.Content.Source = uri; #endif } } }
35.051724
255
0.69454
[ "Apache-2.0" ]
Antyos/Ao3-Tracker
Ao3TrackReader/Ao3TrackReader/Controls/LookupView.xaml.cs
2,035
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace QuantLib { public class SoftCallability : Callability { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal SoftCallability(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.SoftCallability_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SoftCallability obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~SoftCallability() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_SoftCallability(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public SoftCallability(CallabilityPrice price, Date date, double trigger) : this(NQuantLibcPINVOKE.new_SoftCallability(CallabilityPrice.getCPtr(price), Date.getCPtr(date), trigger), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
36.571429
191
0.660156
[ "BSD-3-Clause" ]
x-xing/Quantlib-SWIG
CSharp/csharp/SoftCallability.cs
1,792
C#
using System; namespace NetCache { /// <summary>Define cache name and cache default ttl</summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class CacheAttribute : Attribute { private int _ttlSecond; /// <summary>Cache name</summary> public string? CacheName { get; } /// <summary>Default ttl if method don't have ttl parameter or ttl less than 1</summary> public int TtlSecond { get => _ttlSecond; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, Res.Value_Must_Than_Zero); _ttlSecond = value; } } public CacheAttribute() { } /// <summary>ctor</summary> /// <param name="cacheName">Cache name</param> public CacheAttribute(string cacheName) { if (string.IsNullOrEmpty(cacheName)) throw new ArgumentNullException(nameof(cacheName)); CacheName = cacheName; } } }
28
117
0.592105
[ "MIT" ]
pengweiqhca/NetCache
src/NetCache.Core/CacheAttribute.cs
1,066
C#
/* * Copyright (c) 2009, DIaLOGIKa * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of copyright holders, nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Diagnostics; using DIaLOGIKa.b2xtranslator.StructuredStorage.Reader; namespace DIaLOGIKa.b2xtranslator.OfficeGraph { /// <summary> /// This record specifies the number of colors in the palette that are available. /// </summary> [OfficeGraphBiffRecordAttribute(GraphRecordNumber.ChartColors)] public class ChartColors : OfficeGraphBiffRecord { public const GraphRecordNumber ID = GraphRecordNumber.ChartColors; /// <summary> /// A signed integer that specifies the number of colors currently available. /// /// MUST be equal to the number of items in the rgColor field of the Palette record immediately following this record. /// MUST be equal to 0x0038. /// </summary> public Int16 icvMac; public ChartColors(IStreamReader reader, GraphRecordNumber id, UInt16 length) : base(reader, id, length) { // assert that the correct record type is instantiated Debug.Assert(this.Id == ID); // initialize class members from stream this.icvMac = reader.ReadInt16(); // assert that the correct number of bytes has been read from the stream Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position); } } }
45.878788
128
0.691546
[ "BSD-3-Clause" ]
datadiode/B2XTranslator
src/Common/OfficeGraph/BiffRecords/ChartColors.cs
3,030
C#
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for System.Web.Mail // SSCLI 1.0 has no support for System.Web.Mail #if !NETCF && !SSCLI using System; using System.IO; using System.Text; #if NET_2_0 || MONO_2_0 using System.Net.Mail; #else using System.Web.Mail; #endif using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Send an e-mail when a specific logging event occurs, typically on errors /// or fatal errors. /// </summary> /// <remarks> /// <para> /// The number of logging events delivered in this e-mail depend on /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The /// <see cref="SmtpAppender"/> keeps only the last /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its /// cyclic buffer. This keeps memory requirements at a reasonable level while /// still delivering useful application context. /// </para> /// <note type="caution"> /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. /// For these features to be enabled you need to ensure that you are using a version of /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending /// unauthenticated messages to a server listening on port 25 (the default) is supported. /// </note> /// <para> /// Authentication is supported by setting the <see cref="Authentication"/> property to /// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>. /// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/> /// and <see cref="Password"/> properties must also be set. /// </para> /// <para> /// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class SmtpAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public SmtpAppender() { } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string To { get { return m_to; } set { m_to = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions). /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string Cc { get { return m_cc; } set { m_cc = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses /// that will be blind carbon copied. /// </summary> /// <value> /// A semicolon-delimited list of e-mail addresses. /// </value> /// <remarks> /// <para> /// A semicolon-delimited list of recipient e-mail addresses. /// </para> /// </remarks> public string Bcc { get { return m_bcc; } set { m_bcc = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets the e-mail address of the sender. /// </summary> /// <value> /// The e-mail address of the sender. /// </value> /// <remarks> /// <para> /// The e-mail address of the sender. /// </para> /// </remarks> public string From { get { return m_from; } set { m_from = value; } } /// <summary> /// Gets or sets the subject line of the e-mail message. /// </summary> /// <value> /// The subject line of the e-mail message. /// </value> /// <remarks> /// <para> /// The subject line of the e-mail message. /// </para> /// </remarks> public string Subject { get { return m_subject; } set { m_subject = value; } } /// <summary> /// Gets or sets the name of the SMTP relay mail server to use to send /// the e-mail messages. /// </summary> /// <value> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </value> /// <remarks> /// <para> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </para> /// </remarks> public string SmtpHost { get { return m_smtpHost; } set { m_smtpHost = value; } } /// <summary> /// Obsolete /// </summary> /// <remarks> /// Use the BufferingAppenderSkeleton Fix methods instead /// </remarks> /// <remarks> /// <para> /// Obsolete property. /// </para> /// </remarks> [Obsolete("Use the BufferingAppenderSkeleton Fix methods")] public bool LocationInfo { get { return false; } set { ; } } /// <summary> /// The mode to use to authentication with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>, /// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>. /// The default value is <see cref="SmtpAuthentication.None"/>. When using /// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/> /// and <see cref="Password"/> to use to authenticate. /// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current /// thread, if impersonating, or the process will be used to authenticate. /// </para> /// </remarks> public SmtpAuthentication Authentication { get { return m_authentication; } set { m_authentication = value; } } /// <summary> /// The username to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the username will be ignored. /// </para> /// </remarks> public string Username { get { return m_username; } set { m_username = value; } } /// <summary> /// The password to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the password will be ignored. /// </para> /// </remarks> public string Password { get { return m_password; } set { m_password = value; } } /// <summary> /// The port on which the SMTP server is listening /// </summary> /// <remarks> /// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note> /// <para> /// The port on which the SMTP server is listening. The default /// port is <c>25</c>. The Port can only be changed when running on /// the MS .NET 1.1 runtime. /// </para> /// </remarks> public int Port { get { return m_port; } set { m_port = value; } } /// <summary> /// Gets or sets the priority of the e-mail message /// </summary> /// <value> /// One of the <see cref="MailPriority"/> values. /// </value> /// <remarks> /// <para> /// Sets the priority of the e-mails generated by this /// appender. The default priority is <see cref="MailPriority.Normal"/>. /// </para> /// <para> /// If you are using this appender to report errors then /// you may want to set the priority to <see cref="MailPriority.High"/>. /// </para> /// </remarks> public MailPriority Priority { get { return m_mailPriority; } set { m_mailPriority = value; } } #if NET_2_0 || MONO_2_0 /// <summary> /// Enable or disable use of SSL when sending e-mail message /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public bool EnableSsl { get { return m_enableSsl; } set { m_enableSsl = value; } } /// <summary> /// Gets or sets the reply-to e-mail address. /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public string ReplyTo { get { return m_replyTo; } set { m_replyTo = value; } } #endif /// <summary> /// Gets or sets the subject encoding to be used. /// </summary> /// <remarks> /// The default encoding is the operating system's current ANSI codepage. /// </remarks> public Encoding SubjectEncoding { get { return m_subjectEncoding; } set { m_subjectEncoding = value; } } /// <summary> /// Gets or sets the body encoding to be used. /// </summary> /// <remarks> /// The default encoding is the operating system's current ANSI codepage. /// </remarks> public Encoding BodyEncoding { get { return m_bodyEncoding; } set { m_bodyEncoding = value; } } #endregion // Public Instance Properties #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Sends the contents of the cyclic buffer as an e-mail message. /// </summary> /// <param name="events">The logging events to send.</param> override protected void SendBuffer(LoggingEvent[] events) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize again. try { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); string t = Layout.Header; if (t != null) { writer.Write(t); } for(int i = 0; i < events.Length; i++) { // Render the event and append the text to the buffer RenderLoggingEvent(writer, events[i]); } t = Layout.Footer; if (t != null) { writer.Write(t); } SendEmail(writer.ToString()); } catch(Exception e) { ErrorHandler.Error("Error occurred while sending e-mail notification.", e); } } #endregion // Override implementation of BufferingAppenderSkeleton #region Override implementation of AppenderSkeleton /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // Override implementation of AppenderSkeleton #region Protected Methods /// <summary> /// Send the email message /// </summary> /// <param name="messageBody">the body text to include in the mail</param> virtual protected void SendEmail(string messageBody) { #if NET_2_0 || MONO_2_0 // .NET 2.0 has a new API for SMTP email System.Net.Mail // This API supports credentials and multiple hosts correctly. // The old API is deprecated. // Create and configure the smtp client SmtpClient smtpClient = new SmtpClient(); if (!String.IsNullOrEmpty(m_smtpHost)) { smtpClient.Host = m_smtpHost; } smtpClient.Port = m_port; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = m_enableSsl; if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } using (MailMessage mailMessage = new MailMessage()) { mailMessage.Body = messageBody; mailMessage.BodyEncoding = m_bodyEncoding; mailMessage.From = new MailAddress(m_from); mailMessage.To.Add(m_to); if (!String.IsNullOrEmpty(m_cc)) { mailMessage.CC.Add(m_cc); } if (!String.IsNullOrEmpty(m_bcc)) { mailMessage.Bcc.Add(m_bcc); } if (!String.IsNullOrEmpty(m_replyTo)) { // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' #if !NET_4_0 && !MONO_4_0 mailMessage.ReplyTo = new MailAddress(m_replyTo); #else mailMessage.ReplyToList.Add(new MailAddress(m_replyTo)); #endif } mailMessage.Subject = m_subject; mailMessage.SubjectEncoding = m_subjectEncoding; mailMessage.Priority = m_mailPriority; // TODO: Consider using SendAsync to send the message without blocking. This would be a change in // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. smtpClient.Send(mailMessage); } #else // .NET 1.x uses the System.Web.Mail API for sending Mail MailMessage mailMessage = new MailMessage(); mailMessage.Body = messageBody; mailMessage.BodyEncoding = m_bodyEncoding; mailMessage.From = m_from; mailMessage.To = m_to; if (m_cc != null && m_cc.Length > 0) { mailMessage.Cc = m_cc; } if (m_bcc != null && m_bcc.Length > 0) { mailMessage.Bcc = m_bcc; } mailMessage.Subject = m_subject; #if !MONO && !NET_1_0 && !NET_1_1 && !CLI_1_0 mailMessage.SubjectEncoding = m_subjectEncoding; #endif mailMessage.Priority = m_mailPriority; #if NET_1_1 // The Fields property on the MailMessage allows the CDO properties to be set directly. // This property is only available on .NET Framework 1.1 and the implementation must understand // the CDO properties. For details of the fields available in CDO see: // // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp // try { if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); } // Set the port if not the default value if (m_port != 25) { mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port); } } catch(MissingMethodException missingMethodException) { // If we were compiled against .NET 1.1 but are running against .NET 1.0 then // we will get a MissingMethodException when accessing the MailMessage.Fields property. ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException); } #else if (m_authentication != SmtpAuthentication.None) { ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } if (m_port != 25) { ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } #endif // if NET_1_1 if (m_smtpHost != null && m_smtpHost.Length > 0) { SmtpMail.SmtpServer = m_smtpHost; } SmtpMail.Send(mailMessage); #endif // if NET_2_0 } #endregion // Protected Methods #region Private Instance Fields private string m_to; private string m_cc; private string m_bcc; private string m_from; private string m_subject; private string m_smtpHost; private Encoding m_subjectEncoding = Encoding.UTF8; private Encoding m_bodyEncoding = Encoding.UTF8; // authentication fields private SmtpAuthentication m_authentication = SmtpAuthentication.None; private string m_username; private string m_password; // server port, default port 25 private int m_port = 25; private MailPriority m_mailPriority = MailPriority.Normal; #if NET_2_0 || MONO_2_0 private bool m_enableSsl = false; private string m_replyTo; #endif #endregion // Private Instance Fields #region SmtpAuthentication Enum /// <summary> /// Values for the <see cref="SmtpAppender.Authentication"/> property. /// </summary> /// <remarks> /// <para> /// SMTP authentication modes. /// </para> /// </remarks> public enum SmtpAuthentication { /// <summary> /// No authentication /// </summary> None, /// <summary> /// Basic authentication. /// </summary> /// <remarks> /// Requires a username and password to be supplied /// </remarks> Basic, /// <summary> /// Integrated authentication /// </summary> /// <remarks> /// Uses the Windows credentials from the current thread or process to authenticate. /// </remarks> Ntlm } #endregion // SmtpAuthentication Enum private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; /// <summary> /// trims leading and trailing commas or semicolons /// </summary> private static string MaybeTrimSeparators(string s) { #if NET_2_0 || MONO_2_0 return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); #else return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); #endif } } } #endif // !NETCF && !SSCLI
31.423423
174
0.626768
[ "Apache-2.0" ]
BUTTER-Tools/log4net-2.0.8
src/Appender/SmtpAppender.cs
20,928
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Core1.Mobile { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
15.055556
44
0.745387
[ "MIT" ]
ojraqueno/vstemplates
Core/Core1.Mobile/Core1.Mobile/MainPage.xaml.cs
273
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Bright.Serialization; using System.Collections.Generic; namespace cfg.test { public partial class TbTestRef { private readonly Dictionary<int, test.TestRef> _dataMap; private readonly List<test.TestRef> _dataList; public TbTestRef(ByteBuf _buf) { _dataMap = new Dictionary<int, test.TestRef>(); _dataList = new List<test.TestRef>(); for(int n = _buf.ReadSize() ; n > 0 ; --n) { test.TestRef _v; _v = test.TestRef.DeserializeTestRef(_buf); _dataList.Add(_v); _dataMap.Add(_v.Id, _v); } PostInit(); } public Dictionary<int, test.TestRef> DataMap => _dataMap; public List<test.TestRef> DataList => _dataList; public test.TestRef GetOrDefault(int key) => _dataMap.TryGetValue(key, out var v) ? v : null; public test.TestRef Get(int key) => _dataMap[key]; public test.TestRef this[int key] => _dataMap[key]; public void Resolve(Dictionary<string, object> _tables) { foreach(var v in _dataList) { v.Resolve(_tables); } PostResolve(); } public void TranslateText(System.Func<string, string, string> translator) { foreach(var v in _dataList) { v.TranslateText(translator); } } partial void PostInit(); partial void PostResolve(); } }
28.419355
97
0.555051
[ "MIT" ]
HFX-93/luban_examples
Projects/Csharp_DotNet5_bin/Gen/test/TbTestRef.cs
1,762
C#
using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using eg_03_csharp_auth_code_grant_core.Models; using Microsoft.AspNetCore.Authorization; using eg_03_csharp_auth_code_grant_core.Common; namespace eg_03_csharp_auth_code_grant_core.Controllers { public class HomeController : Controller { public IRequestItemsService RequestItemsService { get; } public HomeController(IRequestItemsService requestItemsService) { RequestItemsService = requestItemsService; } public IActionResult Index() { string egName = RequestItemsService.EgName; if (!string.IsNullOrWhiteSpace(egName)) { return Redirect(egName); } return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [Route("/dsReturn")] public IActionResult DsReturn(string state, string @event, string envelopeId) { ViewBag.title = "Return from DocuSign"; ViewBag._event = @event; ViewBag.state = state; ViewBag.envelopeId = envelopeId; return View(); } } }
29.791667
112
0.632168
[ "MIT" ]
shadim/eg-03-csharp-auth-code-grant-core
eg-03-csharp-auth-code-grant-core/Controllers/HomeController.cs
1,432
C#
using System; using System.Diagnostics; using System.Globalization; using Octokit.Internal; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PullRequestReview { public PullRequestReview() { } public PullRequestReview(long id) { Id = id; } public PullRequestReview(long id, string commitId, User user, string body, string htmlUrl, string pullRequestUrl, PullRequestReviewState state) { Id = id; CommitId = commitId; User = user; Body = body; HtmlUrl = htmlUrl; PullRequestUrl = pullRequestUrl; State = state; } /// <summary> /// The review Id. /// </summary> public long Id { get; protected set; } /// <summary> /// The state of the review /// </summary> public StringEnum<PullRequestReviewState> State { get; protected set; } /// <summary> /// The commit Id the review is associated with. /// </summary> public string CommitId { get; protected set; } /// <summary> /// The user that created the review. /// </summary> public User User { get; protected set; } /// <summary> /// The text of the review. /// </summary> public string Body { get; protected set; } /// <summary> /// The URL for this review on Github.com /// </summary> public string HtmlUrl { get; protected set; } /// <summary> /// The URL for the pull request via the API. /// </summary> public string PullRequestUrl { get; protected set; } internal string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "Id: {0}, State: {1}, User: {2}", Id, State.DebuggerDisplay, User.DebuggerDisplay); } } } public enum PullRequestReviewState { [Parameter(Value = "APPROVED")] Approved, [Parameter(Value = "CHANGES_REQUESTED")] ChangesRequested, [Parameter(Value = "COMMENTED")] Commented, [Parameter(Value = "DISMISSED")] Dismissed, [Parameter(Value = "PENDING")] Pending } }
26.329545
154
0.551144
[ "MIT" ]
Kaneraz/octokit.net
Octokit/Models/Response/PullRequestReview.cs
2,319
C#
using System.Runtime.CompilerServices; namespace RI.Framework.Utilities.Comparison { /// <summary> /// Contains utilities for customized comparison of objects. /// </summary> [CompilerGenerated] public sealed class NamespaceDoc { } }
15.625
65
0.728
[ "Apache-2.0" ]
gosystemsgmbh/RI_Framework
RI.Framework.Common/Utilities/Comparison/_NamespaceDoc.cs
252
C#
using Collector.Common.Validation.NationalIdentifier.Interface; using System; using System.Text.RegularExpressions; namespace Collector.Common.Validation.NationalIdentifier.Validators { /// <remarks> /// Allowed formats: DDMMYYZZZQQ or DDMMYY-ZZZQQ /// where DD = day, MM = month, YY = year, ZZZ = serial number, QQ = control digits /// Century of the birthdate is determined by the serial number /// 000–499 = 1900–1999 /// 500–749 = If YY &gt;= 54 then 1854–1899 , if YY &lt;= 39 then 2000-2039. YY &gt; 39 and YY &lt; 54 then undefined /// 750-899 = If YY &lt;= 39 then 2000-2039 otherwise undefined /// 900-999 = If YY &gt;= 40 then 1940-1999, if YY &lt;= 39 then 2000-2039 /// For temporary National Identifier 4 is added at the beginning i.e. 40 is added to the day so 01 becomes 41 and 30 becomes 70. /// </remarks> public class NorwegianNationalIdentifierValidator : NationalIdentifierValidator { /// <remarks>Regex has been check with SDL Regex Fuzzer tool so it should not be a source for DOS attacks. IF YOU UPDATE THE REGEX recheck it again with the SDL tool.</remarks>> private static readonly Regex NationalIdentifierWhitelistValidator = new Regex(@"^([0-3]\d[0-1]\d{3}\-?\d{5})$", RegexOptions.ECMAScript); /// <remarks>Regex has been check with SDL Regex Fuzzer tool so it should not be a source for DOS attacks. IF YOU UPDATE THE REGEX recheck it again with the SDL tool.</remarks>> private static readonly Regex TemporaryNationalIdentifierWhitelistValidator = new Regex(@"^([4-7]\d[0-1]\d{3}\-?\d{5})$", RegexOptions.ECMAScript); /// <remarks>The two first element are set to zero for padding so index don't need to be adjusted when doing calculations.</remarks>> private static readonly int[] SumOneFactors = {0, 1, 2, 5, 4, 9, 8, 1, 6, 7, 3}; /// <remarks>The first element are set to zero for padding so index don't need to be adjusted when doing calculations.</remarks>> private static readonly int[] SumTwoFactors = {1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5}; public override CountryCode CountryCode => CountryCode.NO; public override bool IsValid(string nationalIdentifier) { if (nationalIdentifier == null) return false; var isTemporary = false; if (!NationalIdentifierWhitelistValidator.IsMatch(nationalIdentifier)) { if (!TemporaryNationalIdentifierWhitelistValidator.IsMatch(nationalIdentifier)) return false; isTemporary = true; } // valueToCheck should have format: DDMMYYZZZQQ var valueToCheck = nationalIdentifier.Replace("-", string.Empty); var year = int.Parse(valueToCheck.Substring(4, 2)); var serialNumber = int.Parse(valueToCheck.Substring(6, 3)); var yearhWithCentuary = ExtractYearhWithCentury(year, serialNumber); if (yearhWithCentuary < 0) return false; var month = int.Parse(valueToCheck.Substring(2, 2)); var day = int.Parse(valueToCheck.Substring(0, 2)); if (isTemporary) day -= 40; // 40 is added to the day of temporary numbers so subtract away it return IsValidDate(yearhWithCentuary, month, day) && HasValidControlDigits(valueToCheck); } public override ParsedNationalIdentifierData Parse(string nationalIdentifier) { ParsedNationalIdentifierData parsedObj = new ParsedNationalIdentifierData(); if (nationalIdentifier == null) return parsedObj; var isTemporary = false; if (!NationalIdentifierWhitelistValidator.IsMatch(nationalIdentifier)) { if (!TemporaryNationalIdentifierWhitelistValidator.IsMatch(nationalIdentifier)) return parsedObj; isTemporary = true; } // valueToCheck should have format: DDMMYYZZZQQ var valueToCheck = nationalIdentifier.Replace("-", string.Empty); var year = int.Parse(valueToCheck.Substring(4, 2)); var serialNumber = int.Parse(valueToCheck.Substring(6, 3)); var yearhWithCentury = ExtractYearhWithCentury(year, serialNumber); if (yearhWithCentury < 0) return parsedObj; var month = int.Parse(valueToCheck.Substring(2, 2)); var day = int.Parse(valueToCheck.Substring(0, 2)); if (isTemporary) day -= 40; // 40 is added to the day of temporary numbers so subtract away it parsedObj.Valid = IsValidDate(yearhWithCentury, month, day) && HasValidControlDigits(valueToCheck); if (parsedObj.Valid) { //the last digit of the sequence number is odd for males and even for females. parsedObj.Gender = serialNumber % 2 == 1 ? Gender.MALE : Gender.FEMALE; var birthday = new DateTime(yearhWithCentury, month, day); parsedObj.DateOfBirth = birthday; parsedObj.AgeInYears = GetAge(birthday); } return parsedObj; } public override string Normalize(string nationalIdentifier) { if (!IsValid(nationalIdentifier)) throw new ArgumentException(ErrorMessages.GetInvalidIdentifierMessage(nationalIdentifier, CountryCode), nameof(nationalIdentifier)); return nationalIdentifier.Replace("-", ""); } private static int ExtractYearhWithCentury(int year, int serialNumber) { /* * 000–499 omfatter personer født i perioden 1900–1999. * 500–749 omfatter personer født i perioden 1854–1899. * 500–999 omfatter personer født i perioden 2000–2039. * 900–999 omfatter personer født i perioden 1940–1999. * * 000–499 = 1900–1999 * 500–749 = If YY >= 54 then 1854–1899 , if YY <= 39 then 2000-2039. YY > 39 and YY < 54 then undefined * 750-899 = If YY <= 39 then 2000-2039 otherwise undefined * 900-999 = If YY >= 40 then 1940-1999, if YY <= 39 then 2000-2039 */ int century; if (serialNumber <= 499 || (serialNumber >= 900 && serialNumber <= 999 && year >= 40)) { century = 1900; } else if (serialNumber >= 500 && serialNumber <= 999 && year <= 39) { century = 2000; } else if (serialNumber >= 500 && serialNumber <= 749 && year >= 54) { century = 1800; } else { return -1; } return century + year; } // Check that the two control digits are correct // a10a9 a8a7 a6a5 a4a3a2 a1a0; // a10a9 = day, a8a7 = month, a6a5= year, a4a3a2 = semi-random number, a1 = First Control digit, a0 = Second Control digit private static bool HasValidControlDigits(string value) { var civicRegNumber = long.Parse(value); var firstControlDigitCalulcated = 0L; for (var i = 1; i < 11; ++i) { var digit = GetDigitAtPosition(civicRegNumber, i); firstControlDigitCalulcated += digit * SumOneFactors[i]; } var secondControlDigitCalulcated = 0L; for (var i = 0; i < 11; ++i) { var digit = GetDigitAtPosition(civicRegNumber, i); secondControlDigitCalulcated += digit * SumTwoFactors[i]; } return firstControlDigitCalulcated % 11 == 0 && secondControlDigitCalulcated % 11 == 0; } } }
43.804598
185
0.621884
[ "Apache-2.0" ]
tapmui/common-validation
Nationaldentifier/Validators/NorwegianNationalIdentifierValidator.cs
7,660
C#
using System; using System.Collections.Generic; namespace HashCode2022_OnePizze { public static class Utils { public static void AddSorted<T>(this List<T> list, T item, IComparer<T> comparer) { if (list.Count == 0) { list.Add(item); return; } if (comparer.Compare(list[list.Count - 1], item) <= 0) { list.Add(item); return; } if (comparer.Compare(list[0], item) >= 0) { list.Insert(0, item); return; } int index = list.BinarySearch(item, comparer); if (index < 0) index = ~index; list.Insert(index, item); } public static void SwapItems<T>(List<T> list, int item1, int item2) { T tmp = list[item1]; list[item1] = list[item2]; list[item2] = tmp; } public static void SwapItems<T>(List<T> list1, int item1, List<T> list2, int item2) { T tmp = list1[item1]; list1[item1] = list2[item2]; list2[item2] = tmp; } public static int IntersectSize(int[] a, int[] b) { int size = 0; int posA = 0; int posB = 0; while ((posA < a.Length) && (posB < b.Length)) { if (a[posA] < b[posB]) posA++; else if (a[posA] > b[posB]) posB++; else if (a[posA] == b[posB]) { size++; posA++; posB++; } else throw new Exception("Ha?"); } return size; } public static int IntersectSize<T>(HashSet<T> a, HashSet<T> b) { HashSet<T> small; HashSet<T> big; if (a.Count < b.Count) { small = a; big = b; } else { small = b; big = a; } int size = 0; // Iterate on the smaller HashSet (faster) foreach (T val in small) if (big.Contains(val)) size++; return size; } } }
25.46875
91
0.384867
[ "Apache-2.0" ]
sagishporer/hashcode-practice-one-pizza
OnePizza/Utils.cs
2,447
C#
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Common")] [assembly: AssemblyCopyright("Copyright (C) 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("ja")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27.483871
52
0.739437
[ "MIT" ]
nkast/WpfFontPipeline
Samples/DrawString/DrawString.Common/Properties/AssemblyInfo.cs
1,226
C#
using Dapr.Actors; using Dapr.Actors.Client; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Volo.Abp; using Volo.Abp.DependencyInjection; using Volo.Abp.DynamicProxy; using Volo.Abp.Http; using Volo.Abp.Http.Client.Authentication; using Volo.Abp.Http.Client.DynamicProxying; using Volo.Abp.MultiTenancy; using Volo.Abp.Threading; namespace LINGYUN.Abp.Dapr.Actors.DynamicProxying { public class DynamicDaprActorProxyInterceptor<TService> : AbpInterceptor, ITransientDependency where TService: IActor { protected ICurrentTenant CurrentTenant { get; } protected AbpDaprRemoteServiceOptions DaprServiceOptions { get; } protected AbpDaprActorProxyOptions DaprActorProxyOptions { get; } protected IDynamicProxyHttpClientFactory HttpClientFactory { get; } protected IRemoteServiceHttpClientAuthenticator ClientAuthenticator { get; } public ILogger<DynamicDaprActorProxyInterceptor<TService>> Logger { get; set; } public DynamicDaprActorProxyInterceptor( IOptions<AbpDaprActorProxyOptions> daprActorProxyOptions, IOptionsSnapshot<AbpDaprRemoteServiceOptions> daprActorOptions, IDynamicProxyHttpClientFactory httpClientFactory, IRemoteServiceHttpClientAuthenticator clientAuthenticator, ICurrentTenant currentTenant) { CurrentTenant = currentTenant; HttpClientFactory = httpClientFactory; ClientAuthenticator = clientAuthenticator; DaprActorProxyOptions = daprActorProxyOptions.Value; DaprServiceOptions = daprActorOptions.Value; Logger = NullLogger<DynamicDaprActorProxyInterceptor<TService>>.Instance; } public override async Task InterceptAsync(IAbpMethodInvocation invocation) { var isAsyncMethod = invocation.Method.IsAsync(); if (!isAsyncMethod) { // see: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-howto/ // Dapr Actor文档: Actor方法的返回类型必须为Task或Task<object> throw new AbpException("The return type of Actor method must be Task or Task<object>"); } if (invocation.Arguments.Length > 1) { // see: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-howto/ // Dapr Actor文档: Actor方法最多可以有一个参数 throw new AbpException("Actor method can have one argument at a maximum"); } await MakeRequestAsync(invocation); } private async Task MakeRequestAsync(IAbpMethodInvocation invocation) { // 获取Actor配置 var actorProxyConfig = DaprActorProxyOptions.ActorProxies.GetOrDefault(typeof(TService)) ?? throw new AbpException($"Could not get DynamicDaprActorProxyConfig for {typeof(TService).FullName}."); var remoteServiceConfig = DaprServiceOptions.RemoteServices.GetConfigurationOrDefault(actorProxyConfig.RemoteServiceName); // Actors的定义太多, 可以考虑使用默认的 BaseUrl 作为远程地址 if (remoteServiceConfig.BaseUrl.IsNullOrWhiteSpace()) { throw new AbpException($"Could not get BaseUrl for {actorProxyConfig.RemoteServiceName} Or Default."); } var actorProxyOptions = new ActorProxyOptions { HttpEndpoint = remoteServiceConfig.BaseUrl }; // 自定义请求处理器 // 添加请求头用于传递状态 // TODO: Actor一次只能处理一个请求,使用状态管理来传递状态的可行性? var httpClientHandler = new DaprHttpClientHandler(); AddHeaders(httpClientHandler); httpClientHandler.PreConfigure(async (requestMessage) => { // 占位 var httpClient = HttpClientFactory.Create(AbpDaprActorsModule.DaprHttpClient); await ClientAuthenticator.Authenticate( new RemoteServiceHttpClientAuthenticateContext( httpClient, requestMessage, remoteServiceConfig, actorProxyConfig.RemoteServiceName)); // 标头 if (requestMessage.Headers.Authorization == null && httpClient.DefaultRequestHeaders.Authorization != null) { requestMessage.Headers.Authorization = httpClient.DefaultRequestHeaders.Authorization; } }); // 代理工厂 var proxyFactory = new ActorProxyFactory(actorProxyOptions, (HttpMessageHandler)httpClientHandler); await MakeRequestAsync(invocation, proxyFactory); } private async Task MakeRequestAsync( IAbpMethodInvocation invocation, ActorProxyFactory proxyFactory ) { var invokeType = typeof(TService); // 约定的 RemoteServiceAttribute 为Actor名称 var remoteServiceAttr = invokeType.GetTypeInfo().GetCustomAttribute<RemoteServiceAttribute>(); var actorType = remoteServiceAttr != null ? remoteServiceAttr.Name : invokeType.Name; var actorId = new ActorId(invokeType.FullName); try { // 创建强类型代理 var actorProxy = proxyFactory.CreateActorProxy<TService>(actorId, actorType); // 远程调用 var task = (Task)invocation.Method.Invoke(actorProxy, invocation.Arguments); await task; // 存在返回值 if (!invocation.Method.ReturnType.GenericTypeArguments.IsNullOrEmpty()) { // 处理返回值 invocation.ReturnValue = typeof(Task<>) .MakeGenericType(invocation.Method.ReturnType.GenericTypeArguments[0]) .GetProperty(nameof(Task<object>.Result), BindingFlags.Public | BindingFlags.Instance) .GetValue(task); } } catch (ActorMethodInvocationException amie) // 其他异常忽略交给框架处理 { if (amie.InnerException != null && amie.InnerException is ActorInvokeException aie) { // Dapr 包装了远程服务异常 throw new AbpDaprActorCallException( new RemoteServiceErrorInfo { Message = aie.Message, Code = aie.ActualExceptionType } ); } throw; } } private void AddHeaders(DaprHttpClientHandler handler) { //TenantId if (CurrentTenant.Id.HasValue) { //TODO: Use AbpAspNetCoreMultiTenancyOptions to get the key handler.AddHeader(TenantResolverConsts.DefaultTenantKey, CurrentTenant.Id.Value.ToString()); } //Culture //TODO: Is that the way we want? Couldn't send the culture (not ui culture) var currentCulture = CultureInfo.CurrentUICulture.Name ?? CultureInfo.CurrentCulture.Name; if (!currentCulture.IsNullOrEmpty()) { handler.AcceptLanguage(currentCulture); } } } }
41.538043
206
0.614549
[ "MIT" ]
ai408/abp-vue-admin-element-typescript
aspnet-core/modules/dapr/LINGYUN.Abp.Dapr.Actors/LINGYUN/Abp/Dapr/Actors/DynamicProxying/DynamicDaprActorProxyInterceptor.cs
7,945
C#
using System.Threading.Tasks; using AElf.Kernel.Blockchain.Events; using Volo.Abp.EventBus; namespace AElf.Kernel.Consensus.Application { /// <summary> /// Trigger consensus to update mining scheduler. /// </summary> public class BestChainFoundEventHandler : ILocalEventHandler<BestChainFoundEventData> { private readonly IConsensusService _consensusService; public BestChainFoundEventHandler(IConsensusService consensusService) { _consensusService = consensusService; } public async Task HandleEventAsync(BestChainFoundEventData eventData) { await _consensusService.TriggerConsensusAsync(new ChainContext { BlockHash = eventData.BlockHash, BlockHeight = eventData.BlockHeight }); } } }
30.321429
89
0.673734
[ "MIT" ]
IamWenboZhang/AElf
src/AElf.Kernel.Consensus/Application/BestChainFoundEventHandler.cs
849
C#
namespace TonSdk.Modules.Debot.Models { /// <summary> /// Describes how much funds will be debited from the target contract balance /// as a result of the transaction. /// </summary> public struct Spending { /// <summary> /// Amount of nanotokens that will be sent to <see cref="Dst"/> address. /// </summary> public ulong Amount { get; set; } /// <summary> /// Destination address of recipient of funds. /// </summary> public string Dst { get; set; } } }
28.35
86
0.552028
[ "Apache-2.0" ]
vcvetkovs/TonSdk
src/TonSdk/Modules/Debot/Models/Spending.cs
569
C#
using System; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Draft.Endpoints; using Draft.Responses.Statistics; namespace Draft.Requests.Statistics { /// <summary> /// A request to retrieve the statistical information for the server. /// </summary> /// <remarks>Which server depends on how the <see cref="EndpointPool" /> was built.</remarks> public interface IGetServerStatisticsRequest { /// <summary> /// The underlying <see cref="IEtcdClient" /> for this request. /// </summary> IEtcdClient EtcdClient { get; } /// <summary> /// Execute this request. /// </summary> Task<IServerStatistics> Execute(); /// <summary> /// Allows use of the <c>await</c> keyword for this request. /// </summary> TaskAwaiter<IServerStatistics> GetAwaiter(); } }
26.8
97
0.618337
[ "MIT" ]
NathanTurnbow/Draft
source/Draft/Requests/Statistics/IGetServerStatisticsRequest.cs
940
C#
using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using Cake.Core.IO; using Cake.NuGet; using NSubstitute; using Xunit; namespace Cake.Core.Tests.Unit.Packaging.NuGet { public class NuGetAssemblyCompatibilityFilterTests { public sealed class TheFilterCompatibleAssembliesMethod { private static readonly FrameworkName _dummyFrameworkName = new FrameworkName(".NETFramework,Version=v4.5.1"); [Fact] public void Should_Throw_If_Target_Framework_Is_Null() { // Given var filter = new NuGetAssemblyCompatibilityFilter(Substitute.For<INuGetFrameworkCompatibilityFilter>(), Substitute.For<INuGetPackageReferenceBundler>()); // When // ReSharper disable once ExpressionIsAlwaysNull var result = Record.Exception(() => filter.FilterCompatibleAssemblies(null, new FilePath[0])); // Then Assert.IsArgumentNullException(result, "targetFramework"); } [Fact] public void Should_Throw_If_Assembly_Paths_Is_Null() { // Given var filter = new NuGetAssemblyCompatibilityFilter(Substitute.For<INuGetFrameworkCompatibilityFilter>(), Substitute.For<INuGetPackageReferenceBundler>()); // When var result = Record.Exception(() => filter.FilterCompatibleAssemblies(_dummyFrameworkName, null)); // Then Assert.IsArgumentNullException(result, "assemblyPaths"); } [Fact] public void Should_Return_Empty_When_No_References_Are_Compatible() { // Given var targetFramework = _dummyFrameworkName; var compatibilityFilter = Substitute.For<INuGetFrameworkCompatibilityFilter>(); compatibilityFilter.GetCompatibleItems(targetFramework, Arg.Any<IEnumerable<NuGetPackageReferenceSet>>()) .Returns(Enumerable.Empty<NuGetPackageReferenceSet>()); var referenceSetFactory = Substitute.For<INuGetPackageReferenceBundler>(); var assemblyFiles = new FilePath[] { "dummy.dll", "dummy2.dll" }; var filter = new NuGetAssemblyCompatibilityFilter(compatibilityFilter, referenceSetFactory); // When var result = filter.FilterCompatibleAssemblies(targetFramework, assemblyFiles); // Then Assert.Empty(result); } [Fact] public void Should_Throw_If_Any_Assembly_Path_Is_Not_Relative() { // Given var compatibilityFilter = Substitute.For<INuGetFrameworkCompatibilityFilter>(); var referenceSetFactory = Substitute.For<INuGetPackageReferenceBundler>(); var assemblyFiles = new FilePath[] { "/dir/dummy.dll", "dummy2.dll" }; var filter = new NuGetAssemblyCompatibilityFilter(compatibilityFilter, referenceSetFactory); // When var result = Record.Exception(() => filter.FilterCompatibleAssemblies(_dummyFrameworkName, assemblyFiles)); // Then Assert.IsCakeException(result, "All assemblyPaths must be relative to the package directory."); } [Fact] public void Should_Return_Compatible_References() { // TODO: this is a pretty bad test -- some refactoring of the SUT implementation should simplify this // Given var targetFramework = new FrameworkName(".NETFramework,Version=v4.0"); var compatibleAssemblies = new FilePath[] { "lib/net40/compatible1.dll", "lib/net40/compatible2.dll", "compatible3.dll" }; var allAssemblies = compatibleAssemblies.Concat(new FilePath[] { "lib/net452/incompatible1.dll", "lib/net452/incompatible2.dll" }).ToArray(); var compatibilityFilter = Substitute.For<INuGetFrameworkCompatibilityFilter>(); compatibilityFilter.GetCompatibleItems(targetFramework, Arg.Any<IEnumerable<NuGetPackageReferenceSet>>()) .Returns(args => new[] { new NuGetPackageReferenceSet(args.Arg<FrameworkName>(), compatibleAssemblies) }); var referenceSetFactory = Substitute.For<INuGetPackageReferenceBundler>(); var filter = new NuGetAssemblyCompatibilityFilter(compatibilityFilter, referenceSetFactory); // When var result = filter.FilterCompatibleAssemblies(targetFramework, allAssemblies); // Then Assert.Equal(compatibleAssemblies.Select(ca => ca.FullPath).ToArray(), result.Select(ca => ca.FullPath).ToArray()); } } } }
41.015873
123
0.599265
[ "MIT" ]
EvilMindz/cake
src/Cake.NuGet.Tests/Unit/NuGetAssemblyCompatibilityFilterTests.cs
5,168
C#
using System; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using BusStop.Constants; using BusStop.Interfaces; namespace BusStop.Domain.IO { /// <summary> /// Used for reading time tables from sources containing data in the following format: /// <br>Posh 10:15 11:10</br> /// <br>Posh 10:10 11:00</br> /// <br>Grotty 10:10 11:00</br> /// <br>Grotty 16:30 18:45</br> /// </summary> internal sealed class TimeTableReader : ITimeTableReader { private const string TimeTableServicePartDelimiter = " "; private const string TimeFormat = "HH':'mm"; private static readonly string[] allowedBusCompaniesIds = new string[] { BusCompany.Grotty, BusCompany.Posh }; private readonly IFileReader fileReader; public TimeTableReader(IFileReader fileReader) { this.fileReader = fileReader; } public async Task<TimeTable> ReadTimeTableAsync(string filePath, CancellationToken cancellationToken) { string fileContents = await fileReader.ReadFileAsync(filePath, cancellationToken).ConfigureAwait(false); var result = ParseTimeTableFile(fileContents); return result; } private static TimeTable ParseTimeTableFile(string contents) { var timeTableServices = contents .Split(Environment.NewLine) .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(ParseServiceRecord) .ToList(); var result = new TimeTable(timeTableServices); return result; } private static TimeTableService ParseServiceRecord(string line, int index) { var serviceRecordParts = line.Split(TimeTableServicePartDelimiter); if (serviceRecordParts.Length != 3) { throw new FormatException(FormattableString.Invariant($"Line on row {index + 1} is not in correct format. Actual value: \"{line}\".")); } string companyId = serviceRecordParts[0]; string departureTimeString = serviceRecordParts[1]; string arrivalTimeString = serviceRecordParts[2]; ValidateCompanyId(companyId, index); DateTime departureTime = ParseTime(departureTimeString, nameof(departureTime), index); DateTime arrivalTime = ParseTime(arrivalTimeString, nameof(arrivalTime), index); var result = new TimeTableService(companyId, departureTime, arrivalTime); return result; } private static void ValidateCompanyId(string companyId, int lineIndex) { if (!allowedBusCompaniesIds.Any(x => x.Equals(companyId, StringComparison.InvariantCulture))) { throw new FormatException(FormattableString.Invariant($"The companyId at line {lineIndex + 1} is using an unknown format. Actual value: \"{companyId}\".")); } } private static DateTime ParseTime(string time, string timeType, int lineIndex) { if (!DateTime.TryParseExact(time, TimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime result)) { throw new FormatException(FormattableString.Invariant($"The {timeType} at line {lineIndex + 1} is using an unknown format. Actual value: \"{time}\".")); } return result; } } }
36.791667
172
0.638448
[ "MIT" ]
ExamRepos/BusStop
BusStop/Domain/IO/TimeTableReader.cs
3,534
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Globalization; using System.Windows.Forms; using AH.DUtility; using AH.ModuleController.PHRMSSR; namespace AH.ModuleController.UI.PHRMS.Forms { public partial class frmTransferReceive : AH.Shared.UI.frmSmartFormStandard { PHRMSSR.PHRMSWSClient phrSr = new PHRMSSR.PHRMSWSClient(); public frmTransferReceive() { InitializeComponent(); } private void PopulateTreeViewControl() { TreeNode parentNode; TreeNode childNode; List<PharmacyUser> pharmacylist = phrSr.GetUserByID(Utility.UserId).ToList(); foreach (PharmacyUser pharmacy in pharmacylist) { parentNode = new TreeNode(pharmacy.Warehouse.TypeName); trList.Nodes.Add(parentNode); List<TransferRequisition> trid = phrSr.GetTRID(pharmacy.Warehouse.TypeID).ToList(); foreach (TransferRequisition transfer in trid) { childNode = parentNode.Nodes.Add(transfer.ID); } parentNode.Collapse(); } } private void frmTransferReceive_Load(object sender, EventArgs e) { PopulateTreeViewControl(); txtPharmacy.DataBindings.Clear(); txtPharmacy.DataBindings.Add("Text", phrSr.GetUserByID(Utility.UserId).ToList(), "Warehouse.TypeID"); FormatGridProd(dgvTRDetails); FormatGridProd(dgvStockDetails); FormatGridProd(dgvTransferReceive); dgvTRDetails.Columns["PharmacyID"].Visible = false; dgvTRDetails.Columns["Rate"].Visible = false; dgvTRDetails.Columns["SlRate"].Visible = false; dgvTRDetails.Columns["Vat"].Visible = false; dgvTRDetails.Columns["Disc"].Visible = false; dgvTRDetails.Columns["MRRID"].Visible = false; dgvTRDetails.Columns["BatchID"].Visible = false; dgvTRDetails.Columns["ExpireDate"].Visible = false; dgvTRDetails.Columns["checkBoxColumn"].Visible = false; dgvTRDetails.Columns[22].Visible = false; dgvTransferReceive.Columns["TrrQty"].ReadOnly = true; dgvStockDetails.Columns["PharmacyID"].Visible = false; grpStockDet.Visible = false; dgvStockDetails.Visible = false; btnAddItems.Visible = false; btnCloseStockDetails.Visible = false; } private void FormatGridProd(DataGridView dtv) { dtv.AutoGenerateColumns = false; //dtv.EditMode = DataGridViewEditMode.EditOnKeystroke; //dtv.Location = new Point(lvPurchaseOrder.Location.X, lvPurchaseOrder.Location.Y); DataGridViewTextBoxColumn colTrId = new DataGridViewTextBoxColumn(); colTrId.Name = "TRID"; colTrId.DataPropertyName = "TRID"; colTrId.Width = 80; colTrId.Visible = true; dtv.Columns.Add(colTrId); DataGridViewTextBoxColumn colDrugId = new DataGridViewTextBoxColumn(); colDrugId.Name = "DRUGID"; colDrugId.DataPropertyName = "DRUGID"; colDrugId.Width = 80; colDrugId.Visible = true; dtv.Columns.Add(colDrugId); DataGridViewTextBoxColumn colDrugTitle = new DataGridViewTextBoxColumn(); colDrugTitle.Name = "Brand Name"; colDrugTitle.DataPropertyName = "DRUGNAME"; colDrugTitle.Width = 210; colDrugTitle.ReadOnly = true; colDrugTitle.Visible = true; dtv.Columns.Add(colDrugTitle); DataGridViewTextBoxColumn colTypeID = new DataGridViewTextBoxColumn(); colTypeID.Name = "TYPEID"; colTypeID.DataPropertyName = "TYPEID"; colTypeID.Width = 0; colTypeID.Visible = false; dtv.Columns.Add(colTypeID); DataGridViewTextBoxColumn colUnitID = new DataGridViewTextBoxColumn(); colUnitID.Name = "UNITID"; colUnitID.DataPropertyName = "UNITID"; colUnitID.Width = 0; colUnitID.Visible = false; dtv.Columns.Add(colUnitID); DataGridViewTextBoxColumn colGroupID = new DataGridViewTextBoxColumn(); colGroupID.Name = "GROUPID"; colGroupID.DataPropertyName = "GROUPID"; colGroupID.Width = 0; colGroupID.Visible = false; dtv.Columns.Add(colGroupID); DataGridViewTextBoxColumn colCompanyID = new DataGridViewTextBoxColumn(); colCompanyID.Name = "COMPANYID"; colCompanyID.DataPropertyName = "COMPANYID"; colCompanyID.Width = 0; colCompanyID.Visible = false; dtv.Columns.Add(colCompanyID); DataGridViewTextBoxColumn colCompanyTitle = new DataGridViewTextBoxColumn(); colCompanyTitle.Name = "Company"; colCompanyTitle.DataPropertyName = "COMPANYNAME"; colCompanyTitle.Width = 200; colCompanyTitle.Visible = true; colCompanyTitle.ReadOnly = true; dtv.Columns.Add(colCompanyTitle); DataGridViewTextBoxColumn colGroupTitle = new DataGridViewTextBoxColumn(); colGroupTitle.Name = "Generic Name"; colGroupTitle.DataPropertyName = "GROUPNAME"; colGroupTitle.Width = 230; colGroupTitle.Visible = true; colGroupTitle.ReadOnly = true; dtv.Columns.Add(colGroupTitle); DataGridViewTextBoxColumn colUnitName = new DataGridViewTextBoxColumn(); colUnitName.Name = "Unit"; colUnitName.DataPropertyName = "UNITNAME"; colUnitName.Width = 0; colUnitName.Visible = false; colUnitName.ReadOnly = true; dtv.Columns.Add(colUnitName); DataGridViewTextBoxColumn colPackName = new DataGridViewTextBoxColumn(); colPackName.Name = "Unit Pack"; colPackName.DataPropertyName = "PACKNAME"; colPackName.Width = 0; colPackName.Visible = false; colPackName.ReadOnly = true; dtv.Columns.Add(colPackName); DataGridViewTextBoxColumn colpharmacyid = new DataGridViewTextBoxColumn(); colpharmacyid.Name = "PharmacyID"; colpharmacyid.DataPropertyName = "PharmacyID"; colpharmacyid.Width = 50; colpharmacyid.Visible = true; dtv.Columns.Add(colpharmacyid); DataGridViewTextBoxColumn colreqqty = new DataGridViewTextBoxColumn(); colreqqty.Name = "ReqQty"; colreqqty.DataPropertyName = "ReqQty"; colreqqty.Width = 60; colreqqty.ReadOnly = true; dtv.Columns.Add(colreqqty); DataGridViewTextBoxColumn coltrrqty = new DataGridViewTextBoxColumn(); coltrrqty.Name = "TrrQty"; coltrrqty.DataPropertyName = "TrrQty"; coltrrqty.Width = 60; coltrrqty.ReadOnly = false; coltrrqty.DefaultCellStyle.Format = "0.00##"; dtv.Columns.Add(coltrrqty); DataGridViewTextBoxColumn colUrate = new DataGridViewTextBoxColumn(); colUrate.Name = "Rate"; colUrate.DataPropertyName = "Rate"; colUrate.Width = 70; colUrate.DefaultCellStyle.Format = "0.00##"; dtv.Columns.Add(colUrate); DataGridViewTextBoxColumn colSlrate = new DataGridViewTextBoxColumn(); colSlrate.Name = "SlRate"; colSlrate.DataPropertyName = "SlRate"; colSlrate.Width = 70; colSlrate.Visible = true; dtv.Columns.Add(colSlrate); DataGridViewTextBoxColumn colvat = new DataGridViewTextBoxColumn(); colvat.Name = "Vat"; colvat.DataPropertyName = "Vat"; colvat.Width = 0; colvat.Visible = false; dtv.Columns.Add(colvat); DataGridViewTextBoxColumn colDiscount = new DataGridViewTextBoxColumn(); colDiscount.Name = "Disc"; colDiscount.DataPropertyName = "Disc"; colDiscount.Width = 0; colDiscount.Visible = false; dtv.Columns.Add(colDiscount); DataGridViewTextBoxColumn colMrrID = new DataGridViewTextBoxColumn(); colMrrID.Name = "MRRID"; colMrrID.DataPropertyName = "MRRID"; colMrrID.Width = 70; colMrrID.Visible = true; dtv.Columns.Add(colMrrID); DataGridViewTextBoxColumn colBatchID = new DataGridViewTextBoxColumn(); colBatchID.Name = "BatchID"; colBatchID.DataPropertyName = "BatchID"; colBatchID.Width = 70; colBatchID.ReadOnly = true; colBatchID.Visible = true; dtv.Columns.Add(colBatchID); DataGridViewTextBoxColumn colExpDate = new DataGridViewTextBoxColumn(); colExpDate.Name = "ExpireDate"; colExpDate.DataPropertyName = "ExpireDate"; colExpDate.Width = 0; colExpDate.Visible = false; dtv.Columns.Add(colExpDate); DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn(); checkBoxColumn.HeaderText = ""; checkBoxColumn.Width = 18; checkBoxColumn.Visible = true; checkBoxColumn.Name = "checkBoxColumn"; dtv.Columns.Insert(21, checkBoxColumn); DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn(); Deletelink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "Delete"; Deletelink.DataPropertyName = "lnkColumn"; Deletelink.Width = 60; //Deletelink.LinkBehavior = LinkBehavior.SystemDefault; Deletelink.Text = "Delete"; dtv.Columns.Add(Deletelink); } private void populateDataToGridDrug(DataGridView dtv, string trid) { short index = 0; dgvTRDetails.Rows.Clear(); dgvTRDetails.Visible = true; List<TransferRequisition> list = new List<TransferRequisition>(); list.Clear(); list.AddRange(phrSr.GetTRDetails(trid).ToList()); foreach (TransferRequisition data in list) { string[] row = new string[] { data.ID, data.DrugMaster.ID, data.DrugMaster.Name, data.DrugMaster.DrugPackType.ID, data.DrugMaster.DrugUnit.ID, data.DrugMaster.DrugGroup.ID, data.DrugMaster.DrugCompany.ID, data.DrugMaster.DrugCompany.Name, data.DrugMaster.DrugGroup.Name, data.DrugMaster.DrugUnit.Name, data.DrugMaster.DrugPackType.Name, data.Warehouse.TypeID, data.TrQty.ToString(), data.TrrQty.ToString() }; AddRowsToCollection(dgvTRDetails, row, index); index++; } } private void AddRowsToCollection(DataGridView dtv, string[] row, short index) { dtv.Rows.Insert(index, row); } private void trList_AfterSelect(object sender, TreeViewEventArgs e) { txtTRID.Text = trList.SelectedNode.Text; populateDataToGridDrug(dgvTRDetails,txtTRID.Text); txtfromPharmacy.DataBindings.Clear(); txttoPharmacy.DataBindings.Clear(); txtFromPhar.DataBindings.Clear(); txtToPhar.DataBindings.Clear(); txtfromPharmacy.DataBindings.Add("Text", phrSr.GetTRDetails(txtTRID.Text).ToList(), "Warehouse.TypeID"); txtFromPhar.DataBindings.Add("Text", phrSr.GetTRDetails(txtTRID.Text).ToList(), "Warehouse.TypeName"); txttoPharmacy.DataBindings.Add("Text", phrSr.GetTRDetails(txtTRID.Text).ToList(), "Warehouse.ToTypeID"); txtToPhar.DataBindings.Add("Text", phrSr.GetTRDetails(txtTRID.Text).ToList(), "Warehouse.ToTypeName"); LoadListDataGrid(); btnSave.Enabled = true; //if (dgvStockDetails.Rows.Count > 0) //{ // LoadListDataGrid(); //} //else //{ // txtPR.Text = string.Empty; // txtPO.Text = string.Empty; // txtGRN.Text = string.Empty; // txtTransNo.Text = string.Empty; // txtChallanNo.Text = string.Empty; // txtChallanDate.Text = string.Empty; //} } private void dgvTRDetails_CellClick(object sender, DataGridViewCellEventArgs e) { //string i = dgvDemandReq.CurrentRow.Cells[0].Value.ToString(); //frmItemDetailsByBatch oitmdet = new frmItemDetailsByBatch(i); //oitmdet.ShowDialog(); grpStockDet.Visible = true; btnAddItems.Visible = true; btnCloseStockDetails.Visible = true; grpStockDet.Height = 200; grpStockDet.Width = 850; dgvStockDetails.Height = 170; dgvStockDetails.Width = 780; populateDataToGridForStock(dgvStockDetails, dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()); txtTrrQty.Text = dgvTRDetails.CurrentRow.Cells[13].Value.ToString(); btnAddItems.Location = new Point(grpStockDet.Location.X + 795, grpStockDet.Location.Y + 12); btnCloseStockDetails.Location = new Point(grpStockDet.Location.X + 795, grpStockDet.Location.Y + 40); dgvStockDetails.Columns["PharmacyID"].Visible = false; dgvStockDetails.Columns["Rate"].Visible = false; dgvStockDetails.Columns["SlRate"].Visible = false; dgvStockDetails.Columns["Vat"].Visible = false; dgvStockDetails.Columns["Disc"].Visible = false; dgvStockDetails.Columns["MRRID"].Visible = false; dgvStockDetails.Columns["Company"].Visible = false; dgvStockDetails.Columns[22].Visible = false; } private void LoadListDataGrid() { txtPR.DataBindings.Clear(); txtPO.DataBindings.Clear(); txtGRN.DataBindings.Clear(); txtTransNo.DataBindings.Clear(); txtChallanNo.DataBindings.Clear(); txtChallanDate.DataBindings.Clear(); txtPR.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "PurchaseOrder.PurchaseRequisition.ID"); txtPO.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "PurchaseOrder.ID"); txtGRN.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "MRRID"); txtTransNo.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "TransactionType"); txtChallanNo.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "ChallanNo"); txtChallanDate.DataBindings.Add("Text", phrSr.GetDrugDetailsBatch(dgvTRDetails.CurrentRow.Cells[0].Value.ToString(), dgvTRDetails.CurrentRow.Cells[1].Value.ToString(), dgvTRDetails.CurrentRow.Cells[11].Value.ToString()).ToList(), "ChallanDate"); } private void populateDataToGridForStock(DataGridView dtv, string trid,string drugid,string pharmacyid) { short index = 0; dgvStockDetails.Visible = true; dgvStockDetails.Rows.Clear(); List<MaterialReceive> list = new List<MaterialReceive>(); list.Clear(); list.AddRange(phrSr.GetDrugDetailsBatch(trid,drugid,pharmacyid).ToList()); foreach (MaterialReceive data in list) { string[] row = new string[] { "", data.ItemsOrder.DrugMaster.ID, data.ItemsOrder.DrugMaster.Name, data.ItemsOrder.DrugMaster.DrugPackType.ID, data.ItemsOrder.DrugMaster.DrugUnit.ID, data.ItemsOrder.DrugMaster.DrugGroup.ID, data.ItemsOrder.DrugMaster.DrugCompany.ID, data.ItemsOrder.DrugMaster.DrugCompany.Name, data.ItemsOrder.DrugMaster.DrugGroup.Name, data.ItemsOrder.DrugMaster.DrugUnit.Name, data.ItemsOrder.DrugMaster.DrugPackType.Name, "", data.PurchaseOrder.PurchaseRequisition.RequisitionQty.ToString(), "0", data.ItemsOrder.URate.ToString(), data.ItemsOrder.SlRate.ToString(), data.ItemsOrder.VAT.ToString(), data.ItemsOrder.Discount.ToString(), data.MRRID, data.BatchNo, data.ExpireDate.ToString("dd/MM/yyyy") //data.MRRID, //data.ExpireDate.ToString("dd/MM/yyyy") }; AddRowsToCollection(dgvStockDetails, row, index); index++; } dgvStockDetails.Columns[0].Visible = false; } private void btnAdd_Click(object sender, EventArgs e) { } private void btnCloseStockDetails_Click(object sender, EventArgs e) { grpStockDet.Visible = false; dgvStockDetails.Visible = false; btnAddItems.Visible = false; btnCloseStockDetails.Visible = false; } private void btnAddItems_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dgvStockDetails.Rows) { float sum = 0; bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value); if (isSelected) { for (int i = 0; i < dgvStockDetails.Rows.Count; i++) { if (Convert.ToBoolean(dgvStockDetails.Rows[i].Cells["checkBoxColumn"].Value) == true) { sum += float.Parse(dgvStockDetails.Rows[i].Cells["TrrQty"].Value.ToString()); txtSumTrrQty.Text = sum.ToString(); //sum += float.Parse(dgvStockDetails.Rows[i].Cells["IssueQty"].Value.ToString()); //lblTotalReq.Text = sum.ToString(); //if (float.Parse(lblTotalReq.Text.ToString()) > float.Parse(dgvStockDetails.Rows[i].Cells["ReqQty"].Value.ToString())) //{ // MessageBox.Show("IssueQty cann't be more than ReqQty"); // return; //} if (float.Parse(dgvStockDetails.Rows[i].Cells["TrrQty"].Value.ToString()) == 0) { MessageBox.Show("TrrQty can not be zero"); return; } if (float.Parse(txtSumTrrQty.Text) > float.Parse(txtTrrQty.Text)) { MessageBox.Show("TrrQty cann't be more than RemQty"); return; } //if (float.Parse(dgvStockDetails.Rows[i].Cells["IssueQty"].Value.ToString()) > float.Parse(dgvStockDetails.Rows[i].Cells["RemCalc"].Value.ToString())) //{ // MessageBox.Show("IssueQty cann't be more than PendingReqQty"); // return; //} } } for (int j = 0; j < dgvTransferReceive.Rows.Count; j++) { if (row.Cells[1].Value.ToString() == dgvTransferReceive.Rows[j].Cells[1].Value.ToString() && row.Cells[19].Value.ToString() == dgvTransferReceive.Rows[j].Cells[19].Value.ToString()) { MessageBox.Show("This Item is Duplicate"); grpStockDet.Visible = false; btnAddItems.Visible = false; btnCloseStockDetails.Visible = false; return; } } dgvTransferReceive.Rows.Add(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[4].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[6].Value.ToString(), row.Cells[7].Value.ToString(), row.Cells[8].Value.ToString(), row.Cells[9].Value.ToString(), row.Cells[10].Value.ToString(), row.Cells[11].Value.ToString(), row.Cells[12].Value.ToString(), row.Cells[13].Value.ToString(), row.Cells[14].Value.ToString(), row.Cells[15].Value.ToString(), row.Cells[16].Value.ToString(), row.Cells[17].Value.ToString(), row.Cells[18].Value.ToString(), row.Cells[19].Value.ToString(), row.Cells[20].Value.ToString(), row.Cells[22].Value.ToString() ); dgvTransferReceive.Columns["checkBoxColumn"].Visible = false; dgvTransferReceive.Columns["TRID"].Visible = false; dgvTransferReceive.Columns["PharmacyID"].Visible = false; dgvTransferReceive.Columns["Rate"].Visible = false; dgvTransferReceive.Columns["SlRate"].Visible = false; dgvTransferReceive.Columns["MRRID"].Visible = false; this.dgvTransferReceive.Focus(); } } //dgvIssueDetails.Columns["ReqQty"].HeaderText = "IssueQty"; //for (int i = 0; i < dgvIssueDetails.Rows.Count; i++) //{ // dgvIssueDetails.Rows[i].Cells[19].Value = float.Parse(dgvIssueDetails.Rows[i].Cells[15].Value.ToString()) * float.Parse(dgvIssueDetails.Rows[i].Cells[18].Value.ToString()); // dgvIssueDetails.Rows[i].Cells[22].Value = float.Parse(dgvIssueDetails.Rows[i].Cells[15].Value.ToString()) * float.Parse(dgvIssueDetails.Rows[i].Cells[18].Value.ToString()) + float.Parse(dgvIssueDetails.Rows[i].Cells[20].Value.ToString()) - float.Parse(dgvIssueDetails.Rows[i].Cells[21].Value.ToString()); //} grpStockDet.Visible = false; btnAddItems.Visible = false; btnCloseStockDetails.Visible = false; } private void btnEdit_Click(object sender, EventArgs e) { } private void btnSave_Click(object sender, EventArgs e) { List<string> vf = new List<string>() { "txtReceivedBy", "cboCostCategoey", "cboCostCenter" }; Control control = Utility.ReqFieldValidator(this, vf); if (control != null) { MessageBox.Show(Utility.getFMS(control.Name) + Utility.Req, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning); control.Focus(); return; } if (dgvTransferReceive.Rows.Count == 0) { MessageBox.Show("Please Select Item "); return; } //for (int k = 0; k < dgvTransferReceive.Rows.Count; k++) //{ //if (float.Parse(dgvTransferReceive.Rows[k].Cells["IssueQty"].Value.ToString()) == 0) //{ // MessageBox.Show("Issue Quantity can not be zero"); // return; //} //if (Convert.ToDateTime(dgvTransferReceive.Rows[k].Cells["ExpireDate"].Value) < Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"))) //{ // MessageBox.Show("Expire Date cannot be earlier than Current Date"); // return; //} //} //if (txtIssueDate.Text == " / /") //{ // MessageBox.Show("Date cannot be Empty"); // return; //} try { TransferReceive issueObj = this.populateTransferReceive(); string i = phrSr.SaveTransferReceive(issueObj); if (i == "0") { MessageBox.Show(Utility.InsertMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { MessageBox.Show(Utility.InsertMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Information); btnSave.Enabled = false; dgvTRDetails.Rows.Clear(); dgvTransferReceive.Rows.Clear(); } } catch (System.ServiceModel.CommunicationException commp) { MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception ex) { MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private TransferReceive populateTransferReceive() { TransferReceive otransfer = new TransferReceive(); otransfer.TrrType = "1"; otransfer.TrrDate = DateTime.Parse(txtTransactionDate.Text); otransfer.Remarks = txtRemarks.Text; TransferRequisition otr = new TransferRequisition(); otr.ID = txtTRID.Text; otransfer.TransferRequisition = otr; Warehouse ophr = new Warehouse(); ophr.TypeID = txtfromPharmacy.Text; ophr.ToTypeID = txttoPharmacy.Text; otransfer.Warehouse = ophr; MaterialReceive omr = new MaterialReceive(); omr.MRRID = txtGRN.Text; omr.ChallanNo = txtChallanNo.Text; omr.ChallanDate = DateTime.Parse(txtChallanDate.Text); omr.VoucherNo = "1234"; omr.TransactionType = txtTransNo.Text; PurchaseOrder opo = new PurchaseOrder(); opo.ID = txtPO.Text; PurchaseRequisition opr = new PurchaseRequisition(); opr.ID = txtPR.Text; opo.PurchaseRequisition = opr; omr.PurchaseOrder = opo; otransfer.MaterialReceive = omr; EntryParameter ep = new EntryParameter(); ep.CompanyID = Utility.CompanyID; ep.EntryBy = Utility.UserId; ep.LocationID = Utility.LocationID; ep.MachineID = Utility.MachineID; otransfer.EntryParameter = ep; string trrstring = ""; foreach (DataGridViewRow dr in dgvTransferReceive.Rows) { trrstring += dr.Cells[1].Value.ToString() + "," + dr.Cells[3].Value.ToString() + "," + dr.Cells[4].Value.ToString() + "," + dr.Cells[5].Value.ToString() + "," + dr.Cells[6].Value.ToString() + "," + dr.Cells[14].Value.ToString() + "," + dr.Cells[15].Value.ToString() + "," + dr.Cells[16].Value.ToString() + "," + dr.Cells[17].Value.ToString() + "," + dr.Cells[12].Value.ToString() + "," + dr.Cells[13].Value.ToString() + "," + dr.Cells[20].Value.ToString() + "," + dr.Cells[19].Value.ToString() ; trrstring += ";"; } otransfer.TrrDetails = trrstring; return otransfer; } private void dgvStockDetails_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dgvStockDetails.Columns["TrrQty"].Index) { dgvStockDetails.Rows[e.RowIndex].ErrorText = ""; float newInteger; // Don't try to validate the 'new row' until finished // editing since there // is not any point in validating its initial value. if (dgvStockDetails.Rows[e.RowIndex].IsNewRow) { return; } if (!float.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0) { e.Cancel = true; dgvStockDetails.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer"; } } } private void dgvTransferReceive_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dgvTransferReceive_CellContentClick_1(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 22) { int selRowIndex = e.RowIndex; if (selRowIndex < 0) { dgvTransferReceive.Rows.Clear(); } else { dgvTransferReceive.Rows.RemoveAt(selRowIndex); } } } } }
47.525547
511
0.533958
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/PHRMS/Forms/frmTransferReceive.cs
32,557
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 qldb-2019-01-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.QLDB.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.QLDB.Model.Internal.MarshallTransformations { /// <summary> /// ListJournalS3Exports Request Marshaller /// </summary> public class ListJournalS3ExportsRequestMarshaller : IMarshaller<IRequest, ListJournalS3ExportsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListJournalS3ExportsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListJournalS3ExportsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.QLDB"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-01-02"; request.HttpMethod = "GET"; if (publicRequest.IsSetMaxResults()) request.Parameters.Add("max_results", StringUtils.FromInt(publicRequest.MaxResults)); if (publicRequest.IsSetNextToken()) request.Parameters.Add("next_token", StringUtils.FromString(publicRequest.NextToken)); request.ResourcePath = "/journal-s3-exports"; request.MarshallerVersion = 2; request.UseQueryString = true; return request; } private static ListJournalS3ExportsRequestMarshaller _instance = new ListJournalS3ExportsRequestMarshaller(); internal static ListJournalS3ExportsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListJournalS3ExportsRequestMarshaller Instance { get { return _instance; } } } }
35.652174
156
0.633537
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/QLDB/Generated/Model/Internal/MarshallTransformations/ListJournalS3ExportsRequestMarshaller.cs
3,280
C#
using Clarity.Common.CodingUtilities; using Clarity.Common.Infra.Files; namespace Clarity.Engine.Media.Skyboxes { public interface ISkyboxLoader { bool TryLoad(IReadOnlyFileSystem fileSystem, string path, out ISkybox skybox, out string[] imageFileRelativePaths, out ErrorInfo error); } }
30.9
144
0.770227
[ "MIT" ]
Zulkir/ClarityWorlds
Source/Clarity.Engine/Media/Skyboxes/ISkyboxLoader.cs
311
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace RakNet { using System; using System.Runtime.InteropServices; public class PacketConsoleLogger : PacketLogger { private HandleRef swigCPtr; internal PacketConsoleLogger(IntPtr cPtr, bool cMemoryOwn) : base(RakNetPINVOKE.PacketConsoleLogger_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(PacketConsoleLogger obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } ~PacketConsoleLogger() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; RakNetPINVOKE.delete_PacketConsoleLogger(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } public PacketConsoleLogger() : this(RakNetPINVOKE.new_PacketConsoleLogger(), true) { } public virtual void SetLogCommandParser(LogCommandParser lcp) { RakNetPINVOKE.PacketConsoleLogger_SetLogCommandParser(swigCPtr, LogCommandParser.getCPtr(lcp)); } public override void WriteLog(string str) { RakNetPINVOKE.PacketConsoleLogger_WriteLog(swigCPtr, str); } } }
28.649123
133
0.638089
[ "Apache-2.0" ]
Colton-Soneson/FissionEditor
VulkanEditor/SDK/Source/Raknet/DependentExtensions/Swig/InternalSwigItems/InternalSwigWindowsCSharpSample/InternalSwigTestApp/SwigFiles/PacketConsoleLogger.cs
1,633
C#
using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Microsoft.AppCenter; using Microsoft.AppCenter.Analytics; using Microsoft.AppCenter.Crashes; using Reviewer.Core; using PhotoTour.Services; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace PhotoTour.Core { public partial class App : Application { public App() { InitializeComponent(); MonkeyCache.FileStore.Barrel.ApplicationId = "phototour"; DependencyService.Register<IStorageService, StorageService>(); DependencyService.Register<IDataService, MongoDataService>(); MainPage = new NavigationPage(new PhotoListPage()); } protected override void OnStart() { base.OnStart(); AppCenter.Start($"ios={APIKeys.AppCenterIOSKey};" + $"android={APIKeys.AppCenterDroidKey};", typeof(Analytics), typeof(Crashes)); Analytics.SetEnabledAsync(true); } protected override void OnSleep() { base.OnSleep(); } protected override void OnResume() { base.OnResume(); } } }
19.62963
65
0.733019
[ "MIT" ]
Azure-Samples/azuredevtour
xamarin/Reviewer.Core/App.xaml.cs
1,062
C#
namespace PDFToJPGExpert { partial class frmPromotion { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmPromotion)); this.label1 = new System.Windows.Forms.Label(); this.lnkPromotion = new System.Windows.Forms.LinkLabel(); this.picPromotion = new System.Windows.Forms.PictureBox(); this.chkVisitWebpage = new System.Windows.Forms.CheckBox(); this.chkDoNotShowAgain = new System.Windows.Forms.CheckBox(); this.btnOK = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.picPromotion)).BeginInit(); this.SuspendLayout(); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.ForeColor = System.Drawing.Color.DarkBlue; this.label1.Name = "label1"; // // lnkPromotion // resources.ApplyResources(this.lnkPromotion, "lnkPromotion"); this.lnkPromotion.BackColor = System.Drawing.Color.Transparent; this.lnkPromotion.LinkColor = System.Drawing.Color.DarkBlue; this.lnkPromotion.Name = "lnkPromotion"; this.lnkPromotion.TabStop = true; this.lnkPromotion.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkPromotion_LinkClicked); // // picPromotion // this.picPromotion.Image = global::PDFToJPGExpert.Properties.Resources.onlinepdfapps_com_main_screen_700_373; resources.ApplyResources(this.picPromotion, "picPromotion"); this.picPromotion.Name = "picPromotion"; this.picPromotion.TabStop = false; this.picPromotion.Click += new System.EventHandler(this.picPromotion_Click); // // chkVisitWebpage // resources.ApplyResources(this.chkVisitWebpage, "chkVisitWebpage"); this.chkVisitWebpage.BackColor = System.Drawing.Color.Transparent; this.chkVisitWebpage.Checked = true; this.chkVisitWebpage.CheckState = System.Windows.Forms.CheckState.Checked; this.chkVisitWebpage.ForeColor = System.Drawing.Color.DarkBlue; this.chkVisitWebpage.Name = "chkVisitWebpage"; this.chkVisitWebpage.UseVisualStyleBackColor = false; // // chkDoNotShowAgain // resources.ApplyResources(this.chkDoNotShowAgain, "chkDoNotShowAgain"); this.chkDoNotShowAgain.BackColor = System.Drawing.Color.Transparent; this.chkDoNotShowAgain.ForeColor = System.Drawing.Color.DarkBlue; this.chkDoNotShowAgain.Name = "chkDoNotShowAgain"; this.chkDoNotShowAgain.UseVisualStyleBackColor = false; // // btnOK // this.btnOK.Image = global::PDFToJPGExpert.Properties.Resources.check; resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // frmPromotion // resources.ApplyResources(this, "$this"); this.Controls.Add(this.btnOK); this.Controls.Add(this.chkDoNotShowAgain); this.Controls.Add(this.chkVisitWebpage); this.Controls.Add(this.picPromotion); this.Controls.Add(this.lnkPromotion); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmPromotion"; this.ShowInTaskbar = true; ((System.ComponentModel.ISupportInitialize)(this.picPromotion)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.LinkLabel lnkPromotion; private System.Windows.Forms.PictureBox picPromotion; public System.Windows.Forms.CheckBox chkVisitWebpage; public System.Windows.Forms.CheckBox chkDoNotShowAgain; private System.Windows.Forms.Button btnOK; } }
44.735537
144
0.618142
[ "MIT" ]
fourDotsSoftware/PDF-To-JPG-Expert
PDF To JPG Expert/frmPromotion.Designer.cs
5,415
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class CallGCSuppressFinalizeCorrectlyFixerTests : CodeFixTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new BasicCallGCSuppressFinalizeCorrectlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CSharpCallGCSuppressFinalizeCorrectlyAnalyzer(); } protected override CodeFixProvider GetBasicCodeFixProvider() { return new BasicCallGCSuppressFinalizeCorrectlyFixer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new CSharpCallGCSuppressFinalizeCorrectlyFixer(); } } }
34.333333
160
0.731686
[ "Apache-2.0" ]
amcasey/roslyn-analyzers
src/System.Runtime.Analyzers/UnitTests/CallGCSuppressFinalizeCorrectlyTests.Fixer.cs
1,133
C#
using System; using System.IO; namespace CNUnit.Tools { public static class Constants { public const string JUnitXslt = "https://raw.githubusercontent.com/nunit/nunit-transforms/master/nunit3-junit/nunit3-junit.xslt"; public static readonly string OutDirDefault = Path.Combine(Environment.CurrentDirectory, "cnunit-reports"); public static readonly string JUnitXsltFile = Path.Combine(Environment.CurrentDirectory, "nunit3-junit.xslt"); } }
34.285714
137
0.745833
[ "MIT" ]
unickq/CNUnit
CNUnit/Tools/Constants.cs
482
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace ee.iLawyer.ExControls { public class MultiComboBox : ComboBox { static MultiComboBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiComboBox), new FrameworkPropertyMetadata(typeof(MultiComboBox))); } private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(e.Property, e.NewValue); } /// <summary> /// 选中项列表 /// </summary> public ObservableCollection<MultiCbxBaseData> ChekedItems { get { return (ObservableCollection<MultiCbxBaseData>)GetValue(ChekedItemsProperty); } set { SetValue(ChekedItemsProperty, value); } } public static readonly DependencyProperty ChekedItemsProperty = DependencyProperty.Register("ChekedItems", typeof(ObservableCollection<MultiCbxBaseData>), typeof(MultiComboBox), new PropertyMetadata(new ObservableCollection<MultiCbxBaseData>(), OnPropertyChanged)); /// <summary> /// ListBox竖向列表 /// </summary> private ListBox _ListBoxV; /// <summary> /// ListBox横向列表 /// </summary> private ListBox _ListBoxH; public override void OnApplyTemplate() { base.OnApplyTemplate(); _ListBoxV = Template.FindName("PART_ListBox", this) as ListBox; _ListBoxH = Template.FindName("PART_ListBoxChk", this) as ListBox; _ListBoxH.ItemsSource = ChekedItems; _ListBoxV.SelectionChanged += _ListBoxV_SelectionChanged; _ListBoxH.SelectionChanged += _ListBoxH_SelectionChanged; if (ItemsSource != null) { foreach (var item in ItemsSource) { MultiCbxBaseData bdc = item as MultiCbxBaseData; if (bdc.IsCheck) { _ListBoxV.SelectedItems.Add(bdc); } } } } private void _ListBoxH_SelectionChanged(object sender, SelectionChangedEventArgs e) { foreach (var item in e.RemovedItems) { MultiCbxBaseData datachk = item as MultiCbxBaseData; for (int i = 0; i < _ListBoxV.SelectedItems.Count; i++) { MultiCbxBaseData datachklist = _ListBoxV.SelectedItems[i] as MultiCbxBaseData; if (datachklist.ID == datachk.ID) { _ListBoxV.SelectedItems.Remove(_ListBoxV.SelectedItems[i]); } } } } void _ListBoxV_SelectionChanged(object sender, SelectionChangedEventArgs e) { foreach (var item in e.AddedItems) { MultiCbxBaseData datachk = item as MultiCbxBaseData; datachk.IsCheck = true; if (ChekedItems.IndexOf(datachk) < 0) { ChekedItems.Add(datachk); } } foreach (var item in e.RemovedItems) { MultiCbxBaseData datachk = item as MultiCbxBaseData; datachk.IsCheck = false; ChekedItems.Remove(datachk); } } public void SelectAll() { this._ListBoxV.SelectAll(); } public void UnselectAll() { this._ListBoxV.UnselectAll(); } public class MultiCbxBaseData { private int _id; /// <summary> /// 关联主键 /// </summary> public int ID { get { return _id; } set { _id = value; } } private string _viewName; /// <summary> /// 显示名称 /// </summary> public string ViewName { get { return _viewName; } set { _viewName = value; } } private bool _isCheck; /// <summary> /// 是否选中 /// </summary> public bool IsCheck { get { return _isCheck; } set { _isCheck = value; } } } } }
29.254777
213
0.517091
[ "Apache-2.0" ]
Egoily/iLawyer
03.Application/ee.iLawyer/ExControls/MultiComboBox.cs
4,645
C#
using System; namespace CoRDependencyInjection.Exceptions { /// <summary> /// Thrown when the chain is empty and build was requested. /// </summary> public class EmptyChainException : CoRDependencyInjectionException { public EmptyChainException(string message) : base(message) { } public EmptyChainException() { } public EmptyChainException(string message, Exception innerException) : base(message, innerException) { } } }
24.090909
108
0.626415
[ "MIT" ]
esavini/cor-di
CoRDependencyInjection/Exceptions/EmptyChainException.cs
532
C#
using System; using System.Threading.Tasks; using Diagnostics.ModelsAndUtils.Models; using Diagnostics.ModelsAndUtils.Models.ResponseExtensions; using Diagnostics.RuntimeHost.Models; using Diagnostics.RuntimeHost.Utilities; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Newtonsoft.Json; using Microsoft.CSharp.RuntimeBinder; namespace Diagnostics.RuntimeHost.Controllers { [Authorize] [Produces("application/json")] [Route(UriElements.AzureKubernetesServiceResource)] public class AzureKubernetesServiceController : DiagnosticControllerBase<AzureKubernetesService> { public AzureKubernetesServiceController(IServiceProvider services, IRuntimeContext<AzureKubernetesService> runtimeContext) : base(services, runtimeContext) { } [HttpPost(UriElements.Query)] public async Task<IActionResult> ExecuteQuery(string subscriptionId, string resourceGroupName, string clusterName, [FromBody]CompilationPostBody<dynamic> jsonBody, string startTime = null, string endTime = null, string timeGrain = null, [FromQuery][ModelBinder(typeof(FormModelBinder))] Form Form = null) { return await base.ExecuteQuery(GetResource(subscriptionId, resourceGroupName, clusterName), jsonBody, startTime, endTime, timeGrain, Form: Form); } [HttpPost(UriElements.Detectors)] public async Task<IActionResult> ListDetectors(string subscriptionId, string resourceGroupName, string clusterName, [FromBody] dynamic postBody, [FromQuery(Name = "text")] string text = null, [FromQuery] string l = "") { return await base.ListDetectors(GetResource(subscriptionId, resourceGroupName, clusterName), text, language: l.ToLower()); } [HttpPost(UriElements.Detectors + UriElements.DetectorResource)] public async Task<IActionResult> GetDetector(string subscriptionId, string resourceGroupName, string clusterName, string detectorId, [FromBody] dynamic postBody, string startTime = null, string endTime = null, string timeGrain = null, [FromQuery][ModelBinder(typeof(FormModelBinder))] Form form = null, [FromQuery] string l = "") { return await base.GetDetector(GetResource(subscriptionId, resourceGroupName, clusterName), detectorId, startTime, endTime, timeGrain, form: form, language: l.ToLower()); } [HttpPost(UriElements.DiagnosticReport)] public async Task<IActionResult> DiagnosticReport(string subscriptionId, string resourceGroupName, string clusterName, [FromBody] DiagnosticReportQuery queryBody, string startTime = null, string endTime = null, string timeGrain = null, [FromQuery][ModelBinder(typeof(FormModelBinder))] Form form = null) { var validateBody = InsightsAPIHelpers.ValidateQueryBody(queryBody); if (!validateBody.Status) { return BadRequest($"Invalid post body. {validateBody.Message}"); } if (!DateTimeHelper.PrepareStartEndTimeWithTimeGrain(startTime, endTime, timeGrain, out DateTime startTimeUtc, out DateTime endTimeUtc, out TimeSpan timeGrainTimeSpan, out string errorMessage)) { return BadRequest(errorMessage); } return await base.GetDiagnosticReport(GetResource(subscriptionId, resourceGroupName, clusterName), queryBody, startTimeUtc, endTimeUtc, timeGrainTimeSpan, form: form); } [HttpPost(UriElements.Detectors + UriElements.DetectorResource + UriElements.StatisticsQuery)] public async Task<IActionResult> ExecuteSystemQuery(string subscriptionId, string resourceGroupName, string clusterName, [FromBody]CompilationPostBody<dynamic> jsonBody, string detectorId, string dataSource = null, string timeRange = null) { return await base.ExecuteQuery(GetResource(subscriptionId, resourceGroupName, clusterName), jsonBody, null, null, null, detectorId, dataSource, timeRange); } [HttpPost(UriElements.Detectors + UriElements.DetectorResource + UriElements.Statistics + UriElements.StatisticsResource)] public async Task<IActionResult> GetSystemInvoker(string subscriptionId, string resourceGroupName, string clusterName, string detectorId, string invokerId, string dataSource = null, string timeRange = null) { return await base.GetSystemInvoker(GetResource(subscriptionId, resourceGroupName, clusterName), detectorId, invokerId, dataSource, timeRange); } [HttpPost(UriElements.Insights)] public async Task<IActionResult> GetInsights(string subscriptionId, string resourceGroupName, string clusterName, [FromBody] dynamic postBody, string pesId, string supportTopicId = null, string supportTopic = null, string startTime = null, string endTime = null, string timeGrain = null) { string postBodyString; try { postBodyString = JsonConvert.SerializeObject(postBody.Parameters); } catch (RuntimeBinderException) { postBodyString = ""; } return await base.GetInsights(GetResource(subscriptionId, resourceGroupName, clusterName), pesId, supportTopicId, startTime, endTime, timeGrain, supportTopic, postBodyString); } /// <summary> /// Publish package. /// </summary> /// <param name="pkg">The package.</param> /// <returns>Task for publishing package.</returns> [HttpPost(UriElements.Publish)] public async Task<IActionResult> PublishPackageAsync([FromBody] Package pkg) { return await PublishPackage(pkg); } /// <summary> /// List all gists. /// </summary> /// <returns>Task for listing all gists.</returns> [HttpPost(UriElements.Gists)] public async Task<IActionResult> ListGistsAsync(string subscriptionId, string resourceGroupName, string clusterName, [FromBody] dynamic postBody) { return await base.ListGists(GetResource(subscriptionId, resourceGroupName, clusterName)); } /// <summary> /// List the gist. /// </summary> /// <param name="subscriptionId">Subscription id.</param> /// <param name="resourceGroupName">Resource group name.</param> /// <param name="siteName">Site name.</param> /// <param name="gistId">Gist id.</param> /// <returns>Task for listing the gist.</returns> [HttpPost(UriElements.Gists + UriElements.GistResource)] public async Task<IActionResult> GetGistAsync(string subscriptionId, string resourceGroupName, string clusterName, string gistId, [FromBody] dynamic postBody, string startTime = null, string endTime = null, string timeGrain = null) { return await base.GetGist(GetResource(subscriptionId, resourceGroupName, clusterName), gistId, startTime, endTime, timeGrain); } } }
58.4
337
0.707049
[ "MIT" ]
pappleby64/Azure-AppServices-Diagnostics
src/Diagnostics.RuntimeHost/Controllers/AzureKubernetesService/AzureKubernetesServiceController.cs
7,010
C#
using UIKit; namespace Example { public class Application { // This is the main entry point of the application. static void Main (string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } }
20.6875
82
0.691843
[ "MIT", "Unlicense" ]
sunnypatel1602/PathMenuXamarin
Example/Main.cs
333
C#
using UnityEngine; using System.Linq; using System.Collections; using System.Collections.Generic; using System; using MapzenGo.Helpers; using uAdventure.Runner; namespace uAdventure.Geo { public class NavigationController : MonoBehaviour { public Transform arrow; // ----------------------- // Singleton // ----------------------- protected static NavigationController instance; public static NavigationController Instance { get { return instance ?? (instance = FindObjectOfType<NavigationController>()); } private set { instance = value; } } // ---------------------- // Private variables // --------------------- private bool inited = false; private bool navigating = false; private NavigationStep currentStep; private List<NavigationStep> steps; private Dictionary<string, MonoBehaviour> referenceCache; private Dictionary<NavigationStep, bool> stepCompleted; private Dictionary<NavigationStep, int> completedElementsForStep; private GeoPositionedCharacter character; // ---------------------- // Init // -------------------- void Init() { if (!inited) { referenceCache = new Dictionary<string, MonoBehaviour>(); stepCompleted = new Dictionary<NavigationStep, bool>(); completedElementsForStep = new Dictionary<NavigationStep, int>(); inited = true; } } // --------------------- // Properties // --------------------- public NavigationType NavigationStrategy { get; set; } public List<NavigationStep> Steps { get { return steps; } set { Init(); steps = value; stepCompleted.Clear(); // All the steps are to-do steps.ForEach(s => stepCompleted.Add(s, false)); } } // ------------------------- // Public methods // ------------------------- public void Navigate() { Init(); navigating = true; if (Steps.Count > 0) { currentStep = Steps[0]; } SaveNavigation(Game.Instance.GameState.GetMemory("geo_extension")); } private void SaveNavigation(Memory memory) { memory.Set("navigating", navigating); if (navigating) { memory.Set("navigation_strategy", NavigationStrategy.ToString()); memory.Set("navigation_steps", String.Join(",", Steps.ConvertAll(s => s.Reference).ToArray())); memory.Set("navigation_locks", String.Join(",", Steps.ConvertAll(s => s.LockNavigation.ToString()).ToArray())); memory.Set("navigation_completed", String.Join(",", Steps.ConvertAll(s => stepCompleted.ContainsKey(s) && stepCompleted[s]).ConvertAll(b => b.ToString()).ToArray())); memory.Set("navigation_elems_completed", String.Join(",", Steps.ConvertAll(s => completedElementsForStep.ContainsKey(s) ? completedElementsForStep[s] : 0).ConvertAll(i => i.ToString()).ToArray())); } } public void RestoreNavigation(Memory memory) { if (memory.Get<bool>("navigating")) { stepCompleted.Clear(); completedElementsForStep.Clear(); try { navigating = true; NavigationStrategy = memory.Get<string>("navigation_strategy").ToEnum<NavigationType>(); var locks = memory.Get<string>("navigation_locks").Split(',').ToList().ConvertAll(l => bool.Parse(l)); var completed = memory.Get<string>("navigation_completed").Split(',').ToList().ConvertAll(l => bool.Parse(l)); var elems = memory.Get<string>("navigation_elems_completed").Split(',').ToList().ConvertAll(l => int.Parse(l)); Steps = memory.Get<string>("navigation_steps").Split(',').ToList().ConvertAll(r => new NavigationStep(r)); for (int i = 0; i < steps.Count; i++) { Steps[i].LockNavigation = locks[i]; stepCompleted[Steps[i]] = completed[i]; completedElementsForStep.Add(Steps[i], elems[i]); } } catch { navigating = false; } } } public void FlagsUpdated() { referenceCache.Clear(); this.Update(); } // ----------------------- // MonoBehaviour methods // ------------------------ void Awake() { Instance = this; Init(); } public void Update() { if (navigating) { if (NavigationStrategy == NavigationType.Closeness) { currentStep = FindClosestStep(Steps); } else if (currentStep == null) { currentStep = FindNextStep(Steps); } if (currentStep != null) { // Check if reached bool reached = IsReached(currentStep); UpdateArrow(reached); // Go next if (reached && !currentStep.LockNavigation && CompleteStep(currentStep)) { // If the step is completed successfully we set the current step to null currentStep = null; if (stepCompleted.All(kv => kv.Value)) { // Navigation finished navigating = false; SaveNavigation(Game.Instance.GameState.GetMemory("geo_extension")); DestroyImmediate(this.gameObject); } } } } } // -------------------- // Private methods // ------------------- private NavigationStep FindNextStep(List<NavigationStep> steps) { return steps.Find(s => !stepCompleted[s]); // The first not completed } private bool IsReached(NavigationStep currentStep) { if (!character) { character = FindObjectOfType<GeoPositionedCharacter>(); } var mb = GetReference(currentStep.Reference); if (mb == null) return false; // If the element is not there, just try to skip it else if (mb is GeoPositioner) { var wrap = mb as GeoPositioner; var position = (Vector2d)wrap.Context.TransformManagerParameters["Position"]; var interactionRange = (float) wrap.Context.TransformManagerParameters["InteractionRange"]; var distance = GM.SeparationInMeters(position, character.LatLon); var realDistance = GM.SeparationInMeters(position, GeoExtension.Instance.Location); // Is inside if the character is in range but also the real coords are saying so // Otherwise, if there is no character or gps, only one of the checks is valid return (!character || distance < interactionRange) && (!GeoExtension.Instance.IsStarted() || realDistance < interactionRange) && (GeoExtension.Instance.IsStarted() || character); } else if (mb is GeoElementMB) { var geomb = mb as GeoElementMB; // Is inside if the character is inside the influence but also the real coords are saying so // Otherwise, if there is no character or gps, only one of the checks is valid var location = character ? character.LatLon : GeoExtension.Instance.Location; if (geomb.Geometry.InsideInfluence(location)) { if (geomb.Geometry.Type == GMLGeometry.GeometryType.LineString) { var step = 0; completedElementsForStep.TryGetValue(currentStep, out step); var position = geomb.Geometry.Points[step]; var distance = GM.SeparationInMeters(position, location); return distance < geomb.Geometry.Influence; } else return true; } else return false; } else return false; } /// <summary> /// To complete the step, all the elements inside the step must be completed. /// For all the elements except for paths (LineString geometries) the elements are one, /// so the step is completed in one element completition. /// </summary> /// <param name="currentStep"></param> private bool CompleteStep(NavigationStep currentStep) { bool completed = false; var elems = GetElementsFor(currentStep); if (elems == 1) { completed = true; } else { // If this is the first time we deal with this step, lets say we are in the 0 if (!completedElementsForStep.ContainsKey(currentStep)) { completedElementsForStep.Add(currentStep, 0); } // Add one completedElementsForStep[currentStep]++; // Is completed if it matches in number if(completedElementsForStep[currentStep] == elems) { completed = true; } } // Only complete completed &= !currentStep.LockNavigation; stepCompleted[currentStep] = completed; SaveNavigation(Game.Instance.GameState.GetMemory("geo_extension")); return completed; } private int GetElementsFor(NavigationStep currentStep) { var mb = GetReference(currentStep.Reference); var geoElementMb = mb as GeoElementMB; if(geoElementMb != null && geoElementMb.Geometry.Type == GMLGeometry.GeometryType.LineString) { // If it is a path, all the points are elements return geoElementMb.Geometry.Points.Length; } else { // Just itself is the element return 1; } } private void UpdateArrow(bool reached) { var nan = false; if(currentStep != null && character) { var pos = GetElementPosition(currentStep.Reference); nan = double.IsNaN(pos.x); if (!nan) { var direction = GM.LatLonToMeters(pos) - GM.LatLonToMeters(character.LatLon); arrow.position = character.transform.position; arrow.rotation = Quaternion.Euler(0, Mathf.Atan2((float)direction.normalized.x, (float)direction.normalized.y) * Mathf.Rad2Deg, 0); } } arrow.gameObject.SetActive(!reached && character && !nan); } /// <summary> /// Finds the closest step based on the element position. Only returns not completed steps. /// </summary> /// <param name="steps">All the steps</param> /// <returns>Closest not completed step</returns> private NavigationStep FindClosestStep(List<NavigationStep> steps) { if (!character) { character = FindObjectOfType<GeoPositionedCharacter>(); } var latLon = new Vector2d(double.NegativeInfinity, double.NegativeInfinity); // Minus infinite, as the elements will be positioned at inifine if (character) // If there is a character { latLon = character.LatLon; // use the position of the character to calculate distance } else if (GeoExtension.Instance.IsLocationValid()) // If We have a location source we use it { latLon = Input.location.lastData.LatLonD(); } var notCompleted = steps .FindAll(e => !stepCompleted[e] && !double.IsNaN(GetElementPosition(e.Reference).x)); // Filter the completed if (notCompleted.Count > 0) return notCompleted.FindMin(s => GM.SeparationInMeters(GetElementPosition(s.Reference), latLon)); // Order the rest to distance else return null; } /// <summary> /// Returns any element position (LatLon) by reference, looking for existing instances. /// </summary> /// <param name="reference">Reference id of the element</param> /// <returns>Position in Latitude Longitude Vector2d format</returns> private Vector2d GetElementPosition(string reference) { var mb = GetReference(reference); if (mb == null) return new Vector2d(double.NaN, double.NaN); if(mb is GeoElementMB) { return GetGeoElementPosition((mb as GeoElementMB)); } else if(mb is GeoPositioner) { // Only works with geopositioned elements TODO make it compatible with the rest of types return (Vector2d) (mb as GeoPositioner).Context.TransformManagerParameters["Position"]; } return new Vector2d(double.PositiveInfinity, double.PositiveInfinity); } /// <summary> /// Returns a MonoBehaviour of type GeoElementMB or GeoWrapper that holds the referenced element. /// </summary> /// <param name="reference">Element reference id</param> /// <returns>The monobehaviour in case it exists</returns> private MonoBehaviour GetReference(string reference) { if (!referenceCache.ContainsKey(reference) || referenceCache[reference] == null) { referenceCache.Clear(); FindObjectsOfType<GeoElementMB>().ToList().ForEach(geoElem => referenceCache.Add(geoElem.Reference.getTargetId(), geoElem)); FindObjectsOfType<GeoPositioner>().ToList().ForEach(geoWrap => referenceCache.Add(geoWrap.Context.getTargetId(), geoWrap)); } var mb = referenceCache.ContainsKey(reference) ? referenceCache[reference] : null; return mb; } /// <summary> /// Returns the GeoElement position in the map. /// The point is calculated based on the type of the geometry: /// - Point: Just the point's position /// - LineString: The first point's position /// - Geometry: The closest point to the geometry /// </summary> /// <param name="geoElementMB">Element to return positioning of</param> /// <returns>The position in latitude and longitude Vector2d format</returns> private Vector2d GetGeoElementPosition(GeoElementMB geoElementMB) { var geometry = geoElementMB.Geometry; if (geometry == null) { return Vector2d.zero; } switch (geometry.Type) { case GMLGeometry.GeometryType.LineString: int step; completedElementsForStep.TryGetValue(currentStep, out step); return geometry.Points[step]; default: case GMLGeometry.GeometryType.Polygon: case GMLGeometry.GeometryType.Point: return geometry.Center; } } } public static class ExtensionLocationInfo { public static Vector2 LatLon(this LocationInfo l) { return new Vector2(l.latitude, l.longitude); } public static Vector2d LatLonD(this LocationInfo l) { return new Vector2d(l.latitude, l.longitude); } } public static class ExtensionList { public static T FindMin<T,TResult>(this List<T> l, Func<T,TResult> selector) { var min = l.Min(selector); return l.Find(e => selector(e).Equals(min)); } } }
37.174672
213
0.520968
[ "CC0-1.0" ]
Grupo-M-JuegosSerios/ProyectFinal
ProyectoFinal/Assets/uAdventureGeo/Scripts/Runner/NavigationController.cs
17,028
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Threading; namespace System.Management.Automation.Runspaces { /// <summary> /// PipelineWriter allows the caller to provide an asynchronous stream of objects /// as input to a <see cref="System.Management.Automation.Runspaces.Pipeline"/>. /// </summary> /// <seealso cref="System.Management.Automation.Runspaces.Pipeline.Input"/> public abstract class PipelineWriter { /// <summary> /// Signaled when buffer space is available in the underlying stream. /// </summary> public abstract WaitHandle WaitHandle { get; } /// <summary> /// Check if the stream is open for further writes. /// </summary> /// <value>true if the underlying stream is open, otherwise false</value> /// <remarks> /// Attempting to write to the underlying stream if IsOpen is false throws /// a <see cref="PipelineClosedException"/>. /// </remarks> public abstract bool IsOpen { get; } /// <summary> /// Returns the number of objects currently in the underlying stream. /// </summary> public abstract int Count { get; } /// <summary> /// Get the capacity of the stream. /// </summary> /// <value> /// The capacity of the stream. /// </value> /// <remarks> /// The capacity is the number of objects that stream may contain at one time. Once this /// limit is reached, attempts to write into the stream block until buffer space /// becomes available. /// </remarks> public abstract int MaxCapacity { get; } /// <summary> /// Close the stream. /// </summary> /// <remarks> /// Causes subsequent calls to IsOpen to return false and calls to /// a write operation to throw an ObjectDisposedException. /// All calls to Close() after the first call are silently ignored. /// </remarks> /// <exception cref="ObjectDisposedException"> /// The stream is already disposed /// </exception> public abstract void Close(); /// <summary> /// Flush the buffered data from the stream. Closed streams may be flushed, /// but disposed streams may not. /// </summary> /// <exception cref="ObjectDisposedException"> /// The stream is already disposed /// </exception> public abstract void Flush(); /// <summary> /// Write a single object into the underlying stream. /// </summary> /// <param name="obj">The object to add to the stream.</param> /// <returns> /// One, if the write was successful, otherwise; /// zero if the stream was closed before the object could be written, /// or if the object was AutomationNull.Value. /// </returns> /// <exception cref="PipelineClosedException"> /// The underlying stream is already closed /// </exception> /// <remarks> /// AutomationNull.Value is ignored /// </remarks> public abstract int Write(object obj); /// <summary> /// Write multiple objects to the underlying stream. /// </summary> /// <param name="obj">Object or enumeration to read from.</param> /// <param name="enumerateCollection"> /// If enumerateCollection is true, and <paramref name="obj"/> /// is an enumeration according to LanguagePrimitives.GetEnumerable, /// the objects in the enumeration will be unrolled and /// written separately. Otherwise, <paramref name="obj"/> /// will be written as a single object. /// </param> /// <returns>The number of objects written.</returns> /// <exception cref="PipelineClosedException"> /// The underlying stream is already closed /// </exception> /// <remarks> /// If the enumeration contains elements equal to /// AutomationNull.Value, they are ignored. /// This can cause the return value to be less than the size of /// the collection. /// </remarks> public abstract int Write(object obj, bool enumerateCollection); } internal class DiscardingPipelineWriter : PipelineWriter { private readonly ManualResetEvent _waitHandle = new ManualResetEvent(true); public override WaitHandle WaitHandle { get { return _waitHandle; } } private bool _isOpen = true; public override bool IsOpen { get { return _isOpen; } } private int _count = 0; public override int Count { get { return _count; } } public override int MaxCapacity { get { return int.MaxValue; } } public override void Close() { _isOpen = false; } public override void Flush() { } public override int Write(object obj) { const int numberOfObjectsWritten = 1; _count += numberOfObjectsWritten; return numberOfObjectsWritten; } public override int Write(object obj, bool enumerateCollection) { if (!enumerateCollection) { return this.Write(obj); } int numberOfObjectsWritten = 0; IEnumerable enumerable = LanguagePrimitives.GetEnumerable(obj); if (enumerable != null) { foreach (object o in enumerable) { numberOfObjectsWritten++; } } else { numberOfObjectsWritten++; } _count += numberOfObjectsWritten; return numberOfObjectsWritten; } } }
31.716495
97
0.557939
[ "MIT" ]
10088/PowerShell
src/System.Management.Automation/utils/IObjectWriter.cs
6,153
C#
using System; using System.Collections.Generic; using System.Linq; class ListManipulationAdvanced { static void Main(string[] args) { List<int> numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToList(); bool madeChanges = false; while (true) { string[] input = Console.ReadLine() .Split(); string command = input[0]; if (command == "end") { break; } if (command == "Add") { int number = int.Parse(input[1]); numbers.Add(number); madeChanges = true; } else if (command == "Remove") { int number = int.Parse(input[1]); numbers.Remove(number); madeChanges = true; } else if (command == "RemoveAt") { int index = int.Parse(input[1]); numbers.RemoveAt(index); madeChanges = true; } else if (command == "Insert") { int number = int.Parse(input[1]); int index = int.Parse(input[2]); madeChanges = true; numbers.Insert(index, number); } else if (command == "Contains") { int number = int.Parse(input[1]); Console.WriteLine(numbers.Contains(number) ? "Yes" : "No such number"); } else if (command == "PrintEven") { var evenNumbers = numbers.Where(n => n % 2 == 0); Console.WriteLine(string.Join(' ', evenNumbers)); } else if (command == "PrintOdd") { var evenNumbers = numbers.Where(n => n % 2 == 1); Console.WriteLine(string.Join(' ', evenNumbers)); } else if (command == "GetSum") { Console.WriteLine(numbers.Sum()); } else if (command == "Filter") { PrintFilter(numbers, input); } } if (madeChanges) { Console.WriteLine(string.Join(' ', numbers)); } } public static void PrintFilter(List<int> array, string[] input) { string condition = input[1]; int number = int.Parse(input[2]); if (condition == ">") { var numbers = array.Where(n => n > number); Console.WriteLine(string.Join(' ', numbers)); } else if (condition == ">=") { var numbers = array.Where(n => n >= number); Console.WriteLine(string.Join(' ', numbers)); } else if (condition == "==") { var numbers = array.Where(n => n == number); Console.WriteLine(string.Join(' ', numbers)); } else if (condition == "<=") { var numbers = array.Where(n => n <= number); Console.WriteLine(string.Join(' ', numbers)); } else if (condition == "<") { var numbers = array.Where(n => n < number); Console.WriteLine(string.Join(' ', numbers)); } } }
26.259843
87
0.436882
[ "MIT" ]
Zdravko-Kardzhaliyski/Technology-Fundamentals
5.ListsLab/ListsLab/ListManipulationAdvanced/ListManipulationAdvanced.cs
3,337
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Automation { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// LinkedWorkspaceOperations operations. /// </summary> public partial interface ILinkedWorkspaceOperations { /// <summary> /// Retrieve the linked workspace for the account id. /// <see href="http://aka.ms/azureautomationsdk/linkedworkspaceoperations" /> /// </summary> /// <param name='resourceGroupName'> /// Name of an Azure Resource group. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LinkedWorkspace>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
38.888889
256
0.66
[ "MIT" ]
alexeldeib/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/ILinkedWorkspaceOperations.cs
2,100
C#
namespace Melon.Net.Http.Resolver { /// <summary> /// The name of named clients resolver /// </summary> public interface INameOfNamedClientsResolver { /// <summary> /// Resolve the name of named clients /// </summary> /// <typeparam name="T">the http client type</typeparam> /// <returns>the name of named clients</returns> string Resolve<T>() where T : IHttpClient; } }
27.75
64
0.59009
[ "MIT" ]
jack2gs/NSwagDemo
Melon.Net.Http/Resolver/INameOfNamedClientsResolver.cs
446
C#
using NBitcoin; using NTumbleBit.BouncyCastle.Crypto.Engines; using NTumbleBit.BouncyCastle.Crypto.Parameters; using NTumbleBit.BouncyCastle.Math; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NTumbleBit { public static class Utils { internal static HttpMessageHandler SetAntiFingerprint(this HttpClientHandler handler) { handler.AllowAutoRedirect = false; handler.UseCookies = false; handler.AutomaticDecompression = DecompressionMethods.None; handler.CheckCertificateRevocationList = false; handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ClientCertificates.Clear(); handler.CookieContainer = null; handler.Credentials = null; handler.PreAuthenticate = false; return handler; } public static void Shuffle<T>(T[] arr, Random rand) { rand = rand ?? new Random(); for(int i = 0; i < arr.Length; i++) { var fromIndex = rand.Next(arr.Length); var from = arr[fromIndex]; var toIndex = rand.Next(arr.Length); var to = arr[toIndex]; arr[toIndex] = from; arr[fromIndex] = to; } } public static void Shuffle<T>(List<T> arr, Random rand) { rand = rand ?? new Random(); for(int i = 0; i < arr.Count; i++) { var fromIndex = rand.Next(arr.Count); var from = arr[fromIndex]; var toIndex = rand.Next(arr.Count); var to = arr[toIndex]; arr[toIndex] = from; arr[fromIndex] = to; } } public static void Shuffle<T>(T[] arr, int seed) { Random rand = new Random(seed); Shuffle(arr, rand); } public static void Shuffle<T>(T[] arr) { Shuffle(arr, null); } public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> nodes, Func<T, IEnumerable<T>> dependsOn) { List<T> result = new List<T>(); var elems = nodes.ToDictionary(node => node, node => new HashSet<T>(dependsOn(node))); while(elems.Count > 0) { var elem = elems.FirstOrDefault(x => x.Value.Count == 0); if(elem.Key == null) { //cycle detected can't order return nodes; } elems.Remove(elem.Key); foreach(var selem in elems) { selem.Value.Remove(elem.Key); } result.Add(elem.Key); } return result; } internal static byte[] ChachaEncrypt(byte[] data, ref byte[] key) { byte[] iv = null; return ChachaEncrypt(data, ref key, ref iv); } public static byte[] Combine(params byte[][] arrays) { var len = arrays.Select(a => a.Length).Sum(); int offset = 0; var combined = new byte[len]; foreach(var array in arrays) { Array.Copy(array, 0, combined, offset, array.Length); offset += array.Length; } return combined; } internal static byte[] ChachaEncrypt(byte[] data, ref byte[] key, ref byte[] iv) { ChaChaEngine engine = new ChaChaEngine(); key = key ?? RandomUtils.GetBytes(ChachaKeySize); iv = iv ?? RandomUtils.GetBytes(ChachaKeySize / 2); engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv)); byte[] result = new byte[iv.Length + data.Length]; Array.Copy(iv, result, iv.Length); engine.ProcessBytes(data, 0, data.Length, result, iv.Length); return result; } public const int ChachaKeySize = 128 / 8; internal static byte[] ChachaDecrypt(byte[] encrypted, byte[] key) { ChaChaEngine engine = new ChaChaEngine(); var iv = new byte[ChachaKeySize / 2]; Array.Copy(encrypted, iv, iv.Length); engine.Init(false, new ParametersWithIV(new KeyParameter(key), iv)); byte[] result = new byte[encrypted.Length - iv.Length]; engine.ProcessBytes(encrypted, iv.Length, encrypted.Length - iv.Length, result, 0); return result; } internal static void Pad(ref byte[] bytes, int keySize) { int paddSize = keySize - bytes.Length; if(bytes.Length == keySize) return; if(paddSize < 0) throw new InvalidOperationException("Bug in NTumbleBit, copy the stacktrace and send us"); var padded = new byte[paddSize + bytes.Length]; Array.Copy(bytes, 0, padded, paddSize, bytes.Length); bytes = padded; } internal static BigInteger GenerateEncryptableInteger(RsaKeyParameters key) { while(true) { var bytes = RandomUtils.GetBytes(RsaKey.KeySize / 8); BigInteger input = new BigInteger(1, bytes); if(input.CompareTo(key.Modulus) >= 0) continue; return input; } } // http://stackoverflow.com/a/14933880/2061103 public static void DeleteRecursivelyWithMagicDust(string destinationDir) { const int magicDust = 10; for (var gnomes = 1; gnomes <= magicDust; gnomes++) { try { Directory.Delete(destinationDir, true); } catch (DirectoryNotFoundException) { return; // good! } catch (IOException) { if (gnomes == magicDust) throw; // System.IO.IOException: The directory is not empty System.Diagnostics.Debug.WriteLine("Gnomes prevent deletion of {0}! Applying magic dust, attempt #{1}.", destinationDir, gnomes); // see http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true for more magic Thread.Sleep(100); continue; } catch (UnauthorizedAccessException) { if (gnomes == magicDust) throw; // Wait, maybe another software make us authorized a little later System.Diagnostics.Debug.WriteLine("Gnomes prevent deletion of {0}! Applying magic dust, attempt #{1}.", destinationDir, gnomes); // see http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true for more magic Thread.Sleep(100); continue; } return; } // depending on your use case, consider throwing an exception here } public static IPAddress GetInternetConnectedAddress() { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; IPAddress networkAddress = endPoint.Address; return networkAddress; } } } }
28.555046
134
0.674859
[ "MIT" ]
ArcSin2000X/BreezeProject
NTumbleBit/Utils.cs
6,227
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using PcapDotNet.Packets.Arp; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Gre { /// <summary> /// RFC 1701, RFC 1702, RFC 2637, RFC 2784. /// <pre> /// +-----+---+---+---+---+---+-------+---+-------+---------+-------------------+ /// | Bit | 0 | 1 | 2 | 3 | 4 | 5-7 | 8 | 9-12 | 13-15 | 16-31 | /// +-----+---+-----------+---+-------+---+-------+---------+-------------------+ /// | 0 | C | R | K | S | s | Recur | A | Flags | Version | Protocol Type | /// +-----+---+-----------+---+-------+---+-------+---------+-------------------+ /// | 32 | Checksum (optional) | Offset (optional) | /// +-----+-------------------------------------------------+-------------------+ /// | 32 | Key (optional) | /// +-----+---------------------------------------------------------------------+ /// | 32 | Sequence Number (optional) | /// +-----+---------------------------------------------------------------------+ /// | 32 | Acknowledgment Number (optional) | /// +-----+---------------------------------------------------------------------+ /// | 32 | Routing (optional) | /// +-----+---------------------------------------------------------------------+ /// </pre> /// </summary> public sealed class GreDatagram : EthernetBaseDatagram { private static class Offset { public const int ChecksumPresent = 0; public const int RoutingPresent = 0; public const int KeyPresent = 0; public const int SequenceNumberPresent = 0; public const int StrictSourceRoute = 0; public const int RecursionControl = 0; public const int AcknowledgmentSequenceNumberPresent = 1; public const int FutureUseBits = 1; public const int Version = 1; public const int ProtocolType = 2; public const int Checksum = 4; public const int RoutingOffset = 6; } private static class Mask { public const byte ChecksumPresent = 0x80; public const byte RoutingPresent = 0x40; public const byte KeyPresent = 0x20; public const byte SequenceNumberPresent = 0x10; public const byte StrictSourceRoute = 0x08; public const byte RecursionControl = 0x07; public const byte AcknowledgmentSequenceNumberPresent = 0x80; public const byte FutureUseBits = 0x78; public const byte Version = 0x07; } private static class Shift { public const int FutureUseBits = 3; } /// <summary> /// The minimum number of bytes the GRE header can contain. /// </summary> public const int HeaderMinimumLength = 4; /// <summary> /// The length of the full GRE header on bytes. /// </summary> public override int HeaderLength { get { return GetHeaderLength(ChecksumPresent, KeyPresent, SequenceNumberPresent, AcknowledgmentSequenceNumberPresent, Routing); } } /// <summary> /// Ethernet type (next protocol). /// </summary> public override EthernetType EtherType { get { return ProtocolType; } } /// <summary> /// If the Checksum Present bit is set to 1, then the Checksum field is present and contains valid information. /// If either the Checksum Present bit or the Routing Present bit are set, BOTH the Checksum and Offset fields are present in the GRE packet. /// </summary> public bool ChecksumPresent { get { return (this[Offset.ChecksumPresent] & Mask.ChecksumPresent) == Mask.ChecksumPresent; } } /// <summary> /// If the Routing Present bit is set to 1, then it indicates that the Offset and Routing fields are present and contain valid information. /// If either the Checksum Present bit or the Routing Present bit are set, BOTH the Checksum and Offset fields are present in the GRE packet. /// </summary> public bool RoutingPresent { get { return (this[Offset.RoutingPresent] & Mask.RoutingPresent) == Mask.RoutingPresent; } } /// <summary> /// If the Key Present bit is set to 1, then it indicates that the Key field is present in the GRE header. /// Otherwise, the Key field is not present in the GRE header. /// </summary> public bool KeyPresent { get { return (this[Offset.KeyPresent] & Mask.KeyPresent) == Mask.KeyPresent; } } /// <summary> /// If the Sequence Number Present bit is set to 1, then it indicates that the Sequence Number field is present. /// Otherwise, the Sequence Number field is not present in the GRE header. /// </summary> public bool SequenceNumberPresent { get { return (this[Offset.SequenceNumberPresent] & Mask.SequenceNumberPresent) == Mask.SequenceNumberPresent; } } /// <summary> /// If the source route is incomplete, then the Strict Source Route bit is checked. /// If the source route is a strict source route and the next IP destination or autonomous system is NOT an adjacent system, the packet MUST be dropped. /// </summary> public bool StrictSourceRoute { get { return (this[Offset.StrictSourceRoute] & Mask.StrictSourceRoute) == Mask.StrictSourceRoute; } } /// <summary> /// Recursion control contains a three bit unsigned integer which contains the number of additional encapsulations which are permissible. /// This SHOULD default to zero. /// </summary> public byte RecursionControl { get { return (byte)(this[Offset.RecursionControl] & Mask.RecursionControl); } } /// <summary> /// Set to one (1) if packet contains Acknowledgment Number to be used for acknowledging previously transmitted data. /// </summary> public bool AcknowledgmentSequenceNumberPresent { get { return (this[Offset.AcknowledgmentSequenceNumberPresent] & Mask.AcknowledgmentSequenceNumberPresent) == Mask.AcknowledgmentSequenceNumberPresent; } } /// <summary> /// Must be set to zero (0). /// </summary> public byte FutureUseBits { get { return (byte)((this[Offset.FutureUseBits] & Mask.FutureUseBits) >> Shift.FutureUseBits); } } /// <summary> /// The GRE Version Number. /// </summary> public GreVersion Version { get { return (GreVersion)(this[Offset.Version] & Mask.Version); } } /// <summary> /// The Protocol Type field contains the protocol type of the payload packet. /// These Protocol Types are defined in [RFC1700] as "ETHER TYPES" and in [ETYPES]. /// An implementation receiving a packet containing a Protocol Type which is not listed in [RFC1700] or [ETYPES] SHOULD discard the packet. /// </summary> public EthernetType ProtocolType { get { return (EthernetType)ReadUShort(Offset.ProtocolType, Endianity.Big); } } /// <summary> /// The Checksum field contains the IP (one's complement) checksum sum of the all the 16 bit words in the GRE header and the payload packet. /// For purposes of computing the checksum, the value of the checksum field is zero. /// This field is present only if the Checksum Present bit is set to one. /// </summary> public ushort Checksum { get { return ReadUShort(Offset.Checksum, Endianity.Big); } } /// <summary> /// True iff the checksum value is correct according to the datagram data. /// Valid only if the Checksum Present bit is set to one. /// </summary> public bool IsChecksumCorrect { get { if (_isChecksumCorrect == null) _isChecksumCorrect = (CalculateChecksum() == Checksum); return _isChecksumCorrect.Value; } } /// <summary> /// The offset field indicates the octet offset from the start of the Routing field to the first octet of the active Source Route Entry to be examined. /// This field is present if the Routing Present or the Checksum Present bit is set to 1, and contains valid information only if the Routing Present bit is set to 1. /// </summary> public ushort RoutingOffset { get { return ReadUShort(Offset.RoutingOffset, Endianity.Big); } } /// <summary> /// The index in the Routing collection of the active source route entry. /// </summary> public int? ActiveSourceRouteEntryIndex { get { TryParseRouting(); return _activeSourceRouteEntryIndex; } } /// <summary> /// The active Source Route Entry to be examined. /// Contains valid information only if the Routing Present bit is set to 1. /// if the offset points to the end of the routing information, returns null. /// </summary> public GreSourceRouteEntry ActiveSourceRouteEntry { get { int? activeSourceRouteEntryIndex = ActiveSourceRouteEntryIndex; if (activeSourceRouteEntryIndex == null || activeSourceRouteEntryIndex.Value == Routing.Count) return null; return Routing[activeSourceRouteEntryIndex.Value]; } } /// <summary> /// The Key field contains a four octet number which was inserted by the encapsulator. /// It may be used by the receiver to authenticate the source of the packet. /// The Key field is only present if the Key Present field is set to 1. /// </summary> public uint Key { get { return ReadUInt(OffsetKey, Endianity.Big); } } /// <summary> /// (High 2 octets of Key) Size of the payload, not including the GRE header /// </summary> public ushort KeyPayloadLength { get { return ReadUShort(OffsetKeyPayloadLength, Endianity.Big); } } /// <summary> /// (Low 2 octets of Key) Contains the Peer's Call ID for the session to which this packet belongs. /// </summary> public ushort KeyCallId { get { return ReadUShort(OffsetKeyCallId, Endianity.Big); } } /// <summary> /// The Sequence Number field contains an unsigned 32 bit integer which is inserted by the encapsulator. /// It may be used by the receiver to establish the order in which packets have been transmitted from the encapsulator to the receiver. /// </summary> public uint SequenceNumber { get { return ReadUInt(OffsetSequenceNumber, Endianity.Big); } } /// <summary> /// Contains the sequence number of the highest numbered GRE packet received by the sending peer for this user session. /// Present if A bit (Bit 8) is one (1). /// </summary> public uint AcknowledgmentSequenceNumber { get { return ReadUInt(OffsetAcknowledgmentSequenceNumber, Endianity.Big); } } /// <summary> /// The Routing field is optional and is present only if the Routing Present bit is set to 1. /// The Routing field is a list of Source Route Entries (SREs). /// Each SRE has the form: /// <pre> /// +-----+----------------+------------+------------+ /// | Bit | 0-15 | 16-23 | 24-31 | /// +-----+----------------+------------+------------+ /// | 0 | Address Family | SRE Offset | SRE Length | /// +-----+----------------+------------+------------+ /// | 32 | Routing Information ... | /// +-----+------------------------------------------+ /// </pre> /// The routing field is terminated with a "NULL" SRE containing an address family of type 0x0000 and a length of 0. /// </summary> public ReadOnlyCollection<GreSourceRouteEntry> Routing { get { TryParseRouting(); return _routing; } } /// <summary> /// Creates a Layer that represents the datagram to be used with PacketBuilder. /// </summary> public override ILayer ExtractLayer() { return new GreLayer { Version = Version, ProtocolType = ProtocolType, RecursionControl = RecursionControl, FutureUseBits = FutureUseBits, ChecksumPresent = ChecksumPresent, Checksum = ChecksumPresent ? (ushort?)Checksum : null, Key = KeyPresent ? (uint?)Key : null, SequenceNumber = SequenceNumberPresent ? (uint?)SequenceNumber : null, AcknowledgmentSequenceNumber = AcknowledgmentSequenceNumberPresent ? (uint?)AcknowledgmentSequenceNumber : null, Routing = RoutingPresent ? Routing : null, RoutingOffset = RoutingPresent ? (ushort?)RoutingOffset : null, StrictSourceRoute = StrictSourceRoute, }; } /// <summary> /// A GRE Datagram is valid if its length is enough for the GRE header, its routing information is valid, /// the bits for future use are set to 0, it has acknowledgment sequence number only if it's Enhanced GRE, /// if it has checksum the checksum is correct and its payload is correct. /// </summary> /// <returns>true iff the datagram is valid.</returns> protected override bool CalculateIsValid() { if (Length < HeaderMinimumLength || Length < HeaderLength) return false; Datagram payloadByProtocolType = PayloadByEtherType; return (IsValidRouting && FutureUseBits == 0 && (Version == GreVersion.EnhancedGre || Version == GreVersion.Gre && !AcknowledgmentSequenceNumberPresent) && (!ChecksumPresent || IsChecksumCorrect) && (payloadByProtocolType == null || payloadByProtocolType.IsValid)); } internal GreDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } internal static int GetHeaderLength(bool isChecksumPresent, bool isKeyPresent, bool isSequenceNumberPresent, bool isAcknowledgmentSequenceNumberPresent, IEnumerable<GreSourceRouteEntry> routing) { return HeaderMinimumLength + (isChecksumPresent || routing != null ? sizeof(ushort) + sizeof(ushort) : 0) + (isKeyPresent ? sizeof(uint) : 0) + (isSequenceNumberPresent ? sizeof(uint) : 0) + (isAcknowledgmentSequenceNumberPresent ? sizeof(uint) : 0) + (routing != null ? routing.Sum(entry => entry.Length) + GreSourceRouteEntry.HeaderLength : 0); } internal static void WriteHeader(byte[] buffer, int offset, byte recursionControl, byte flags, GreVersion version, EthernetType protocolType, bool checksumPresent, uint? key, uint? sequenceNumber, uint? acknowledgmentSequenceNumber, ReadOnlyCollection<GreSourceRouteEntry> routing, ushort? routingOffset, bool strictSourceRoute) { buffer.Write(offset + Offset.ChecksumPresent, (byte)((checksumPresent ? Mask.ChecksumPresent : 0) | (routing != null ? Mask.RoutingPresent : 0) | (key != null ? Mask.KeyPresent : 0) | (sequenceNumber != null ? Mask.SequenceNumberPresent : 0) | (strictSourceRoute ? Mask.StrictSourceRoute : 0) | (recursionControl & Mask.RecursionControl))); buffer.Write(offset + Offset.FutureUseBits, (byte)((acknowledgmentSequenceNumber != null ? Mask.AcknowledgmentSequenceNumberPresent : 0) | ((flags << Shift.FutureUseBits) & Mask.FutureUseBits) | ((byte)version & Mask.Version))); buffer.Write(offset + Offset.ProtocolType, (ushort)protocolType, Endianity.Big); offset += Offset.Checksum; if (checksumPresent || routing != null) { offset += sizeof(ushort); if (routingOffset != null) buffer.Write(offset, routingOffset.Value, Endianity.Big); offset += sizeof(ushort); } if (key != null) buffer.Write(ref offset, key.Value, Endianity.Big); if (sequenceNumber != null) buffer.Write(ref offset, sequenceNumber.Value, Endianity.Big); if (acknowledgmentSequenceNumber != null) buffer.Write(ref offset, acknowledgmentSequenceNumber.Value, Endianity.Big); if (routing != null) { foreach (GreSourceRouteEntry entry in routing) entry.Write(buffer, ref offset); buffer.Write(ref offset, (uint)0, Endianity.Big); } } internal static void WriteChecksum(byte[] buffer, int offset, int length, ushort? checksum) { ushort checksumValue = checksum == null ? CalculateChecksum(buffer, offset, length) : checksum.Value; buffer.Write(offset + Offset.Checksum, checksumValue, Endianity.Big); } private int OffsetKey { get { return HeaderMinimumLength + ((ChecksumPresent || RoutingPresent) ? sizeof(ushort) + sizeof(ushort) : 0); } } private int OffsetKeyPayloadLength { get { return OffsetKey; } } private int OffsetKeyCallId { get { return OffsetKey + sizeof(ushort); } } private int OffsetSequenceNumber { get { return OffsetKey + (KeyPresent ? sizeof(uint) : 0); } } private int OffsetAcknowledgmentSequenceNumber { get { return OffsetSequenceNumber + (SequenceNumberPresent ? sizeof(uint) : 0); } } private int OffsetRouting { get { return OffsetAcknowledgmentSequenceNumber + (AcknowledgmentSequenceNumberPresent ? sizeof(uint) : 0); } } private void TryParseRouting() { if (_routing != null || !RoutingPresent) return; List<GreSourceRouteEntry> entries = new List<GreSourceRouteEntry>(); int routingStartOffset = StartOffset + OffsetRouting; int entryOffset = routingStartOffset; int totalLength = StartOffset + Length; while (totalLength >= entryOffset) { GreSourceRouteEntry entry; if (entryOffset == routingStartOffset + RoutingOffset) _activeSourceRouteEntryIndex = entries.Count; if (!GreSourceRouteEntry.TryReadEntry(Buffer, ref entryOffset, totalLength - entryOffset, out entry)) { _isValidRouting = false; break; } if (entry == null) break; entries.Add(entry); } _routing = new ReadOnlyCollection<GreSourceRouteEntry>(entries); } private ushort CalculateChecksum() { return CalculateChecksum(Buffer, StartOffset, Length); } private static ushort CalculateChecksum(byte[] buffer, int offset, int length) { uint sum = Sum16Bits(buffer, offset, Math.Min(Offset.Checksum, length)) + Sum16Bits(buffer, offset + Offset.Checksum + sizeof(ushort), length - Offset.Checksum - sizeof(ushort)); return Sum16BitsToChecksum(sum); } private bool IsValidRouting { get { TryParseRouting(); return _isValidRouting; } } private ReadOnlyCollection<GreSourceRouteEntry> _routing; private bool _isValidRouting = true; private bool? _isChecksumCorrect; private int? _activeSourceRouteEntryIndex; } }
42.679208
202
0.545632
[ "BSD-3-Clause" ]
okaywang/MyPcap
PcapDotNet/src/PcapDotNet.Packets/Gre/GreDatagram.cs
21,553
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("hamstr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("hamstr")] [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("d5d2a73f-e426-4fcb-8768-d24f4bf64c15")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.432432
84
0.74296
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
JustMeGaaRa/Silent.Algorithms
hamstr/Properties/AssemblyInfo.cs
1,388
C#