content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace InsaneOne.EcsRts { struct AddPlayerResourcesEvent { public int Value; } }
14.857143
34
0.644231
[ "MIT" ]
InsaneOneHub/ecs-based-rts
Assets/Sources/Components/Events/AddPlayerResourcesEvent.cs
104
C#
using System.Threading.Tasks; using FluentAssertions.Specialized; namespace FluentAssertions; public static class AsyncAssertionsExtensions { #pragma warning disable AV1755 // "Name of async method ... should end with Async"; Async suffix is too noisy in fluent API /// <summary> /// Asserts that the completed <see cref="Task{TResult}"/> provides the specified result. /// </summary> /// <param name="task">The <see cref="GenericAsyncFunctionAssertions{T}"/> containing the <see cref="Task{TResult}"/>.</param> /// <param name="expected">The expected value.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because"/>. /// </param> public static async Task<AndWhichConstraint<GenericAsyncFunctionAssertions<T>, T>> WithResult<T>( this Task<AndWhichConstraint<GenericAsyncFunctionAssertions<T>, T>> task, T expected, string because = "", params object[] becauseArgs) { var andWhichConstraint = await task; var subject = andWhichConstraint.Subject; subject.Should().Be(expected, because, becauseArgs); return andWhichConstraint; } /// <summary> /// Asserts that the completed <see cref="TaskCompletionSource{TResult}"/> provides the specified result. /// </summary> /// <param name="task">The <see cref="TaskCompletionSourceAssertions{T}"/> containing the <see cref="TaskCompletionSource{TResult}"/>.</param> /// <param name="expected">The expected value.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because"/>. /// </param> public static async Task<AndWhichConstraint<TaskCompletionSourceAssertions<T>, T>> WithResult<T>( this Task<AndWhichConstraint<TaskCompletionSourceAssertions<T>, T>> task, T expected, string because = "", params object[] becauseArgs) { var andWhichConstraint = await task; var subject = andWhichConstraint.Subject; subject.Should().Be(expected, because, becauseArgs); return andWhichConstraint; } }
49.218182
146
0.685999
[ "Apache-2.0" ]
IT-VBFK/fluentassertions
Src/FluentAssertions/AsyncAssertionsExtensions.cs
2,707
C#
namespace DIYTracker.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Materials", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Price = c.Double(nullable: false), SingleUnits = c.String(), PluralUnits = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ProjectMaterials", c => new { Id = c.Int(nullable: false, identity: true), Quantity = c.Int(nullable: false), Project_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Projects", t => t.Project_Id) .Index(t => t.Project_Id); CreateTable( "dbo.Projects", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), User_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.User_Id) .Index(t => t.User_Id); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), FirstName = c.String(), LastName = c.String(), UserType = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ProjectTools", c => new { Id = c.Int(nullable: false, identity: true), Project_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Projects", t => t.Project_Id) .Index(t => t.Project_Id); CreateTable( "dbo.Steps", c => new { Id = c.Int(nullable: false, identity: true), Order = c.Int(nullable: false), Description = c.String(), DurationInMinutes = c.String(), Project_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Projects", t => t.Project_Id) .Index(t => t.Project_Id); CreateTable( "dbo.Todoes", c => new { ID = c.Int(nullable: false, identity: true), Description = c.String(), CreatedDate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Tools", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Price = c.Double(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.Steps", "Project_Id", "dbo.Projects"); DropForeignKey("dbo.ProjectTools", "Project_Id", "dbo.Projects"); DropForeignKey("dbo.ProjectMaterials", "Project_Id", "dbo.Projects"); DropForeignKey("dbo.Projects", "User_Id", "dbo.Users"); DropIndex("dbo.Steps", new[] { "Project_Id" }); DropIndex("dbo.ProjectTools", new[] { "Project_Id" }); DropIndex("dbo.Projects", new[] { "User_Id" }); DropIndex("dbo.ProjectMaterials", new[] { "Project_Id" }); DropTable("dbo.Tools"); DropTable("dbo.Todoes"); DropTable("dbo.Steps"); DropTable("dbo.ProjectTools"); DropTable("dbo.Users"); DropTable("dbo.Projects"); DropTable("dbo.ProjectMaterials"); DropTable("dbo.Materials"); } } }
36.6
81
0.385792
[ "MIT" ]
TacoMantra/DIYTracker
DIYTracker/Migrations/202011230130194_Initial.cs
4,577
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Ec2.Outputs { [OutputType] public sealed class ManagedPrefixListEntry { /// <summary> /// CIDR block of this entry. /// </summary> public readonly string Cidr; /// <summary> /// Description of this entry. Due to API limitations, updating only the description of an existing entry requires temporarily removing and re-adding the entry. /// </summary> public readonly string? Description; [OutputConstructor] private ManagedPrefixListEntry( string cidr, string? description) { Cidr = cidr; Description = description; } } }
28.333333
168
0.637255
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Ec2/Outputs/ManagedPrefixListEntry.cs
1,020
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Enjin.SDK.GraphQL; using Enjin.SDK.Utility; using SimpleJSON; using UnityEngine; namespace Enjin.SDK.Core { public class EnjinIdentities { /// <summary> /// Gets a specific identity /// </summary> /// <param name="id">ID of identity to get</param> /// <returns>Identity associated with passed id</returns> public Identity Get(int id, int levels = 1) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["GetIdentity"], id.ToString())); if (Enjin.ServerResponse != ResponseCodes.SUCCESS) return null; return JsonUtility .FromJson<JSONArrayHelper<Identity>>(EnjinHelpers.GetJSONString( Regex.Replace(GraphQuery.queryReturn, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1"), levels)).result[0]; } /// <summary> /// Creates a new identity /// </summary> /// <param name="newIdentity">New Identity to create</param> /// <returns>Created Identity</returns> public Identity Create(Identity newIdentity, int levels = 1) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["CreateIdentity"], newIdentity.user.id.ToString(), newIdentity.wallet.ethAddress)); if (Enjin.ServerResponse != ResponseCodes.SUCCESS) return null; return JsonUtility.FromJson<Identity>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, levels)); } /// <summary> /// Updates an Identty /// </summary> /// <param name="identity">Identity to update</param> /// <returns>Updated Identity</returns> public Identity Update(Identity identity, int levels = 2) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["UpdateIdentity"], identity.id.ToString(), identity.user.id.ToString(), identity.wallet.ethAddress)); if (Enjin.ServerResponse != ResponseCodes.SUCCESS) return null; return JsonUtility.FromJson<Identity>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, levels)); } /// <summary> /// Deletes an identity. if user attached to it, it's deleted as well /// </summary> /// <param name="id">Identitiy ID to delete</param> /// <returns>true/false on success</returns> public bool Delete(string id) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["DeleteIdentity"], id.ToString())); if (Enjin.ServerResponse != ResponseCodes.SUCCESS) return false; return true; } /// <summary> /// Unlinks identity from wallet /// </summary> /// <param name="id">ID of identity to unlink</param> /// <returns>Updated identity</returns> public bool UnLink(int id) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["UnlinkIdentity"], id.ToString())); if (Enjin.ServerResponse != ResponseCodes.SUCCESS) return false; return true; } public Wallet GetWalletBalances(string ethAddress, int levels = 2) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["GetWalletBalances"], ethAddress)); return JsonUtility.FromJson<Wallet>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, levels)); } public Wallet GetWalletBalancesForApp(string ethAddress, int appId, int levels = 2) { GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["GetWalletBalancesForApp"], ethAddress, appId.ToString())); return JsonUtility.FromJson<Wallet>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, levels)); } } }
38.12381
133
0.610292
[ "MIT" ]
Drake-s-Games-LLC/Enjin-Unity-sample
Enjin Test Project/Assets/Enjin/SDK/Core/EnjinIdentities.cs
4,005
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class song_select_button : MonoBehaviour { public track Track; public Text title; public Text artist; public Text duration; public Text bpm; public Image album_cover; public Image selected_cursor; [HideInInspector] public song_select_panel song_Select_Panel; [HideInInspector] public Button button; // Init private void Awake() { button = GetComponent<Button>(); } // Strings and album cover setup void Start() { title.text = Track.title; artist.text = Track.artist; duration.text = get_duration_string(Track.song.length); bpm.text = get_bpm_string(Track.bpm); album_cover.sprite = Track.album_cover; } // Returns the string to display the song duration private string get_duration_string(float length) { string minutes = Mathf.FloorToInt(length / 60f).ToString(); string seconds = Mathf.FloorToInt(length % 60f).ToString(); if (seconds.Length < 2) { seconds = "0" + seconds; } return "Duration - " + minutes + ":" + seconds; } // Returns the string to display the bpm private string get_bpm_string(float bpm) { return "BPM - " + Mathf.FloorToInt(bpm).ToString(); } // Called when the player selects this song public void on_select() { song_Select_Panel.on_song_select(this); } }
22.983051
61
0.728614
[ "MIT" ]
Dmcdominic/Beatsketball
Beatsketball/Assets/Scripts/Song Selection/song_select_button.cs
1,358
C#
namespace CommonTools.Lib11.GoogleTools { public class FirebaseCredentials { public string BaseURL { get; set; } public string ApiKey { get; set; } public string Email { get; set; } public string Password { get; set; } public string HumanName { get; set; } public string Roles { get; set; } public string NameAndRole => $"“{HumanName}” ({Roles})"; } }
28.5
65
0.550439
[ "MIT" ]
peterson1/PermissionSetter
CommonTools.Lib11/GoogleTools/FirebaseCredentials.cs
462
C#
using System.Collections; using System.Collections.Generic; using NaughtyAttributes; using UnityEngine; using UnityEngine.Events; public class InputManager : MonoBehaviour { private static InputManager control; public bool isRebinding; public KeyCode cancelRebindKey = KeyCode.Escape; [SerializeField] private Keybinds keyBinds; [SerializeField] [ValidateInput("SetSingleton")] private List<InputEvent> events = new List<InputEvent>(); private Dictionary<string, InputAction> lookup; private int numKeyCodes; private void Awake() { control = this; numKeyCodes = System.Enum.GetNames(typeof(KeyCode)).Length; LoadKeyBinds(); BuildLookup(); } private bool SetSingleton() { if (control == this) return true; control = this; return true; } private void Update() { foreach (InputEvent e in events) { switch (e.type) { case InputEventType.OnKeyDown: if (GetKeyDown(e.name, e.negative)) e.callback.Invoke(); break; case InputEventType.OnKey: if (GetKey(e.name, e.negative)) e.callback.Invoke(); break; case InputEventType.OnKeyUp: if (GetKeyUp(e.name, e.negative)) e.callback.Invoke(); break; case InputEventType.OnAxisDown: if (GetAxisDown(e.name)) e.callback.Invoke(); break; case InputEventType.OnAxisUp: if (GetAxisUp(e.name)) e.callback.Invoke(); break; } } } private string[] GetInputNames() { string[] names = new string[keyBinds.actions.Length]; for (int i = 0; i < names.Length; i++) names[i] = keyBinds.actions[i].name; return names; } public bool AddListener(string name, bool negative, InputEventType type, UnityAction callback) { if (lookup == null) BuildLookup(); if (lookup.ContainsKey(name)) { events.Add(new InputEvent(name, negative, type, callback)); return true; } else return false; } /// <summary> /// Has the key been pressed this frame? /// </summary> /// <param name="name">The name of the input.</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static bool GetKeyDown(string name, bool negative = false) { control.CheckNameValid(name); InputAction action = control.lookup[name]; return Input.GetKeyDown(negative?action.modifiedNegative1 : action.modifiedPositive1) || Input.GetKeyDown(negative?action.modifiedNegative2 : action.modifiedPositive2); } /// <summary> /// Is the key being pressed right now? /// </summary> /// <param name="name">The name of the input.</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static bool GetKey(string name, bool negative = false) { control.CheckNameValid(name); InputAction action = control.lookup[name]; return Input.GetKey(negative?action.modifiedNegative1 : action.modifiedPositive1) || Input.GetKey(negative?action.modifiedNegative2 : action.modifiedPositive2); } /// <summary> /// Has the key been released this frame? /// </summary> /// <param name="name">The name of the input.</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static bool GetKeyUp(string name, bool negative = false) { control.CheckNameValid(name); InputAction action = control.lookup[name]; return Input.GetKeyUp(negative?action.modifiedNegative1 : action.modifiedPositive1) || Input.GetKeyUp(negative?action.modifiedNegative1 : action.modifiedPositive1); } /// <summary> /// Get the keycode of the input. /// </summary> /// <param name="name">The name of the input.</param> /// <param name="primary">Should query the primary bindings?</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static KeyCode GetBinding(string name, bool primary = true, bool negative = false) { if (primary) return negative ? control.lookup[name].modifiedNegative1 : control.lookup[name].modifiedPositive1; else return negative ? control.lookup[name].modifiedNegative2 : control.lookup[name].modifiedPositive2; } /// <summary> /// Returns -1 if the negative key is pressed, 1 if the positive key is pressed, and 0 if both or neither. /// </summary> /// <param name="name">The name of the input.</param> public static int GetAxis(string name) => (GetKey(name) ? 1 : 0) + (GetKey(name, true) ? -1 : 0); /// <summary> /// Has either of the keys on the axis been pressed this frame? /// </summary> /// <param name="name">The name of the input.</param> public static bool GetAxisDown(string name) => GetKeyDown(name) || GetKeyDown(name, true); /// <summary> /// Has either of the keys on the axis been released this frame? /// </summary> /// <param name="name">The name of the input.</param> public static bool GetAxisUp(string name) => GetKeyUp(name) || GetKeyUp(name, true); /// <summary> /// Sets the bindings of all keys back to their defaults. /// </summary> public static void ResetAllBindings() { for (int i = 0; i < control.keyBinds.actions.Length; i++) control.keyBinds.actions[i].ResetBindings(); SaveKeyBinds(); } /// <summary> /// Resets a single input binding. /// </summary> /// <param name="name">The name of the input.</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static void ResetBinding(string name, bool negative = false) { control.CheckNameValid(name); control.lookup[name].ResetBinding(negative); SaveKeyBinds(); } private void CheckNameValid(string name) { if (!lookup.ContainsKey(name)) throw new System.Exception($"hmm fuck, dont seem to have any binding w the name {name}???"); } // to b used w SaveSystem.cs on github: // https://github.com/celechii/Unity-Tools/blob/7d1182ea0f34b9b517bdbd67f88cb275316f1c2e/SaveSystem.cs // <3 /// <summary> /// Uses the save system to save the keybind JSON to /Resources/Saves/Keybinds.txt /// </summary> public static void SaveKeyBinds() { SaveSystem.SaveTxt("Keybinds", control.keyBinds); } /// <summary> /// Uses the save system to load the keybind JSON from /Resources/Saves/Keybinds.txt /// If nothing is found, it will load the defaults instead. /// </summary> public void LoadKeyBinds() { if (SaveSystem.SaveExists("Keybinds.txt")) keyBinds = SaveSystem.LoadTxt<Keybinds>("Keybinds"); else ResetAllBindings(); BuildLookup(); } private void BuildLookup() { if (lookup == null) lookup = new Dictionary<string, InputAction>(); else lookup.Clear(); for (int i = 0; i < keyBinds.actions.Length; i++) lookup.Add(keyBinds.actions[i].name, keyBinds.actions[i]); } /// <summary> /// Start the rebind process for a single input. /// </summary> /// <param name="name">The name of the input.</param> /// <param name="callback">Method to call when the rebinding is complete.</param> /// <param name="negative">Should access the negative value? Default is positive.</param> public static void RebindKey(string name, System.Action callback = null, bool negative = false) { control.CheckNameValid(name); Debug.Log(control); control.StartCoroutine(control.RebindInput(name, callback, negative)); } private IEnumerator RebindInput(string name, System.Action callback = null, bool negative = false) { isRebinding = true; yield return null; while (isRebinding) { if (Input.GetKeyDown(cancelRebindKey)) { isRebinding = false; break; } if (Input.anyKeyDown) { for (int i = 0; i < numKeyCodes; i++) { if (Input.GetKeyDown((KeyCode)i)) { lookup[name].SetKey((KeyCode)i, negative); isRebinding = false; } } } yield return null; } SaveKeyBinds(); callback?.Invoke(); } public static string GetKeyCodeNiceName(KeyCode key) { switch (key) { case KeyCode.Mouse0: return "Left Mouse Button"; case KeyCode.Mouse1: return "Right Mouse Button"; case KeyCode.Mouse2: return "Middle Mouse Button"; case KeyCode.Mouse3: case KeyCode.Mouse4: case KeyCode.Mouse5: case KeyCode.Mouse6: return "Mouse Button " + ((KeyCode)(int)key - 323); case KeyCode.Alpha0: case KeyCode.Alpha1: case KeyCode.Alpha2: case KeyCode.Alpha3: case KeyCode.Alpha4: case KeyCode.Alpha5: case KeyCode.Alpha6: case KeyCode.Alpha7: case KeyCode.Alpha8: case KeyCode.Alpha9: return ((int)key - 48).ToString(); case KeyCode.Keypad0: case KeyCode.Keypad1: case KeyCode.Keypad2: case KeyCode.Keypad3: case KeyCode.Keypad4: case KeyCode.Keypad5: case KeyCode.Keypad6: case KeyCode.Keypad7: case KeyCode.Keypad8: case KeyCode.Keypad9: return "NUM " + ((KeyCode)(int)key - 256); default: return MakeKeyReadable(key); } } public static string MakeKeyReadable(KeyCode key) { string entry = key.ToString(); for (int i = 1; i < entry.Length; i++) { if (entry[i] >= 'A' && entry[i] <= 'Z') { entry = entry.Insert(i, " "); i++; } } return entry; } [System.Serializable] private struct Keybinds { public InputAction[] actions; } [System.Serializable] public class InputAction { public string name; public KeyCode positive1; public KeyCode negative1; [Space] public KeyCode positive2; public KeyCode negative2; [HideInInspector] public KeyCode modifiedPositive1; [HideInInspector] public KeyCode modifiedNegative1; [HideInInspector] public KeyCode modifiedPositive2; [HideInInspector] public KeyCode modifiedNegative2; public void SetKey(KeyCode key, bool primary = true, bool negative = false) { if (primary) { if (negative) modifiedNegative1 = key; else modifiedPositive1 = key; } else { if (negative) modifiedNegative2 = key; else modifiedPositive2 = key; } } public void ResetBindings() { modifiedPositive1 = positive1; modifiedNegative1 = negative1; modifiedPositive2 = positive2; modifiedNegative2 = negative2; } public void ResetBinding(bool primary = true, bool negative = false) { if (primary) { if (negative) modifiedNegative1 = this.negative1; else modifiedPositive1 = positive1; } else { if (negative) modifiedNegative2 = this.negative2; else modifiedPositive2 = positive2; } } } [System.Serializable] private class InputEvent { [Dropdown("GetInputNames")] public string name; [AllowNesting] [HideIf("hideNegative")] public bool negative; public InputEventType type; [Space] public UnityEvent callback; private bool hideNegative => type == InputEventType.OnAxisDown || type == InputEventType.OnAxisUp; public InputEvent(string name, bool negative, InputEventType type, UnityAction callback) { this.name = name; this.negative = negative; this.type = type; this.callback = new UnityEvent(); this.callback.AddListener(callback); } private string[] GetInputNames() => InputManager.control.GetInputNames(); } public enum InputEventType { OnKeyDown, OnKey, OnKeyUp, OnAxisDown, OnAxisUp } }
28.694301
107
0.693572
[ "BSD-3-Clause" ]
celechii/Unity-Tools
InputManager.cs
11,078
C#
using UnityEngine; using UnityEditor; namespace UniBt.Editor.Inspector { [CustomEditor(typeof(Wait))] public sealed class WaitInspector : TaskInspector { private Wait wait; public override void OnEnable() { base.OnEnable(); wait = task as Wait; } public override void OnInspectorGUI() { string name = wait.Name; BehaviorTreeEditorUtility.BeginInspectorGUI(ref name); if (name != wait.Name) { wait.Name = name; AssetDatabase.SaveAssets(); } GUILayout.Space(7f); if (BehaviorTreeEditorUtility.DrawHeader("Wait Time", false)) { DrawTick(); } BehaviorTreeEditorUtility.EndInspectorGUI(node); } private void DrawTick() { GUILayout.BeginHorizontal(); GUILayout.Space(7f); float tick = EditorGUILayout.FloatField("Tick", wait.tick); if (tick != wait.tick) { if (tick <= 0) tick = 0.1f; wait.tick = tick; UpdateComment(); AssetDatabase.SaveAssets(); } GUILayout.EndHorizontal(); } private void UpdateComment() { string comment = ""; comment += "Wait: "; comment += wait.tick + "s"; wait.comment = comment; } } }
26.067797
73
0.483745
[ "MIT" ]
gitter-badger/UniBt
Assets/UniBt/Scripts/Editor/InspectorDrawers/Built-In Nodes/WaitInspector.cs
1,540
C#
using System.Collections.Generic; using System.Threading.Tasks; using WRLDCWarehouse.Data; using WRLDCWarehouse.Core.Entities; using WRLDCWarehouse.ETL.Extracts; using WRLDCWarehouse.ETL.Loads; using WRLDCWarehouse.ETL.Enums; using WRLDCWarehouse.Core.ForiegnEntities; using Microsoft.Extensions.Logging; namespace WRLDCWarehouse.ETL.Jobs { public class JobReadForeignAcTransLines { public async Task ImportForeignAcTransLines(WRLDCWarehouseDbContext _context, ILogger _log, string oracleConnStr, EntityWriteOption opt) { AcTransLineExtract acTransLineExtract = new AcTransLineExtract(); List<AcTransmissionLineForeign> acTransLinesForeign = acTransLineExtract.ExtractAcTransLineForeign(oracleConnStr); LoadAcTransmissionLine loadAcTransLine = new LoadAcTransmissionLine(); foreach (AcTransmissionLineForeign acTransLineForeign in acTransLinesForeign) { AcTransmissionLine insertedAcTransLine = await loadAcTransLine.LoadSingleAsync(_context, _log, acTransLineForeign, opt); } } } }
39.642857
144
0.763964
[ "MIT" ]
POSOCO/wrldc_data_warehouse_csharp
WRLDCWarehouse.ETL/Jobs/JobReadForeignAcTransLines.cs
1,112
C#
using System.Collections.Generic; using Repository.Models.Issue; namespace Repository.Issue { public interface IIssueRepository { int Create(int projectId, string title, string description, int priorityId, int? assigneeId, int createdBy); List<IssueSummaryModel> GetByFilters(int userId, int status); SingleIssueModel Get(int issueId); void UpdateTitleDescription(int issueId, string title, string description, int updatedBy); void UpdateStatus(int issueId, int status, int userId); List<TimelineModel> GetTimeline(int id); void UpdateAssignee(int issueId, int? assigneeId, int userId); void UpdatePriority(int issueId, int priorityId, int userId); void NewComment(int issueId, string comment, int userId); } }
44.222222
116
0.723618
[ "MIT" ]
yrshaikh/Issue-Tracker
Src/Repository/Issue/IIssueRepository.cs
798
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ namespace iTin.Core.Localization.Exceptions { using System; /// <summary> /// Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class InvalidPeriodException { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal InvalidPeriodException() { } /// <summary> /// Devuelve la instancia de ResourceManager almacenada en caché utilizada por esta clase. /// </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("iTin.Core.Localization.Exceptions.InvalidPeriodException", typeof(InvalidPeriodException).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Reemplaza la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos mediante esta clase de recurso fuertemente tipado. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Busca una cadena traducida similar a End datetime must be greater than start datetime. /// </summary> internal static string ENDDATE_MUSTBE_GREATHER_STARTDATE { get { return ResourceManager.GetString("ENDDATE_MUSTBE_GREATHER_STARTDATE", resourceCulture); } } } }
46.027397
214
0.630357
[ "MIT" ]
iAJTin/iCPUID
src/lib/net/iTin.Core/iTin.Core/Localization/Exceptions/InvalidPeriodException.Designer.cs
3,374
C#
using System; using System.Collections.Generic; using System.Text; namespace MD380FileIO { public class Channel { public int ID { get; set; } public string Name { get; set; } //0x61=Analogue 0x62=Digital public byte AnalogDigital { get; set; } // Power Level H=0x24 L=0x04 public byte PowerLevel { get; set; } public int ContactID { get; set; } public decimal RxFrequency { get; set; } public decimal TxFrequency { get; set; } } }
21.75
48
0.601533
[ "MIT" ]
kc9yjp/md380reader
MD380File/Channel.cs
524
C#
 using Google.Protobuf; using Microsoft.AspNetCore.WebUtilities; using Yngdieng.Protos; namespace Yngdieng.Common { public static class DocRefs { public static DocRef Decode(string docId) { return DocRef.Parser.ParseFrom(Base64UrlTextEncoder.Decode(docId)); } public static string Encode(DocRef docRef) { return Base64UrlTextEncoder.Encode(docRef.ToByteArray()); } } }
22.75
79
0.657143
[ "MIT" ]
MindongLab/yngdieng
server/common/DocRefs.cs
457
C#
//----------------------------------------------------------------------- // <copyright file="ActorRefFactoryExtensions.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- namespace Akka.Actor { public static class ActorRefFactoryExtensions { public static IActorRef ActorOf<TActor>(this IActorRefFactory factory, string name = null) where TActor : ActorBase, new() { return factory.ActorOf(Props.Create<TActor>(), name: name); } } }
35.8
130
0.534916
[ "Apache-2.0" ]
Chinchilla-Software-Com/akka.net
src/core/Akka/Actor/ActorRefFactoryExtensions.cs
718
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System.ComponentModel; using Microsoft.EntityFrameworkCore.Metadata.Builders; using OpenIddict.EntityFrameworkCore.Models; namespace OpenIddict.EntityFrameworkCore; /// <summary> /// Defines a relational mapping for the Token entity. /// </summary> /// <typeparam name="TToken">The type of the Token entity.</typeparam> /// <typeparam name="TApplication">The type of the Application entity.</typeparam> /// <typeparam name="TAuthorization">The type of the Authorization entity.</typeparam> /// <typeparam name="TKey">The type of the Key entity.</typeparam> [EditorBrowsable(EditorBrowsableState.Never)] public class OpenIddictEntityFrameworkCoreTokenConfiguration<TToken, TApplication, TAuthorization, TKey> : IEntityTypeConfiguration<TToken> where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization> where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken> where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken> where TKey : notnull, IEquatable<TKey> { public void Configure(EntityTypeBuilder<TToken> builder!!) { // Warning: optional foreign keys MUST NOT be added as CLR properties because // Entity Framework would throw an exception due to the TKey generic parameter // being non-nullable when using value types like short, int, long or Guid. builder.HasKey(token => token.Id); // Warning: the non-generic overlord is deliberately used to work around // a breaking change introduced in Entity Framework Core 3.x (where a // generic entity type builder is now returned by the HasIndex() method). builder.HasIndex(nameof(OpenIddictEntityFrameworkCoreToken.ReferenceId)) .IsUnique(); builder.HasIndex( nameof(OpenIddictEntityFrameworkCoreToken.Application) + nameof(OpenIddictEntityFrameworkCoreApplication.Id), nameof(OpenIddictEntityFrameworkCoreToken.Status), nameof(OpenIddictEntityFrameworkCoreToken.Subject), nameof(OpenIddictEntityFrameworkCoreToken.Type)); builder.Property(token => token.ConcurrencyToken) .HasMaxLength(50) .IsConcurrencyToken(); builder.Property(token => token.Id) .ValueGeneratedOnAdd(); builder.Property(token => token.ReferenceId) .HasMaxLength(100); builder.Property(token => token.Status) .HasMaxLength(50); builder.Property(token => token.Subject) .HasMaxLength(400); builder.Property(token => token.Type) .HasMaxLength(50); builder.ToTable("OpenIddictTokens"); } }
43.492754
139
0.715761
[ "Apache-2.0" ]
Thodor12/openiddict-core
src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreTokenConfiguration.cs
3,003
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.IdentityModel.Tokens; using OpenIddict.Validation; namespace Microsoft.Extensions.DependencyInjection; /// <summary> /// Exposes the necessary methods required to configure the OpenIddict validation services. /// </summary> public class OpenIddictValidationBuilder { /// <summary> /// Initializes a new instance of <see cref="OpenIddictValidationBuilder"/>. /// </summary> /// <param name="services">The services collection.</param> public OpenIddictValidationBuilder(IServiceCollection services) => Services = services ?? throw new ArgumentNullException(nameof(services)); /// <summary> /// Gets the services collection. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public IServiceCollection Services { get; } /// <summary> /// Registers an event handler using the specified configuration delegate. /// </summary> /// <typeparam name="TContext">The event context type.</typeparam> /// <param name="configuration">The configuration delegate.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public OpenIddictValidationBuilder AddEventHandler<TContext>( Action<OpenIddictValidationHandlerDescriptor.Builder<TContext>> configuration) where TContext : OpenIddictValidationEvents.BaseContext { if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } // Note: handlers registered using this API are assumed to be custom handlers by default. var builder = OpenIddictValidationHandlerDescriptor.CreateBuilder<TContext>() .SetType(OpenIddictValidationHandlerType.Custom); configuration(builder); return AddEventHandler(builder.Build()); } /// <summary> /// Registers an event handler using the specified descriptor. /// </summary> /// <param name="descriptor">The handler descriptor.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public OpenIddictValidationBuilder AddEventHandler(OpenIddictValidationHandlerDescriptor descriptor) { if (descriptor is null) { throw new ArgumentNullException(nameof(descriptor)); } // Register the handler in the services collection. Services.Add(descriptor.ServiceDescriptor); return Configure(options => options.Handlers.Add(descriptor)); } /// <summary> /// Removes the event handler that matches the specified descriptor. /// </summary> /// <param name="descriptor">The descriptor corresponding to the handler to remove.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public OpenIddictValidationBuilder RemoveEventHandler(OpenIddictValidationHandlerDescriptor descriptor) { if (descriptor is null) { throw new ArgumentNullException(nameof(descriptor)); } Services.RemoveAll(descriptor.ServiceDescriptor.ServiceType); Services.PostConfigure<OpenIddictValidationOptions>(options => { for (var index = options.Handlers.Count - 1; index >= 0; index--) { if (options.Handlers[index].ServiceDescriptor.ServiceType == descriptor.ServiceDescriptor.ServiceType) { options.Handlers.RemoveAt(index); } } }); return this; } /// <summary> /// Amends the default OpenIddict validation configuration. /// </summary> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <remarks>This extension can be safely called multiple times.</remarks> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder Configure(Action<OpenIddictValidationOptions> configuration) { if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } Services.Configure(configuration); return this; } /// <summary> /// Registers encryption credentials. /// </summary> /// <param name="credentials">The encrypting credentials.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCredentials(EncryptingCredentials credentials) { if (credentials is null) { throw new ArgumentNullException(nameof(credentials)); } return Configure(options => options.EncryptionCredentials.Add(credentials)); } /// <summary> /// Registers an encryption key. /// </summary> /// <param name="key">The security key.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionKey(SecurityKey key) { if (key is null) { throw new ArgumentNullException(nameof(key)); } // If the encryption key is an asymmetric security key, ensure it has a private key. if (key is AsymmetricSecurityKey asymmetricSecurityKey && asymmetricSecurityKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0055)); } if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes256KW)) { return AddEncryptionCredentials(new EncryptingCredentials(key, SecurityAlgorithms.Aes256KW, SecurityAlgorithms.Aes256CbcHmacSha512)); } if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaOAEP)) { return AddEncryptionCredentials(new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); } throw new InvalidOperationException(SR.GetResourceString(SR.ID0056)); } /// <summary> /// Registers an encryption certificate. /// </summary> /// <param name="certificate">The encryption certificate.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate(X509Certificate2 certificate) { if (certificate is null) { throw new ArgumentNullException(nameof(certificate)); } // If the certificate is a X.509v3 certificate that specifies at least one // key usage, ensure that the certificate key can be used for key encryption. if (certificate.Version >= 3) { var extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList(); if (extensions.Count != 0 && !extensions.Any(extension => extension.KeyUsages.HasFlag(X509KeyUsageFlags.KeyEncipherment))) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0060)); } } if (!certificate.HasPrivateKey) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0061)); } return AddEncryptionKey(new X509SecurityKey(certificate)); } /// <summary> /// Registers an encryption certificate retrieved from an embedded resource. /// </summary> /// <param name="assembly">The assembly containing the certificate.</param> /// <param name="resource">The name of the embedded resource.</param> /// <param name="password">The password used to open the certificate.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate( Assembly assembly, string resource, string? password) #if SUPPORTS_EPHEMERAL_KEY_SETS // Note: ephemeral key sets are currently not supported on macOS. => AddEncryptionCertificate(assembly, resource, password, RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.EphemeralKeySet); #else => AddEncryptionCertificate(assembly, resource, password, X509KeyStorageFlags.MachineKeySet); #endif /// <summary> /// Registers an encryption certificate retrieved from an embedded resource. /// </summary> /// <param name="assembly">The assembly containing the certificate.</param> /// <param name="resource">The name of the embedded resource.</param> /// <param name="password">The password used to open the certificate.</param> /// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate( Assembly assembly, string resource, string? password, X509KeyStorageFlags flags) { if (assembly is null) { throw new ArgumentNullException(nameof(assembly)); } if (string.IsNullOrEmpty(resource)) { throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); } using var stream = assembly.GetManifestResourceStream(resource); if (stream is null) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); } return AddEncryptionCertificate(stream, password, flags); } /// <summary> /// Registers an encryption certificate extracted from a stream. /// </summary> /// <param name="stream">The stream containing the certificate.</param> /// <param name="password">The password used to open the certificate.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate(Stream stream, string? password) #if SUPPORTS_EPHEMERAL_KEY_SETS // Note: ephemeral key sets are currently not supported on macOS. => AddEncryptionCertificate(stream, password, RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.EphemeralKeySet); #else => AddEncryptionCertificate(stream, password, X509KeyStorageFlags.MachineKeySet); #endif /// <summary> /// Registers an encryption certificate extracted from a stream. /// </summary> /// <param name="stream">The stream containing the certificate.</param> /// <param name="password">The password used to open the certificate.</param> /// <param name="flags"> /// An enumeration of flags indicating how and where /// to store the private key of the certificate. /// </param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The X.509 certificate is attached to the server options.")] public OpenIddictValidationBuilder AddEncryptionCertificate( Stream stream, string? password, X509KeyStorageFlags flags) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } using var buffer = new MemoryStream(); stream.CopyTo(buffer); return AddEncryptionCertificate(new X509Certificate2(buffer.ToArray(), password, flags)); } /// <summary> /// Registers an encryption certificate retrieved from the X.509 user or machine store. /// </summary> /// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate(string thumbprint) { if (string.IsNullOrEmpty(thumbprint)) { throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); } var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); if (certificate is null) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); } return AddEncryptionCertificate(certificate); static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) { using var store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly); return store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) .OfType<X509Certificate2>() .SingleOrDefault(); } } /// <summary> /// Registers an encryption certificate retrieved from the specified X.509 store. /// </summary> /// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param> /// <param name="name">The name of the X.509 store.</param> /// <param name="location">The location of the X.509 store.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddEncryptionCertificate( string thumbprint, StoreName name, StoreLocation location) { if (string.IsNullOrEmpty(thumbprint)) { throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); } using var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) .OfType<X509Certificate2>() .SingleOrDefault(); if (certificate is null) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); } return AddEncryptionCertificate(certificate); } /// <summary> /// Registers the specified values as valid audiences. Setting the audiences is recommended /// when the authorization server issues access tokens for multiple distinct resource servers. /// </summary> /// <param name="audiences">The audiences valid for this resource server.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder AddAudiences(params string[] audiences) { if (audiences is null) { throw new ArgumentNullException(nameof(audiences)); } if (audiences.Any(audience => string.IsNullOrEmpty(audience))) { throw new ArgumentException(SR.GetResourceString(SR.ID0123), nameof(audiences)); } return Configure(options => options.Audiences.UnionWith(audiences)); } /// <summary> /// Enables authorization validation so that a database call is made for each API request /// to ensure the authorization associated with the access token is still valid. /// Note: enabling this option may have an impact on performance and /// can only be used with an OpenIddict-based authorization server. /// </summary> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder EnableAuthorizationEntryValidation() => Configure(options => options.EnableAuthorizationEntryValidation = true); /// <summary> /// Enables token validation so that a database call is made for each API request /// to ensure the token entry associated with the access token is still valid. /// Note: enabling this option may have an impact on performance but is required /// when the OpenIddict server is configured to use reference tokens. /// </summary> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder EnableTokenEntryValidation() => Configure(options => options.EnableTokenEntryValidation = true); /// <summary> /// Sets a static OpenID Connect server configuration, that will be used to /// resolve the metadata/introspection endpoints and the issuer signing keys. /// </summary> /// <param name="configuration">The server configuration.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder SetConfiguration(OpenIddictConfiguration configuration) { if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } return Configure(options => options.Configuration = configuration); } /// <summary> /// Sets the client identifier client_id used when communicating /// with the remote authorization server (e.g for introspection). /// </summary> /// <param name="identifier">The client identifier.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder SetClientId(string identifier) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException(SR.GetResourceString(SR.ID0124), nameof(identifier)); } return Configure(options => options.ClientId = identifier); } /// <summary> /// Sets the client identifier client_secret used when communicating /// with the remote authorization server (e.g for introspection). /// </summary> /// <param name="secret">The client secret.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder SetClientSecret(string secret) { if (string.IsNullOrEmpty(secret)) { throw new ArgumentException(SR.GetResourceString(SR.ID0125), nameof(secret)); } return Configure(options => options.ClientSecret = secret); } /// <summary> /// Sets the issuer address, which is used to determine the actual location of the /// OAuth 2.0/OpenID Connect configuration document when using provider discovery. /// </summary> /// <param name="address">The issuer address.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder SetIssuer(Uri address) { if (address is null) { throw new ArgumentNullException(nameof(address)); } return Configure(options => options.Issuer = address); } /// <summary> /// Sets the issuer address, which is used to determine the actual location of the /// OAuth 2.0/OpenID Connect configuration document when using provider discovery. /// </summary> /// <param name="address">The issuer address.</param> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder SetIssuer(string address) { if (string.IsNullOrEmpty(address)) { throw new ArgumentException(SR.GetResourceString(SR.ID0126), nameof(address)); } if (!Uri.TryCreate(address, UriKind.Absolute, out Uri? uri) || !uri.IsWellFormedOriginalString()) { throw new ArgumentException(SR.GetResourceString(SR.ID0127), nameof(address)); } return SetIssuer(uri); } /// <summary> /// Configures OpenIddict to use introspection instead of local/direct validation. /// </summary> /// <returns>The <see cref="OpenIddictValidationBuilder"/>.</returns> public OpenIddictValidationBuilder UseIntrospection() => Configure(options => options.ValidationType = OpenIddictValidationType.Introspection); /// <inheritdoc/> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => base.Equals(obj); /// <inheritdoc/> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => base.GetHashCode(); /// <inheritdoc/> [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() => base.ToString(); }
41.174603
138
0.680898
[ "Apache-2.0" ]
Shaddix/openiddict-core
src/OpenIddict.Validation/OpenIddictValidationBuilder.cs
20,754
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Wisp { class Parser { private int i; private string code; public Parser(string code) { this.code = code; i = 0; } public IValue Parse() { while (true) { var c = code[i]; if (c == ' ' || c == '\t' || c == '\n') { i++; continue; } else if (c >= '0' && c <= '9') { return parseNumeric(); } else if (c == '"') { i++; return parseString(); } else if (c == '(') { i++; return parseList(); } else { return parseSymbol(); } } } private IValue parseSymbol() { var res = ""; while (i < code.Length) { var c = code[i]; if (c == ' ' || c == '\t' || c == '\n' || c == ')') { return new Symbol(res); } res += c; ++i; } return new Symbol(res); } private IValue parseList() { var res = new List(); while (i < code.Length) { var c = code[i]; if (c == ' ' || c == '\t' || c == '\n') { ++i; continue; } else if (c == ')') { ++i; return res; } else { res.Add(Parse()); } } throw new ParserException("Didn't find list )"); } private IValue parseString() { var res = ""; while (i < code.Length) { var c = code[i]; if (c == '"') { ++i; break; } res += c; ++i; } if (i == code.Length) { throw new ParserException("Ending quote not found"); } return new WispString(res); } private IValue parseNumeric() { var res = ""; while (i < code.Length) { var c = code[i]; if (c == ' ' || c == '\t' || c == '\n' || c == ')') { break; } res += c; ++i; } double r; if (double.TryParse(res, out r)) { return new Number(r); } else { throw new ParserException("Could not parse as a number: " + res); } } private class ParserException : Exception { public ParserException() { } public ParserException(string message) : base(message) { } public ParserException(string message, Exception innerException) : base(message, innerException) { } } } }
20.688
102
0.430008
[ "MIT" ]
m-r-hunt/Wisp
Wisp/Parser.cs
2,588
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Models; using DAL; using System.Collections.Generic; using DBUtil; using Utils; namespace DBHelperTest { [TestClass] public class DeleteTest { #region 变量 private BsOrderDal m_BsOrderDal = ServiceHelper.Get<BsOrderDal>(); private SysUserDal m_SysUserDal = ServiceHelper.Get<SysUserDal>(); #endregion #region 测试删除用户 [TestMethod] public void TestDeleteUser() { m_SysUserDal.Delete("13"); } #endregion #region 测试根据查询条件删除用户 [TestMethod] public void TestDeleteUserByCondition() { using (var session = DBHelper.GetSession()) { session.DeleteByCondition<SYS_USER>(string.Format("id>=12")); } } #endregion } }
22.15
77
0.600451
[ "MIT" ]
0611163/DBHelper
DBHelper/DBHelperTest/DeleteTest.cs
928
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Ecs20140526.Models { public class DetachDiskResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } } }
18.736842
54
0.688202
[ "Apache-2.0" ]
alibabacloud-sdk-swift/alibabacloud-sdk
ecs-20140526/csharp/core/Models/DetachDiskResponse.cs
356
C#
namespace Microsoft.Examples.V3.Controllers { using Microsoft.Web.Http; using Models; using System.Web.Http; public class AgreementsController : ApiController { // GET ~/v3/agreements/{accountId} // GET ~/agreements/{accountId}?api-version=3.0 public IHttpActionResult Get( string accountId, ApiVersion apiVersion ) => Ok( new Agreement( GetType().FullName, accountId, apiVersion.ToString() ) ); } }
34.538462
159
0.685969
[ "MIT" ]
AzureMentor/aspnet-api-versioning
samples/webapi/ByNamespaceWebApiSample/V3/Controllers/AgreementsController.cs
451
C#
using MasteringEFCore.MultiTenancy.Starter.Core.Commands.Files; using MasteringEFCore.MultiTenancy.Starter.Data; using MasteringEFCore.MultiTenancy.Starter.Helpers; using MasteringEFCore.MultiTenancy.Starter.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading.Tasks; namespace MasteringEFCore.MultiTenancy.Starter.Infrastructure.Commands.Files { public class UpdateFileCommand : CommandFileBase, ICreateFileCommand<int> { public UpdateFileCommand(BlogFilesContext context) : base(context) { } public Guid Id { get; set; } public string ContentType { get; set; } public string ContentDisposition { get; set; } public byte[] Content { get; set; } public long Length { get; set; } public string Name { get; set; } public string FileName { get; set; } public int Handle() { UpdateFile(); return Context.SaveChanges(); } public async Task<int> HandleAsync() { UpdateFile(); return await Context.SaveChangesAsync(); } private void UpdateFile() { File file = new File() { Id = Id, Name = Name, FileName = FileName, Content = Content, Length = Length, ContentType = ContentType }; Context.Update(file); } } }
28.298246
77
0.605704
[ "MIT" ]
PacktPublishing/Mastering-Entity-Framework-Core
Chapter 12/Starter/MasteringEFCore.MultiTenancy.Starter/Infrastructure/Commands/Files/UpdateFileCommand.cs
1,615
C#
using EltraCommon.ObjectDictionary.Common.DeviceDescription.Profiles.Application.Parameters; using EltraCommon.ObjectDictionary.Common.DeviceDescription.Profiles.Application.Parameters.Events; using EltraCommon.ObjectDictionary.Xdd.DeviceDescription.Profiles.Application.Parameters; using EltraXamCommon.Controls; using System.Timers; using System; using System.Threading.Tasks; using Xamarin.Forms; using System.Diagnostics; using System.ComponentModel; using System.Collections.Generic; using EltraNavigoStreema.Views.Devices.Streema.StreemaControl.Station; using System.Reflection; namespace EltraNavigoStreema.Views.StreemaControl { public class StreemaControlViewModel : XamToolViewModel { #region Private fields private double _volumeValue; private bool _isMuteActive; private bool _internalChange; private ushort _statusWordValue; private XddParameter _volumeParameter; private XddParameter _muteParameter; private XddParameter _statusWordParameter; private Timer _valumeHistereseTimer; private List<StreemaStationViewModel> _stationList; #endregion #region Constructors public StreemaControlViewModel() { Title = "Streema Control"; Uuid = "A8BEC143-7BBE-4C3B-A425-6C2D38C32E1A"; } #endregion #region Properties public List<StreemaStationViewModel> StationList { get => _stationList ?? (_stationList = new List<StreemaStationViewModel>()); set => SetProperty(ref _stationList, value); } public ushort StatusWordValue { get => _statusWordValue; set => SetProperty(ref _statusWordValue, value); } public bool IsMuteActive { get => _isMuteActive; set => SetProperty(ref _isMuteActive, value); } public double VolumeValue { get => _volumeValue; set => SetProperty(ref _volumeValue, value); } #endregion #region Events handling private void OnDeviceInitialized(object sender, EventArgs e) { InitializeStateMachineParameter(); InitializeVolumeParameter(); InitializeMuteParameter(); InitializeStationList(); } private void InitializeStationList() { var stationList = new List<StreemaStationViewModel>(); var stationsCountParameter = Device.SearchParameter("PARAM_StationsCount") as XddParameter; if (stationsCountParameter != null && stationsCountParameter.GetValue(out ushort maxCount)) { for (int i = 0; i < maxCount; i++) { var stationViewModel = new StreemaStationViewModel(this, i); stationList.Add(stationViewModel); } } foreach (var station in stationList) { station.Agent = Agent; station.Device = Device; } StationList = stationList; } private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) { if(e.PropertyName == "IsMuteActive") { if (!_internalChange) { Task.Run(async () => { if (_muteParameter != null && _muteParameter.SetValue(IsMuteActive)) { if (!await _muteParameter.Write()) { _internalChange = true; IsMuteActive = !IsMuteActive; _internalChange = false; } } }); } } } private void InitializeMuteParameter() { _muteParameter = Device.SearchParameter(0x4201, 0x00) as XddParameter; if (_muteParameter != null) { _muteParameter.ParameterChanged += OnVolumeParameterChanged; Task.Run(async () => { await _muteParameter.UpdateValue(); }).ContinueWith((t) => { if (_muteParameter.GetValue(out bool val)) { IsMuteActive = val; } }); } } private void InitializeVolumeParameter() { _volumeParameter = Device.SearchParameter(0x4200, 0x00) as XddParameter; if (_volumeParameter != null) { _volumeParameter.ParameterChanged += OnVolumeParameterChanged; Task.Run(async () => { await _volumeParameter.UpdateValue(); }).ContinueWith((t) => { if (_volumeParameter.GetValue(out int volumeValue)) { VolumeValue = volumeValue; } }); } } private void InitializeStateMachineParameter() { _statusWordParameter = Device.SearchParameter("PARAM_StatusWord") as XddParameter; if (_statusWordParameter != null) { _statusWordParameter.ParameterChanged += OnStatusWordParameterChanged; Task.Run(async () => { await _statusWordParameter.UpdateValue(); }).ContinueWith((t) => { if (_statusWordParameter.GetValue(out ushort val)) { StatusWordValue = val; } }); } } private void OnVolumeParameterChanged(object sender, ParameterChangedEventArgs e) { if(e.Parameter is Parameter volumeParameter) { if (volumeParameter.GetValue(out int volumeValue)) { VolumeValue = volumeValue; } } } private void OnStatusWordParameterChanged(object sender, ParameterChangedEventArgs e) { if (e.Parameter is Parameter statusWordParameter) { if (statusWordParameter.GetValue(out ushort val)) { StatusWordValue = val; } } } private void OnVolumeHistereseElapsed(object sender, ElapsedEventArgs e) { _valumeHistereseTimer.Stop(); OnVolumeChanged(); } #endregion #region Methods public override void SetUp() { if (CanSetUp) { Assembly assembly = GetType().GetTypeInfo().Assembly; var assemblyName = assembly.GetName(); Image = ImageSource.FromResource($"{assemblyName.Name}.Resources.music_32px.png"); UpdateViewModels = false; DeviceInitialized += OnDeviceInitialized; PropertyChanged += OnViewModelPropertyChanged; } base.SetUp(); } private void CreateVolumeHistereseTimer() { if(_valumeHistereseTimer!=null) { _valumeHistereseTimer.Stop(); _valumeHistereseTimer.Dispose(); } _valumeHistereseTimer = new Timer(500); _valumeHistereseTimer.Elapsed += OnVolumeHistereseElapsed; _valumeHistereseTimer.Enabled = true; _valumeHistereseTimer.AutoReset = true; } private void OnVolumeChanged() { if(_volumeParameter != null) { int volumeValue = Convert.ToInt32(VolumeValue); if(_volumeParameter.SetValue(volumeValue)) { Task.Run(async ()=> { Debug.Print($"before write, new value = {volumeValue}\r\n"); if (await _volumeParameter.Write()) { Debug.Print($"after write, new value = {volumeValue}\r\n"); } else { Debug.Print($"after write failed, value = {volumeValue}\r\n"); } }); } } } public void SliderVolumeValueChanged(double newValue) { if(_volumeParameter != null && _volumeParameter.GetValue(out int volumeValue)) { int newIntValue = Convert.ToInt32(newValue); if (volumeValue != newIntValue) { _volumeValue = Math.Round(newValue); CreateVolumeHistereseTimer(); } } } #endregion } }
29.224684
103
0.512507
[ "Apache-2.0" ]
eltra-ch/eltra-sdk
samples/Streema/Navigo/EltraNavigoStreema/Views/Streema/StreemaControl/StreemaControlViewModel.cs
9,237
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using ARSoft.Tools.Net; using ARSoft.Tools.Net.Dns; namespace Arashi { public class DNSChina { public static List<DomainName> ChinaList = File.Exists(DNSChinaConfig.Config.ChinaListPath) ? File.ReadAllLines(DNSChinaConfig.Config.ChinaListPath).ToList().ConvertAll(DomainName.Parse) : new List<DomainName>(); public static bool IsChinaName(DomainName name) => ChinaList.Any(name.IsEqualOrSubDomainOf); public static DnsMessage ResolveOverChinaDns(DnsMessage dnsMessage) { if (!DNSChinaConfig.Config.UseHttpDns) return new DnsClient(IPAddress.Parse(DNSChinaConfig.Config.ChinaDnsIp), AoiConfig.Config.TimeOut) .SendMessage(dnsMessage); var domainName = dnsMessage.Questions.FirstOrDefault()?.Name.ToString().TrimEnd('.'); var dnsStr = string.Empty; if (dnsMessage.IsEDnsEnabled) { foreach (var eDnsOptionBase in dnsMessage.EDnsOptions.Options.ToArray()) if (eDnsOptionBase is ClientSubnetOption option) { var task = new WebClient().DownloadStringTaskAsync( string.Format(DNSChinaConfig.Config.HttpDnsEcsUrl, domainName, option.Address)); task.Wait(1000); dnsStr = task.Result; break; } } else { var task = new WebClient().DownloadStringTaskAsync( string.Format(DNSChinaConfig.Config.HttpDnsUrl, domainName)); task.Wait(1000); dnsStr = task.Result; } if (string.IsNullOrWhiteSpace(dnsStr)) throw new TimeoutException(); var ttlTime = Convert.ToInt32(dnsStr.Split(',')[1]); var dnsAnswerList = dnsStr.Split(',')[0].Split(';'); var dnsAMessage = new DnsMessage { IsRecursionAllowed = true, IsRecursionDesired = true, TransactionID = dnsMessage.TransactionID, AnswerRecords = new List<DnsRecordBase>(dnsAnswerList .Select(item => new ARecord(DomainName.Parse(domainName), ttlTime, IPAddress.Parse(item))) .Cast<DnsRecordBase>().ToList()) }; dnsAMessage.Questions.AddRange(dnsMessage.Questions); dnsAMessage.AnswerRecords.Add(new TxtRecord(DomainName.Parse("china.arashi-msg"), 0, "ArashiDNS.P ChinaList")); return dnsAMessage; } } }
42.307692
113
0.586182
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
mili-tan/ArashiDNS.Aoi
Arashi.Aoi/DNS/DNSChina.cs
2,752
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using md = System.Data.Entity.Core.Metadata.Edm; // // The PropertyRef class (and its subclasses) represent references to a property // of a type. // The PropertyRefList class represents a list of expected properties // where each property from the type is described as a PropertyRef // // These classes are used by the StructuredTypeEliminator module as part of // eliminating all structured types. The basic idea of this module is that all // structured types are flattened out into a single level. To avoid a large amount // of potentially unnecessary information, we try to identify what pieces of information // are really necessary at each node of the tree. This is where PropertyRef comes in. // A PropertyRef (and more generally, a PropertyRefList) identifies a list of // properties, and can be attached to a node/var to indicate that these were the // only desired properties. // namespace System.Data.Entity.Core.Query.PlanCompiler { using System.Data.Entity.Core.Query.InternalTrees; // <summary> // A PropertyRef class encapsulates a reference to one or more properties of // a complex instance - a record type, a complex type or an entity type. // A PropertyRef may be of the following kinds. // - a simple property reference (just a reference to a simple property) // - a typeid reference - applies only to entitytype and complextypes // - an entitysetid reference - applies only to ref and entity types // - a nested property reference (a reference to a nested property - a.b) // - an "all" property reference (all properties) // </summary> internal abstract class PropertyRef { // <summary> // Create a nested property ref, with "p" as the prefix. // The best way to think of this function as follows. // Consider a type T where "this" describes a property X on T. Now // consider a new type S, where "p" is a property of S and is of type T. // This function creates a PropertyRef that describes the same property X // from S.p instead // </summary> // <param name="p"> the property to prefix with </param> // <returns> the nested property reference </returns> internal virtual PropertyRef CreateNestedPropertyRef(PropertyRef p) { return new NestedPropertyRef(p, this); } // <summary> // Create a nested property ref for a simple property. Delegates to the function // above // </summary> // <param name="p"> the simple property </param> // <returns> a nestedPropertyRef </returns> internal PropertyRef CreateNestedPropertyRef(md.EdmMember p) { return CreateNestedPropertyRef(new SimplePropertyRef(p)); } // <summary> // Creates a nested property ref for a rel-property. Delegates to the function above // </summary> // <param name="p"> the rel-property </param> // <returns> a nested property ref </returns> internal PropertyRef CreateNestedPropertyRef(RelProperty p) { return CreateNestedPropertyRef(new RelPropertyRef(p)); } // <summary> // The tostring method for easy debuggability // </summary> public override string ToString() { return ""; } } }
42.719512
132
0.669712
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Core/Query/PlanCompiler/PropertyRef.cs
3,503
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("Nucleus.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Nucleus.Tests")] [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("0e22b4fa-f414-449c-8053-f12644ea09e8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.783784
85
0.725436
[ "MIT" ]
6A/nucleus
Nucleus.Tests/Properties/AssemblyInfo.cs
1,438
C#
// Copyright (c) 2013 Richard Long & HexBeerium // // Released under the MIT license ( http://opensource.org/licenses/MIT ) // using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace dotnet.lib.CoreAnnex.work { class WorkQueue { private Queue<Job> _queue; public WorkQueue() { _queue = new Queue<Job>(); } public void enqueue(Job job) { // vvv http://jaksa76.blogspot.com/2009/03/blocking-queue-in-c.html lock (_queue) { _queue.Enqueue(job); Monitor.Pulse(_queue); } // ^^^ http://jaksa76.blogspot.com/2009/03/blocking-queue-in-c.html } public Job dequeue() { Job answer; // vvv http://jaksa76.blogspot.com/2009/03/blocking-queue-in-c.html lock (_queue) { while (0 == _queue.Count) { Monitor.Wait(_queue); } answer = _queue.Dequeue(); } // ^^^ http://jaksa76.blogspot.com/2009/03/blocking-queue-in-c.html return answer; } } }
22.877193
80
0.480828
[ "MIT" ]
rlong/dotnet.lib.CoreAnnex
work/WorkQueue.cs
1,306
C#
namespace aspmvc5_glimpse_trace.Services { using System.Web.Mvc; using Boilerplate.Web.Mvc; using aspmvc5_glimpse_trace.Constants; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class ManifestService : IManifestService { private readonly UrlHelper urlHelper; public ManifestService(UrlHelper urlHelper) { this.urlHelper = urlHelper; } /// <summary> /// Gets the manifest JSON for the current site. This allows you to customize the icon and other browser /// settings for Chrome/Android and FireFox (FireFox support is coming). See https://w3c.github.io/manifest/ /// for the official W3C specification. See http://html5doctor.com/web-manifest-specification/ for more /// information. See https://developer.chrome.com/multidevice/android/installtohomescreen for Chrome's /// implementation. /// </summary> /// <returns>The manifest JSON for the current site.</returns> public string GetManifestJson() { JObject document = new JObject( new JProperty("short_name", Application.ShortName), new JProperty("name", Application.Name), new JProperty("icons", new JArray( GetIconJObject("~/content/icons/android-chrome-36x36.png", "36x36", "image/png", "0.75"), GetIconJObject("~/content/icons/android-chrome-48x48.png", "48x48", "image/png", "1.0"), GetIconJObject("~/content/icons/android-chrome-72x72.png", "72x72", "image/png", "1.5"), GetIconJObject("~/content/icons/android-chrome-96x96.png", "96x96", "image/png", "2.0"), GetIconJObject("~/content/icons/android-chrome-144x144.png", "144x144", "image/png", "3.0"), GetIconJObject("~/content/icons/android-chrome-192x192.png", "192x192", "image/png", "4.0")))); return document.ToString(Formatting.Indented); } /// <summary> /// Gets a <see cref="JObject"/> containing the specified image details. /// </summary> /// <param name="iconPath">The path to the icon image.</param> /// <param name="sizes">The size of the image in the format AxB.</param> /// <param name="type">The MIME type of the image.</param> /// <param name="density">The pixel density of the image.</param> /// <returns>A <see cref="JObject"/> containing the image details.</returns> private JObject GetIconJObject(string iconPath, string sizes, string type, string density) { return new JObject( new JProperty("src", this.urlHelper.Content(iconPath)), new JProperty("sizes", sizes), new JProperty("type", type), new JProperty("density", density)); } } }
48.393443
119
0.599255
[ "MIT" ]
ashumeow/noobs
aspnet/aspmvc5_glimpse_trace/aspmvc5_glimpse_trace/Services/Manifest/ManifestService.cs
2,954
C#
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using System.Management.Automation; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Creates Azure Site Recovery disk replication configuration for V2A-RCM replication. /// </summary> [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesAsrInMageRcmDiskInput", DefaultParameterSetName = ASRParameterSets.ReplicateVMwareToAzure, SupportsShouldProcess = true)] [Alias("New-ASRInMageRcmDiskInput")] [OutputType(typeof(ASRInMageRcmDiskInput))] public class AzureRmAsrInMageRcmDiskInput : SiteRecoveryCmdletBase { #region Parameters /// <summary> /// Gets or sets the disk Id. /// </summary> [Parameter( Mandatory = true, HelpMessage = "Specify the Id of the disk that this mapping corresponds to.")] [ValidateNotNullOrEmpty] public string DiskId { get; set; } /// <summary> /// Gets or sets the log storage account ARM Id. /// </summary> [Parameter( Mandatory = true, HelpMessage = "Specifies the log or cache storage account Id to be used to store replication logs.")] [ValidateNotNullOrEmpty] public string LogStorageAccountId { get; set; } /// <summary> /// Gets or sets the disk type. /// </summary> [Parameter( Mandatory = true, HelpMessage = "Specifies the recovery disk type.")] [ValidateNotNullOrEmpty] [ValidateSet( Constants.Standard_LRS, Constants.Premium_LRS, Constants.StandardSSD_LRS)] [PSArgumentCompleter("Standard_LRS", "Premium_LRS", "StandardSSD_LRS")] public string DiskType { get; set; } /// <summary> /// Gets or sets the disk encryption set ARM Id. /// </summary> [Parameter( HelpMessage = "Specifies the disk encryption set ARM Id.")] public string DiskEncryptionSetId { get; set; } #endregion Parameters /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); ASRInMageRcmDiskInput diskRelicationConfig = null; if (this.ShouldProcess( this.DiskId, VerbsCommon.New)) { diskRelicationConfig = new ASRInMageRcmDiskInput() { DiskId = this.DiskId, DiskType = this.DiskType, LogStorageAccountId = this.LogStorageAccountId, DiskEncryptionSetId = this.DiskEncryptionSetId }; } this.WriteObject(diskRelicationConfig); } } }
40.892473
214
0.582698
[ "MIT" ]
Agazoth/azure-powershell
src/RecoveryServices/RecoveryServices.SiteRecovery/DiskReplicationConfiguration/AzureRmInMageRcmDiskInput.cs
3,713
C#
using System.Collections.Generic; using UnityEngine; namespace UnityEditor.Timeline { class TimelineCursors { public enum CursorType { MixBoth, MixLeft, MixRight, Replace, Ripple, Pan } class CursorInfo { public readonly string assetPath; public readonly Vector2 hotSpot; public readonly MouseCursor mouseCursorType; public CursorInfo(string assetPath, Vector2 hotSpot, MouseCursor mouseCursorType) { this.assetPath = assetPath; this.hotSpot = hotSpot; this.mouseCursorType = mouseCursorType; } } const string k_CursorAssetRoot = "Cursors/"; const string k_CursorAssetsNamespace = "Timeline."; const string k_CursorAssetExtension = ".png"; const string k_MixBothCursorAssetName = k_CursorAssetsNamespace + "MixBoth" + k_CursorAssetExtension; const string k_MixLeftCursorAssetName = k_CursorAssetsNamespace + "MixLeft" + k_CursorAssetExtension; const string k_MixRightCursorAssetName = k_CursorAssetsNamespace + "MixRight" + k_CursorAssetExtension; const string k_ReplaceCursorAssetName = k_CursorAssetsNamespace + "Replace" + k_CursorAssetExtension; const string k_RippleCursorAssetName = k_CursorAssetsNamespace + "Ripple" + k_CursorAssetExtension; static readonly string s_PlatformPath = (Application.platform == RuntimePlatform.WindowsEditor) ? "Windows/" : "macOS/"; static readonly string s_CursorAssetDirectory = k_CursorAssetRoot + s_PlatformPath; static readonly Dictionary<CursorType, CursorInfo> s_CursorInfoLookup = new Dictionary<CursorType, CursorInfo> { {CursorType.MixBoth, new CursorInfo(s_CursorAssetDirectory + k_MixBothCursorAssetName, new Vector2(16, 18), MouseCursor.CustomCursor)}, {CursorType.MixLeft, new CursorInfo(s_CursorAssetDirectory + k_MixLeftCursorAssetName, new Vector2(7, 18), MouseCursor.CustomCursor)}, {CursorType.MixRight, new CursorInfo(s_CursorAssetDirectory + k_MixRightCursorAssetName, new Vector2(25, 18), MouseCursor.CustomCursor)}, {CursorType.Replace, new CursorInfo(s_CursorAssetDirectory + k_ReplaceCursorAssetName, new Vector2(16, 28), MouseCursor.CustomCursor)}, {CursorType.Ripple, new CursorInfo(s_CursorAssetDirectory + k_RippleCursorAssetName, new Vector2(26, 19), MouseCursor.CustomCursor)}, {CursorType.Pan, new CursorInfo(null, Vector2.zero, MouseCursor.Pan)} }; static readonly Dictionary<string, Texture2D> s_CursorAssetCache = new Dictionary<string, Texture2D>(); static CursorType? s_CurrentCursor; public static void SetCursor(CursorType cursorType) { if (s_CurrentCursor.HasValue && s_CurrentCursor.Value == cursorType) return; s_CurrentCursor = cursorType; var cursorInfo = s_CursorInfoLookup[cursorType]; Texture2D cursorAsset = null; if (cursorInfo.mouseCursorType == MouseCursor.CustomCursor) { cursorAsset = LoadCursorAsset(cursorInfo.assetPath); } EditorGUIUtility.SetCurrentViewCursor(cursorAsset, cursorInfo.hotSpot, cursorInfo.mouseCursorType); } public static void ClearCursor() { if (!s_CurrentCursor.HasValue) return; EditorGUIUtility.ClearCurrentViewCursor(); s_CurrentCursor = null; } static Texture2D LoadCursorAsset(string assetPath) { if (!s_CursorAssetCache.ContainsKey(assetPath)) { s_CursorAssetCache.Add(assetPath, (Texture2D)EditorGUIUtility.Load(assetPath)); } return s_CursorAssetCache[assetPath]; } } }
41.416667
149
0.662223
[ "MIT" ]
11xdev-coder/Snek
Library/PackageCache/com.unity.timeline@1.4.8/Editor/Manipulators/Cursors/TimelineCursors.cs
3,976
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov // Created: 2009.11.07 namespace Xtensive.Sql.Compiler { internal class CycleItemNode : Node { public readonly int Index; internal override void AcceptVisitor(NodeVisitor visitor) { visitor.Visit(this); } // Constructors public CycleItemNode(int index) { Index = index; } } }
19.615385
62
0.633333
[ "MIT" ]
SergeiPavlov/dataobjects-net
DataObjects/Sql/Compiler/Internals/Nodes/CycleItemNode.cs
510
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace Opal { // Yes this is inspired by the Poiyomi editor public class OpalBRDFEditor : ShaderGUI { public static GUIStyle opalLogoStyle, centerBoldStyle, centerBoldBiggerStyle; public static Texture2D sssSkinTex, sssPlantTex, sssGrayTex; public Texture2D newRamp; bool rampExplainOut = false; public enum EditorPage { BRDF, Surface, Toggles } public EditorPage activePage = EditorPage.BRDF; public enum SurfaceModel { Standard, Retroreflective } public SurfaceModel pbrModel; public static Dictionary<SurfaceModel, string> pbrModelWords = new Dictionary<SurfaceModel, string>() { { SurfaceModel.Standard, "" }, { SurfaceModel.Retroreflective, "RETROREFLECTIVE" }, }; public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) { if (opalLogoStyle == null) { opalLogoStyle = new GUIStyle(EditorStyles.boldLabel); opalLogoStyle.alignment = TextAnchor.MiddleCenter; opalLogoStyle.fontStyle = FontStyle.Bold; opalLogoStyle.fontSize = 24; } if (centerBoldStyle == null) { centerBoldStyle = new GUIStyle(EditorStyles.boldLabel); centerBoldStyle.alignment = TextAnchor.MiddleCenter; } if (centerBoldBiggerStyle == null) { centerBoldBiggerStyle = new GUIStyle(EditorStyles.boldLabel); centerBoldBiggerStyle.alignment = TextAnchor.MiddleCenter; centerBoldBiggerStyle.fontSize += 4; } if (sssSkinTex == null) sssSkinTex = Resources.Load<Texture2D>("BRDF/SSS"); if (sssPlantTex == null) sssPlantTex = Resources.Load<Texture2D>("BRDF/SSS_plant"); if (sssGrayTex == null) sssGrayTex = Resources.Load<Texture2D>("BRDF/SSS_gray"); //base.OnGUI(materialEditor, properties); //return; GUILayout.Label("Opal - BRDF", opalLogoStyle); GUILayout.Label("IGNORE VRCSDK WARNINGS! DO NOT DISABLE KEYWORDS!", centerBoldStyle); GUILayout.BeginHorizontal(); if (GUILayout.Button("BRDF", EditorStyles.miniButtonLeft)) activePage = EditorPage.BRDF; if (GUILayout.Button("Surface", EditorStyles.miniButtonMid)) activePage = EditorPage.Surface; if (GUILayout.Button("Toggles", EditorStyles.miniButtonRight)) activePage = EditorPage.Toggles; GUILayout.EndHorizontal(); Material material = materialEditor.target as Material; Undo.RecordObject(material, "Changed parameters"); GUILayout.Space(10); if (activePage == EditorPage.BRDF) { GUILayout.Label("BRDF Editor", centerBoldBiggerStyle); GUILayout.Space(10); GUILayout.Label("NOTE: Disable shadows for BRDF ramps that light the back! (Ex: Crystal shading)", centerBoldStyle); GUILayout.Space(10); if (newRamp) material.SetTexture("_BRDFTex", newRamp); if (GUIHelpers.AskTexture(ref material, "_BRDFTex", "BRDF Ramp")) { material.EnableKeyword("HAS_BRDF_MAP"); Texture2D texture = material.GetTexture("_BRDFTex") as Texture2D; if (texture.wrapMode != TextureWrapMode.Clamp) { GUILayout.Space(10); GUILayout.BeginHorizontal(); GUILayout.Label("WARNING: BRDF Ramp's 'wrapMode' is not Clamp!", EditorStyles.boldLabel); if (GUILayout.Button("Fix")) { TextureImporter importer = TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter; if (importer == null) return; importer.wrapMode = TextureWrapMode.Clamp; importer.isReadable = true; TextureImporterSettings importerSettings = new TextureImporterSettings(); importer.ReadTextureSettings(importerSettings); EditorUtility.SetDirty(importer); importer.SaveAndReimport(); } GUILayout.EndHorizontal(); } } else material.DisableKeyword("HAS_BRDF_MAP"); GUILayout.Space(10); GUILayout.Label("Presets", centerBoldStyle); GUILayout.Space(10); GUILayout.BeginHorizontal(); if (GUILayout.Button("None", EditorStyles.miniButtonLeft)) material.SetTexture("_BRDFTex", null); if (GUILayout.Button("Skin", EditorStyles.miniButtonMid)) material.SetTexture("_BRDFTex", sssSkinTex); if (GUILayout.Button("Plant", EditorStyles.miniButtonMid)) material.SetTexture("_BRDFTex", sssPlantTex); if (GUILayout.Button("Gray", EditorStyles.miniButtonRight)) material.SetTexture("_BRDFTex", sssGrayTex); GUILayout.EndHorizontal(); if (GUILayout.Button("Open Ramp Maker")) { RampTexMaker window = EditorWindow.GetWindow<RampTexMaker>(); window.connection = this; window.Show(); } if (GUILayout.Button("Can't pick?", EditorStyles.miniButton)) rampExplainOut = !rampExplainOut; if (rampExplainOut) { GUILayout.Label("Preset Help", centerBoldStyle); GUILayout.Space(10); GUILayout.Label("None: Softer lighting than Unity Standard, use for softer looking materials"); GUILayout.Label("Skin: Use for skin or anything flesh-like"); GUILayout.Label("Plant: Use for plant like coloring (has green midtones)"); GUILayout.Label("Gray: Use for even softer lighting, for fur and such"); } } if (activePage == EditorPage.Surface) { GUILayout.Label("Surface", centerBoldBiggerStyle); GUILayout.Space(10); GUILayout.Label("Base Map", centerBoldStyle); GUIHelpers.AskTexture(ref material, "_MainTex", "Main Texture"); GUIHelpers.AskColor(ref material, "_Color", "Color"); GUIHelpers.AskScaleOffsetInfo(ref material, "_MainTex", "Scale and Offset"); GUILayout.Space(10); GUILayout.Label("Bump Mapping", centerBoldStyle); if (GUIHelpers.AskTexture(ref material, "_BumpMap", "Normal Map")) material.EnableKeyword("HAS_BUMP_MAP"); else material.DisableKeyword("HAS_BUMP_MAP"); GUIHelpers.AskFloat(ref material, "_NormalDepth", "Depth"); GUILayout.Space(10); GUILayout.Label("Emission", centerBoldStyle); GUIHelpers.AskTexture(ref material, "_EmissionMap", "Emission Map"); GUIHelpers.AskColorHDR(ref material, "_EmissionColor", "Color"); GUILayout.Space(10); GUILayout.Label("Ambient Occlusion", centerBoldStyle); if (GUIHelpers.AskTexture(ref material, "_OcclusionMap", "Occlusion Map")) material.EnableKeyword("HAS_AO_MAP"); else material.DisableKeyword("HAS_AO_MAP"); GUILayout.Space(10); GUILayout.Label("Detail Maps", centerBoldStyle); //GUIHelpers.AskTexture(ref material, "_DetailAlbedo", "Detail Albedo"); GUIHelpers.AskFloat(ref material, "_DetailBumpScale", "Detail Normal Scale"); GUIHelpers.AskTexture(ref material, "_DetailBumpMap", "Detail Normal Map"); GUIHelpers.AskScaleOffsetInfo(ref material, "_DetailAlbedo", "Scale and Offset"); GUILayout.Space(10); GUILayout.Label("Material", centerBoldStyle); GUIHelpers.AskFloatRange(ref material, "_Roughness", "Roughness", 0, 1); GUIHelpers.AskFloatRange(ref material, "_Metallic", "Metallic", 0, 1); GUIHelpers.AskFloatRange(ref material, "_Hardness", "Hardness", 0, 1); GUILayout.BeginHorizontal(); GUILayout.Label("Surface Model", EditorStyles.boldLabel); pbrModel = (SurfaceModel)EditorGUILayout.EnumPopup("", (SurfaceModel)material.GetInt("_PBRModel")); material.SetInt("_PBRModel", (int)pbrModel); GUILayout.EndHorizontal(); foreach (var pair in pbrModelWords) { if (string.IsNullOrEmpty(pair.Value)) continue; if (pair.Key == pbrModel) material.EnableKeyword(pair.Value); else material.DisableKeyword(pair.Value); } GUILayout.Space(10); } if (activePage == EditorPage.Toggles) { GUILayout.Label("Toggles", centerBoldBiggerStyle); GUILayout.Space(10); if (GUIHelpers.AskBool(ref material, "_RecieveShadowsToggle", "Recieve Shadows")) material.EnableKeyword("RECIEVE_SHADOWS"); else material.DisableKeyword("RECIEVE_SHADOWS"); } } } }
38.676692
137
0.550156
[ "MIT" ]
zCubed3/OpalCollection
Scripts/Editor/OpalBRDFEditor.cs
10,290
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; namespace Microsoft.Xna.Framework { /// <summary> /// Provides helper methods to make it easier /// to safely raise events. /// </summary> internal static class EventHelpers { /// <summary> /// Safely raises an event by storing a copy of the event's delegate /// in the <paramref name="handler"/> parameter and checking it for /// null before invoking it. /// </summary> /// <typeparam name="TEventArgs"></typeparam> /// <param name="sender">The object raising the event.</param> /// <param name="handler"><see cref="EventHandler{TEventArgs}"/> to be invoked</param> /// <param name="e">The <typeparamref name="TEventArgs"/> passed to <see cref="EventHandler{TEventArgs}"/></param> internal static void Raise<TEventArgs>(object sender, EventHandler<TEventArgs> handler, TEventArgs e) { if (handler != null) handler(sender, e); } /// <summary> /// Safely raises an event by storing a copy of the event's delegate /// in the <paramref name="handler"/> parameter and checking it for /// null before invoking it. /// </summary> /// <param name="sender">The object raising the event.</param> /// <param name="handler"><see cref="EventHandler"/> to be invoked</param> /// <param name="e">The <see cref="EventArgs"/> passed to <see cref="EventHandler"/></param> internal static void Raise(object sender, EventHandler handler, EventArgs e) { if (handler != null) handler(sender, e); } } }
40.933333
122
0.606406
[ "MIT" ]
06needhamt/MonoGame
MonoGame.Framework/EventHelpers.cs
1,844
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> //------------------------------------------------------------------------------ namespace DelonixRegiaHMS.Manage { public partial class Guest_Account_Add { /// <summary> /// alertSuccess control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl alertSuccess; /// <summary> /// alertError control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl alertError; /// <summary> /// lblMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl lblMessage; /// <summary> /// tbxEmail control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxEmail; /// <summary> /// tbxPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputPassword tbxPassword; /// <summary> /// tbxFirstName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxFirstName; /// <summary> /// tbxLastName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxLastName; /// <summary> /// tbxAddress control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxAddress; /// <summary> /// tbxPostalCode control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxPostalCode; /// <summary> /// tbxCountry control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText tbxCountry; /// <summary> /// btnSubmit control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlButton btnSubmit; } }
35.695652
85
0.547381
[ "MIT" ]
JiaJian/swen
DelonixRegia/DelonixRegiaHMS/Manage/Guest_Account_Add.aspx.designer.cs
4,107
C#
using System; using System.Runtime.Serialization; namespace Wexflow.Core.Service.Contracts { public enum LaunchType { Startup, Trigger, Periodic, Cron } [DataContract] public class WorkflowInfo:IComparable { [DataMember] public int Id { get; private set; } [DataMember] public string Name { get; private set; } [DataMember] public LaunchType LaunchType { get; private set; } [DataMember] public bool IsEnabled { get; private set; } [DataMember] public bool IsApproval { get; private set; } [DataMember] public bool IsWaitingForApproval { get; set; } [DataMember] public string Description { get; private set; } [DataMember] public bool IsRunning { get; set; } [DataMember] public bool IsPaused { get; set; } [DataMember] public string Period { get; set; } [DataMember] public string CronExpression { get; private set; } [DataMember] public string Path { get; set; } [DataMember] public bool IsExecutionGraphEmpty { get; set; } [DataMember] public Variable[] LocalVariables { get; set; } public WorkflowInfo(int id, string name, LaunchType launchType, bool isEnabled, bool isApproval, bool isWaitingForApproval, string desc, bool isRunning, bool isPaused, string period, string cronExpression, string path, bool isExecutionGraphEmpty, Variable[] localVariables) { Id = id; Name = name; LaunchType = launchType; IsEnabled = isEnabled; IsApproval = isApproval; IsWaitingForApproval = isWaitingForApproval; Description = desc; IsRunning = isRunning; IsPaused = isPaused; Period = period; CronExpression = cronExpression; Path = path; IsExecutionGraphEmpty = isExecutionGraphEmpty; LocalVariables = localVariables; } public int CompareTo(object obj) { var wfi = (WorkflowInfo)obj; return wfi.Id.CompareTo(Id); } } }
31.549296
281
0.588839
[ "MIT" ]
fossabot/Wexflow
src/dotnet/Wexflow.Core.Service.Contracts/WorkflowInfo.cs
2,242
C#
using IdentityModel; using IdentityServer4; using IdentityServer4.Events; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; namespace IdentityServerCenter.EFCore { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly ILogger<ExternalController> _logger; private readonly IEventService _events; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, ILogger<ExternalController> logger, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _logger = logger; _events = events; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public async Task<IActionResult> Challenge(string provider, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return await ProcessWindowsLoginAsync(returnUrl); } else { // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } if (_logger.IsEnabled(LogLevel.Debug)) { var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}"); _logger.LogDebug("External claims: {@claims}", externalClaims); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additional claims or properties // for the specific protocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); //ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); //ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user var isuser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username, IdentityProvider = provider, AdditionalClaims = additionalLocalClaims }; await HttpContext.SignInAsync(isuser, localSignInProps); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username, true, context?.ClientId)); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage("Redirect", returnUrl); } } return Redirect(returnUrl); } private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, treating windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.FindFirst(ClaimTypes.PrimarySid).Value)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return Redirect(props.RedirectUri); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return Challenge(AccountOptions.WindowsAuthenticationSchemeName); } } private (TestUser user, string provider, string providerUserId, IEnumerable<Claim> claims) FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = _users.FindByExternalProvider(provider, providerUserId); return (user, provider, providerUserId, claims); } private TestUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList()); return user; } private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var id_token = externalResult.Properties.GetTokenValue("id_token"); if (id_token != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } } //private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) //{ //} //private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) //{ //} } }
44.25
155
0.611647
[ "Apache-2.0" ]
zhongbodong/IdentityServer4
IdentityServerCenter.EFCore/Quickstart/Account/ExternalController.cs
11,505
C#
using System.Web; using System.Web.Mvc; namespace NurTek.Proxy.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19.214286
80
0.654275
[ "MIT" ]
mjsamet/NurTek.Proxy.Core
examples/NurTek.Proxy.Web/App_Start/FilterConfig.cs
271
C#
using System; using System.Linq; namespace SlimJim.Model { public sealed class VisualStudioVersion { private static readonly VisualStudioVersion vs2008 = new VisualStudioVersion("2008", "10.00", "9.0"); private static readonly VisualStudioVersion vs2010 = new VisualStudioVersion("2010", "11.00", "10.0"); private static readonly VisualStudioVersion vs2012 = new VisualStudioVersion("2012", "12.00", "12.0"); private static readonly VisualStudioVersion vs2013 = new VisualStudioVersion("2013", "12.00", "13.0"); private static readonly VisualStudioVersion vs2015 = new VisualStudioVersion("2015", "12.00", "14.0"); private static readonly VisualStudioVersion vs2017 = new VisualStudioVersion("2017", "12.00", "15.0"); private static readonly VisualStudioVersion vs2019 = new VisualStudioVersion("2019", "12.00", "16.0"); private string _year; private VisualStudioVersion(string year, string slnFileVersionNumber, string pathVersionNumber) { Year = year; SlnFileVersionNumber = slnFileVersionNumber; PathVersionNumber = pathVersionNumber; } /// <summary> /// Starting with Visual Studio 2015, the year, but the version is used in the solution header: /// Example VS2017 solution header: /// # Visual Studio 15 /// VisualStudioVersion = 15.0.26430.15 /// MinimumVisualStudioVersion = 10.0.40219.1 /// </summary> /// public string Year { get { if (_year == "2015" || _year == "2017" || _year == "2019") { return PathVersionNumber.Substring(0, 2); } return _year; } private set { _year = value; } } public string SlnFileVersionNumber { get; private set; } public string PathVersionNumber { get; private set; } public static VisualStudioVersion VS2008 { get { return vs2008; } } public static VisualStudioVersion VS2010 { get { return vs2010; } } public static VisualStudioVersion VS2012 { get { return vs2012; } } public static VisualStudioVersion VS2013 { get { return vs2013; } } public static VisualStudioVersion VS2015 { get { return vs2015; } } public static VisualStudioVersion VS2017 { get { return vs2017; } } public static VisualStudioVersion VS2019 { get { return vs2019; } } public static VisualStudioVersion[] AllExtentions { get { return new[] { vs2008, vs2010, vs2012, vs2013, vs2015, vs2017, vs2019 }; } } public static VisualStudioVersion ParseVersionString(string versionNumber) { return AllExtentions.FirstOrDefault(v => versionNumber.Contains(v._year)) ?? VS2019; } public override string ToString() { return string.Format("{0} ({1})", Year, SlnFileVersionNumber); } } }
26.54717
105
0.668443
[ "MIT" ]
jpk6789/SlimJim
src/SlimJim/Model/VisualStudioVersion.cs
2,814
C#
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.EndpointSpecifications { using Pipeline; using Pipeline.Pipes; using PublishPipeSpecifications; using Topology; using Topology.Observers; public class PublishPipeConfiguration : IPublishPipeConfiguration { readonly PublishPipeSpecification _specification; public PublishPipeConfiguration(IPublishTopology publishTopology) { _specification = new PublishPipeSpecification(); _specification.Connect(new TopologyPublishPipeSpecificationObserver(publishTopology)); } public PublishPipeConfiguration(IPublishPipeSpecification parentSpecification) { _specification = new PublishPipeSpecification(); _specification.Connect(new ParentPublishPipeSpecificationObserver(parentSpecification)); } public IPublishPipeSpecification Specification => _specification; public IPublishPipeConfigurator Configurator => _specification; public IPublishPipe CreatePipe() { return new PublishPipe(_specification); } } }
38.361702
101
0.703827
[ "Apache-2.0" ]
aallfredo/MassTransitPHP
src/MassTransit/Configuration/EndpointSpecifications/PublishPipeConfiguration.cs
1,805
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 iotevents-data-2018-10-23.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.IoTEventsData.Model; namespace Amazon.IoTEventsData { /// <summary> /// Interface for accessing IoTEventsData /// /// AWS IoT Events monitors your equipment or device fleets for failures or changes in /// operation, and triggers actions when such events occur. AWS IoT Events Data API commands /// enable you to send inputs to detectors, list detectors, and view or update a detector's /// status. /// </summary> #if NETSTANDARD13 [Obsolete("Support for .NET Standard 1.3 is in maintenance mode and will only receive critical bug fixes and security patches. Visit https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/migration-from-net-standard-1-3.html for further details.")] #endif public partial interface IAmazonIoTEventsData : IAmazonService, IDisposable { #region BatchPutMessage /// <summary> /// Sends a set of messages to the AWS IoT Events system. Each message payload is transformed /// into the input you specify (<code>"inputName"</code>) and ingested into any detectors /// that monitor that input. If multiple messages are sent, the order in which the messages /// are processed isn't guaranteed. To guarantee ordering, you must send messages one /// at a time and wait for a successful response. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchPutMessage service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchPutMessage service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/BatchPutMessage">REST API Reference for BatchPutMessage Operation</seealso> Task<BatchPutMessageResponse> BatchPutMessageAsync(BatchPutMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchUpdateDetector /// <summary> /// Updates the state, variable values, and timer settings of one or more detectors (instances) /// of a specified detector model. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchUpdateDetector service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchUpdateDetector service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/BatchUpdateDetector">REST API Reference for BatchUpdateDetector Operation</seealso> Task<BatchUpdateDetectorResponse> BatchUpdateDetectorAsync(BatchUpdateDetectorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDetector /// <summary> /// Returns information about the specified detector (instance). /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDetector service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDetector service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ResourceNotFoundException"> /// The resource was not found. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/DescribeDetector">REST API Reference for DescribeDetector Operation</seealso> Task<DescribeDetectorResponse> DescribeDetectorAsync(DescribeDetectorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDetectors /// <summary> /// Lists detectors (the instances of a detector model). /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDetectors service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDetectors service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ResourceNotFoundException"> /// The resource was not found. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/ListDetectors">REST API Reference for ListDetectors Operation</seealso> Task<ListDetectorsResponse> ListDetectorsAsync(ListDetectorsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
49.830508
256
0.678118
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/IoTEventsData/Generated/_netstandard/IAmazonIoTEventsData.cs
8,820
C#
using System.Collections; using System.Collections.Generic; using Joystick_Pack.Scripts.Joysticks; using UnityEngine; using UnityEditor; [CustomEditor(typeof(FloatingJoystick))] public class FloatingJoystickEditor : JoystickEditor { public override void OnInspectorGUI() { base.OnInspectorGUI(); if (background != null) { RectTransform backgroundRect = (RectTransform)background.objectReferenceValue; backgroundRect.anchorMax = Vector2.zero; backgroundRect.anchorMin = Vector2.zero; backgroundRect.pivot = center; } } }
27.909091
90
0.69544
[ "MIT" ]
neziruran/SirStudiosTest
Assets/Joystick Pack/Scripts/Editor/FloatingJoystickEditor.cs
616
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess_Game { class Bishop : Piece { public Bishop(String colour) : base(colour) { Name = "B"; } internal override bool validateMove(Move move, ChessBoard board) { if (Math.Abs(move.to.Item1 - move.from.Item1) == Math.Abs(move.to.Item2 - move.from.Item2) ) { // End position possible int numberOfMoves = Math.Abs(move.to.Item1 - move.from.Item1) - 1; int moveYPosition = move.from.Item2; int moveXPosition = move.from.Item1; int Xdir = move.to.Item1 - move.from.Item1 > 0 ? 1 : -1; int Ydir = move.to.Item2 - move.from.Item2 > 0 ? 1 : -1; for (int i = 0; i < numberOfMoves; i++) { moveXPosition += Xdir; moveYPosition += Ydir; if (board.Board[moveXPosition, moveYPosition].Piece != null) { return false; } } return board.getSquare(move.to).Piece == null || board.getSquare(move.to).Piece.Colour != Colour; } return false; } } }
33.560976
113
0.493459
[ "MIT" ]
DeepanshuKapoor/Chess-Game
selfchess/Bishop.cs
1,378
C#
//-------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExperienceExtractor.Data.Schema; namespace ExperienceExtractor.Components.PostProcessors { public class PartitionField : Field { public TimeSpan StaleTime { get; set; } } }
40.851852
95
0.625567
[ "Apache-2.0" ]
STDGA/experience-extractor
src/ExperienceExtractor.Components/PostProcessors/PartitionField.cs
1,105
C#
using System; using System.Web; using System.Web.SessionState; namespace MicroAPI.Demo { /// <summary> /// Demo 的摘要说明 /// </summary> public class Demo : MicroAPI { public Demo() { RegTextAction("get_server_time", getServerTime); RegJsonAction("get_server_info_json", getServerInfo_json); RegXmlAction("get_server_info_xml", getServerInfo_xml); } string getServerTime(HttpContext context) { return DateTime.Now.ToString(); } dynamic getServerInfo_json(HttpContext context) { return new { MachineName = Environment.MachineName, Platform = Environment.OSVersion.Platform.ToString(), OSVersion = Environment.OSVersion.VersionString }; } ServerInfo getServerInfo_xml(HttpContext context) { return new ServerInfo { MachineName = Environment.MachineName, Platform = Environment.OSVersion.Platform.ToString(), OSVersion = Environment.OSVersion.VersionString }; } } public class ServerInfo { public string MachineName { get; set; } public string Platform { get; set; } public string OSVersion { get; set; } } }
27.56
70
0.571118
[ "MIT" ]
starchen88/MicroAPI
MicroAPI/Demo/Demo.ashx.cs
1,390
C#
using System; namespace Library.API.Models { public class BookWithConcatenatedAuthorName { public Guid Id { get; set; } public string Author { get; set; } public string Title { get; set; } public string Description { get; set; } } }
17.625
47
0.606383
[ "MIT" ]
yangzuo0621/RESTfulAPIAspNetCore
src/Library/Library.API.Swagger/Models/BookWithConcatenatedAuthorName.cs
284
C#
// *********************************************************************** // Copyright (c) 2016 NUnit Project // // 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 Microsoft.Extensions.Testing.Abstractions; using NUnit.Framework; using NUnit.Runner.TestListeners; namespace NUnit.Runner.Test.TestListeners { [TestFixture] public class TestExecutionListenerTests { const string STARTED_TEST_CASE_XML = "<start-test id=\"1006\" name=\"CanSubtract(-1,-1,0)\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.CanSubtract(-1,-1,0)\" methodname=\"CanSubtract\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Runnable\" seed=\"1663476057\" start-time=\"2016-06-06 23:31:34Z\" />"; const string SUCCESS_TEST_CASE_XML = "<test-case id=\"1006\" name=\"CanSubtract(-1,-1,0)\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.CanSubtract(-1,-1,0)\" methodname=\"CanSubtract\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Runnable\" seed=\"1663476057\" result=\"Passed\" start-time=\"2016-06-06 23:31:34Z\" end-time=\"2016-06-06 23:31:34Z\" duration=\"0.000001\" asserts=\"1\" />"; const string IGNORE_TEST_CASE_XML = "<test-case id=\"1021\" name=\"IgnoredTest\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.IgnoredTest\" methodname=\"IgnoredTest\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Ignored\" seed=\"1580158007\" result=\"Skipped\" label=\"Ignored\" start-time=\"2016-06-06 23:45:17Z\" end-time=\"2016-06-06 23:45:17Z\" duration=\"0.000001\" asserts=\"0\">" + " <properties>" + " <property name=\"_SKIPREASON\" value=\"Ignored Test\" />" + " </properties>" + " <reason>" + " <message><![CDATA[Ignored Test]]></message>" + " </reason>" + "</test-case>"; const string EXPLICIT_TEST_CASE_XML = "<test-case id=\"1022\" name=\"ExplicitTest\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.ExplicitTest\" methodname=\"ExplicitTest\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Explicit\" seed=\"1196887609\" result=\"Skipped\" label=\"Explicit\" start-time=\"2016-06-06 23:45:17Z\" end-time=\"2016-06-06 23:45:17Z\" duration=\"0.000505\" asserts=\"0\">" + " <properties>" + " <property name=\"_SKIPREASON\" value=\"Explicit Test\" />" + " </properties>" + " <reason>" + " <message><![CDATA[Explicit Test]]></message>" + " </reason>" + "</test-case>"; const string ERROR_TEST_CASE_XML = "<test-case id=\"1018\" name=\"ErrorTest\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.ErrorTest\" methodname=\"ErrorTest\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Runnable\" seed=\"1658039280\" result=\"Failed\" label=\"Error\" start-time=\"2016-06-06 19:57:35Z\" end-time=\"2016-06-06 19:57:35Z\" duration=\"0.023031\" asserts=\"0\">" + " <failure>" + " <message><![CDATA[System.ArgumentException : Value does not fall within the expected range.]]></message>" + " <stack-trace><![CDATA[ at NUnitWithDotNetCoreRC2.Test.CalculatorTests.ErrorTest() in D:\\Src\\test\\NUnitWithDotNetCoreRC2.Test\\CalculatorTests.cs:line 50]]></stack-trace>" + " </failure>" + "</test-case>"; const string FAILED_TEST_CASE_XML = "<test-case id=\"1017\" name=\"FailedTest\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.FailedTest\" methodname=\"FailedTest\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Runnable\" seed=\"1355097167\" result=\"Failed\" start-time=\"2016-06-06 19:57:35Z\" end-time=\"2016-06-06 19:57:35Z\" duration=\"0.017533\" asserts=\"1\">" + " <failure>" + " <message><![CDATA[ Expected: 3" + "But was: 2" + "]]></message>" + " <stack-trace><![CDATA[at NUnitWithDotNetCoreRC2.Test.CalculatorTests.FailedTest() in D:\\Src\\test\\NUnitWithDotNetCoreRC2.Test\\CalculatorTests.cs:line 44" + "]]></stack-trace>" + " </failure>" + "</test-case>"; const string TESTCONTEXT_OUTPUT_TEST_CASE_XML = "<test-case id=\"1020\" name=\"TestWithTestContextOutput\" fullname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests.TestWithTestContextOutput\" methodname=\"TestWithTestContextOutput\" classname=\"NUnitWithDotNetCoreRC2.Test.CalculatorTests\" runstate=\"Runnable\" seed=\"1328488278\" result=\"Passed\" start-time=\"2016-06-06 19:57:35Z\" end-time=\"2016-06-06 19:57:35Z\" duration=\"0.000001\" asserts=\"0\">" + " <output><![CDATA[Test context output" + "]]></output>" + "</test-case>"; const string TEST_SUITE_XML = "<test-suite type=\"ParameterizedMethod\" id=\"1004\" name=\"LoadWithFrenchCanadianCulture\" fullname=\"NUnit.Framework.Internal.CultureSettingAndDetectionTests.LoadWithFrenchCanadianCulture\" runstate=\"Runnable\" testcasecount=\"1\">" + " <test-case id=\"0-3896\" name=\"LoadWithFrenchCanadianCulture\" fullname=\"NUnit.Framework.Internal.CultureSettingAndDetectionTests.LoadWithFrenchCanadianCulture\" methodname=\"LoadWithFrenchCanadianCulture\" classname=\"NUnit.Framework.Internal.CultureSettingAndDetectionTests\" runstate=\"Runnable\" seed=\"1611686282\" >" + " <properties>" + " <property name = \"SetCulture\" value=\"fr-CA\" />" + " <property name = \"UICulture\" value=\"en-CA\" />" + " </properties>" + " </test-case>" + "</test-suite>"; const string TEST_OUTPUT = "<test-output stream=\"theStream\" testname=\"NUnit.Output.Test\">This is the test output</test-output>"; const string TEST_OUTPUT_WITH_CDATA = "<test-output stream=\"theStream\" testname=\"NUnit.Output.CDataTest\"><![CDATA[Test CData output]]></test-output>"; Mocks.MockTestExecutionSink _sink; TestExecutionListener _listener; [OneTimeSetUp] public void OneTimeSetUp() { _sink = new Mocks.MockTestExecutionSink(); _listener = new TestExecutionListener(_sink, new CommandLineOptions("--designtime"), @"\src"); } [Test] public void CanParseSuccess() { var eventHandler = new EventHandler<TestEventArgs>((sender, args) => Assert.That(args.TestOutput, Is.EqualTo("Passed"))); _listener.TestFinished += eventHandler; _listener.OnTestEvent(SUCCESS_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.ErrorMessage, Is.Null.Or.Empty); Assert.That(testResult.ErrorStackTrace, Is.Null.Or.Empty); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Passed)); Assert.That(testResult.StartTime.Hour, Is.EqualTo(23)); Assert.That(testResult.EndTime.Minute, Is.EqualTo(31)); Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.000001d).Within(0.001d)); _listener.TestFinished -= eventHandler; } [Test] public void CanParseIgnoredTests() { var eventHandler = new EventHandler<TestEventArgs>((sender, args) => Assert.That(args.TestOutput, Is.EqualTo("Skipped"))); _listener.TestFinished += eventHandler; _listener.OnTestEvent(IGNORE_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.ErrorMessage, Is.EqualTo("Ignored Test")); Assert.That(testResult.ErrorStackTrace, Is.Null.Or.Empty); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Skipped)); Assert.That(testResult.StartTime.Hour, Is.EqualTo(23)); Assert.That(testResult.EndTime.Minute, Is.EqualTo(45)); Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.000001d).Within(0.001d)); _listener.TestFinished -= eventHandler; } [Test] public void CanParseExplicitTests() { var eventHandler = new EventHandler<TestEventArgs>((sender, args) => Assert.That(args.TestOutput, Is.EqualTo("Skipped"))); _listener.TestFinished += eventHandler; _listener.OnTestEvent(EXPLICIT_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.ErrorMessage, Is.EqualTo("Explicit Test")); Assert.That(testResult.ErrorStackTrace, Is.Null.Or.Empty); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Skipped)); Assert.That(testResult.StartTime.Hour, Is.EqualTo(23)); Assert.That(testResult.EndTime.Minute, Is.EqualTo(45)); Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.000001d).Within(0.001d)); _listener.TestFinished -= eventHandler; } [Test] public void CanParseTestErrors() { var eventHandler = new EventHandler<TestEventArgs>((sender, args) => Assert.That(args.TestOutput, Is.EqualTo("Failed"))); _listener.TestFinished += eventHandler; _listener.OnTestEvent(ERROR_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.ErrorMessage?.Trim(), Does.StartWith("System.ArgumentException")); Assert.That(testResult.ErrorStackTrace?.Trim(), Does.StartWith("at NUnitWithDotNetCoreRC2.Test.CalculatorTests.ErrorTest()")); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Failed)); Assert.That(testResult.StartTime.Hour, Is.EqualTo(19)); Assert.That(testResult.EndTime.Minute, Is.EqualTo(57)); Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.023031).Within(0.001d)); _listener.TestFinished -= eventHandler; } [Test] public void CanParseTestFailures() { var eventHandler = new EventHandler<TestEventArgs>((sender, args) => Assert.That(args.TestOutput, Is.EqualTo("Failed"))); _listener.TestFinished += eventHandler; _listener.OnTestEvent(FAILED_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.ErrorMessage?.Trim(), Does.StartWith("Expected: 3")); Assert.That(testResult.ErrorStackTrace?.Trim(), Does.StartWith("at NUnitWithDotNetCoreRC2.Test.CalculatorTests.FailedTest()")); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Failed)); Assert.That(testResult.StartTime.Hour, Is.EqualTo(19)); Assert.That(testResult.EndTime.Minute, Is.EqualTo(57)); Assert.That(testResult.Duration.TotalSeconds, Is.EqualTo(0.017533).Within(0.001d)); _listener.TestFinished -= eventHandler; } [Test] public void CanParseTestOutput() { _listener.OnTestEvent(TESTCONTEXT_OUTPUT_TEST_CASE_XML); var testResult = _sink.TestResult; Assert.That(testResult, Is.Not.Null); Assert.That(testResult.Messages.Count, Is.EqualTo(1)); Assert.That(testResult.Messages[0], Does.StartWith("Test context output")); } [Test] public void FiresTestFinished() { string test = null; string output = null; _listener.TestFinished += (sender, args) => { test = args.TestName; output = args.TestOutput; }; _listener.OnTestEvent(TESTCONTEXT_OUTPUT_TEST_CASE_XML); Assert.That(test, Is.Not.Null); Assert.That(test, Is.EqualTo("NUnitWithDotNetCoreRC2.Test.CalculatorTests.TestWithTestContextOutput")); Assert.That(output, Is.Not.Null); Assert.That(output, Does.StartWith("Test context output")); } [Test] public void FiresSuiteFinished() { string test = null; _listener.SuiteFinished += (sender, args) => test = args.TestName; _listener.OnTestEvent(TEST_SUITE_XML); Assert.That(test, Is.Not.Null); Assert.That(test, Is.EqualTo("NUnit.Framework.Internal.CultureSettingAndDetectionTests.LoadWithFrenchCanadianCulture")); } [TestCase(TEST_OUTPUT, "NUnit.Output.Test", "This is the test output")] [TestCase(TEST_OUTPUT_WITH_CDATA, "NUnit.Output.CDataTest", "Test CData output")] public void FiresTestOutput(string xml, string expectedTest, string expectedOutput) { string test = null; string stream = null; string output = null; _listener.TestOutput += (sender, args) => { test = args.TestName; stream = args.Stream; output = args.TestOutput; }; _listener.OnTestEvent(xml); Assert.That(test, Is.Not.Null); Assert.That(test, Is.EqualTo(expectedTest)); Assert.That(output, Is.Not.Null); Assert.That(output, Is.EqualTo(expectedOutput)); Assert.That(stream, Is.Not.Null); Assert.That(stream, Is.EqualTo("theStream")); } [Test] public void TestStarted() { bool raised = false; var eventHandler = new EventHandler<TestEventArgs>((sender, args) => raised = true); _listener.TestStarted += eventHandler; _listener.OnTestEvent(STARTED_TEST_CASE_XML); Assert.That(raised, Is.True); _listener.TestFinished -= eventHandler; } } }
52.083893
426
0.620063
[ "MIT" ]
devopsschool-sample-programs/dotnet-test-nunit
test/dotnet-test-nunit.test/TestListeners/TestExecutionListenerTests.cs
15,523
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Text; namespace com.tmobile.oss.security.taap.poptoken.builder.mstest { [TestClass] public class PopTokenBuilderUnitTest { string _publicRsaKeyPem; string _publicRsaKeyXml; string _privateRsaKeyPem; string _privateRsaKeyXml; string audience; string issuer; [TestInitialize] public void TestInitialize() { // 1) Create RSA public/private keys (one time) // Download OpenSSL for Windows // https://sourceforge.net/projects/gnuwin32/postdownload // # Create a 2048 bit Private RSA key in PKCS1 format // openssl genrsa -out private-key-pkcs1.pem 2048 //# Convert the Private RSA key to PKCS8 format. // openssl pkcs8 -topk8 -inform PEM -in private-key-pkcs1.pem -outform PEM -nocrypt -out private-key-pkcs8.pem //# Create a Public RSA key in PKCS8 format // openssl rsa -in private-key-pkcs8.pem -outform PEM -pubout -out public-key.pem // private-key-pkcs8.pem // public-key.pem // Private Key var privateKeyPemRsaStringBuilder = new StringBuilder(); privateKeyPemRsaStringBuilder.AppendLine("-----BEGIN PRIVATE KEY-----"); privateKeyPemRsaStringBuilder.AppendLine("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfZ1rsV+eOlhU1Yq1LQoxyTwznSEbtUQ+7916ww+xa5lOd3ldSxIJ/f/76oTwSnJtfhFlgxjxKqIRUa8O3NhRVZ5aEvMHpjHMeTNa7ewr7kpqWA5K0dJE8KsCB2Nx0+BGLgCEC3lpF37xZVIkczpzSfnQ4uCyuKPNuP1pZgAE27a5AuJU2pjGS4RXR77AlhHReVI1sT0CMbiTBnD4kJ4G9QfrayqD3FMNMvYOKeBZkLapir+NTblTnAzGyRu69hQLM0Dg9Xx8D28mFYTn8yBENxhZjtqOvxLcmpihp3zYA6fosG3z/gbhZBnTPfy3K1Z6DX/AZs4LgyS0hpoQxZsB3AgMBAAECggEAXOpJBITE08dF+4VWUA0tgp/zfIkT1tcuXbl2d4Dsr5ucV+Q3cGZdTuaUARGky5B/vLCPzKogkMAjynW6cnvSZGnqQdspCPK2U44kiMnTAAtXkmPoysk7sx+UcNuwvXmv+GmqVFq5sgsVZdixx5njrYrKQhmQ6b+zDateBddoXdRH+N9RrU5lwzqhwPnswO79cjPkHd5+3H/2dirNXa5VNK0ykdGd6f0V5aesDcZwl/96VGgOX9T23Ghf4gNt2JoAcp4wKwz2u0AUgM4sJP13FXbfRhB61c9aBjldzoTVpNZofI7xADxjVWl4HRdFB+5e3xGTbDbRU/Vl/4RWpO2c0QKBgQDNswWxPnuWcewQOWvcrmHuciEH4K22WAE/PfDKamInnXMp+OHdOX30v1dI2D+amDFxN0F/MKyMwqvvU471Man+uX3drg/GXBpMHNSEwZsJK6hgLFXMwgDLC4VIMm+e6TkgCFWVZXs2yL7bDPXBN9YEhepa5tmOIrOph/lBbj6WDwKBgQDGYi9HMxCCoYVPSXQ707/2kmMLuqTWuKpJzMKU6hjAbXzc6U5rfGC4fIPDqALX2CCwq3IEoNP6aBjaml2dNtsmTVMgN0JqAPdPeJoGIRp3qbsWz4dF0k72xU7HuvyX2hyCAom48EvsCxxi8giiyYL4ZXmxtTEhfvVvTWY2JgVXGQKBgEbjD+4iA0M4ZUq+Dx7Q9azPpfRqCFNThrJ9rRKEkOjoCL0JKQUs/+wtWG4hH+It2rQSf77OTlh/6fKjEBwNjnDbCbYwev031lQuh0ps0fnaEr955+OVY+KVSMw1nWPdKbORS7UdcNXTXnpsv/BjRpzubXIAJi8mZFXjJxHWZTkfAoGAWB+VUNNmKiEFzsqaT1kolKdCSBuIzbkKK+5BIVU72X7JUHhy1VxSuqDVBzzCxo7DNrdx1ox6nWlQYQrhOsz7XHBM1Kq3Xc9ADJVOFhruXumOqftV47YgTY4oCKEPQ4Un1Li75OMZVqk42tsY6vcIrr6k6EPMp0x2ShLfrH4HMUECgYEAip2YXm8yrDpWOSeL5fnqtA0zFnLc28Bxc47RRcy3jjMPQ9ADfRXfa087Te+WzG0p1wZJWSpTINQjTX+BdUMpmicgU7iX/QDDAVuvKImbb9TBCO0D9OZ+fnogq03MwerZyTuws2pS5BEytgdlcTYG+w+prDZi0ll8U+EQgWeaFUQ="); privateKeyPemRsaStringBuilder.AppendLine("-----END PRIVATE KEY-----"); _privateRsaKeyPem = privateKeyPemRsaStringBuilder.ToString(); // (Optional) Private Key converted from PEM format to XML format _privateRsaKeyXml = "<RSAKeyValue><Modulus>n2da7FfnjpYVNWKtS0KMck8M50hG7VEPu/desMPsWuZTnd5XUsSCf3/++qE8EpybX4RZYMY8SqiEVGvDtzYUVWeWhLzB6YxzHkzWu3sK+5KalgOStHSRPCrAgdjcdPgRi4AhAt5aRd+8WVSJHM6c0n50OLgsrijzbj9aWYABNu2uQLiVNqYxkuEV0e+wJYR0XlSNbE9AjG4kwZw+JCeBvUH62sqg9xTDTL2DingWZC2qYq/jU25U5wMxskbuvYUCzNA4PV8fA9vJhWE5/MgRDcYWY7ajr8S3JqYoad82AOn6LBt8/4G4WQZ0z38tytWeg1/wGbOC4MktIaaEMWbAdw==</Modulus><Exponent>AQAB</Exponent><P>zbMFsT57lnHsEDlr3K5h7nIhB+CttlgBPz3wympiJ51zKfjh3Tl99L9XSNg/mpgxcTdBfzCsjMKr71OO9TGp/rl93a4PxlwaTBzUhMGbCSuoYCxVzMIAywuFSDJvnuk5IAhVlWV7Nsi+2wz1wTfWBIXqWubZjiKzqYf5QW4+lg8=</P><Q>xmIvRzMQgqGFT0l0O9O/9pJjC7qk1riqSczClOoYwG183OlOa3xguHyDw6gC19ggsKtyBKDT+mgY2ppdnTbbJk1TIDdCagD3T3iaBiEad6m7Fs+HRdJO9sVOx7r8l9ocggKJuPBL7AscYvIIosmC+GV5sbUxIX71b01mNiYFVxk=</Q><DP>RuMP7iIDQzhlSr4PHtD1rM+l9GoIU1OGsn2tEoSQ6OgIvQkpBSz/7C1YbiEf4i3atBJ/vs5OWH/p8qMQHA2OcNsJtjB6/TfWVC6HSmzR+doSv3nn45Vj4pVIzDWdY90ps5FLtR1w1dNeemy/8GNGnO5tcgAmLyZkVeMnEdZlOR8=</DP><DQ>WB+VUNNmKiEFzsqaT1kolKdCSBuIzbkKK+5BIVU72X7JUHhy1VxSuqDVBzzCxo7DNrdx1ox6nWlQYQrhOsz7XHBM1Kq3Xc9ADJVOFhruXumOqftV47YgTY4oCKEPQ4Un1Li75OMZVqk42tsY6vcIrr6k6EPMp0x2ShLfrH4HMUE=</DQ><InverseQ>ip2YXm8yrDpWOSeL5fnqtA0zFnLc28Bxc47RRcy3jjMPQ9ADfRXfa087Te+WzG0p1wZJWSpTINQjTX+BdUMpmicgU7iX/QDDAVuvKImbb9TBCO0D9OZ+fnogq03MwerZyTuws2pS5BEytgdlcTYG+w+prDZi0ll8U+EQgWeaFUQ=</InverseQ><D>XOpJBITE08dF+4VWUA0tgp/zfIkT1tcuXbl2d4Dsr5ucV+Q3cGZdTuaUARGky5B/vLCPzKogkMAjynW6cnvSZGnqQdspCPK2U44kiMnTAAtXkmPoysk7sx+UcNuwvXmv+GmqVFq5sgsVZdixx5njrYrKQhmQ6b+zDateBddoXdRH+N9RrU5lwzqhwPnswO79cjPkHd5+3H/2dirNXa5VNK0ykdGd6f0V5aesDcZwl/96VGgOX9T23Ghf4gNt2JoAcp4wKwz2u0AUgM4sJP13FXbfRhB61c9aBjldzoTVpNZofI7xADxjVWl4HRdFB+5e3xGTbDbRU/Vl/4RWpO2c0Q==</D></RSAKeyValue>"; // Public Key var publicKeyPemRsaStringBuilder = new StringBuilder(); publicKeyPemRsaStringBuilder.AppendLine("-----BEGIN PUBLIC KEY-----"); publicKeyPemRsaStringBuilder.AppendLine("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn2da7FfnjpYVNWKtS0KMck8M50hG7VEPu/desMPsWuZTnd5XUsSCf3/++qE8EpybX4RZYMY8SqiEVGvDtzYUVWeWhLzB6YxzHkzWu3sK+5KalgOStHSRPCrAgdjcdPgRi4AhAt5aRd+8WVSJHM6c0n50OLgsrijzbj9aWYABNu2uQLiVNqYxkuEV0e+wJYR0XlSNbE9AjG4kwZw+JCeBvUH62sqg9xTDTL2DingWZC2qYq/jU25U5wMxskbuvYUCzNA4PV8fA9vJhWE5/MgRDcYWY7ajr8S3JqYoad82AOn6LBt8/4G4WQZ0z38tytWeg1/wGbOC4MktIaaEMWbAdwIDAQAB"); publicKeyPemRsaStringBuilder.AppendLine("-----END PUBLIC KEY-----"); _publicRsaKeyPem = publicKeyPemRsaStringBuilder.ToString(); // (Optional) Public Key converted from PEM format to XML format _publicRsaKeyXml = "<RSAKeyValue><Modulus>n2da7FfnjpYVNWKtS0KMck8M50hG7VEPu/desMPsWuZTnd5XUsSCf3/++qE8EpybX4RZYMY8SqiEVGvDtzYUVWeWhLzB6YxzHkzWu3sK+5KalgOStHSRPCrAgdjcdPgRi4AhAt5aRd+8WVSJHM6c0n50OLgsrijzbj9aWYABNu2uQLiVNqYxkuEV0e+wJYR0XlSNbE9AjG4kwZw+JCeBvUH62sqg9xTDTL2DingWZC2qYq/jU25U5wMxskbuvYUCzNA4PV8fA9vJhWE5/MgRDcYWY7ajr8S3JqYoad82AOn6LBt8/4G4WQZ0z38tytWeg1/wGbOC4MktIaaEMWbAdw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; // 3) Setup Audience/Issuer audience = "123"; issuer = "abc"; } /// <summary> /// Calling oAuth2 server to get bearer token with poptoken happy path (Pem Format) /// </summary> [TestMethod] public void PopTokenBuilder_Build_ValidateToken_OAuth2Example_PEMFormat_Success_Test1a() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { PopEhtsKeyEnum.Authorization.GetDescription(), "Basic UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/oauth2/v6/tokens" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act var popToken = popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyPem) // PEM format .Build(); var publicRsaSecurityKey = PopTokenBuilderUtils.CreateRsaSecurityKey(_publicRsaKeyPem); // PEM format var tokenValidationResult = PopTokenBuilderUtils.ValidateToken(popToken, issuer, audience, publicRsaSecurityKey); // Assert Assert.IsNotNull(popToken); Assert.IsNotNull(tokenValidationResult); Assert.IsTrue(tokenValidationResult.IsValid); Assert.IsTrue(tokenValidationResult.Claims.Count == 9); } /// <summary> /// Calling oAuth2 server to get bearer token with poptoken happy path (Xml Format - Optional) /// </summary> [TestMethod] public void PopTokenBuilder_Build_ValidateToken_OAuth2Example_XMLFormat_Success_Test1b() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { PopEhtsKeyEnum.Authorization.GetDescription(), "Basic UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/oauth2/v6/tokens" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act var popToken = popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyXml) // XML format .Build(); var publicRsaSecurityKey = PopTokenBuilderUtils.CreateRsaSecurityKey(_publicRsaKeyXml); // XML format var tokenValidationResult = PopTokenBuilderUtils.ValidateToken(popToken, issuer, audience, publicRsaSecurityKey); // Assert Assert.IsNotNull(popToken); Assert.IsNotNull(tokenValidationResult); Assert.IsTrue(tokenValidationResult.IsValid); Assert.IsTrue(tokenValidationResult.Claims.Count == 9); } /// <summary> /// Using bearer token to call WebApi endpoint with poptoken happy path (Pem Format) /// </summary> [TestMethod] public void PopTokenBuilder_Build_ValidateToken_ApiExample_PEMFormat_Success_Test2a() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { PopEhtsKeyEnum.ContentType.GetDescription(), PopEhtsKeyEnum.ApplicationJson.GetDescription() }, { PopEhtsKeyEnum.CacheControl.GetDescription(), PopEhtsKeyEnum.NoCache.GetDescription() }, { PopEhtsKeyEnum.Authorization.GetDescription(), "Bearer UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/commerce/v1/orders" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, { PopEhtsKeyEnum.Body.GetDescription(), "{\"orderId\": 100, \"product\": \"Mobile Phone\"}" } }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act var popToken = popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyPem) // Pem format .Build(); var publicRsaSecurityKey = PopTokenBuilderUtils.CreateRsaSecurityKey(_publicRsaKeyPem); // Pem format var tokenValidationResult = PopTokenBuilderUtils.ValidateToken(popToken, issuer, audience, publicRsaSecurityKey); // Assert Assert.IsNotNull(popToken); Assert.IsNotNull(tokenValidationResult); Assert.IsTrue(tokenValidationResult.IsValid); Assert.IsTrue(tokenValidationResult.Claims.Count == 9); } /// <summary> /// Using bearer token to call WebApi endpoint with poptoken happy path (Xml Format - Optional) /// </summary> [TestMethod] public void PopTokenBuilder_Build_ValidateToken_ApiExample_XmlFormat_Success_Test2b() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { PopEhtsKeyEnum.ContentType.GetDescription(), PopEhtsKeyEnum.ApplicationJson.GetDescription() }, { PopEhtsKeyEnum.CacheControl.GetDescription(), PopEhtsKeyEnum.NoCache.GetDescription() }, { PopEhtsKeyEnum.Authorization.GetDescription(), "Bearer UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/commerce/v1/orders" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, { PopEhtsKeyEnum.Body.GetDescription(), "{\"orderId\": 100, \"product\": \"Mobile Phone\"}" } }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act var popToken = popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyXml) // XML format .Build(); var publicRsaSecurityKey = PopTokenBuilderUtils.CreateRsaSecurityKey(_publicRsaKeyXml); // XML format var tokenValidationResult = PopTokenBuilderUtils.ValidateToken(popToken, issuer, audience, publicRsaSecurityKey); //Assert Assert.IsNotNull(popToken); Assert.IsNotNull(tokenValidationResult); Assert.IsTrue(tokenValidationResult.IsValid); Assert.IsTrue(tokenValidationResult.Claims.Count == 9); } [TestMethod] [ExpectedException(typeof(PopTokenBuilderException), "The ehtsKeyValueMap should not be null or empty and should not contain any null or empty ehts keys or values")] public void PopTokenBuilder_Build_EhtsKeyValueMap_Null_Test() { // Arrange var popTokenBuilder = new PopTokenBuilder(audience, issuer); HashSet<KeyValuePair<string, string>> ehtsKeyValueMap = null; // ehtsKeyValueMap is null // Act popTokenBuilder.SetEhtsKeyValueMap(ehtsKeyValueMap) .SignWith(_privateRsaKeyPem) .Build(); // Assert // Expected: PopTokenBuilderException } [TestMethod] [ExpectedException(typeof(PopTokenBuilderException), "The ehtsKeyValueMap should not contain more than 100 entries")] public void PopTokenBuilder_Build_EhtsKeyValueMap_GreaterThan100_Test() { // Arrange var popTokenBuilder = new PopTokenBuilder(audience, issuer); var keyValuePairDictionary = new Dictionary<string, string>(); for (var i = 0; i < 101; i++) // Create 101 key value pairs { keyValuePairDictionary.Add(popTokenBuilder.GetUniqueIdentifier(), popTokenBuilder.GetUniqueIdentifier()); } var ehtsKeyValueMap = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); // Act popTokenBuilder.SetEhtsKeyValueMap(ehtsKeyValueMap) .SignWith(_privateRsaKeyPem) .Build(); // Assert // Expected: PopTokenBuilderException } [TestMethod] [ExpectedException(typeof(PopTokenBuilderException), "A privateKeyXmlOrPemRsa shall be provided to sign the PoP token")] public void PopTokenBuilder_Build_Both_RsaSecurityKey_privateKeyXmlRsa_Null_Test() { // Arrange var popTokenBuilder = new PopTokenBuilder(audience, issuer); var keyValuePairDictionary = new Dictionary<string, string>(); for (var i = 0; i < 100; i++) { keyValuePairDictionary.Add(popTokenBuilder.GetUniqueIdentifier(), popTokenBuilder.GetUniqueIdentifier()); } var ehtsKeyValueMap = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); _privateRsaKeyPem = null; // privateKeyXmlRsa is null // Act popTokenBuilder.SetEhtsKeyValueMap(ehtsKeyValueMap) .SignWith(_privateRsaKeyPem) .Build(); // Assert // Expected: PopTokenBuilderException } [TestMethod] [ExpectedException(typeof(PopTokenBuilderException), "The ehtsKeyValueMap should not be null or empty and should not contain any null or empty ehts keys or values")] public void PopTokenBuilder_DoesContainAnyEmptyKeysOrValues_ValueIsNull_Test() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { PopEhtsKeyEnum.ContentType.GetDescription(), null }, // Value is null { PopEhtsKeyEnum.Authorization.GetDescription(), "Bearer UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/commerce/v1/orders" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, { PopEhtsKeyEnum.Body.GetDescription(), "{\"orderId\": 100, \"product\": \"Mobile Phone\"}" } }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyPem) .Build(); // Assert // Expected: PopTokenBuilderException } [TestMethod] [ExpectedException(typeof(PopTokenBuilderException), "The ehtsKeyValueMap should not be null or empty and should not contain any null or empty ehts keys or values")] public void PopTokenBuilder_DoesContainAnyEmptyKeysOrValues_KeyIsEmpty_Test() { // Arrange var keyValuePairDictionary = new Dictionary<string, string> { { string.Empty, PopEhtsKeyEnum.ApplicationJson.GetDescription() }, // Key is empty { PopEhtsKeyEnum.Authorization.GetDescription(), "Bearer UtKV75JJbVAewOrkHMXhLbiQ11SS" }, { PopEhtsKeyEnum.Uri.GetDescription(), "/commerce/v1/orders" }, { PopEhtsKeyEnum.HttpMethod.GetDescription(), PopEhtsKeyEnum.Post.GetDescription() }, { PopEhtsKeyEnum.Body.GetDescription(), "{\"orderId\": 100, \"product\": \"Mobile Phone\"}" } }; var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(keyValuePairDictionary); var popTokenBuilder = new PopTokenBuilder(audience, issuer); // Act popTokenBuilder.SetEhtsKeyValueMap(hashMapKeyValuePair) .SignWith(_privateRsaKeyPem) .Build(); // Assert // Expected: PopTokenBuilderException } } }
61.702265
1,714
0.68908
[ "Apache-2.0" ]
cprothm1/tmobile-api-security-lib
poptoken-lib/poptoken-builder/cs-lib-tmobile-oss-poptoken-builder/poptoken.builder.test/PopTokenBuilder.UnitTest.cs
19,066
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ServeurCShark; using System.ServiceModel; namespace AppliServeurCShark { class Program { static void Main(string[] args) { /*Uri baseAddress = new Uri("http://localhost:53942"); var serveur = new Service1(); var host = new ServiceHost(serveur); */ // en cas de pb d'accès à l'url au lancement sous windows, ouvrir la console en admin et entrer la commande: // netsh http add urlacl url=http://+:53942/ delegate=yes user=le nom de l'user windows using (ServiceHost host = new ServiceHost(typeof(Service1))) { host.Open(); Console.WriteLine("Server is running"); Console.ReadKey(); host.Close(); } } } }
27.142857
120
0.570526
[ "Unlicense" ]
groupeCShark/ServeurLauncher
AppliServeurCShark/Program.cs
954
C#
using System; namespace Orchard.Scripting.Compiler { public class Token { public TokenKind Kind { get; set; } public int Position { get; set; } public object Value { get; set; } public override string ToString() { return Value == null ? String.Format("Token '{0}' at position {1}", Kind, Position) : String.Format("Token '{0}' ({1}) at position {2}", Kind, Value, Position); } } }
34.076923
172
0.591422
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Modules/Orchard.Scripting/Compiler/Token.cs
445
C#
namespace ZetaShortPaths; [UsedImplicitly] public static class DirectoryInfoExtensions { [UsedImplicitly] public static FileSystemInfo[] GetFileSystemInfos(this DirectoryInfo i, SearchOption searchOption) { return i.GetFileSystemInfos(@"*", searchOption); } [UsedImplicitly] public static void MoveTo(this DirectoryInfo i, DirectoryInfo to, bool ovewriteExisting = true) { doCopyDir(i.FullName, to.FullName, ovewriteExisting); } [UsedImplicitly] public static bool IsEmpty(this DirectoryInfo i) { return ZspIOHelper.IsDirectoryEmpty(i); } private static void doCopyDir(string sourceFolder, string destFolder, bool ovewriteExisting) { // https://stackoverflow.com/a/3911658/107625 if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder); // Get Files & Copy var files = Directory.GetFiles(sourceFolder); foreach (var file in files) { var name = Path.GetFileName(file); // ADD Unique File Name Check to Below. var dest = ZspPathHelper.Combine(destFolder, name); File.Copy(file, dest, ovewriteExisting); } // Get dirs recursively and copy files var folders = Directory.GetDirectories(sourceFolder); foreach (var folder in folders) { var name = Path.GetFileName(folder); var dest = ZspPathHelper.Combine(destFolder, name); doCopyDir(folder, dest, ovewriteExisting); } } }
30.764706
102
0.648821
[ "Apache-2.0" ]
UweKeim/ZetaShortPaths
Source/Runtime/DirectoryInfoExtensions.cs
1,571
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace RedemptionEngine.ObjectClasses { public class CharacterAttribute { private string name; //The attribute/stat name private int attributeValue; //the current value of the attribute/stat private int maxValue; //the maximum value of the attribute/stat public CharacterAttribute(string nm, int val, int max) { name = nm; attributeValue = val; maxValue = max; } public string Name //returns name of the attribute { get { return name; } } public int Value //get/set the value of your attribute (can be negative to infinity) { get { return attributeValue; } set { this.attributeValue = (int)MathHelper.Clamp(value, Int32.MinValue, maxValue); } } public int MaxValue //maximum value { get { return maxValue; } set { this.maxValue = value; } } } }
26.511628
93
0.578947
[ "MIT" ]
Erbelding/Redemption
PROJECT/REDEMPTION/RedemptionEngine/ObjectClasses/CharacterAttribute.cs
1,142
C#
using Assets.Scripts.Animations; using Assets.Scripts.Systems; using UnityEngine; namespace Assets.Scripts.Physics { [RequireComponent(typeof(CustomCollision))] public class Character : MonoBehaviour { [HideInInspector] public CustomCollision collision; [SerializeField] private CustomCollision bodyCollision; private Vector2 currentVelocity; public bool facingRight = true; [SerializeField] private float maxJumpHeight; [SerializeField] private float minJumpDivisor; [SerializeField] private float timeToMaxJumpHeight; private float gravity; private float jumpVelocity; private float minJumpVelocity; [SerializeField] private float moveSpeed; [SerializeField] private LayerMask collisionMask; private float xInput; private bool walkingBackwards = false; private bool onSecondJump = false; [SerializeField] private Animator robotAnimator; [SerializeField] private WheelAnimation wheelAnimation; [SerializeField] private AudioClip jumpSound; [SerializeField] private AudioClip secondJumpSound; [SerializeField] private bool ignoreSound; private void Awake() { collision = GetComponent<CustomCollision>(); CalculateGravity(); if (!facingRight) transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); } [ContextMenu("Recalculate gravity")] private void CalculateGravity() { gravity = (-2 * maxJumpHeight) / timeToMaxJumpHeight * 2; jumpVelocity = Mathf.Abs(gravity) * timeToMaxJumpHeight; minJumpVelocity = jumpVelocity / minJumpDivisor; } public void SetXInput(float xInput) { walkingBackwards = false; this.xInput = xInput; } public void OnJumpButtonDown() { if (collision.info.bellow) { if (!ignoreSound) SoundSystem.Instance.PlaySoundEffect(jumpSound); currentVelocity.y = jumpVelocity; } else if (CanJumpAgain()) { robotAnimator.Play("jetpack-on"); SoundSystem.Instance.PlaySoundEffect(secondJumpSound); currentVelocity.y = jumpVelocity; } } public bool CanJumpAgain() { if (onSecondJump) { return false; } else { onSecondJump = true; return true; } } public void OnJumpButtonUp() { if (currentVelocity.y > minJumpVelocity) { currentVelocity.y = minJumpVelocity; } } public void ResetCurrentVelocity() { currentVelocity = Vector2.zero; } private void FixedUpdate() { ApplyGravityIfEnabled(); TestFaceSwap(); currentVelocity.x = xInput * moveSpeed; Vector2 velocity = currentVelocity * Time.deltaTime; collision.UpdateRayOrigins(); bodyCollision.UpdateRayOrigins(); collision.info.Reset(); bodyCollision.info.Reset(); if (velocity.x != 0) { collision.HandleHorizontalCollisions(ref velocity, collisionMask); bodyCollision.HandleHorizontalCollisions(ref velocity, collisionMask); } if (velocity.y != 0) { collision.HandleVerticalCollisions(ref velocity, collisionMask); } wheelAnimation.SetVelocity(Mathf.Abs(velocity.x)); transform.Translate(velocity); if (collision.info.bellow) { if (onSecondJump) onSecondJump = false; } if (collision.info.bellow || collision.info.above) { currentVelocity.y = 0; } } private void ApplyGravityIfEnabled() { currentVelocity.y += gravity * Time.deltaTime; } private void TestFaceSwap() { if (walkingBackwards) return; if (facingRight && currentVelocity.x < 0 || !facingRight && currentVelocity.x > 0) SwapFaceDirection(); } public void SwapFaceDirection() { facingRight = !facingRight; transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); } } public enum CharacterEvent { MOVEMENT_REESTABLISHED, } }
29.329268
124
0.571102
[ "MIT" ]
theGusPassos/Broken-Delivery-Service
Assets/Scripts/Physics/Character.cs
4,812
C#
using System; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using System.Net.Sockets; using System.Security.Authentication; using System.Text; namespace Rosie.SmartThings { public class SmartThingsUpdateListener { SmartThingsApi api; public SmartThingsUpdateListener (SmartThingsApi api) { this.api = api; } public bool IsConnected => client?.Connected ?? false; public event Action<SmartThingsUpdate> UpdateReceived; public UserLocation Location { get; set; } public async Task StartListening () { if (IsConnected) return; Location = Location ?? await api.GetDefaultLocation (); var clientId = await api.GetSocketClientID (Location); int port = 443; int.TryParse (Location.Shard.Client.Port, out port); Task.Run (() => { RunClient (clientId, Location.Shard.Client.Host, port);}); } public void Close () { sslStream?.Dispose (); sslStream = null; client?.Close (); client = null; } SslStream sslStream; TcpClient client; void RunClient (string clientId,string server, int port) { try { client = new TcpClient (server, port); Console.WriteLine ("Client connected."); sslStream = new SslStream ( client.GetStream (), false, new RemoteCertificateValidationCallback (ValidateServerCertificate), null ); // The server name must match the name on the server certificate. try { sslStream.AuthenticateAsClient (server); } catch (AuthenticationException e) { Console.WriteLine ("Exception: {0}", e.Message); if (e.InnerException != null) { Console.WriteLine ("Inner exception: {0}", e.InnerException.Message); } Console.WriteLine ("Authentication failed - closing the connection."); client.Close (); return; } //Send the register command SendMessage ($"register {clientId}"); //Send a ping every 30 seconds Task.Run (async () => { while (IsConnected) { await Task.Delay (TimeSpan.FromSeconds (300)); SendMessage ("ping"); } }); while (IsConnected) { try { // Read message from the server. ReadMessage (); } catch (Exception ex) { Console.WriteLine (ex); } } // Close the client connection. client.Close (); Console.WriteLine ("Client closed."); } catch (Exception ex) { Console.WriteLine (ex); } } void SendMessage (string message) { sslStream.Write (Encoding.UTF8.GetBytes (message)); sslStream.Flush (); } StringBuilder messageData = new StringBuilder (); void ReadMessage () { // Read the message sent by the server. // The end of the message is signaled using the // "<EOF>" marker. byte [] buffer = new byte [2048]; int bytes = -1; do { bytes = sslStream.Read (buffer, 0, buffer.Length); // Use Decoder class to convert from bytes to UTF8 // in case a character spans two buffers. Decoder decoder = Encoding.UTF8.GetDecoder (); char [] chars = new char [decoder.GetCharCount (buffer, 0, bytes)]; decoder.GetChars (buffer, 0, bytes, chars, 0); messageData.Append (chars); var message = messageData.ToString (); if (!message.Contains ("\n")) continue; messageData.Clear (); var messages = message.Split (new [] { '\n' }, StringSplitOptions.None); foreach (var m in messages) { if (!HandleMessage (m)) { messageData.Append (m); } } } while (bytes != 0); } bool HandleMessage (string message) { if (string.IsNullOrWhiteSpace(message) || message.StartsWith ("register") || message.StartsWith ("echo")) return true; try { var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<SmartThingsUpdate> (message); SendMessage ($"ack {resp.Event.Id}"); UpdateReceived?.Invoke (resp); Console.WriteLine ("Server says: {0}", message); return true; } catch (Exception ex) { Console.WriteLine (ex); return false; } } public static bool ValidateServerCertificate ( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; Console.WriteLine ("Certificate error: {0}", sslPolicyErrors); // Do not allow this client to communicate with unauthenticated servers. return false; } } }
27.277778
108
0.658746
[ "Apache-2.0" ]
Clancey/Rosie
src/SmartThings/Rosie.SmartThings/SmartThingsUpdateListener.cs
4,421
C#
using System; using System.Collections.Generic; using System.Text; using ProtoBuf; namespace PlusServer.Data { [ProtoContract] public class GameUser { [ProtoMember(1)] public int UserId { get; set; } [ProtoMember(2)] public string NickName { get; set; } } }
18.111111
45
0.595092
[ "MIT" ]
jessegame/plusgame
PlusServer/Data/GameUser.cs
328
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SistemaVentas.Datos; namespace SistemaVentas.Presentacion.REPORTES { public partial class MenuReportes : Form { public MenuReportes() { InitializeComponent(); } int idusuario; private void MenuReportes_Load(object sender, EventArgs e) { PanelBienvenida.Visible = true; PanelBienvenida.Dock = DockStyle.Fill; } private void btnVentas_Click(object sender, EventArgs e) { panelVentas.Visible = true; panelVentas.Dock = DockStyle.Fill; PanelBienvenida.Visible = false; PanelProductos.Visible = false; PanelPorCobrarPagar.Visible = false; //--------------Paneles panel6.Enabled = false; PanelEmpleado.Visible = false; //Botones btnVentas.BackColor = Color.White; btnVentas.ForeColor = Color.OrangeRed; btnCobrar.BackColor = Color.FromArgb(242, 243, 244); btnCobrar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.BackColor = Color.FromArgb(242, 243, 244); BtnProductos.ForeColor = Color.FromArgb(64, 64, 64); BtnProductos.BackColor = Color.FromArgb(242, 243, 244); //Controles internos chekFiltros.Checked = false; PanelFiltros.Visible = false; } private void btnResumenVentas_Click(object sender, EventArgs e) { panel6.Enabled = true; btnResumenVentas.ForeColor = Color.OrangeRed; btnEmpleado.ForeColor = Color.DimGray; PResumenVentas.Visible = true; PVentasPorempleado.Visible = false; btnHoy.ForeColor = Color.OrangeRed; PanelEmpleado.Visible = false; chekFiltros.Checked = false; PanelFiltros.Visible = false; TFILTROS.ForeColor = Color.DimGray; ReporteResumenVentasHoy(); } private void ReporteResumenVentasHoy() { DataTable dt = new DataTable(); Obtener_datos.ReporteResumenVentasHoy(ref dt); ReporteVentas.ResumenVentas rpt = new ReporteVentas.ResumenVentas(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.RefreshReport(); } private void btnHoy_Click(object sender, EventArgs e) { if (PResumenVentas.Visible == true) { ReporteResumenVentasHoy(); } if (PVentasPorempleado.Visible == true) { ReporteResumenVentasHoyEmpleado(); } btnHoy.ForeColor = Color.OrangeRed; chekFiltros.Checked = false; PanelFiltros.Visible = false; TFILTROS.ForeColor = Color.DimGray; } private void chekFiltros_CheckedChanged(object sender, EventArgs e) { if (chekFiltros.Checked==true) { if (PResumenVentas.Visible==true) { ReporteResumenVentasFechas(); } if (PVentasPorempleado.Visible==true) { ReporteResumenVentasEmpleadoFechas(); } btnHoy.ForeColor = Color.DimGray; PanelFiltros.Visible = true; TFILTROS.ForeColor = Color.OrangeRed; } else { if (PResumenVentas.Visible == true) { ReporteResumenVentasHoy(); } if (PVentasPorempleado.Visible == true) { ReporteResumenVentasHoyEmpleado(); } btnHoy.ForeColor = Color.OrangeRed; PanelFiltros.Visible = false; TFILTROS.ForeColor = Color.DimGray; } } private void ReporteResumenVentasFechas() { DataTable dt = new DataTable(); Obtener_datos.ReporteResumenVentasFechas(ref dt, TXTFI.Value, TXTFF.Value); ReporteVentas.ResumenVentas rpt = new ReporteVentas.ResumenVentas(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.RefreshReport(); } private void btnEmpleado_Click(object sender, EventArgs e) { panel6.Enabled = true; btnResumenVentas.ForeColor = Color.DimGray; btnEmpleado.ForeColor = Color.OrangeRed; PResumenVentas.Visible = false; PVentasPorempleado.Visible = true; btnHoy.ForeColor = Color.OrangeRed; chekFiltros.Checked = false; PanelFiltros.Visible = false; TFILTROS.ForeColor = Color.DimGray; PanelEmpleado.Visible = true; mostrarUsuarios(); ReporteResumenVentasHoyEmpleado(); } private void ReporteResumenVentasHoyEmpleado() { DataTable dt = new DataTable(); Obtener_datos.ReporteResumenVentasHoyEmpleado(ref dt, idusuario); ReporteVentas.ResumenVentas rpt = new ReporteVentas.ResumenVentas(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.RefreshReport(); } private void ReporteResumenVentasEmpleadoFechas() { DataTable dt = new DataTable(); Obtener_datos.ReporteResumenVentasEmpleadoFechas(ref dt, idusuario,TXTFI.Value , TXTFF.Value ); ReporteVentas.ResumenVentas rpt = new ReporteVentas.ResumenVentas(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer1.RefreshReport(); } private void mostrarUsuarios() { DataTable dt = new DataTable(); Obtener_datos.mostrarUsuarios(ref dt); txtEmpleado.DisplayMember = "nombre"; MessageBox.Show(txtEmpleado.ValueMember.ToString()); txtEmpleado.ValueMember = "idUsuario"; txtEmpleado.DataSource = dt; } private void txtEmpleado_SelectedIndexChanged(object sender, EventArgs e) { idusuario =Convert.ToInt32 ( txtEmpleado.SelectedValue); if (chekFiltros.Checked==true ) { ReporteResumenVentasEmpleadoFechas(); } else { ReporteResumenVentasHoyEmpleado(); } } private void TXTFI_ValueChanged(object sender, EventArgs e) { validarFiltros(); } private void TXTFF_ValueChanged(object sender, EventArgs e) { validarFiltros(); } private void validarFiltros() { if (chekFiltros.Checked == true) { if (PResumenVentas.Visible == true) { ReporteResumenVentasFechas(); } if (PVentasPorempleado.Visible == true) { ReporteResumenVentasEmpleadoFechas(); } } } private void btnCobrar_Click(object sender, EventArgs e) { panelVentas.Visible = false; PanelBienvenida.Visible = false; PanelProductos.Visible = false; PanelPorCobrarPagar.Visible = true; PanelPorCobrarPagar.Dock = DockStyle.Fill; //Botones btnVentas.BackColor = Color.FromArgb(242, 243, 244); btnVentas.ForeColor = Color.FromArgb(64, 64, 64); btnCobrar.BackColor = Color.White; btnCobrar.ForeColor = Color.OrangeRed; BtnPagar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.BackColor = Color.FromArgb(242, 243, 244); BtnProductos.ForeColor = Color.FromArgb(64, 64, 64); BtnProductos.BackColor = Color.FromArgb(242, 243, 244); ReporteCuestasPorCobrar(); } private void ReporteCuestasPorCobrar() { DataTable dt = new DataTable(); Obtener_datos.ReporteCuestasPorCobrar(ref dt); ReportePorCobrar.ReporteCobrar rpt = new ReportePorCobrar.ReporteCobrar(); rpt.Table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer2.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer2.RefreshReport(); } private void BtnPagar_Click(object sender, EventArgs e) { panelVentas.Visible = false; PanelBienvenida.Visible = false; PanelProductos.Visible = false; PanelPorCobrarPagar.Visible = true; PanelPorCobrarPagar.Dock = DockStyle.Fill; //Botones btnVentas.BackColor = Color.FromArgb(242, 243, 244); btnVentas.ForeColor = Color.FromArgb(64, 64, 64); btnCobrar.BackColor = Color.FromArgb(242, 243, 244); btnCobrar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.ForeColor = Color.OrangeRed; BtnPagar.BackColor = Color.White; BtnProductos.ForeColor = Color.FromArgb(64, 64, 64); BtnProductos.BackColor = Color.FromArgb(242, 243, 244); ReporteCuestasPorPagar(); } private void ReporteCuestasPorPagar() { DataTable dt = new DataTable(); Obtener_datos.ReporteCuestasPorPagar(ref dt); ReportePorPagar.ReportePagar rpt = new ReportePorPagar.ReportePagar(); rpt.Table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer2.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' reportViewer2.RefreshReport(); } private void BtnProductos_Click(object sender, EventArgs e) { panelVentas.Visible = false; PanelBienvenida.Visible = false; PanelProductos.Visible = true; PanelProductos.Dock = DockStyle.Fill; PanelPorCobrarPagar.Visible = false; //Botones btnVentas.BackColor = Color.FromArgb(242, 243, 244); btnVentas.ForeColor = Color.FromArgb(64, 64, 64); btnCobrar.BackColor = Color.FromArgb(242, 243, 244); btnCobrar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.ForeColor = Color.FromArgb(64, 64, 64); BtnPagar.BackColor = Color.FromArgb(242, 243, 244); BtnProductos.ForeColor = Color.OrangeRed; BtnProductos.BackColor = Color.White; //Paneles PInventarios.Visible = false; Pvencidos.Visible = false; PStockBajo.Visible = false; ReportViewer3.Visible = false; } private void btnInventarios_Click(object sender, EventArgs e) { PInventarios.Visible = true; PStockBajo.Visible = false; Pvencidos.Visible = false; ReportViewer3.Visible = true; imprimir_inventarios_todos(); } private void imprimir_inventarios_todos() { DataTable dt = new DataTable(); Obtener_datos.imprimir_inventarios_todos(ref dt); REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportInventarios_Todos rpt = new REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportInventarios_Todos(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.RefreshReport(); } private void btnPvencidos_Click(object sender, EventArgs e) { PInventarios.Visible = false; PStockBajo.Visible = false; Pvencidos.Visible = true; ReportViewer3.Visible = true; mostrar_productos_vencidos(); } private void mostrar_productos_vencidos() { DataTable dt = new DataTable (); Obtener_datos.mostrar_productos_vencidos(ref dt); REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportePVencidos rpt = new REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportePVencidos(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.RefreshReport(); } private void btnStockBajo_Click(object sender, EventArgs e) { PInventarios.Visible = false; PStockBajo.Visible = true; Pvencidos.Visible = false; ReportViewer3.Visible = true; mostrarProdctosMinimo(); } private void mostrarProdctosMinimo() { DataTable dt = new DataTable(); Obtener_datos.MOSTRAR_Inventarios_bajo_minimo(ref dt); REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportePbajomin rpt = new REPORTES_DE_KARDEX_listo.REPORTES_DE_INVENTARIOS_todos.ReportePbajomin(); rpt.table1.DataSource = dt; rpt.DataSource = dt; #pragma warning disable CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.Report = rpt; #pragma warning restore CS0618 // 'ReportViewerBase.Report' está obsoleto: 'Telerik.ReportViewer.WinForms.ReportViewer.Report is now obsolete. Please use the Telerik.ReportViewer.WinForms.ReportViewer.ReportSource property instead. For more information, please visit: http://www.telerik.com/support/kb/reporting/general/q2-2012-api-changes-reportsources.aspx#winformsviewer.' ReportViewer3.RefreshReport(); } } }
53.701847
375
0.663342
[ "MIT" ]
pedromaironi/Pedroveloper
SistemaVentas/Presentacion/REPORTES/MenuReportes.cs
20,373
C#
namespace FortniteReplayAnalyzer.ExternalApis { public class S3Response { public bool Success { get; internal set; } public string Guid { get; internal set; } } }
23.875
50
0.65445
[ "MIT" ]
flyrev/Fortnite-Replay-Analyzer
app/ExternalApis/S3Response.cs
193
C#
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** namespace MBF.Test { #region -- Using Directive -- using System.Collections.Generic; using MBF.Algorithms.Alignment; using NUnit.Framework; #endregion -- Using Directive -- /// <summary> /// Test Mumer implementation. /// </summary> [TestFixture] public class LongestIncreasingSubsequenceTest { /// <summary> /// Test LongestIncreasingSubsequence with MUM set which has neither /// crosses nor overlaps /// </summary> [Test] public void TestLISWithoutCrossAndOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> MUM = new List<MaxUniqueMatch>(); MaxUniqueMatch mum = null; mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 3; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 1; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 3; mum.SecondSequenceStart = 3; mum.SecondSequenceMumOrder = 2; MUM.Add(mum); ILongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); IList<MaxUniqueMatch> lisList = lis.GetLongestSequence(MUM); List<MaxUniqueMatch> expectedOutput = new List<MaxUniqueMatch>(); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 3; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 1; expectedOutput.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 3; mum.SecondSequenceStart = 3; mum.SecondSequenceMumOrder = 2; expectedOutput.Add(mum); Assert.IsTrue(this.CompareMumList(lisList, expectedOutput)); } /// <summary> /// Test LongestIncreasingSubsequence with MUM set which has crosses. /// First MUM is bigger /// </summary> [Test] public void TestLISWithCross1() { // Create a list of Mum classes. List<MaxUniqueMatch> MUM = new List<MaxUniqueMatch>(); MaxUniqueMatch mum = null; mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 4; mum.SecondSequenceStart = 4; mum.SecondSequenceMumOrder = 1; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 3; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 2; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 10; mum.FirstSequenceMumOrder = 3; mum.Length = 3; mum.SecondSequenceStart = 10; mum.SecondSequenceMumOrder = 3; MUM.Add(mum); ILongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); IList<MaxUniqueMatch> lisList = lis.GetLongestSequence(MUM); List<MaxUniqueMatch> expectedOutput = new List<MaxUniqueMatch>(); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 4; mum.SecondSequenceStart = 4; mum.SecondSequenceMumOrder = 1; expectedOutput.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 10; mum.FirstSequenceMumOrder = 3; mum.Length = 3; mum.SecondSequenceStart = 10; mum.SecondSequenceMumOrder = 3; expectedOutput.Add(mum); Assert.IsTrue(this.CompareMumList(lisList, expectedOutput)); } /// <summary> /// Test LongestIncreasingSubsequence with MUM set which has crosses. /// Second MUM is bigger /// </summary> [Test] public void TestLISWithCross2() { // Create a list of Mum classes. List<MaxUniqueMatch> MUM = new List<MaxUniqueMatch>(); MaxUniqueMatch mum = null; mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 3; mum.SecondSequenceStart = 4; mum.SecondSequenceMumOrder = 1; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 4; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 2; MUM.Add(mum); ILongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); IList<MaxUniqueMatch> lisList = lis.GetLongestSequence(MUM); List<MaxUniqueMatch> expectedOutput = new List<MaxUniqueMatch>(); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 4; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 2; expectedOutput.Add(mum); Assert.IsTrue(this.CompareMumList(lisList, expectedOutput)); } /// <summary> /// Test LongestIncreasingSubsequence with MUM set which has overlap /// </summary> [Test] public void TestLISWithCrossAndOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> MUM = new List<MaxUniqueMatch>(); MaxUniqueMatch mum = null; mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 5; mum.SecondSequenceStart = 5; mum.SecondSequenceMumOrder = 1; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 3; mum.FirstSequenceMumOrder = 2; mum.Length = 5; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 2; MUM.Add(mum); ILongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); IList<MaxUniqueMatch> lisList = lis.GetLongestSequence(MUM); List<MaxUniqueMatch> expectedOutput = new List<MaxUniqueMatch>(); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 5; mum.SecondSequenceStart = 5; mum.SecondSequenceMumOrder = 1; expectedOutput.Add(mum); Assert.IsTrue(this.CompareMumList(lisList, expectedOutput)); } /// <summary> /// Test LongestIncreasingSubsequence with MUM set which has overlap /// </summary> [Test] public void TestLISWithOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> MUM = new List<MaxUniqueMatch>(); MaxUniqueMatch mum = null; mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 4; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 1; MUM.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 2; mum.FirstSequenceMumOrder = 2; mum.Length = 5; mum.SecondSequenceStart = 4; mum.SecondSequenceMumOrder = 2; MUM.Add(mum); ILongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); IList<MaxUniqueMatch> lisList = lis.GetLongestSequence(MUM); List<MaxUniqueMatch> expectedOutput = new List<MaxUniqueMatch>(); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 0; mum.FirstSequenceMumOrder = 1; mum.Length = 4; mum.SecondSequenceStart = 0; mum.SecondSequenceMumOrder = 1; expectedOutput.Add(mum); mum = new MaxUniqueMatch(); mum.FirstSequenceStart = 4; mum.FirstSequenceMumOrder = 2; mum.Length = 3; mum.SecondSequenceStart = 6; mum.SecondSequenceMumOrder = 2; expectedOutput.Add(mum); Assert.IsTrue(this.CompareMumList(lisList, expectedOutput)); } /// <summary> /// Compares two list of Mum against their SecondSequeceMumOrder value. /// </summary> /// <param name="lisList">First list to be compared.</param> /// <param name="expectedOutput">Second list to be compared.</param> /// <returns>true if the order of their SecondSequeceMumOrder are same.</returns> private bool CompareMumList( IList<MaxUniqueMatch> lisList, IList<MaxUniqueMatch> expectedOutput) { if (lisList.Count == expectedOutput.Count) { bool correctOutput = true; for (int index = 0; index < expectedOutput.Count; index++) { if (lisList[index].FirstSequenceStart != expectedOutput[index].FirstSequenceStart) { correctOutput = false; break; } if (lisList[index].FirstSequenceMumOrder != expectedOutput[index].FirstSequenceMumOrder) { correctOutput = false; break; } if (lisList[index].Length != expectedOutput[index].Length) { correctOutput = false; break; } if (lisList[index].SecondSequenceMumOrder != expectedOutput[index].SecondSequenceMumOrder) { correctOutput = false; break; } if (lisList[index].SecondSequenceStart != expectedOutput[index].SecondSequenceStart) { correctOutput = false; break; } } return correctOutput; } return false; } } }
35.45283
110
0.542044
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/beta/V1/MBF/MBF.Test/LongestIncreasingSubsequenceTest.cs
11,276
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// A summary of the properties of a trial component. To get all the properties, call /// the <a>DescribeTrialComponent</a> API and provide the <code>TrialComponentName</code>. /// </summary> public partial class TrialComponentSummary { private UserContext _createdBy; private DateTime? _creationTime; private string _displayName; private DateTime? _endTime; private UserContext _lastModifiedBy; private DateTime? _lastModifiedTime; private DateTime? _startTime; private TrialComponentStatus _status; private string _trialComponentArn; private string _trialComponentName; private TrialComponentSource _trialComponentSource; /// <summary> /// Gets and sets the property CreatedBy. /// <para> /// Who created the component. /// </para> /// </summary> public UserContext CreatedBy { get { return this._createdBy; } set { this._createdBy = value; } } // Check to see if CreatedBy property is set internal bool IsSetCreatedBy() { return this._createdBy != null; } /// <summary> /// Gets and sets the property CreationTime. /// <para> /// When the component was created. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property DisplayName. /// <para> /// The name of the component as displayed. If <code>DisplayName</code> isn't specified, /// <code>TrialComponentName</code> is displayed. /// </para> /// </summary> [AWSProperty(Min=1, Max=120)] public string DisplayName { get { return this._displayName; } set { this._displayName = value; } } // Check to see if DisplayName property is set internal bool IsSetDisplayName() { return this._displayName != null; } /// <summary> /// Gets and sets the property EndTime. /// <para> /// When the component ended. /// </para> /// </summary> public DateTime EndTime { get { return this._endTime.GetValueOrDefault(); } set { this._endTime = value; } } // Check to see if EndTime property is set internal bool IsSetEndTime() { return this._endTime.HasValue; } /// <summary> /// Gets and sets the property LastModifiedBy. /// <para> /// Who last modified the component. /// </para> /// </summary> public UserContext LastModifiedBy { get { return this._lastModifiedBy; } set { this._lastModifiedBy = value; } } // Check to see if LastModifiedBy property is set internal bool IsSetLastModifiedBy() { return this._lastModifiedBy != null; } /// <summary> /// Gets and sets the property LastModifiedTime. /// <para> /// When the component was last modified. /// </para> /// </summary> public DateTime LastModifiedTime { get { return this._lastModifiedTime.GetValueOrDefault(); } set { this._lastModifiedTime = value; } } // Check to see if LastModifiedTime property is set internal bool IsSetLastModifiedTime() { return this._lastModifiedTime.HasValue; } /// <summary> /// Gets and sets the property StartTime. /// <para> /// When the component started. /// </para> /// </summary> public DateTime StartTime { get { return this._startTime.GetValueOrDefault(); } set { this._startTime = value; } } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this._startTime.HasValue; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the component. States include: /// </para> /// <ul> <li> /// <para> /// InProgress /// </para> /// </li> <li> /// <para> /// Completed /// </para> /// </li> <li> /// <para> /// Failed /// </para> /// </li> </ul> /// </summary> public TrialComponentStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property TrialComponentArn. /// <para> /// The ARN of the trial component. /// </para> /// </summary> [AWSProperty(Max=256)] public string TrialComponentArn { get { return this._trialComponentArn; } set { this._trialComponentArn = value; } } // Check to see if TrialComponentArn property is set internal bool IsSetTrialComponentArn() { return this._trialComponentArn != null; } /// <summary> /// Gets and sets the property TrialComponentName. /// <para> /// The name of the trial component. /// </para> /// </summary> [AWSProperty(Min=1, Max=120)] public string TrialComponentName { get { return this._trialComponentName; } set { this._trialComponentName = value; } } // Check to see if TrialComponentName property is set internal bool IsSetTrialComponentName() { return this._trialComponentName != null; } /// <summary> /// Gets and sets the property TrialComponentSource. /// </summary> public TrialComponentSource TrialComponentSource { get { return this._trialComponentSource; } set { this._trialComponentSource = value; } } // Check to see if TrialComponentSource property is set internal bool IsSetTrialComponentSource() { return this._trialComponentSource != null; } } }
30.645038
108
0.537053
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/TrialComponentSummary.cs
8,029
C#
using EarTrumpet.UI.Helpers; using EarTrumpet.UI.ViewModels; using System; using System.Diagnostics; using System.IO; using System.Text; using System.Windows.Input; namespace EarTrumpet.Actions.ViewModel { public class ImportExportPageViewModel : SettingsPageViewModel { public ICommand Import { get; } public ICommand Export { get; } ActionsCategoryViewModel _parent; public ImportExportPageViewModel(ActionsCategoryViewModel parent) : base(DefaultManagementGroupName) { _parent = parent; Title = Properties.Resources.ImportAndExportTitle; Glyph = "\xE148"; Import = new RelayCommand(OnImport); Export = new RelayCommand(OnExport); } void OnImport() { var dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = ".eta-xml"; dlg.DefaultExt = ".eta-xml"; dlg.Filter = $"{Properties.Resources.EtaXmlFileText}|*.eta-xml"; if (dlg.ShowDialog() == true) { try { EarTrumpetActionsAddon.Current.Import(dlg.FileName); _parent.ReloadSavedPages(); } catch (Exception ex) { Trace.WriteLine(ex); } } } void OnExport() { var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = ".eta-xml"; dlg.DefaultExt = ".eta-xml"; dlg.Filter = $"{Properties.Resources.EtaXmlFileText}|*.eta-xml"; if (dlg.ShowDialog() == true) { try { File.WriteAllText(dlg.FileName, EarTrumpetActionsAddon.Current.Export(), Encoding.Unicode); } catch (Exception ex) { Trace.WriteLine(ex); } } } } }
29.6
112
0.501931
[ "MIT" ]
D-Arora/EarTrumpet
EarTrumpet/Addons/EarTrumpet.Actions/ViewModel/ImportExportPageViewModel.cs
2,005
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; namespace wa.Orm.Pg.Reflection { public class PropertyDescriber { public PropertyInfo Property { get; set; } public string DbName { get; set; } public bool IsKey { get; private set; } public bool IsWriteable { get; private set; } public bool IsReadable { get; private set; } public bool IsArgument { get; private set; } public bool IsGenerated { get; private set; } public PropertyDescriber(PropertyInfo info) { Property = info; DbName = Util.ToUnderscore(info.GetCustomAttribute<ColumnAttribute>()?.Name ?? info.Name); IsKey = info.GetCustomAttribute<KeyAttribute>() != null; IsWriteable = Property.CanWrite && !Property.SetMethod.IsVirtual; IsReadable = Property.CanRead && !Property.GetMethod.IsVirtual; IsArgument = Property.CanRead; IsGenerated = info.GetCustomAttribute<GeneratedAttribute>() != null; } } }
38.413793
102
0.653501
[ "MIT" ]
wootapa/wa-pg-orm
wa.Orm.Pg/Reflection/PropertyDescriber.cs
1,116
C#
using Blazorify.Utilities.Styling.Internals; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace Blazorify.Utilities.Styling { /// <summary> /// Represents a list of css classes. The final result is obtainable with the ToString call. /// </summary> public class CssClassList { private const string Separator = " "; private static readonly char[] _separatorArray = new[] { ' ' }; private readonly List<string> _cssClasses; private readonly CssBuilderOptions _options; private readonly ThreadsafeCssBuilderCache _cache; internal CssClassList(CssBuilderOptions options) { _cssClasses = new List<string>(); _options = options ?? throw new ArgumentNullException(nameof(options)); if (_options.EnumToClassNameConverter == null) { throw new ArgumentException("Options.EnumToClassNameConverter can't be null."); } if (_options.PropertyToClassNameConverter == null) { throw new ArgumentException("Options.PropertyToClassNameConverter can't be null."); } _cache = options.GetCache(); } /// <summary> /// Gets the list of added class names. /// </summary> public IReadOnlyList<string> CssClasses => _cssClasses; /// <summary> /// Adds multiple class definition which can be string, enum, (string, bool), /// (string, Func&gt;bool&lt;), IEnumerable&gt;string&lt;, another CssDefinition, /// IReadOnlyDictionary&gt;string, object&lt; with an optional class key. /// </summary> /// <param name="values">The list of class definitions.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList AddMultiple(params object[] values) { if (values == null || values.Length == 0) { return this; } foreach (var value in values) { if (value is string strValue) { AddInner(strValue); } else if (value is Enum enumValue) { Add(enumValue); } else if (value is ValueTuple<string, bool> tupleWithCondition) { AddInner(tupleWithCondition.Item1, tupleWithCondition.Item2); } else if (value is ValueTuple<string, Func<bool>> tupleWithPredicate) { AddInner(tupleWithPredicate.Item1, tupleWithPredicate.Item2()); } else if (value is IEnumerable<string> cssList) { Add(cssList); } else if (value is CssClassList other) { Add(other); } else if (value is IReadOnlyDictionary<string, object> attributes) { Add(attributes); } else { Add(value); } } return this; } /// <summary> /// Adds the css class to the list if the second parameter is true. /// If the css class is null or empty it is skipped. /// </summary> /// <param name="cssClass">A css class.</param> /// <param name="condition">If true the class is added to the list.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(string cssClass, bool condition = true) { AddInner(cssClass, condition); return this; } /// <summary> /// Adds the css class to the list if the second parameter evaulates to true. /// If the css class is null or empty it is skipped. /// </summary> /// <param name="cssClass">A css class.</param> /// <param name="predicate">a predicate, if it returns true then the css class is added to the list.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(string cssClass, Func<bool> predicate) { if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } AddInner(cssClass, predicate()); return this; } /// <summary> /// Adds the tuples to the list as css classes. The first parameter of the /// tuple is used as css class and it is added only if the second value is true. /// </summary> /// <param name="tuple"> /// A tuple where the first parameter is a css class and the second /// value is a bool which determines if the class should be added. /// </param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(params (string, bool)[] tuple) { if (tuple == null || tuple.Length == 0) { return this; } foreach (var item in tuple) { AddInner(item.Item1, item.Item2); } return this; } /// <summary> /// Adds the tuples to the list as css classes. The first parameter of the /// tuple is used as css class and it is added only if the second function returns true. /// </summary> /// <param name="tuple"> /// A tuple where the first parameter is a css class and the second /// value is a function which determines if the class should be added. /// </param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(params (string, Func<bool>)[] tuple) { if (tuple == null || tuple.Length == 0) { return this; } foreach (var item in tuple) { AddInner(item.Item1, item.Item2()); } return this; } /// <summary> /// Adds the strings as classes to the list. If a string contains more than /// one css class, then it is broken to parts. /// </summary> /// <param name="cssList">A css list enumeration.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(IEnumerable<string> cssList) { if (cssList == null) { return this; } foreach (var value in cssList) { AddInner(value); } return this; } /// <summary> /// Adds the css classes from the other CssDefinition. /// </summary> /// <param name="cssDefinition">A CssDefinition instance.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(CssClassList cssDefinition) { if (cssDefinition == null) { return this; } foreach (var value in cssDefinition._cssClasses) { AddInner(value); } return this; } /// <summary> /// Adds the enum value as css class to the list. The Enum name is converted to css class /// name with <see cref="CssBuilderOptions.EnumToClassNameConverter"/>. This conversion is cached /// which is bound to the options. /// </summary> /// <param name="enumValue">An enum value.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(Enum enumValue) { if (enumValue == null) { return this; } var cssClass = _cache.GetOrAdd(enumValue, (ev) => _options.EnumToClassNameConverter.Invoke(ev)); AddInner(cssClass); return this; } /// <summary> /// Adds the properties as css classes to the list. For class name the property name used /// after converted with <see cref="CssBuilderOptions.PropertyToClassNameConverter"/>. The properties /// added only if it is a boolean with value true. On the object all property must be bool type. /// The conversion method is cached which is bound to the options. /// </summary> /// <param name="values">An object that has only bool property. Preferably an anonymous type.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(object values) { if (values == null) { return this; } var type = values.GetType(); var extractor = _cache.GetOrAdd(type, CreateExtractor); extractor(values, AddInner); return this; } /// <summary> /// Checks if the dictionary has the class element. If yes then adds it's value as classes from it. /// The dictionary can be null. /// </summary> /// <param name="attributes">The attributes dictionary.</param> /// <returns>Returns with this so the calls can be chained.</returns> public CssClassList Add(IReadOnlyDictionary<string, object> attributes) { if (attributes != null && attributes.TryGetValue("class", out var css) && css != null) { AddInner(css as string ?? css.ToString()); } return this; } /// <summary> /// Indicates if the className is added to this. /// </summary> /// <param name="className">The class name to check.</param> /// <returns>True if already added; otherwise false.</returns> public bool HasClass(string className) { return _cssClasses.Contains(className); } /// <summary> /// Returns with the finished css class definition list. /// </summary> /// <returns>The class names separated by spaces.</returns> public override string ToString() { return string.Join(Separator, _cssClasses); } private ProcessCssDelegate CreateExtractor(Type type) { var lines = new List<Expression>(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var valuesParam = Expression.Parameter(typeof(object)); var addMethod = Expression.Parameter(typeof(AddCssDelegate)); var valuesVar = Expression.Variable(type); var castedValuesParam = Expression.Convert(valuesParam, type); var valuesVarAssigment = Expression.Assign(valuesVar, castedValuesParam); lines.Add(valuesVarAssigment); foreach (var property in properties) { if (property.PropertyType != typeof(bool)) { throw new Exception($"Only boolean properties allowed for the css builder. Invalid poperty: {type.Name}.{property.Name} (Type: {property.PropertyType}"); } var conditionGetter = Expression.Property(valuesVar, property); var className = _options.PropertyToClassNameConverter(property); var classNameConstant = Expression.Constant(className); var invokation = Expression.Invoke(addMethod, classNameConstant, conditionGetter); lines.Add(invokation); } var body = Expression.Block(new ParameterExpression[] { valuesVar }, lines); var method = Expression.Lambda<ProcessCssDelegate>(body, valuesParam, addMethod); return method.Compile(); } private void AddInner(string value, bool condition = true) { if (string.IsNullOrEmpty(value) || !condition) { return; } foreach (var cssClass in value.Split(_separatorArray, StringSplitOptions.RemoveEmptyEntries)) { if (_options.ExcludeDuplication && HasClass(cssClass)) { continue; } _cssClasses.Add(cssClass); } } } }
38.055556
174
0.534153
[ "MIT" ]
faddiv/CommonLibraries
CommonLibraries.Core.Web/CommonLibraries.Core.Web/Styling/CssClassList.cs
12,674
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.Razor.LanguageServer { public class RazorLSPOptionsMonitorTest { public RazorLSPOptionsMonitorTest() { var services = new ServiceCollection().AddOptions(); Cache = services.BuildServiceProvider().GetRequiredService<IOptionsMonitorCache<RazorLSPOptions>>(); } private IOptionsMonitorCache<RazorLSPOptions> Cache { get; } [Fact] public async Task UpdateAsync_Invokes_OnChangeRegistration() { // Arrange var expectedOptions = new RazorLSPOptions(Trace.Messages, enableFormatting: false); var configService = Mock.Of<RazorConfigurationService>(f => f.GetLatestOptionsAsync() == Task.FromResult(expectedOptions)); var optionsMonitor = new RazorLSPOptionsMonitor(configService, Cache); var called = false; // Act & Assert optionsMonitor.OnChange(options => { called = true; Assert.Same(expectedOptions, options); }); await optionsMonitor.UpdateAsync(); Assert.True(called, "Registered callback was not called."); } [Fact] public async Task UpdateAsync_DoesNotInvoke_OnChangeRegistration_AfterDispose() { // Arrange var expectedOptions = new RazorLSPOptions(Trace.Messages, enableFormatting: false); var configService = Mock.Of<RazorConfigurationService>(f => f.GetLatestOptionsAsync() == Task.FromResult(expectedOptions)); var optionsMonitor = new RazorLSPOptionsMonitor(configService, Cache); var called = false; var onChangeToken = optionsMonitor.OnChange(options => { called = true; }); // Act 1 await optionsMonitor.UpdateAsync(); // Assert 1 Assert.True(called, "Registered callback was not called."); // Act 2 called = false; onChangeToken.Dispose(); await optionsMonitor.UpdateAsync(); // Assert 2 Assert.False(called, "Registered callback called even after dispose."); } [Fact] public async Task UpdateAsync_ConfigReturnsNull_DoesNotInvoke_OnChangeRegistration() { // Arrange var configService = Mock.Of<RazorConfigurationService>(); var optionsMonitor = new RazorLSPOptionsMonitor(configService, Cache); var called = false; var onChangeToken = optionsMonitor.OnChange(options => { called = true; }); // Act await optionsMonitor.UpdateAsync(); // Assert Assert.False(called, "Registered callback called even when GetLatestOptionsAsync() returns null."); } } }
36.179775
135
0.617391
[ "Apache-2.0" ]
devlead/aspnetcore-tooling
src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorLSPOptionsMonitorTest.cs
3,222
C#
using Voxels.Networking.Clientside; using ZeroFormatter; namespace Voxels.Networking { public class S_UnloadChunkMessageHandler : BaseServerMessageHandler { public override ServerPacketID CommandId { get { return ServerPacketID.ChunkUnload; } } public override void ProcessMessage(byte[] rawCommand) { base.ProcessMessage(rawCommand); var command = ZeroFormatterSerializer.Deserialize<S_UnloadChunkMessage>(rawCommand); var cm = ClientChunkManager.Instance; var index = new Int3(command.X, command.Y, command.Z); cm.UnloadChunk(index); } } }
25.26087
87
0.762478
[ "MIT" ]
TxN/VoxelLand
Assets/Scripts/Networking/ServerMessages/MessageHandlers/S_UnloadChunkMessageHandler.cs
581
C#
using Granikos.SMTPSimulator.Core; using Xunit; namespace SMTPSimulatorTest { public class ValidationHelperTest { [Theory] [InlineData("a.a")] [InlineData("a.a0")] [InlineData("a-a.aa")] [InlineData("a-0.b-a")] [InlineData("a-b-c.d")] [InlineData("a1.b.c")] [InlineData("a-b.d0.c")] [InlineData("o.t-9")] [InlineData("z-2.f6")] [InlineData("x.z9.u")] [InlineData("vy.o9.e-9.dn")] [InlineData("z.c")] [InlineData("p-8.i")] [InlineData("y4o29-i.k-8.n8.t.h-d8.h-0")] [InlineData("z.y-0")] [InlineData("a.a-9.u")] [InlineData("zz.mu")] public void TestIsValidDomainNameSuccess(string domain) { Assert.True(domain.IsValidDomainName()); } [Theory] [InlineData("")] [InlineData("a")] [InlineData("a-")] [InlineData("a0")] [InlineData("a.")] [InlineData("a.-")] [InlineData("a.a-")] public void TestIsValidDomainNameFail(string domain) { Assert.False(domain.IsValidDomainName()); } [Theory] [InlineData("domain.com")] [InlineData("[127.0.0.1]")] [InlineData("[1.1.1.1]")] [InlineData("[IPv6:FE80:0000:0000:0000:0202:B3FF:FE1E:8329]")] [InlineData("[IPv6:FE80::0202:B3FF:FE1E:8329]")] [InlineData("[IPv6:2607:f0d0:1002:51::4]")] [InlineData("[IPv6:fe80::230:48ff:fe33:bc33]")] public void TestIsValidDomainSuccess(string address) { Assert.True(address.IsValidDomain()); } [Theory] [InlineData("127.0.0.1")] [InlineData("[]")] [InlineData("[IPv6:abc]")] [InlineData("IPv6:FE80:0000:0000:0000:0202:B3FF:FE1E:8329")] [InlineData("FE80::0202:B3FF:FE1E:8329")] [InlineData("[IPv6:2607:f0d0:1002:51::4")] [InlineData("IPv6:fe80::230:48ff:fe33:bc33]")] public void TestIsValidDomainFail(string address) { Assert.False(address.IsValidDomain()); } } }
31.414286
71
0.515689
[ "MIT" ]
Granikos/SMTPSimulator
Granikos.SMTPSimulator.Test/ValidationHelperTest.cs
2,201
C#
using AVDump3Lib.Information.InfoProvider; using AVDump3Lib.Information.MetaInfo.Core; using AVDump3Lib.Processing.BlockConsumers.Matroska; using AVDump3Lib.Reporting.Core; using System.Xml.Linq; namespace AVDump3Lib.Reporting.Reports; public class MatroskaReport : XmlReport { protected override XDocument Report { get; } public MatroskaReport(FileMetaInfo fileMetaInfo) { Report = new XDocument(); var rootElem = new XElement("File"); Report.Add(rootElem); var matroskaFile = fileMetaInfo.Providers.OfType<MatroskaProvider>().SingleOrDefault()?.MFI; if(matroskaFile == null) { return; } static void traverse(XElement parent, Section section) { foreach(var item in section) { var child = new XElement(item.Key); parent.Add(child); if(item.Value is Section childSection) { traverse(child, childSection); } else { if(item.Value != null) { if(item.Value is byte[] b) { child.Add(new XAttribute("Size", b.Length)); if(b.Length > 0) { child.Value = BitConverter.ToString(b, 0, Math.Min(1024, b.Length)).Replace("-", "") + (b.Length > 1024 ? "..." : ""); } } else { child.Value = item.Value.ToString(); } } } } } traverse(rootElem, matroskaFile); } }
25.039216
126
0.665623
[ "MIT" ]
acidburn0zzz/AVDump3
AVDump3Lib/Reporting/Reports/MatroskaReport.cs
1,279
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.InteropServices; using WinRT.Interop; namespace WinRT { public interface IWinRTObject : IDynamicInterfaceCastable { bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { return IsInterfaceImplementedFallback(interfaceType, throwIfNotImplemented); } bool IsInterfaceImplementedFallback(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented) { if (QueryInterfaceCache.ContainsKey(interfaceType)) { return true; } Type type = Type.GetTypeFromHandle(interfaceType); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IReadOnlyCollection<>)) { Type itemType = type.GetGenericArguments()[0]; if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { Type iReadOnlyDictionary = typeof(IReadOnlyDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); if (IsInterfaceImplemented(iReadOnlyDictionary.TypeHandle, false)) { if (QueryInterfaceCache.TryGetValue(iReadOnlyDictionary.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } } Type iReadOnlyList = typeof(IReadOnlyList<>).MakeGenericType(new[] { itemType }); if (IsInterfaceImplemented(iReadOnlyList.TypeHandle, throwIfNotImplemented)) { if (QueryInterfaceCache.TryGetValue(iReadOnlyList.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } return false; } else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) { Type itemType = type.GetGenericArguments()[0]; if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { Type iDictionary = typeof(IDictionary<,>).MakeGenericType(itemType.GetGenericArguments()); if (IsInterfaceImplemented(iDictionary.TypeHandle, false)) { if (QueryInterfaceCache.TryGetValue(iDictionary.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } } Type iList = typeof(IList<>).MakeGenericType(new[] { itemType }); if (IsInterfaceImplemented(iList.TypeHandle, throwIfNotImplemented)) { if (QueryInterfaceCache.TryGetValue(iList.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } return false; } else if (type == typeof(System.Collections.IEnumerable)) { Type iEnum = typeof(System.Collections.Generic.IEnumerable<object>); if (IsInterfaceImplemented(iEnum.TypeHandle, false)) { if (QueryInterfaceCache.TryGetValue(iEnum.TypeHandle, out var typedObjRef) && !QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } } Type helperType = type.FindHelperType(); if (helperType is null || !helperType.IsInterface) { return false; } int hr = NativeObject.TryAs<IUnknownVftbl>(GuidGenerator.GetIID(helperType), out var objRef); if (hr < 0) { if (throwIfNotImplemented) { ExceptionHelpers.ThrowExceptionForHR(hr); } return false; } if (typeof(System.Collections.IEnumerable).IsAssignableFrom(type)) { RuntimeTypeHandle projectIEnum = typeof(System.Collections.IEnumerable).TypeHandle; AdditionalTypeData.GetOrAdd(projectIEnum, (_) => new ABI.System.Collections.IEnumerable.AdaptiveFromAbiHelper(type, this)); } var vftblType = helperType.FindVftblType(); using (objRef) { if (vftblType is null) { var qiObjRef = objRef.As<IUnknownVftbl>(GuidGenerator.GetIID(helperType)); if (!QueryInterfaceCache.TryAdd(interfaceType, qiObjRef)) { objRef.Dispose(); } return true; } IObjectReference typedObjRef = (IObjectReference)typeof(IObjectReference).GetMethod("As", Type.EmptyTypes).MakeGenericMethod(vftblType).Invoke(objRef, null); if (!QueryInterfaceCache.TryAdd(interfaceType, typedObjRef)) { typedObjRef.Dispose(); } return true; } } RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType) { var type = Type.GetTypeFromHandle(interfaceType); var helperType = type.GetHelperType(); if (helperType.IsInterface) return helperType.TypeHandle; return default; } IObjectReference NativeObject { get; } bool HasUnwrappableNativeObject { get; } protected ConcurrentDictionary<RuntimeTypeHandle, IObjectReference> QueryInterfaceCache { get; } IObjectReference GetObjectReferenceForType(RuntimeTypeHandle type) { return GetObjectReferenceForTypeFallback(type); } IObjectReference GetObjectReferenceForTypeFallback(RuntimeTypeHandle type) { if (IsInterfaceImplemented(type, true)) { return QueryInterfaceCache[type]; } throw new Exception("Interface " + Type.GetTypeFromHandle(type) +" is not implemented."); } ConcurrentDictionary<RuntimeTypeHandle, object> AdditionalTypeData { get; } object GetOrCreateTypeHelperData(RuntimeTypeHandle type, Func<object> helperDataFactory) { return AdditionalTypeData.GetOrAdd(type, (type) => helperDataFactory()); } internal void Resurrect() { if (NativeObject.Resurrect()) { foreach (var cached in QueryInterfaceCache) { cached.Value.Resurrect(); } } } } }
42.201117
173
0.558247
[ "MIT" ]
avadim777/CsWinRT
src/WinRT.Runtime/IWinRTObject.net5.cs
7,554
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 email-2010-12-01.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.SimpleEmail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.SimpleEmail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateConfigurationSetTrackingOptions operation /// </summary> public class CreateConfigurationSetTrackingOptionsResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateConfigurationSetTrackingOptionsResponse response = new CreateConfigurationSetTrackingOptionsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("CreateConfigurationSetTrackingOptionsResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="response")] private static void UnmarshallResult(XmlUnmarshallerContext context, CreateConfigurationSetTrackingOptionsResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ConfigurationSetDoesNotExist")) { return ConfigurationSetDoesNotExistExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidTrackingOptions")) { return InvalidTrackingOptionsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("TrackingOptionsAlreadyExistsException")) { return TrackingOptionsAlreadyExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonSimpleEmailServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static CreateConfigurationSetTrackingOptionsResponseUnmarshaller _instance = new CreateConfigurationSetTrackingOptionsResponseUnmarshaller(); internal static CreateConfigurationSetTrackingOptionsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateConfigurationSetTrackingOptionsResponseUnmarshaller Instance { get { return _instance; } } } }
40.006944
173
0.630099
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/SimpleEmail/Generated/Model/Internal/MarshallTransformations/CreateConfigurationSetTrackingOptionsResponseUnmarshaller.cs
5,761
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 iam-2010-05-08.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.IdentityManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DetachUserPolicy operation /// </summary> public class DetachUserPolicyResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { DetachUserPolicyResponse response = new DetachUserPolicyResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("DetachUserPolicyResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="response")] private static void UnmarshallResult(XmlUnmarshallerContext context, DetachUserPolicyResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInput")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceeded")) { return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchEntity")) { return NoSuchEntityExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailure")) { return ServiceFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonIdentityManagementServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DetachUserPolicyResponseUnmarshaller _instance = new DetachUserPolicyResponseUnmarshaller(); internal static DetachUserPolicyResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DetachUserPolicyResponseUnmarshaller Instance { get { return _instance; } } } }
39.587838
181
0.59447
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IdentityManagement/Generated/Model/Internal/MarshallTransformations/DetachUserPolicyResponseUnmarshaller.cs
5,859
C#
using Melanchall.DryWetMidi.Core; using Melanchall.DryWetMidi.Interaction; using Melanchall.DryWetMidi.Tests.Utilities; using Melanchall.DryWetMidi.Tools; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace Melanchall.DryWetMidi.Tests.Tools { [TestFixture] public sealed partial class ResizerTests { #region Test methods [Test] public void Resize_ToLength_EventsCollection_Empty() => Resize_ToLength_EventsCollection( midiEvents: Array.Empty<MidiEvent>(), length: (MidiTimeSpan)100, tempoMap: TempoMap.Default, expectedEvents: Array.Empty<MidiEvent>()); [Test] public void Resize_ToLength_EventsCollection_OneEvent_Midi([Values(0, 50, 100)] long deltaTime, [Values(10, 200)] int toTicks) => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = deltaTime } }, length: (MidiTimeSpan)toTicks, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = deltaTime == 0 ? 0 : toTicks } }); [Test] public void Resize_ToLength_EventsCollection_OneEvent_Metric([Values(0, 50, 100)] int seconds, [Values(10, 200)] int toSeconds) => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = TimeConverter.ConvertFrom(new MetricTimeSpan(0, 0, seconds), TempoMap.Default) } }, length: new MetricTimeSpan(0, 0, toSeconds), tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = seconds == 0 ? 0 : TimeConverter.ConvertFrom(new MetricTimeSpan(0, 0, toSeconds), TempoMap.Default) } }); [Test] public void Resize_ToLength_EventsCollection_MultipleEvents_1() => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 0 }, }, length: (MidiTimeSpan)100, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 0 }, }); [Test] public void Resize_ToLength_EventsCollection_MultipleEvents_2() => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 100 }, }, length: (MidiTimeSpan)1500, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 500 }, new TextEvent("B") { DeltaTime = 1000 }, }); [Test] public void Resize_ToLength_EventsCollection_MultipleEvents_3() => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 100 }, }, length: (MidiTimeSpan)15, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 5 }, new TextEvent("B") { DeltaTime = 10 }, }); [Test] public void Resize_ToLength_EventsCollection_MultipleEvents_4() => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 100 }, }, length: (MidiTimeSpan)10, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 10 }, }); [Test] public void Resize_ToLength_EventsCollection_MultipleEvents_5() => Resize_ToLength_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 0 }, }, length: (MidiTimeSpan)1000, tempoMap: TempoMap.Default, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 1000 }, new TextEvent("B") { DeltaTime = 0 }, }); [Test] public void Resize_ByRatio_EventsCollection_Empty() => Resize_ByRatio_EventsCollection( midiEvents: Array.Empty<MidiEvent>(), ratio: 2.0, expectedEvents: Array.Empty<MidiEvent>()); [Test] public void Resize_ByRatio_EventsCollection_OneEvent_Midi([Values(0, 50, 100)] long deltaTime, [Values(0.5, 2.0)] double ratio) => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = deltaTime } }, ratio: ratio, expectedEvents: new[] { new TextEvent("A") { DeltaTime = (long)Math.Round(deltaTime * ratio) } }); [Test] public void Resize_ByRatio_EventsCollection_OneEvent_Metric([Values(0, 50, 100)] int seconds, [Values(0.5, 2.0)] double ratio) => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = TimeConverter.ConvertFrom(new MetricTimeSpan(0, 0, seconds), TempoMap.Default) } }, ratio: ratio, expectedEvents: new[] { new TextEvent("A") { DeltaTime = TimeConverter.ConvertFrom(new MetricTimeSpan(0, 0, (int)Math.Round(seconds * ratio)), TempoMap.Default) } }); [Test] public void Resize_ByRatio_EventsCollection_MultipleEvents_1() => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 0 }, }, ratio: 2.0, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 0 }, }); [Test] public void Resize_ByRatio_EventsCollection_MultipleEvents_2() => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 100 }, }, ratio: 10.0, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 500 }, new TextEvent("B") { DeltaTime = 1000 }, }); [Test] public void Resize_ByRatio_EventsCollection_MultipleEvents_3() => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 100 }, }, ratio: 0.1, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 5 }, new TextEvent("B") { DeltaTime = 10 }, }); [Test] public void Resize_ByRatio_EventsCollection_MultipleEvents_4() => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 100 }, }, ratio: 0.1, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 0 }, new TextEvent("B") { DeltaTime = 10 }, }); [Test] public void Resize_ByRatio_EventsCollection_MultipleEvents_5() => Resize_ByRatio_EventsCollection( midiEvents: new[] { new TextEvent("A") { DeltaTime = 50 }, new TextEvent("B") { DeltaTime = 0 }, }, ratio: 20.0, expectedEvents: new[] { new TextEvent("A") { DeltaTime = 1000 }, new TextEvent("B") { DeltaTime = 0 }, }); [Test] public void Resize_ToLength_EventsCollections_EmptyCollection() => Resize_ToLength_EventsCollections( midiEvents: new[] { Array.Empty<MidiEvent>() }, length: (MidiTimeSpan)100, tempoMap: TempoMap.Default, expectedEvents: new[] { Array.Empty<MidiEvent>() }); [Test] public void Resize_ToLength_EventsCollections_EmptyChunks() => Resize_ToLength_EventsCollections( midiEvents: new[] { Array.Empty<MidiEvent>(), Array.Empty<MidiEvent>() }, length: (MidiTimeSpan)100, tempoMap: TempoMap.Default, expectedEvents: new[] { Array.Empty<MidiEvent>(), Array.Empty<MidiEvent>() }); [Test] public void Resize_ToLength_EventsCollections_OneEvent_1([Values(0, 50, 100)] long deltaTime, [Values(10, 200)] int toTicks) => Resize_ToLength_EventsCollections( midiEvents: new[] { new[] { new TextEvent("A") { DeltaTime = deltaTime } }, Array.Empty<MidiEvent>() }, length: (MidiTimeSpan)toTicks, tempoMap: TempoMap.Default, expectedEvents: new[] { new[] { new TextEvent("A") { DeltaTime = deltaTime == 0 ? 0 : toTicks } }, Array.Empty<MidiEvent>() }); [Test] public void Resize_ToLength_EventsCollections_OneEvent_2([Values(0, 50, 100)] long deltaTime, [Values(10, 200)] int toTicks) => Resize_ToLength_EventsCollections( midiEvents: new[] { Array.Empty<MidiEvent>(), new[] { new TextEvent("A") { DeltaTime = deltaTime } }, }, length: (MidiTimeSpan)toTicks, tempoMap: TempoMap.Default, expectedEvents: new[] { Array.Empty<MidiEvent>(), new[] { new TextEvent("A") { DeltaTime = deltaTime == 0 ? 0 : toTicks } }, }); [Test] public void Resize_ByRatio_EventsCollections_OneEvent_1([Values(0, 50, 100)] long deltaTime, [Values(0.5, 2.0)] double ratio) => Resize_ByRatio_EventsCollections( midiEvents: new[] { new[] { new TextEvent("A") { DeltaTime = deltaTime } }, Array.Empty<MidiEvent>(), }, ratio: ratio, expectedEvents: new[] { new[] { new TextEvent("A") { DeltaTime = (long)Math.Round(deltaTime * ratio) } }, Array.Empty<MidiEvent>(), }); [Test] public void Resize_ByRatio_EventsCollections_OneEvent_2([Values(0, 50, 100)] long deltaTime, [Values(0.5, 2.0)] double ratio) => Resize_ByRatio_EventsCollections( midiEvents: new[] { Array.Empty<MidiEvent>(), new[] { new TextEvent("A") { DeltaTime = deltaTime } }, }, ratio: ratio, expectedEvents: new[] { Array.Empty<MidiEvent>(), new[] { new TextEvent("A") { DeltaTime = (long)Math.Round(deltaTime * ratio) } }, }); #endregion #region Private methods private void Resize_ToLength_EventsCollection( ICollection<MidiEvent> midiEvents, ITimeSpan length, TempoMap tempoMap, ICollection<MidiEvent> expectedEvents) { var expectedTrackChunk = new TrackChunk(expectedEvents); // var trackChunk = new TrackChunk(midiEvents.Select(e => e.Clone())); trackChunk.Resize(length, tempoMap); MidiAsserts.AreEqual(expectedTrackChunk, trackChunk, true, "Invalid track chunk."); // var trackChunks = new[] { new TrackChunk(midiEvents.Select(e => e.Clone())) }; trackChunks.Resize(length, tempoMap); MidiAsserts.AreEqual(new[] { expectedTrackChunk }, trackChunks, true, "Invalid track chunks."); // var midiFile = new MidiFile(new TrackChunk(midiEvents.Select(e => e.Clone()))); midiFile.Resize(length); MidiAsserts.AreEqual(new MidiFile(expectedTrackChunk), midiFile, false, "Invalid MIDI file."); } private void Resize_ByRatio_EventsCollection( ICollection<MidiEvent> midiEvents, double ratio, ICollection<MidiEvent> expectedEvents) { var expectedTrackChunk = new TrackChunk(expectedEvents); // var trackChunk = new TrackChunk(midiEvents.Select(e => e.Clone())); trackChunk.Resize(ratio); MidiAsserts.AreEqual(expectedTrackChunk, trackChunk, true, "Invalid track chunk."); // var trackChunks = new[] { new TrackChunk(midiEvents.Select(e => e.Clone())) }; trackChunks.Resize(ratio); MidiAsserts.AreEqual(new[] { expectedTrackChunk }, trackChunks, true, "Invalid track chunks."); // var midiFile = new MidiFile(new TrackChunk(midiEvents.Select(e => e.Clone()))); midiFile.Resize(ratio); MidiAsserts.AreEqual(new MidiFile(expectedTrackChunk), midiFile, false, "Invalid MIDI file."); } private void Resize_ToLength_EventsCollections( ICollection<ICollection<MidiEvent>> midiEvents, ITimeSpan length, TempoMap tempoMap, ICollection<ICollection<MidiEvent>> expectedEvents) { var expectedTrackChunks = expectedEvents.Select(e => new TrackChunk(e)).ToArray(); // var trackChunks = midiEvents.Select(e => new TrackChunk(e.Select(ee => ee.Clone()))).ToArray(); trackChunks.Resize(length, tempoMap); MidiAsserts.AreEqual(expectedTrackChunks, trackChunks, true, "Invalid track chunks."); // var midiFile = new MidiFile(midiEvents.Select(e => new TrackChunk(e.Select(ee => ee.Clone()))).ToArray()); midiFile.Resize(length); MidiAsserts.AreEqual(new MidiFile(expectedTrackChunks), midiFile, false, "Invalid MIDI file."); } private void Resize_ByRatio_EventsCollections( ICollection<ICollection<MidiEvent>> midiEvents, double ratio, ICollection<ICollection<MidiEvent>> expectedEvents) { var expectedTrackChunks = expectedEvents.Select(e => new TrackChunk(e)).ToArray(); // var trackChunks = midiEvents.Select(e => new TrackChunk(e.Select(ee => ee.Clone()))).ToArray(); trackChunks.Resize(ratio); MidiAsserts.AreEqual(expectedTrackChunks, trackChunks, true, "Invalid track chunks."); // var midiFile = new MidiFile(midiEvents.Select(e => new TrackChunk(e.Select(ee => ee.Clone()))).ToArray()); midiFile.Resize(ratio); MidiAsserts.AreEqual(new MidiFile(expectedTrackChunks), midiFile, false, "Invalid MIDI file."); } #endregion } }
37.367442
172
0.530371
[ "MIT" ]
valimaties/drywetmidi
DryWetMidi.Tests/Tools/Resizer/ResizerTests.Resize.cs
16,070
C#
using Byn.Awrtc.Base; namespace Byn.Awrtc.Browser { public class BrowserWebRtcCall : AWebRtcCall { private NetworkConfig mConfig; public BrowserWebRtcCall(NetworkConfig config) : base(config) { mConfig = config; Initialize(CreateNetwork()); } private IMediaNetwork CreateNetwork() { return new BrowserMediaNetwork(mConfig); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { //Dispose was called by the user -> cleanup other managed objects //cleanup the internal network if (mNetwork != null) mNetwork.Dispose(); mNetwork = null; //unregister on network factory to allow garbage collection //if (this.mFactory != null) // this.mFactory.OnCallDisposed(this); //this.mFactory = null; } } } }
26.341463
81
0.524074
[ "MIT" ]
AwuChen/1am
1am_Unity/Assets/WebRtcVideoChat/scripts/browser/BrowserWebRtcCall.cs
1,082
C#
/* * Lab 4 * Bailey Gann * 4/21/2022 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaileyGann.AdventureGame.Memory { public interface ICharacterRoster { string Add ( Character character ); string Delete ( int id ); Character Get ( int id ); IEnumerable<Character> GetAll (); string Update ( int id, Character character ); } }
20.26087
54
0.658798
[ "MIT" ]
Bailey-Gann/itse1430
labs/Lab3/BaileyGann.AdventureGame/BaileyGann.AdventureGame/Memory/ICharacterRoster.cs
468
C#
// SF API version v41.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Accepted Event Relation ///<para>SObject Name: AcceptedEventRelation</para> ///<para>Custom Object: False</para> ///</summary> public class SfAcceptedEventRelation : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "AcceptedEventRelation"; } } ///<summary> /// Event Relation ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Relation ID /// <para>Name: RelationId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relationId")] [Updateable(false), Createable(false)] public string RelationId { get; set; } ///<summary> /// Event ID /// <para>Name: EventId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "eventId")] [Updateable(false), Createable(false)] public string EventId { get; set; } ///<summary> /// ReferenceTo: Event /// <para>RelationshipName: Event</para> ///</summary> [JsonProperty(PropertyName = "event")] [Updateable(false), Createable(false)] public SfEvent Event { get; set; } ///<summary> /// Response Date /// <para>Name: RespondedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "respondedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? RespondedDate { get; set; } ///<summary> /// Response /// <para>Name: Response</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "response")] [Updateable(false), Createable(false)] public string Response { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Type /// <para>Name: Type</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } } }
27.561404
55
0.65139
[ "MIT" ]
keylightberlin/NetCoreForce
src/NetCoreForce.Models/SfAcceptedEventRelation.cs
4,713
C#
using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Logging; namespace GitVersion; internal class MergeBaseFinder { private readonly ILog log; private readonly Dictionary<Tuple<IBranch, IBranch>, ICommit> mergeBaseCache = new(); private readonly IGitRepository repository; private readonly IRepositoryStore repositoryStore; public MergeBaseFinder(IRepositoryStore repositoryStore, IGitRepository gitRepository, ILog log) { this.repositoryStore = repositoryStore.NotNull(); this.repository = gitRepository.NotNull(); this.log = log.NotNull(); } public ICommit? FindMergeBaseOf(IBranch? first, IBranch? second) { first = first.NotNull(); second = second.NotNull(); var key = Tuple.Create(first, second); if (this.mergeBaseCache.ContainsKey(key)) { this.log.Debug($"Cache hit for merge base between '{first}' and '{second}'."); return this.mergeBaseCache[key]; } using (this.log.IndentLog($"Finding merge base between '{first}' and '{second}'.")) { // Other branch tip is a forward merge var commitToFindCommonBase = second?.Tip; var commit = first.Tip; if (commit == null) return null; if (commitToFindCommonBase?.Parents.Contains(commit) == true) { commitToFindCommonBase = commitToFindCommonBase.Parents.First(); } if (commitToFindCommonBase == null) return null; var findMergeBase = FindMergeBase(commit, commitToFindCommonBase); if (findMergeBase == null) { this.log.Info($"No merge base of {first}' and '{second} could be found."); return null; } // Store in cache. this.mergeBaseCache.Add(key, findMergeBase); this.log.Info($"Merge base of {first}' and '{second} is {findMergeBase}"); return findMergeBase; } } private ICommit? FindMergeBase(ICommit commit, ICommit commitToFindCommonBase) { var findMergeBase = this.repositoryStore.FindMergeBase(commit, commitToFindCommonBase); if (findMergeBase == null) return null; this.log.Info($"Found merge base of {findMergeBase}"); // We do not want to include merge base commits which got forward merged into the other branch ICommit? forwardMerge; do { // Now make sure that the merge base is not a forward merge forwardMerge = GetForwardMerge(commitToFindCommonBase, findMergeBase); if (forwardMerge == null) continue; // TODO Fix the logging up in this section var second = forwardMerge.Parents.First(); this.log.Debug($"Second {second}"); var mergeBase = this.repositoryStore.FindMergeBase(commit, second); if (mergeBase == null) { this.log.Warning("Could not find merge base for " + commit); } else { this.log.Debug($"New Merge base {mergeBase}"); } if (Equals(mergeBase, findMergeBase)) { this.log.Debug("Breaking"); break; } findMergeBase = mergeBase; commitToFindCommonBase = second; this.log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}"); } while (forwardMerge != null); return findMergeBase; } private ICommit? GetForwardMerge(ICommit? commitToFindCommonBase, ICommit? findMergeBase) { var filter = new CommitFilter { IncludeReachableFrom = commitToFindCommonBase, ExcludeReachableFrom = findMergeBase }; var commitCollection = this.repository.Commits.QueryBy(filter); return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase)); } }
33.08871
104
0.597368
[ "MIT" ]
bitbonk/GitVersion
src/GitVersion.Core/Core/MergeBaseFinder.cs
4,103
C#
namespace TeamTaskboard.Web.ViewModels.Account { using System.ComponentModel.DataAnnotations; public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } }
32.04
110
0.62422
[ "MIT" ]
lostm1nd/TeamTaskboard
Source/TeamTaskboard.Web/ViewModels/Account/ResetPasswordViewModel.cs
803
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Media.Devices { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class MediaDeviceControl { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Media.Devices.MediaDeviceControlCapabilities Capabilities { get { throw new global::System.NotImplementedException("The member MediaDeviceControlCapabilities MediaDeviceControl.Capabilities is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Media.Devices.MediaDeviceControl.Capabilities.get #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public bool TryGetValue(out double value) { throw new global::System.NotImplementedException("The member bool MediaDeviceControl.TryGetValue(out double value) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public bool TrySetValue( double value) { throw new global::System.NotImplementedException("The member bool MediaDeviceControl.TrySetValue(double value) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public bool TryGetAuto(out bool value) { throw new global::System.NotImplementedException("The member bool MediaDeviceControl.TryGetAuto(out bool value) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public bool TrySetAuto( bool value) { throw new global::System.NotImplementedException("The member bool MediaDeviceControl.TrySetAuto(bool value) is not implemented in Uno."); } #endif } }
38.039216
157
0.745876
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Devices/MediaDeviceControl.cs
1,940
C#
using Avalonia; using Avalonia.Controls.Metadata; using Avalonia.Controls.Shapes; using Avalonia.Media; using NodeEditor.Model; namespace NodeEditor.Controls; [PseudoClasses(":selected")] public class Connector : Shape { public static readonly StyledProperty<Point> StartPointProperty = AvaloniaProperty.Register<Connector, Point>(nameof(StartPoint)); public static readonly StyledProperty<Point> EndPointProperty = AvaloniaProperty.Register<Connector, Point>(nameof(EndPoint)); public static readonly StyledProperty<double> OffsetProperty = AvaloniaProperty.Register<Connector, double>(nameof(Offset)); static Connector() { StrokeThicknessProperty.OverrideDefaultValue<Connector>(1); AffectsGeometry<Connector>(StartPointProperty, EndPointProperty, OffsetProperty); } public Point StartPoint { get => GetValue(StartPointProperty); set => SetValue(StartPointProperty, value); } public Point EndPoint { get => GetValue(EndPointProperty); set => SetValue(EndPointProperty, value); } public double Offset { get => GetValue(OffsetProperty); set => SetValue(OffsetProperty, value); } protected override Geometry CreateDefiningGeometry() { var geometry = new StreamGeometry(); using var context = geometry.Open(); context.BeginFigure(StartPoint, false); if (DataContext is IConnector connector) { var p1X = StartPoint.X; var p1Y = StartPoint.Y; var p2X = EndPoint.X; var p2Y = EndPoint.Y; connector.GetControlPoints( connector.Orientation, Offset, connector.Start?.Alignment ?? PinAlignment.None, connector.End?.Alignment ?? PinAlignment.None, ref p1X, ref p1Y, ref p2X, ref p2Y); context.CubicBezierTo(new Point(p1X, p1Y), new Point(p2X, p2Y), EndPoint); } else { context.CubicBezierTo(StartPoint, EndPoint, EndPoint); } context.EndFigure(false); return geometry; } }
27.974684
89
0.634842
[ "MIT" ]
janbiehl/NodeEditor
src/NodeEditorAvalonia/Controls/Connector.cs
2,212
C#
// This is a generated file created by Glue. To change this file, edit the camera settings in Glue. // To access the camera settings, push the camera icon. using Camera = FlatRedBall.Camera; namespace Dodgeball { public class CameraSetupData { public float Scale { get; set; } public bool Is2D { get; set; } public int ResolutionWidth { get; set; } public int ResolutionHeight { get; set; } public decimal? AspectRatio { get; set; } public bool AllowWidowResizing { get; set; } public bool IsFullScreen { get; set; } public ResizeBehavior ResizeBehavior { get; set; } } public enum ResizeBehavior { StretchVisibleArea, IncreaseVisibleArea } internal static class CameraSetup { static Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager; public static CameraSetupData Data = new CameraSetupData { Scale = 50f, ResolutionWidth = 1920, ResolutionHeight = 1080, Is2D = true, AspectRatio = 1.7777777777777777777777777778m, IsFullScreen = false, AllowWidowResizing = true, ResizeBehavior = ResizeBehavior.IncreaseVisibleArea, } ; internal static void ResetCamera (Camera cameraToReset = null) { if (cameraToReset == null) { cameraToReset = FlatRedBall.Camera.Main; } cameraToReset.Orthogonal = Data.Is2D; if (Data.Is2D) { cameraToReset.OrthogonalHeight = Data.ResolutionHeight; cameraToReset.OrthogonalWidth = Data.ResolutionWidth; cameraToReset.FixAspectRatioYConstant(); } if (Data.AspectRatio != null) { SetAspectRatioTo(Data.AspectRatio.Value); } } internal static void SetupCamera (Camera cameraToSetUp, Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager) { CameraSetup.graphicsDeviceManager = graphicsDeviceManager; ResetWindow(); ResetCamera(cameraToSetUp); FlatRedBall.FlatRedBallServices.GraphicsOptions.SizeOrOrientationChanged += HandleResolutionChange; } internal static void ResetWindow () { #if WINDOWS || DESKTOP_GL FlatRedBall.FlatRedBallServices.Game.Window.AllowUserResizing = Data.AllowWidowResizing; if (Data.IsFullScreen) { #if DESKTOP_GL graphicsDeviceManager.HardwareModeSwitch = false; FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution(Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height, FlatRedBall.Graphics.WindowedFullscreenMode.FullscreenBorderless); #elif WINDOWS System.IntPtr hWnd = FlatRedBall.FlatRedBallServices.Game.Window.Handle; var control = System.Windows.Forms.Control.FromHandle(hWnd); var form = control.FindForm(); form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; form.WindowState = System.Windows.Forms.FormWindowState.Maximized; #endif } else { FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution((int)(Data.ResolutionWidth * Data.Scale/ 100.0f), (int)(Data.ResolutionHeight * Data.Scale/ 100.0f)); } #elif IOS || ANDROID FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth, FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight); #elif UWP if (Data.IsFullScreen) { FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(Data.ResolutionWidth, Data.ResolutionHeight); } else { FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution((int)(Data.ResolutionWidth * Data.Scale/ 100.0f), (int)(Data.ResolutionHeight * Data.Scale/ 100.0f)); } #endif } private static void HandleResolutionChange (object sender, System.EventArgs args) { if (Data.AspectRatio != null) { SetAspectRatioTo(Data.AspectRatio.Value); } if (Data.Is2D && Data.ResizeBehavior == ResizeBehavior.IncreaseVisibleArea) { FlatRedBall.Camera.Main.OrthogonalHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale/ 100.0f); FlatRedBall.Camera.Main.FixAspectRatioYConstant(); } } private static void SetAspectRatioTo (decimal aspectRatio) { var resolutionAspectRatio = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth / (decimal)FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight; int destinationRectangleWidth; int destinationRectangleHeight; int x = 0; int y = 0; if (aspectRatio > resolutionAspectRatio) { destinationRectangleWidth = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth; destinationRectangleHeight = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleWidth / (float)aspectRatio); y = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight - destinationRectangleHeight) / 2; } else { destinationRectangleHeight = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight; destinationRectangleWidth = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleHeight * (float)aspectRatio); x = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth - destinationRectangleWidth) / 2; } FlatRedBall.Camera.Main.DestinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, destinationRectangleWidth, destinationRectangleHeight); FlatRedBall.Camera.Main.FixAspectRatioYConstant(); } } }
52.643939
329
0.596201
[ "MIT" ]
vchelaru/Dodgeball
Dodgeball/Dodgeball/Setup/CameraSetup.cs
6,949
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d10.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("9B7E4C08-342C-4106-A19F-4F2704F689F0")] [NativeTypeName("struct ID3D10RenderTargetView : ID3D10View")] public unsafe partial struct ID3D10RenderTargetView { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<ID3D10RenderTargetView*, Guid*, void**, int>)(lpVtbl[0]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ID3D10RenderTargetView*, uint>)(lpVtbl[1]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ID3D10RenderTargetView*, uint>)(lpVtbl[2]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetDevice([NativeTypeName("ID3D10Device **")] ID3D10Device** ppDevice) { ((delegate* unmanaged<ID3D10RenderTargetView*, ID3D10Device**, void>)(lpVtbl[3]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), ppDevice); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT *")] uint* pDataSize, [NativeTypeName("void *")] void* pData) { return ((delegate* unmanaged<ID3D10RenderTargetView*, Guid*, uint*, void*, int>)(lpVtbl[4]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), guid, pDataSize, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT")] uint DataSize, [NativeTypeName("const void *")] void* pData) { return ((delegate* unmanaged<ID3D10RenderTargetView*, Guid*, uint, void*, int>)(lpVtbl[5]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), guid, DataSize, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("const IUnknown *")] IUnknown* pData) { return ((delegate* unmanaged<ID3D10RenderTargetView*, Guid*, IUnknown*, int>)(lpVtbl[6]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), guid, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetResource([NativeTypeName("ID3D10Resource **")] ID3D10Resource** ppResource) { ((delegate* unmanaged<ID3D10RenderTargetView*, ID3D10Resource**, void>)(lpVtbl[7]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), ppResource); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetDesc([NativeTypeName("D3D10_RENDER_TARGET_VIEW_DESC *")] D3D10_RENDER_TARGET_VIEW_DESC* pDesc) { ((delegate* unmanaged<ID3D10RenderTargetView*, D3D10_RENDER_TARGET_VIEW_DESC*, void>)(lpVtbl[8]))((ID3D10RenderTargetView*)Unsafe.AsPointer(ref this), pDesc); } } }
51.075949
182
0.686493
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/d3d10/ID3D10RenderTargetView.cs
4,037
C#
namespace Template { using System; public abstract class Bread { public abstract void MixIngredients(); public abstract void Bake(); public virtual void Slice() { Console.WriteLine("Slicing the " + GetType().Name + " bread!"); } // Template method public void Make() { MixIngredients(); Bake(); Slice(); } } }
18.04
75
0.490022
[ "MIT" ]
stanislavstoyanov99/SoftUni-Software-Engineering
DB-with-C#/Labs-And-Homeworks/Entity Framework Core/13. Design Patterns - Exercise/Template/Bread.cs
453
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; namespace Microsoft.Build.BuildEngine { /// <summary> /// Reads registry at the base key and returns a Dictionary keyed on ToolsVersion. /// Dictionary contains another dictionary of (property name, property value) pairs. /// If a registry value is not a string, this will throw a InvalidToolsetDefinitionException. /// An example of how the registry will look (note that the DefaultToolsVersion is per-MSBuild-version) /// [HKLM]\SOFTWARE\Microsoft /// msbuild /// 3.5 /// @DefaultToolsVersion = 2.0 /// ToolsVersions /// 2.0 /// @MSBuildToolsPath = D:\SomeFolder /// 3.5 /// @MSBuildToolsPath = D:\SomeOtherFolder /// @MSBuildBinPath = D:\SomeOtherFolder /// @SomePropertyName = PropertyOtherValue /// </summary> internal class ToolsetRegistryReader : ToolsetReader { // Registry location for storing tools version dependent data for msbuild private const string msbuildRegistryPath = @"SOFTWARE\Microsoft\MSBuild"; // Cached registry wrapper at root of the msbuild entries private RegistryKeyWrapper msbuildRegistryWrapper; /// <summary> /// Default constructor /// </summary> internal ToolsetRegistryReader() : this (new RegistryKeyWrapper(msbuildRegistryPath)) { } /// <summary> /// Constructor overload accepting a registry wrapper for unit testing purposes only /// </summary> /// <param name="msbuildRegistryWrapper"></param> internal ToolsetRegistryReader(RegistryKeyWrapper msbuildRegistryWrapper) { error.VerifyThrowArgumentNull(msbuildRegistryWrapper, nameof(msbuildRegistryWrapper)); this.msbuildRegistryWrapper = msbuildRegistryWrapper; } /// <summary> /// Returns the list of tools versions /// </summary> protected override IEnumerable<PropertyDefinition> ToolsVersions { get { string[] toolsVersionNames = new string[] { }; try { toolsVersionNames = msbuildRegistryWrapper.OpenSubKey("ToolsVersions").GetSubKeyNames(); } catch (RegistryException ex) { InvalidToolsetDefinitionException.Throw(ex, "RegistryReadError", ex.Source, ex.Message); } foreach (string toolsVersionName in toolsVersionNames) { yield return new PropertyDefinition(toolsVersionName, string.Empty, msbuildRegistryWrapper.Name + "\\ToolsVersions\\" + toolsVersionName); } } } /// <summary> /// Returns the default tools version, or null if none was specified /// </summary> protected override string DefaultToolsVersion { get { // We expect to find the DefaultToolsVersion value under a registry key named for our // version, e.g., "3.5" RegistryKeyWrapper defaultToolsVersionKey = msbuildRegistryWrapper.OpenSubKey(Constants.AssemblyVersion); if (defaultToolsVersionKey != null) { return GetValue(defaultToolsVersionKey, "DefaultToolsVersion"); } else { return null; } } } /// <summary> /// Provides an enumerator over property definitions for a specified tools version /// </summary> /// <param name="toolsVersion"></param> /// <returns></returns> protected override IEnumerable<PropertyDefinition> GetPropertyDefinitions(string toolsVersion) { RegistryKeyWrapper toolsVersionWrapper = null; try { toolsVersionWrapper = msbuildRegistryWrapper.OpenSubKey("ToolsVersions\\" + toolsVersion); } catch (RegistryException ex) { InvalidToolsetDefinitionException.Throw(ex, "RegistryReadError", ex.Source, ex.Message); } foreach (string propertyName in toolsVersionWrapper.GetValueNames()) { string propertyValue = null; if (propertyName?.Length == 0) { InvalidToolsetDefinitionException.Throw("PropertyNameInRegistryHasZeroLength", toolsVersionWrapper.Name); } try { propertyValue = GetValue(toolsVersionWrapper, propertyName); } catch (RegistryException ex) { InvalidToolsetDefinitionException.Throw(ex, "RegistryReadError", ex.Source, ex.Message); } yield return new PropertyDefinition(propertyName, propertyValue, toolsVersionWrapper.Name + "@" + propertyName); } } /// <summary> /// Reads a string value from the specified registry key /// </summary> /// <param name="baseKeyWrapper">wrapper around key</param> /// <param name="valueName">name of the value</param> /// <returns>string data in the value</returns> private static string GetValue(RegistryKeyWrapper wrapper, string valueName) { if (wrapper.Exists()) { object result = wrapper.GetValue(valueName); // RegistryKey.GetValue returns null if the value is not present // and String.Empty if the value is present and no data is defined. // We preserve this distinction, because a string property in the registry with // no value really has an empty string for a value (which is a valid property value) // rather than null for a value (which is an invalid property value) if (result != null) { // Must be a value of string type if (!(result is string)) { InvalidToolsetDefinitionException.Throw("NonStringDataInRegistry", wrapper.Name + "@" + valueName); } return result.ToString(); } } return null; } } }
39.381503
158
0.569353
[ "MIT" ]
0xced/msbuild
src/Deprecated/Engine/Engine/ToolsetRegistryReader.cs
6,813
C#
using System; using System.Collections.Generic; namespace T3.SimpleCalculator { internal class Program { static void Main(string[] args) { Stack<string> stack = new Stack<string>(); } } }
15.933333
54
0.589958
[ "MIT" ]
Tencho0/SoftuniEducation
C# Advanced/advanced-jan22/StacksandQueues-Lab/T3.SimpleCalculator/Program.cs
241
C#
using System; using System.Collections.Generic; using System.Text; using fyiReporting.RDL; using System.Drawing; using System.ComponentModel; using System.Xml; namespace fyiReporting.CRI { public class BarCodeEAN8 : ICustomReportItem { static public readonly float OptimalHeight = 35.91f; // Optimal height at magnification 1 static public readonly float OptimalWidth = 65.91f; // Optimal width at mag 1 private string _codeEan8 = ""; #region ICustomReportItem Members public bool IsDataRegion() { return false; } public void DrawImage(ref Bitmap bm) { DrawImage(ref bm, _codeEan8); } /// <summary> /// Design time: Draw a hard coded BarCode for design time; Parameters can't be /// relied on since they aren't available. /// </summary> /// <param name="bm"></param> public void DrawDesignerImage(ref Bitmap bm) { DrawImage(ref bm, "12345678"); } public void DrawImage(ref Bitmap bm, string code) { var writer = new ZXing.BarcodeWriter(); writer.Format = ZXing.BarcodeFormat.EAN_8; Graphics g = null; g = Graphics.FromImage(bm); float mag = PixelConversions.GetMagnification(g, bm.Width, bm.Height, OptimalHeight, OptimalWidth); int barHeight = PixelConversions.PixelXFromMm(g, OptimalHeight * mag); int barWidth = PixelConversions.PixelYFromMm(g, OptimalWidth * mag); writer.Options.Height = barHeight; writer.Options.Width = barWidth; bm = writer.Write(code); } public void SetProperties(IDictionary<string, object> props) { try { _codeEan8 = props["Code"].ToString(); } catch (KeyNotFoundException) { throw new Exception("Code property must be specified"); } } public object GetPropertiesInstance(XmlNode iNode) { BarCodeProperties bcp = new BarCodeProperties(this, iNode); foreach (XmlNode n in iNode.ChildNodes) { if (n.Name != "CustomProperty") continue; string pname = XmlHelpers.GetNamedElementValue(n, "Name", ""); switch (pname) { case "Code": bcp.SetBarCode(XmlHelpers.GetNamedElementValue(n, "Value", "")); break; default: break; } } return bcp; } public void SetPropertiesInstance(XmlNode node, object inst) { node.RemoveAll(); // Get rid of all properties BarCodeProperties bcp = inst as BarCodeProperties; if (bcp == null) return; XmlHelpers.CreateChild(node, "Code", bcp.Code); } /// <summary> /// Design time call: return string with <CustomReportItem> ... </CustomReportItem> syntax for /// the insert. The string contains a variable {0} which will be substituted with the /// configuration name. This allows the name to be completely controlled by /// the configuration file. /// </summary> /// <returns></returns> public string GetCustomReportItemXml() { return "<CustomReportItem><Type>{0}</Type>" + string.Format("<Height>{0}mm</Height><Width>{1}mm</Width>", OptimalHeight, OptimalWidth) + "<CustomProperties>" + "<CustomProperty>" + "<Name>Code</Name>" + "<Value>00123456</Value>" + "</CustomProperty>" + "</CustomProperties>" + "</CustomReportItem>"; } #endregion #region IDisposable Members public void Dispose() { return; } #endregion /// <summary> /// BarCodeProperties- All properties are type string to allow for definition of /// a runtime expression. /// </summary> public class BarCodeProperties { string _codeEan8; BarCodeEAN8 _bc; XmlNode _node; internal BarCodeProperties(BarCodeEAN8 bc, XmlNode node) { _bc = bc; _node = node; } internal void SetBarCode(string ns) { _codeEan8 = ns; } [Category("Code"), Description("The text string to be encoded as a BarCodeEAN8 Code.")] public string Code { get { return _codeEan8; } set { _codeEan8 = value; _bc.SetPropertiesInstance(_node, this); } } } } }
29.627219
110
0.526463
[ "Apache-2.0" ]
Enzogord/My-FyiReporting
RdlCri/BarCodeEAN8.cs
5,009
C#
namespace Lab_10 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.search_button = new System.Windows.Forms.Button(); this.id_box = new System.Windows.Forms.TextBox(); this.employee_id_listbox = new System.Windows.Forms.ListBox(); this.log_box = new System.Windows.Forms.ListBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.info_box = new System.Windows.Forms.ListBox(); this.show_log = new System.Windows.Forms.Button(); this.employee_name_listbox = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(381, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(20, 16); this.label2.TabIndex = 1; this.label2.Text = "ID"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(865, 35); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 16); this.label3.TabIndex = 2; this.label3.Text = "Analysis"; // // search_button // this.search_button.Location = new System.Drawing.Point(426, 83); this.search_button.Name = "search_button"; this.search_button.Size = new System.Drawing.Size(100, 23); this.search_button.TabIndex = 8; this.search_button.Text = "search"; this.search_button.UseVisualStyleBackColor = true; this.search_button.Click += new System.EventHandler(this.search_button_Click); // // id_box // this.id_box.Location = new System.Drawing.Point(426, 48); this.id_box.Name = "id_box"; this.id_box.Size = new System.Drawing.Size(100, 22); this.id_box.TabIndex = 11; // // employee_id_listbox // this.employee_id_listbox.FormattingEnabled = true; this.employee_id_listbox.ItemHeight = 16; this.employee_id_listbox.Location = new System.Drawing.Point(53, 86); this.employee_id_listbox.Name = "employee_id_listbox"; this.employee_id_listbox.Size = new System.Drawing.Size(255, 276); this.employee_id_listbox.TabIndex = 17; // // log_box // this.log_box.FormattingEnabled = true; this.log_box.ItemHeight = 16; this.log_box.Location = new System.Drawing.Point(868, 104); this.log_box.Name = "log_box"; this.log_box.Size = new System.Drawing.Size(181, 276); this.log_box.TabIndex = 18; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(1195, 395); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(100, 22); this.textBox7.TabIndex = 28; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(1195, 502); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(100, 22); this.textBox6.TabIndex = 27; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(1195, 449); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(100, 22); this.textBox5.TabIndex = 26; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(1236, 546); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(100, 22); this.textBox4.TabIndex = 25; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(1236, 588); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(100, 22); this.textBox3.TabIndex = 24; // // info_box // this.info_box.FormattingEnabled = true; this.info_box.ItemHeight = 16; this.info_box.Location = new System.Drawing.Point(350, 141); this.info_box.Name = "info_box"; this.info_box.Size = new System.Drawing.Size(396, 276); this.info_box.TabIndex = 29; // // show_log // this.show_log.Location = new System.Drawing.Point(949, 35); this.show_log.Name = "show_log"; this.show_log.Size = new System.Drawing.Size(100, 23); this.show_log.TabIndex = 30; this.show_log.Text = "show"; this.show_log.UseVisualStyleBackColor = true; this.show_log.Click += new System.EventHandler(this.show_csv_Click); // // employee_name_listbox // this.employee_name_listbox.FormattingEnabled = true; this.employee_name_listbox.ItemHeight = 16; this.employee_name_listbox.Location = new System.Drawing.Point(1206, 86); this.employee_name_listbox.Name = "employee_name_listbox"; this.employee_name_listbox.Size = new System.Drawing.Size(122, 276); this.employee_name_listbox.TabIndex = 31; this.employee_name_listbox.SelectedIndexChanged += new System.EventHandler(this.employee_name_listbox_SelectedIndexChanged); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1340, 612); this.Controls.Add(this.employee_name_listbox); this.Controls.Add(this.show_log); this.Controls.Add(this.info_box); this.Controls.Add(this.textBox7); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.log_box); this.Controls.Add(this.employee_id_listbox); this.Controls.Add(this.id_box); this.Controls.Add(this.search_button); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button search_button; private System.Windows.Forms.TextBox id_box; private System.Windows.Forms.ListBox employee_id_listbox; private System.Windows.Forms.ListBox log_box; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.ListBox info_box; private System.Windows.Forms.Button show_log; private System.Windows.Forms.ListBox employee_name_listbox; } }
43.100478
136
0.574489
[ "MIT" ]
GoonerMAK/SWE_4202_OOC-I
Lab_10/Lab 10/Form1.Designer.cs
9,010
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Top.Api; namespace DingTalk.Api.Response { /// <summary> /// OapiUserListbypageResponse. /// </summary> public class OapiUserListbypageResponse : DingTalkResponse { /// <summary> /// errcode /// </summary> [XmlElement("errcode")] public long Errcode { get; set; } /// <summary> /// errmsg /// </summary> [XmlElement("errmsg")] public string Errmsg { get; set; } /// <summary> /// hasMore /// </summary> [XmlElement("hasMore")] public bool HasMore { get; set; } /// <summary> /// userlist /// </summary> [XmlArray("userlist")] [XmlArrayItem("userlist")] public List<UserlistDomain> Userlist { get; set; } /// <summary> /// UserlistDomain Data Structure. /// </summary> [Serializable] public class UserlistDomain : TopObject { /// <summary> /// active /// </summary> [XmlElement("active")] public bool Active { get; set; } /// <summary> /// avatar /// </summary> [XmlElement("avatar")] public string Avatar { get; set; } /// <summary> /// department /// </summary> [XmlArray("department")] [XmlArrayItem("number")] public List<long> Department { get; set; } /// <summary> /// dingId /// </summary> [XmlElement("dingId")] public string DingId { get; set; } /// <summary> /// email /// </summary> [XmlElement("email")] public string Email { get; set; } /// <summary> /// extattr /// </summary> [XmlElement("extattr")] public string Extattr { get; set; } /// <summary> /// hiredDate /// </summary> [XmlElement("hiredDate")] public string HiredDate { get; set; } /// <summary> /// isAdmin /// </summary> [XmlElement("isAdmin")] public bool IsAdmin { get; set; } /// <summary> /// isBoss /// </summary> [XmlElement("isBoss")] public bool IsBoss { get; set; } /// <summary> /// isHide /// </summary> [XmlElement("isHide")] public bool IsHide { get; set; } /// <summary> /// isLeader /// </summary> [XmlElement("isLeader")] public bool IsLeader { get; set; } /// <summary> /// jobnumber /// </summary> [XmlElement("jobnumber")] public string Jobnumber { get; set; } /// <summary> /// mobile /// </summary> [XmlElement("mobile")] public string Mobile { get; set; } /// <summary> /// name /// </summary> [XmlElement("name")] public string Name { get; set; } /// <summary> /// order /// </summary> [XmlElement("order")] public long Order { get; set; } /// <summary> /// orgEmail /// </summary> [XmlElement("orgEmail")] public string OrgEmail { get; set; } /// <summary> /// position /// </summary> [XmlElement("position")] public string Position { get; set; } /// <summary> /// remark /// </summary> [XmlElement("remark")] public string Remark { get; set; } /// <summary> /// tel /// </summary> [XmlElement("tel")] public string Tel { get; set; } /// <summary> /// unionid /// </summary> [XmlElement("unionid")] public string Unionid { get; set; } /// <summary> /// userid /// </summary> [XmlElement("userid")] public string Userid { get; set; } /// <summary> /// workPlace /// </summary> [XmlElement("workPlace")] public string WorkPlace { get; set; } } } }
23.61326
62
0.452737
[ "MIT" ]
lee890720/YiShaAdmin
YiSha.Util/YsSha.Dingtalk/DingTalk/Response/OapiUserListbypageResponse.cs
4,274
C#
using LiteDB; using Repo2.Core.ns11.Exceptions; using Repo2.SDK.WPF45.ChangeNotification; using Repo2.SDK.WPF45.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Repo2.SDK.WPF45.Databases { public abstract partial class LocalRepoBase<T> : R2LiteRepoBase { protected virtual void InsertSeedRecordsFromFile(string jsonFilename, string jsonFilePath) { var jsonStr = File.ReadAllText(jsonFilePath, Encoding.UTF8); var seedRecs = Json.Deserialize<List<T>>(jsonStr); SetStatus($"Seeding {seedRecs.Count:N0} ‹{TypeName}› records from [{jsonFilename}] ..."); using (var db = CreateLiteDatabase()) { var col = db.GetCollection<T>(CollectionName); using (var trans = db.BeginTrans()) { foreach (var rec in seedRecs) if (rec != null) col.Insert(rec); trans.Commit(); } } SetStatus($"Successfully inserted ‹{TypeName}› records from seed file."); } public virtual uint Insert(T newRecord) { if (newRecord == null) throw Fault.NullRef<T>("record to insert"); SetStatus($"Inserting new ‹{TypeName}› record ..."); BsonValue bVal; using (var db = ConnectToDB(out LiteCollection<T> col)) { if (!PreInsertValidate(newRecord, col, out string msg)) throw new InvalidDataException(msg); using (var trans = db.BeginTrans()) { bVal = col.Insert(newRecord); EnsureIndeces(col); trans.Commit(); } } var id = (uint)bVal.AsInt64; SetStatus($"Sucessfully inserted ‹{TypeName}› (id: {id})."); return id; } protected virtual bool PreInsertValidate(T newRecord, LiteCollection<T> col, out string msg) { msg = string.Empty; return true; } public virtual uint BatchInsert(IEnumerable<T> newRecords) { SetStatus($"Inserting {newRecords.Count()} ‹{TypeName}› records ..."); using (var db = ConnectToDB(out LiteCollection<T> col)) { using (var trans = db.BeginTrans()) { foreach (var rec in newRecords) { if (rec == null) continue; if (!PreInsertValidate(rec, col, out string msg)) throw new InvalidDataException(msg); col.Insert(rec); } EnsureIndeces(col); trans.Commit(); } } var newCount = CountAll(); SetStatus($"Successfully inserted {newRecords.Count()} ‹{TypeName}› records. New record count: [{newCount:N0}]"); return newCount; } public virtual uint DeleteAll() { SetStatus($"Deleting all [{CountAll():N0}] ‹{TypeName}› records ..."); using (var db = ConnectToDB(out LiteCollection<T> col)) { db.DropCollection(col.Name); } var newCount = CountAll(); SetStatus($"DeleteAll ‹{TypeName}› completed. New record count: [{newCount:N0}]."); return newCount; } //protected void EnsureIndex<K>(Expression<Func<T, K>> indexExpression, bool isUnique) //{ // using (var db = ConnectToDB(out LiteCollection<T> col)) // { // col.EnsureIndex<K>(indexExpression, isUnique); // } //} public virtual void EnsureIndeces(LiteCollection<T> col) { } } }
32.512195
125
0.517879
[ "MIT" ]
peterson1/Repo2
Repo2.SDK.WPF45/Databases/LocalRepoBase_Write.cs
4,033
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Stratis.FederatedPeg.Features.FederationGateway.Interfaces; using Stratis.FederatedPeg.Features.FederationGateway.Models; using Stratis.FederatedPeg.Features.FederationGateway.RestClients; namespace Stratis.FederatedPeg.Features.FederationGateway.TargetChain { /// <summary> /// Handles block syncing between gateways on 2 chains. This node will request /// blocks from another chain to look for cross chain deposit transactions. /// </summary> public interface IMaturedBlocksSyncManager : IDisposable { /// <summary>Starts requesting blocks from another chain.</summary> void Initialize(); } /// <inheritdoc cref="IMaturedBlocksSyncManager"/> public class MaturedBlocksSyncManager : IMaturedBlocksSyncManager { private readonly ICrossChainTransferStore store; private readonly IFederationGatewayClient federationGatewayClient; private readonly ILogger logger; private readonly CancellationTokenSource cancellation; private Task blockRequestingTask; /// <summary>The maximum amount of blocks to request at a time from alt chain.</summary> private const int MaxBlocksToRequest = 1000; /// <summary>When we are fully synced we stop asking for more blocks for this amount of time.</summary> private const int RefreshDelayMs = 10_000; /// <summary>Delay between initialization and first request to other node.</summary> /// <remarks>Needed to give other node some time to start before bombing it with requests.</remarks> private const int InitializationDelayMs = 10_000; public MaturedBlocksSyncManager(ICrossChainTransferStore store, IFederationGatewayClient federationGatewayClient, ILoggerFactory loggerFactory) { this.store = store; this.federationGatewayClient = federationGatewayClient; this.cancellation = new CancellationTokenSource(); this.logger = loggerFactory.CreateLogger(this.GetType().FullName); } /// <inheritdoc /> public void Initialize() { this.blockRequestingTask = RequestMaturedBlocksContinouslyAsync(); } /// <summary>Continuously requests matured blocks from another chain.</summary> private async Task RequestMaturedBlocksContinouslyAsync() { try { // Initialization delay. // Give other node some time to start API service. await Task.Delay(InitializationDelayMs, this.cancellation.Token).ConfigureAwait(false); while (!this.cancellation.IsCancellationRequested) { bool delayRequired = await this.SyncBatchOfBlocksAsync(this.cancellation.Token).ConfigureAwait(false); if (delayRequired) { // Since we are synced or had a problem syncing there is no need to ask for more blocks right away. // Therefore awaiting for a delay during which new block might be accepted on the alternative chain // or alt chain node might be started. await Task.Delay(RefreshDelayMs, this.cancellation.Token).ConfigureAwait(false); } } } catch (OperationCanceledException) { this.logger.LogTrace("(-)[CANCELLED]"); } } /// <summary>Asks for blocks from another gateway node and then processes them.</summary> /// <returns><c>true</c> if delay between next time we should ask for blocks is required; <c>false</c> otherwise.</returns> /// <exception cref="OperationCanceledException">Thrown when <paramref name="cancellationToken"/> is cancelled.</exception> protected async Task<bool> SyncBatchOfBlocksAsync(CancellationToken cancellationToken = default(CancellationToken)) { int blocksToRequest = 1; // TODO why are we asking for max of 1 block and if it's not suspended then 1000? investigate this logic in maturedBlocksProvider if (!this.store.HasSuspended()) blocksToRequest = MaxBlocksToRequest; // TODO investigate if we can ask for blocks that are reorgable. If so it's a problem and an attack vector. // API method that provides blocks should't give us blocks that are not mature! var model = new MaturedBlockRequestModel(this.store.NextMatureDepositHeight, blocksToRequest); this.logger.LogDebug("Request model created: {0}:{1}, {2}:{3}.", nameof(model.BlockHeight), model.BlockHeight, nameof(model.MaxBlocksToSend), model.MaxBlocksToSend); // Ask for blocks. IList<MaturedBlockDepositsModel> matureBlockDeposits = await this.federationGatewayClient.GetMaturedBlockDepositsAsync(model, cancellationToken).ConfigureAwait(false); bool delayRequired = true; if (matureBlockDeposits != null) { // Log what we've received. foreach (MaturedBlockDepositsModel maturedBlockDeposit in matureBlockDeposits) { foreach (IDeposit deposit in maturedBlockDeposit.Deposits) { this.logger.LogDebug("New deposit received BlockNumber={0}, TargetAddress='{1}', depositId='{2}', Amount='{3}'.", deposit.BlockNumber, deposit.TargetAddress, deposit.Id, deposit.Amount); } } if (matureBlockDeposits.Count > 0) { bool success = await this.store.RecordLatestMatureDepositsAsync(matureBlockDeposits).ConfigureAwait(false); // If we received a portion of blocks we can ask for new portion without any delay. if (success) delayRequired = false; } else { this.logger.LogDebug("Considering ourselves fully synced since no blocks were received"); // If we've received nothing we assume we are at the tip and should flush. // Same mechanic as with syncing headers protocol. await this.store.SaveCurrentTipAsync().ConfigureAwait(false); } } return delayRequired; } /// <inheritdoc /> public void Dispose() { this.cancellation.Cancel(); this.blockRequestingTask?.GetAwaiter().GetResult(); } } }
45.019737
179
0.633348
[ "MIT" ]
rowandh/FederatedSidechains
src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/MaturedBlocksSyncManager.cs
6,845
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Rill.Core; using Rill.Stores.EfCore.Serialization; namespace Rill.Stores.EfCore { internal class RillEventEntity { internal Guid Id { get; } internal Guid CommitId { get; } internal string TypeAssemblyName { get; } internal string TypeNamespace { get; } internal string TypeName { get; } internal long Sequence { get; } internal DateTimeOffset Timestamp { get; } internal string Content { get; } private RillEventEntity( Guid id, Guid commitId, string typeAssemblyName, string typeNamespace, string typeName, long sequence, DateTimeOffset timestamp, string content) { Id = id; CommitId = commitId; Sequence = sequence; Timestamp = timestamp; TypeAssemblyName = typeAssemblyName; TypeNamespace = typeNamespace; TypeName = typeName; Content = content; } internal static RillEventEntity From(RillCommit commit, Event e, IEventContentSerializer contentSerializer) { var ct = EventContentType.From(e.Content.GetType()); return new RillEventEntity( (Guid) e.Id, (Guid) commit.Id, ct.AssemblyName, ct.Namespace, ct.Name, (long) e.Sequence, (DateTime) e.Timestamp, contentSerializer.Serialize(e.Content)); } internal Event ToEvent(IEventContentTypeResolver eventContentTypeResolver, IEventContentSerializer contentSerializer) { var ct = new EventContentType(TypeAssemblyName, TypeNamespace, TypeName); var t = eventContentTypeResolver.Resolve(ct); return Event.From( EventId.From(Id), Rill.Sequence.From(Sequence), Rill.Timestamp.From(Timestamp.UtcDateTime), contentSerializer.Deserialize(Content, t)); } } internal class RillEventEntityConfiguration : IEntityTypeConfiguration<RillEventEntity> { public void Configure(EntityTypeBuilder<RillEventEntity> builder) { builder .ToTable("RillEvent"); builder .HasKey(i => i.Id) .HasName("PK_RillEvent"); builder .HasIndex(i => i.TypeName); builder .HasIndex(i => i.Sequence); // builder // .HasOne<RillEntity>() // .WithMany() // .HasForeignKey(i => i.RillId) // .HasConstraintName("FK_RillEvent_Rill") // .OnDelete(DeleteBehavior.NoAction); builder .HasOne<RillCommitEntity>() .WithMany(i => i.Events) .HasForeignKey(i => i.CommitId) .HasConstraintName("FK_RillEvent_RillCommit") .OnDelete(DeleteBehavior.Cascade); builder .Property(i => i.Id) .IsRequired() .ValueGeneratedNever(); // builder // .Property(i => i.RillId) // .IsRequired() // .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.CommitId) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.TypeAssemblyName) .IsUnicode(false) .HasMaxLength(128) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.TypeNamespace) .IsUnicode(false) .HasMaxLength(128) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.TypeName) .IsUnicode(false) .HasMaxLength(32) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.Sequence) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.Timestamp) .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder .Property(i => i.Content) .IsUnicode() .IsRequired() .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); } } }
35.539007
125
0.538815
[ "MIT" ]
danielwertheim/Rill
src/main/Rill.Stores.EfCore/RillEventEntity.cs
5,013
C#
using System; using ComputerAssistedRoleplay.Model.Weapons.Affliction; namespace ComputerAssistedRoleplay.Model.Character.StatusEffect { class Bleed : IStatusEffect { private CauseBleed affliction; public Bleed(CauseBleed affliction) { this.affliction = affliction; } public void ApplyEffect(CharacterSheet cs) { throw new NotImplementedException(); } public string Description() { return "Der Charakter blutet"; } } }
20.481481
63
0.616637
[ "MIT" ]
ghosta0815/ComputerAssistedRoleplay
ComputerAssistedRoleplay/Model/Character/StatusEffect/Bleed.cs
555
C#
using System; using System.IO; using System.Web; using Ramone.IO; using Ramone.Utility.ObjectSerialization; using System.Text; namespace Ramone.Utility { public class FormUrlEncodingPropertyVisitor : IPropertyVisitor { protected TextWriter Writer; protected Encoding Encoding; protected bool FirstValue = true; public FormUrlEncodingPropertyVisitor(TextWriter writer, Encoding enc = null) { Writer = writer; Encoding = enc ?? Encoding.UTF8; } #region IPropertyVisitor public void Begin() { } public void SimpleValue(string name, object value, string formatedValue) { if (!FirstValue) Writer.Write("&"); Writer.Write(HttpUtility.UrlEncode(name, Encoding)); Writer.Write("="); Writer.Write(HttpUtility.UrlEncode(formatedValue, Encoding)); FirstValue = false; } public void File(IFile file, string name) { throw new InvalidOperationException(string.Format("Cannot serialize Ramone IFile '{0}' as {1}.", name, MediaType.ApplicationFormUrlEncoded)); } public void End() { Writer.Flush(); } #endregion } }
21.385965
148
0.641509
[ "MIT" ]
ArvoX/Ramone
Ramone/Utility/FormUrlEncodingPropertyVisitor.cs
1,221
C#
using System; using System.Configuration; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.ServiceBus; namespace WebJobs { class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { var config = new JobHostConfiguration(); if (config.IsDevelopment) { string eventHubName = ConfigurationManager.AppSettings["EventHubName"]; string eventHubEndpoint = ConfigurationManager.AppSettings["EventHubEndpoint"]; config.UseDevelopmentSettings(); EventHubConfiguration hubConfig = new EventHubConfiguration(); hubConfig.AddReceiver(eventHubName, eventHubEndpoint); config.UseEventHub(hubConfig); } var host = new JobHost(config); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); } } }
32.757576
95
0.635523
[ "MIT" ]
NickSchweitzer/SumpPumpMonitor
WebJobs/Program.cs
1,083
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace LocalHookProviders { using System; using NetHook.Core; using System.Reflection; using System.Runtime.ConstrainedExecution; public sealed class LocalHookProvider_TestInstanceMethodArgs_0 : NetHook.Core.LocalHookRuntimeInstance { public LocalHookProvider_TestInstanceMethodArgs_0(NetHook.Core.LocalHookAdapter adapter) : base(LocalHookAdapter.Current.Get("NetHook.MSTest.UnitTestLocalHook+TestInstance, NetHook.MSTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null;TestInstanceMethodArgs"), typeof(LocalHookProvider_TestInstanceMethodArgs_0).GetMethod("TestInstanceMethodArgs_Hook", BindingFlags.Static | BindingFlags.NonPublic)) { } private static object TestInstanceMethodArgs_Hook(object thisObj, object arg_0, object arg_1, object arg_2, object arg_3, object arg_4, object arg_5, object arg_6, object arg_7, object arg_8, object arg_9) { object[] objectArray = new object[] { arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9 }; object value = IntPtr.Zero; Exception e = null; LocalHookAdapter.Current.BeginInvoke("NetHook.MSTest.UnitTestLocalHook+TestInstance, NetHook.MSTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null;TestInstanceMethodArgs", thisObj, objectArray); try { if (objectArray.Length == 0) value = TestInstanceMethodArgs_Hook(thisObj, arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9); else if (objectArray.Length == 1) value = TestInstanceMethodArgs_Hook(thisObj, arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9); else if (objectArray.Length == 2) value = TestInstanceMethodArgs_Hook(thisObj, arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9); else if (objectArray.Length == 3) value = TestInstanceMethodArgs_Hook(thisObj, arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9); else value = TestInstanceMethodArgs_Hook(thisObj, arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9); } catch (System.Exception ex) { e = ex; throw; } finally { LocalHookAdapter.Current.AfterInvoke("NetHook.MSTest.UnitTestLocalHook+TestInstance, NetHook.MSTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null;TestInstanceMethodArgs", thisObj, value, e); } return value; } } }
56.481481
333
0.637705
[ "Apache-2.0" ]
Evgeniy347/NetHook
NetHook.MSTest/GenerateSourceCode/TestArgsReturnHook.cs
3,184
C#
using System; using Cron.Interface; using Serilog; namespace Cron.CLI.Logging { public class CronLogger: ICronLogger { private readonly ILogger _logger; public CronLogger(ILogger logger) { _logger = logger; } public void Debug(string message) { _logger.Debug(message); } public void Info(string message) { _logger.Information(message); } public void Warning(string message) { _logger.Warning(message); } public void Trace(string message) { _logger.Verbose(message); } public void Error(string message) { _logger.Error(message); } public void Error(Exception e) { _logger.Error(e, "Error occurred"); } public void Error(Exception e, string error) { _logger.Error(e, error); } } }
20.06
52
0.516451
[ "MIT" ]
cronfoundation/cronium-cli
Cron.CLI/Logging/CronLogger.cs
1,005
C#
using ClipperLib; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.IO.Compression; using System.Linq; using System.Xml.Serialization; using Polygons = System.Collections.Generic.List<System.Collections.Generic.List<ClipperLib.IntPoint>>; using GerberLibrary.Core.Primitives; using GerberLibrary.Core; using Ionic.Zip; using TriangleNet; using TriangleNet.Geometry; namespace GerberLibrary { public interface ProgressLog { void AddString(string text, float progress = -1); } public class GerberPanel { public GerberLayoutSet TheSet; public GerberPanel(double width = 100, double height = 100) { TheSet = new GerberLayoutSet(); TheSet.Width = width; TheSet.Height = height; } public Bitmap BoardBitmap = new Bitmap(1000, 1000); public List<PolyLine> CombinedOutline = new List<PolyLine>(); GraphicsPath GP = new GraphicsPath(); Bitmap MMGrid = null; public List<string> AddGerberFolder(string path, bool add = true, bool skipoutlines = false) { if (File.Exists(path) && (Path.GetExtension(path).ToLower() == ".zip" || Path.GetExtension(path).ToLower() == "zip")) { return AddGerberZip(path, add); } List<string> res = new List<string>(); if (add) TheSet.LoadedOutlines.Add(path); string foldername = Path.GetDirectoryName(path + Path.DirectorySeparatorChar); Console.WriteLine("adding folder {0}", foldername); bool had = false; if (Directory.Exists(Path.Combine(path, "ultiboard"))) { Console.WriteLine("found ultiboard folder {0}", foldername); } string[] FileNames = Directory.GetFiles(foldername); List<string> outlinefiles = new List<string>(); List<string> millfiles = new List<string>(); List<string> copperfiles = new List<string>(); foreach (var F in FileNames) { BoardSide BS = BoardSide.Unknown; BoardLayer BL = BoardLayer.Unknown; var FileTypeForFileName = Gerber.FindFileType(F); if (FileTypeForFileName == BoardFileType.Gerber) { Gerber.DetermineBoardSideAndLayer(F, out BS, out BL); if (BS == BoardSide.Both && BL == BoardLayer.Outline) { outlinefiles.Add(F); } else { if (BS == BoardSide.Both && BL == BoardLayer.Mill) { millfiles.Add(F); } else { if (BL == BoardLayer.Copper) { copperfiles.Add(F); } } } } } if (skipoutlines == false) { foreach (var a in outlinefiles) { GerberOutlines[path] = new GerberOutline(a); if (GerberOutlines[path].TheGerber.DisplayShapes.Count > 0) had = true; } if (had == false) { foreach (var a in millfiles) { GerberOutlines[path] = new GerberOutline(a); if (GerberOutlines[path].TheGerber.DisplayShapes.Count > 0) had = true; } } if (had == false) { // TODO: extract an outline from other layers? THIS IS DANGEROUS! Console.WriteLine("Warning: {0} has no outline available?", path); } else { res.Add(path); } } return res; } private List<string> AddGerberZip(string path, bool add) { List<string> res = new List<string>(); Dictionary<string, MemoryStream> Files = new Dictionary<string, MemoryStream>(); using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(path)) { foreach (ZipEntry e in zip1) { MemoryStream MS = new MemoryStream(); if (e.IsDirectory == false) { e.Extract(MS); MS.Seek(0, SeekOrigin.Begin); Files[e.FileName] = MS; } } } if (add) TheSet.LoadedOutlines.Add(path); string foldername = Path.GetDirectoryName(path + Path.DirectorySeparatorChar); Console.WriteLine("adding zip file {0}", foldername); bool had = false; string[] FileNames = Files.Keys.ToArray(); List<string> outlinefiles = new List<string>(); List<string> millfiles = new List<string>(); List<string> copperfiles = new List<string>(); foreach (var F in FileNames) { BoardSide BS = BoardSide.Unknown; BoardLayer BL = BoardLayer.Unknown; Files[F].Seek(0, SeekOrigin.Begin); if (Gerber.FindFileTypeFromStream(new StreamReader(Files[F]), F) == BoardFileType.Gerber) { Gerber.DetermineBoardSideAndLayer(F, out BS, out BL); if (BS == BoardSide.Both && BL == BoardLayer.Outline) { outlinefiles.Add(F); } else { if (BS == BoardSide.Both && BL == BoardLayer.Mill) { millfiles.Add(F); } else { if (BL == BoardLayer.Copper) { copperfiles.Add(F); } } } } } foreach (var a in outlinefiles) { Files[a].Seek(0, SeekOrigin.Begin); GerberOutlines[path] = new GerberOutline(new StreamReader(Files[a]), a); if (GerberOutlines[path].TheGerber.DisplayShapes.Count > 0) had = true; } if (had == false) { foreach (var a in millfiles) { Files[a].Seek(0, SeekOrigin.Begin); GerberOutlines[path] = new GerberOutline(new StreamReader(Files[a]), a); if (GerberOutlines[path].TheGerber.DisplayShapes.Count > 0) had = true; } } if (had == false) { // TODO: extract an outline from other layers? THIS IS DANGEROUS! Console.WriteLine("{0} has no outline available?", path); } else { res.Add(path); } return res; } public void BuildAutoTabs(GerberArtWriter GAW = null, GerberArtWriter GAW2 = null) { if (TheSet.Instances.Count < 3) return; List<Vertex> Vertes = new List<Vertex>(); Dictionary<Vertex, GerberLibrary.GerberInstance> InstanceMap = new Dictionary<Vertex, GerberLibrary.GerberInstance>(); foreach (var a in TheSet.Instances) { if (a.GerberPath.Contains("???_negative") == false) { var outline = GerberOutlines[a.GerberPath]; var P = outline.GetActualCenter(); P = P.Rotate(a.Angle); P.X += a.Center.X; P.Y += a.Center.Y; var V = new Vertex(P.X, P.Y); InstanceMap[V] = a; Vertes.Add(V); } } UpdateShape(); var M = new TriangleNet.Meshing.GenericMesher(); var R = M.Triangulate(Vertes); foreach (var a in R.Edges) { var A = R.Vertices.ElementAt(a.P0); var B = R.Vertices.ElementAt(a.P1); PolyLine P = new PolyLine(); P.Add(A.X, A.Y); P.Add(B.X, B.Y); GerberLibrary.GerberInstance iA = null; GerberLibrary.GerberInstance iB = null; for (int i = 0; i < InstanceMap.Count; i++) { var V = InstanceMap.Keys.ElementAt(i); if (V.ID == A.ID) iA = InstanceMap.Values.ElementAt(i); if (V.ID == B.ID) iB = InstanceMap.Values.ElementAt(i); } if (iA != null && iB != null) { PointD vA = new PointD(A.X, A.Y); PointD vB = new PointD(B.X, B.Y); PointD diffA = vB; diffA.X -= iA.Center.X; diffA.Y -= iA.Center.Y; diffA = diffA.Rotate(-iA.Angle); PointD diffB = vA; diffB.X -= iB.Center.X; diffB.Y -= iB.Center.Y; diffB = diffB.Rotate(-iB.Angle); var outlineA = GerberOutlines[iA.GerberPath]; var outlineB = GerberOutlines[iB.GerberPath]; PointD furthestA = new PointD(); PointD furthestB = new PointD(); double furthestdistA = 0.0; var acA = outlineA.GetActualCenter(); var acB = outlineB.GetActualCenter(); foreach (var s in outlineA.TheGerber.OutlineShapes) { List<PointD> intersect = s.GetIntersections(diffA, acA); if (intersect != null && intersect.Count > 0) { for (int i = 0; i < intersect.Count; i++) { double newD = PointD.Distance(acA, intersect[i]); PolyLine PL = new PolyLine(); var CP = intersect[i].Rotate(iA.Angle); CP.X += iA.Center.X; CP.Y += iA.Center.Y; PL.MakeCircle(1); PL.Translate(CP.X, CP.Y); if (GAW != null) GAW.AddPolygon(PL); if (newD > furthestdistA) { furthestdistA = newD; furthestA = intersect[i]; } } } } double furthestdistB = 0.0; foreach (var s in outlineB.TheGerber.OutlineShapes) { List<PointD> intersect = s.GetIntersections(diffB, acB); if (intersect != null && intersect.Count > 0) { for (int i = 0; i < intersect.Count; i++) { double newD = PointD.Distance(acB, intersect[i]); PolyLine PL = new PolyLine(); var CP = intersect[i].Rotate(iB.Angle); CP.X += iB.Center.X; CP.Y += iB.Center.Y; PL.MakeCircle(1); PL.Translate(CP.X, CP.Y); if (GAW != null) GAW.AddPolygon(PL); if (newD > furthestdistB) { furthestdistB = newD; furthestB = intersect[i]; } } } } if (furthestdistB != 0 && furthestdistA != 0) { furthestA = furthestA.Rotate(iA.Angle); furthestA.X += iA.Center.X; furthestA.Y += iA.Center.Y; furthestB = furthestB.Rotate(iB.Angle); furthestB.X += iB.Center.X; furthestB.Y += iB.Center.Y; var Distance = PointD.Distance(furthestA, furthestB); if (Distance < 7) { var CP = new PointD((furthestA.X + furthestB.X) / 2, (furthestA.Y + furthestB.Y) / 2); var T = AddTab(CP); T.Radius = (float)Math.Max(Distance / 1.5, 3.2f); PolyLine PL = new PolyLine(); PL.MakeCircle(T.Radius); PL.Translate(CP.X, CP.Y); if (GAW2 != null) GAW2.AddPolygon(PL); } } else { var T = AddTab(new PointD((A.X + B.X) / 2, (A.Y + B.Y) / 2)); T.Radius = 3.0f; } } if (GAW != null) GAW.AddPolyLine(P, 0.1); } UpdateShape(); RemoveAllTabs(true); UpdateShape(); } public Dictionary<string, GerberOutline> GerberOutlines = new Dictionary<string, GerberOutline>(); /// <summary> /// Create a board-sized square and subtract all the boardshapes from this shape. /// </summary> /// <param name="offsetinMM"></param> /// <param name="retractMM"></param> /// <returns></returns> public List<PolyLine> GenerateNegativePolygon(double offsetinMM = 3, double retractMM = 1) { Polygons CombinedInstanceOutline = new Polygons(); foreach (var b in TheSet.Instances) { Polygons clips = new Polygons(); var a = GerberOutlines[b.GerberPath]; foreach (var c in b.TransformedOutlines) { // PolyLine PL = new PolyLine(); // PL.FillTransformed(c, new PointD(b.Center), b.Angle); clips.Add(c.toPolygon()); } Clipper cp = new Clipper(); cp.AddPolygons(CombinedInstanceOutline, PolyType.ptSubject); cp.AddPolygons(clips, PolyType.ptClip); cp.Execute(ClipType.ctUnion, CombinedInstanceOutline, PolyFillType.pftNonZero, PolyFillType.pftNonZero); } Polygons BoardMinusCombinedInstanceOutline = new Polygons(); PolyLine Board = new PolyLine(); Board.Vertices.Add(new PointD(0, 0)); Board.Vertices.Add(new PointD(TheSet.Width, 0)); Board.Vertices.Add(new PointD(TheSet.Width, TheSet.Height)); Board.Vertices.Add(new PointD(0, TheSet.Height)); Board.Vertices.Add(new PointD(0, 0)); BoardMinusCombinedInstanceOutline.Add(Board.toPolygon()); foreach (var b in CombinedInstanceOutline) { Polygons clips = new Polygons(); clips.Add(b); Polygons clips2 = Clipper.OffsetPolygons(clips, offsetinMM * 100000.0f, JoinType.jtMiter); Clipper cp = new Clipper(); cp.AddPolygons(BoardMinusCombinedInstanceOutline, PolyType.ptSubject); cp.AddPolygons(clips2, PolyType.ptClip); cp.Execute(ClipType.ctDifference, BoardMinusCombinedInstanceOutline, PolyFillType.pftNonZero, PolyFillType.pftNonZero); } //CombinedOutline.Clear(); Polygons shrunk = Clipper.OffsetPolygons(BoardMinusCombinedInstanceOutline, -retractMM * 100000.0f, JoinType.jtRound); Polygons expanded = Clipper.OffsetPolygons(shrunk, retractMM * 100000.0f, JoinType.jtRound); //CombinedOutline.Clear(); //foreach (var b in TheSet.Tabs) //{ // Polygons clips = new Polygons(); // PolyLine Circle = new PolyLine(); // Circle.MakeCircle(b.Radius); // PolyLine PL = new PolyLine(); // PL.FillTransformed(Circle, new PointD( b.Center), b.Angle); // clips.Add(PL.toPolygon()); // Clipper cp = new Clipper(); // cp.AddPolygons(expanded, PolyType.ptSubject); // cp.AddPolygons(clips, PolyType.ptClip); // cp.Execute(ClipType.ctUnion, expanded, PolyFillType.pftNonZero, PolyFillType.pftNonZero); //} //foreach (var b in CombinedInstanceOutline) //{ // Polygons clips = new Polygons(); // clips.Add(b); // Clipper cp = new Clipper(); // cp.AddPolygons(expanded, PolyType.ptSubject); // cp.AddPolygons(clips, PolyType.ptClip); // cp.Execute(ClipType.ctUnion, expanded, PolyFillType.pftNonZero, PolyFillType.pftNonZero); //} List<PolyLine> Res = new List<PolyLine>(); foreach (var s in expanded) { PolyLine PL = new PolyLine(); PL.fromPolygon(s); Res.Add(PL); } return Res; } public void UpdateShape() { CombinedOutline.Clear(); foreach (var a in TheSet.Instances) { if (GerberOutlines.ContainsKey(a.GerberPath)) { bool doit = false; if (a.LastCenter == null) doit = true; if (doit || (PointD.Distance(new PointD(a.Center), a.LastCenter) != 0 || a.Angle != a.LastAngle)) { a.RebuildTransformed(GerberOutlines[a.GerberPath], TheSet.ExtraTabDrillDistance); } } } if (TheSet.ConstructNegativePolygon) { RemoveInstance("???_negative"); var Neg = GenerateNegativePolygon(TheSet.FillOffset, TheSet.Smoothing); var G = new GerberOutline(""); G.TheGerber.Name = "???_negative"; G.TheGerber.OutlineShapes = Neg; G.TheGerber.DisplayShapes = Neg; G.TheGerber.FixPolygonWindings(); GerberOutlines["???_negative"] = G; AddInstance("???_negative", new PointD(0, 0), true); } foreach (var aa in TheSet.Instances) { aa.Tabs.Clear(); } FindOutlineIntersections(); } private void RemoveInstance(string path) { foreach (var a in TheSet.Instances) { if (a.GerberPath == path) { RemoveInstance(a); return; } } } public void RenderInstanceHoles(GraphicsInterface G, float PW, Color C, AngledThing b, bool errors = false, bool active = false, bool hover = false) { if (b == null) return; var T = G.Transform.Clone(); G.TranslateTransform((float)b.Center.X, (float)b.Center.Y); G.RotateTransform(b.Angle); if (b.GetType() == typeof(GerberInstance)) { GerberInstance GI = b as GerberInstance; if (GerberOutlines.ContainsKey(GI.GerberPath)) { var a = GerberOutlines[GI.GerberPath]; foreach (var Shape in a.TheGerber.OutlineShapes) { if (Shape.Hole == true) { FillShape(G, new SolidBrush(Color.FromArgb(100, 0, 0, 0)), Shape); } } } } G.Transform = T; } /// <summary> /// Render a gerber instance to a graphics interface /// </summary> /// <param name="G"></param> /// <param name="PW"></param> /// <param name="C"></param> /// <param name="b"></param> /// <param name="errors"></param> /// <param name="active"></param> public void RenderInstance(GraphicsInterface G, float PW, Color C, AngledThing b, bool errors = false, bool active = false, bool hover = false) { if (b == null) return; var T = G.Transform.Clone(); G.TranslateTransform((float)b.Center.X, (float)b.Center.Y); G.RotateTransform(b.Angle); Pen P = new Pen(C, PW) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; Pen ActiveP = new Pen(Color.FromArgb(200, 150, 20), PW * 2) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; Pen ActivePD = new Pen(Color.Green, PW * 1) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; Pen ErrorP = new Pen(Color.Red, PW * 2.5f) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; if (b.GetType() == typeof(BreakTab)) { BreakTab BT = b as BreakTab; if (BT.Errors.Count > 0) errors = true; DrawMarker(errors, G, new PointD(0, 0), 1, PW, errors ? ErrorP : P); PolyLine Circle = new PolyLine(); Circle.MakeCircle((b as BreakTab).Radius); if (errors) { DrawShape(G, ErrorP, Circle); for (int i = 0; i < BT.Errors.Count; i++) { G.DrawString(new PointD(BT.Radius + 1, PW * 10 * i), BT.Errors[i], PW, false); } } else { DrawShape(G, P, Circle); } if (active) { DrawShape(G, errors ? ErrorP : ActivePD, Circle); DrawMarker(errors, G, new PointD(0, 0), 1, PW, errors ? ErrorP : ActivePD); DrawShape(G, ActiveP, Circle); DrawMarker(errors, G, new PointD(0, 0), 1, PW, ActiveP); } if (hover) { DrawMarker(errors, G, new PointD(0, 0), 1, PW, new Pen(Color.Blue, PW * 2)); } } if (b.GetType() == typeof(GerberInstance)) { GerberInstance GI = b as GerberInstance; if (GerberOutlines.ContainsKey(GI.GerberPath)) { var a = GerberOutlines[GI.GerberPath]; // a.BuildShapeCache(); float R = 0; float Gf = 0; float B = 0; float A = 0.8f; switch (GI.Tabs.Count) { case 0: R = .70f; break; case 1: R = .70f; Gf = 0.35f; break; case 2: R = .70f; Gf = 0.70f; break; default: Gf = 1.0f; break; } //G.FillTriangles(a.TheGerber.ShapeCacheTriangles, Color.FromArgb((byte)(A * 255.0), (byte)(R * 255.0), (byte)(Gf * 255.0), (byte)(B * 255.0))); foreach (var Shape in a.TheGerber.OutlineShapes) { if (Shape.Hole == false) { //FillShape(G, new SolidBrush(Color.FromArgb(100, 255, 255, 255)), Shape); } else { // FillShape(G, new SolidBrush(Color.FromArgb(100, 0, 0, 0)), Shape); } if (active) { DrawShape(G, ActivePD, Shape); // DrawShapeNormals(G, ActivePD, Shape); } else { DrawShape(G, active ? ActiveP : P, Shape); } } foreach (var Shape in a.TheGerber.DisplayShapes) { DrawShape(G, active ? ActiveP : P, Shape); } var width = (int)(Math.Ceiling(a.TheGerber.BoundingBox.BottomRight.X - a.TheGerber.BoundingBox.TopLeft.X)); var height = (int)(Math.Ceiling(a.TheGerber.BoundingBox.BottomRight.Y - a.TheGerber.BoundingBox.TopLeft.Y)); double ox = (float)(a.TheGerber.TranslationSinceLoad.X + a.TheGerber.BoundingBox.TopLeft.X) + width / 2; double oy = (float)(a.TheGerber.TranslationSinceLoad.Y + a.TheGerber.BoundingBox.TopLeft.Y + height / 2); PointD Ext = G.MeasureString(Path.GetFileName(GI.GerberPath)); double Z = 1; if (Ext.X > width) Z = width / Ext.X; if (Ext.Y * Z > height) Z = height / Ext.Y; G.DrawString(new PointD(ox, oy), Path.GetFileName(GI.GerberPath), Z * 30, true, R, Gf, B, A); } G.Transform = T; if (active) { DrawMarker(false, G, new PointD(b.Center), 1, PW, ActivePD); DrawMarker(false, G, new PointD(b.Center), 1, PW, ActiveP); } } G.Transform = T; } private void DrawShapeNormals(GraphicsInterface G, Pen P, PolyLine Shape) { PointF[] Points = new PointF[2]; for (int j = 0; j < Shape.Count() - 1; j++) { var P1 = Shape.Vertices[j]; var P2 = Shape.Vertices[j + 1]; Points[0].X = (float)((P1.X + P2.X) / 2); Points[0].Y = (float)((P1.Y + P2.Y) / 2); var DP = (P2 - P1); if (DP.Length() > 0) { DP.Normalize(); DP = DP.Rotate(90); Points[1].X = (float)((Points[0].X + DP.X * 2)); Points[1].Y = (float)((Points[0].Y + DP.Y * 2)); G.DrawLines(P, Points); } } } /// <summary> /// Render a full panel to a graphics interface /// </summary> /// <param name="PW"></param> /// <param name="G"></param> /// <param name="targetwidth"></param> /// <param name="targetheight"></param> /// <param name="SelectedInstance"></param> public void DrawBoardBitmap(float PW = 1, GraphicsInterface G = null, int targetwidth = 0, int targetheight = 0, AngledThing SelectedInstance = null, AngledThing Hoverinstance = null, double snapdistance = 1) { if (G == null) { return; } G.Clear(System.Drawing.ColorTranslator.FromHtml("#888885")); RectangleF RR = G.ClipBounds; if (G.IsFast) { G.FillRectangle(System.Drawing.ColorTranslator.FromHtml("#f5f4e8"), 0, 0, (int)TheSet.Width, (int)TheSet.Height); Helpers.DrawMMGrid(G, PW, (float)TheSet.Width, (float)TheSet.Height, (float)snapdistance, (float)snapdistance * 10.0f); } else if ((MMGrid == null || MMGrid.Width != targetwidth || MMGrid.Height != targetheight)) { MMGrid = new Bitmap(targetwidth, targetheight); Graphics G2 = Graphics.FromImage(MMGrid); G2.SmoothingMode = SmoothingMode.HighQuality; G2.Transform = G.Transform; Helpers.DrawMMGrid(new GraphicsGraphicsInterface(G2), PW, (float)TheSet.Width, (float)TheSet.Height, (float)snapdistance, (float)snapdistance * 10.0f); Console.WriteLine("building new millimeter grid!"); } G.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; G.DrawImage(MMGrid, RR.Left, RR.Bottom, RR.Width, -RR.Height); foreach (var b in TheSet.Tabs) { if (b.Errors.Count > 0) { RenderInstance(G, PW, Color.Gray, b, true); } else { RenderInstance(G, PW, Color.Gray, b, false); } } foreach (var b in TheSet.Instances) { RenderInstance(G, PW, Color.DarkGray, b); } foreach (var b in TheSet.Instances) { RenderInstanceHoles(G, PW, Color.DarkGray, b); } Pen OO = new Pen(Color.Orange, PW) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; Pen OO3 = new Pen(Color.FromArgb(140, 40, 40, 30), PW) { LineJoin = System.Drawing.Drawing2D.LineJoin.Round, EndCap = System.Drawing.Drawing2D.LineCap.Round, StartCap = System.Drawing.Drawing2D.LineCap.Round }; SolidBrush BR = new SolidBrush(Color.FromArgb(180, 0, 100, 0)); //BR.Color.A = 180; GP.Reset(); foreach (var FinalPoly in FinalPolygonsWithTabs) { PolyLine PL2 = new PolyLine(); PL2.Vertices = FinalPoly.Vertices; DrawShape(G, OO3, PL2); // DrawMarker(G, PL2.Vertices.First(), 1, PW); // DrawMarker(G, PL2.Vertices.Last(), 1, PW); } // PolyLine PL = new PolyLine(); PL.MakeSquare(0.15); foreach (var s in DrillHoles) { var T = G.Transform.Clone(); G.TranslateTransform((float)s.X, (float)s.Y); FillShape(G, new SolidBrush(Color.FromArgb(140, 0, 0, 0)), PL); DrawShape(G, new Pen(Color.Black), PL); G.Transform = T; } if (Hoverinstance != null) { RenderInstance(G, PW, Color.Blue, Hoverinstance, false, false); } if (SelectedInstance != null) { RenderInstance(G, PW * 2, Color.Black, null, false, true); RenderInstance(G, PW, Color.Black, SelectedInstance, false, true); } } /// <summary> /// Render a solid polygon /// </summary> /// <param name="G"></param> /// <param name="BR"></param> /// <param name="Shape"></param> private void FillShape(GraphicsInterface G, SolidBrush BR, PolyLine Shape) { // todo: cache the triangulated polygon! //G.FillShape(BR, Shape); } /// <summary> /// Render a marker-cross /// </summary> /// <param name="cross">Cross or plus shape?</param> /// <param name="G">Target graphics interface</param> /// <param name="pointD">Cross position</param> /// <param name="crossize">Cross size</param> /// <param name="PW">Global Pen width</param> /// <param name="P">Pen to use (white/PW is default)</param> private static void DrawMarker(bool cross, GraphicsInterface G, PointD pointD, float crossize, float PW, Pen P = null) { if (P == null) P = new Pen(Color.White, PW); if (cross) { G.DrawLine(P, (float)pointD.X - crossize, (float)pointD.Y - crossize, (float)pointD.X + crossize, (float)pointD.Y + crossize); G.DrawLine(P, (float)pointD.X + crossize, (float)pointD.Y - crossize, (float)pointD.X - crossize, (float)pointD.Y + crossize); } else // plus { G.DrawLine(P, (float)pointD.X, (float)pointD.Y - crossize, (float)pointD.X, (float)pointD.Y + crossize); G.DrawLine(P, (float)pointD.X + crossize, (float)pointD.Y, (float)pointD.X - crossize, (float)pointD.Y); } } /// <summary> /// Draw an open polygon /// </summary> /// <param name="G">Target graphicsinterface</param> /// <param name="P">Pen to use</param> /// <param name="Shape"></param> private static void DrawShape(GraphicsInterface G, Pen P, PolyLine Shape) { PointF[] Points = new PointF[Shape.Count()]; for (int j = 0; j < Shape.Count(); j++) { var P1 = Shape.Vertices[j]; Points[j].X = (float)((P1.X)); Points[j].Y = (float)((P1.Y)); } if (Points.Count() > 1) G.DrawLines(P, Points); } List<PointD> DrillHoles = new List<PointD>(); public class TabIntersection { public bool Start; public double Angle; public PointD Location = new PointD(); public PointD Direction = new PointD(); public override string ToString() { return String.Format("{0},{1} , {2}", Start ? "start" : "end", Angle, Location); } } List<PolyLine> GeneratedArcs = new List<PolyLine>(); bool GenerateTabArcs(List<TabIntersection> intersects, BreakTab t, double drillradius = 1) { if (t.Errors.Count > 0) return false; if (intersects.Count < 4) { t.Valid = false; t.Errors.Add("not enough intersections!"); return false; } PointD center = new PointD(t.Center); bool result = true; intersects = (from i in intersects orderby i.Angle select i).ToList(); //intersects.Sort(x => x.Angle); int had = 0; int current = 0; while (intersects[current].Start == true) current = (current + 1) % intersects.Count; int startcurrent = current; while (had < intersects.Count) { var PStart = intersects[current].Location; PointD StartDir = intersects[current].Direction; current = (current + 1) % intersects.Count; had++; PointD EndDir = intersects[current].Direction; var PEnd = intersects[current].Location; current = (current + 1) % intersects.Count; had++; PointD StartNorm = StartDir.Rotate(90); PointD EndNorm = EndDir.Rotate(90); if ((center - PStart).Dot(StartNorm) < 0) { // StartNorm = StartNorm * -1; } if ((center - PEnd).Dot(EndNorm) < 0) { // EndNorm = EndNorm * -1; } if (Helpers.Distance(PStart, PEnd) < drillradius * 2) { t.Errors.Add("distance closer than drillradius"); result = false; } var C1 = PStart + StartNorm * drillradius; var C2 = PEnd + EndNorm * drillradius; var DF = C2 - C1; DF.Normalize(); var DR = DF.Rotate(90); var A1 = C1 + DR * drillradius; var A2 = C2 + DR * drillradius; double AS = Helpers.AngleBetween(C1, PStart); double AE = Helpers.AngleBetween(C1, A1); double BS = Helpers.AngleBetween(C2, PEnd); double BE = Helpers.AngleBetween(C2, A2); if (AE > AS) AE -= Math.PI * 2; if (BE < BS) BE += Math.PI * 2; if (Math.Abs(AE - AS) >= Math.PI * 1.9) { t.Errors.Add("angle too big"); result = false; } if (Math.Abs(BE - BS) >= Math.PI * 1.9) { t.Errors.Add("angle too big"); result = false; } } if (result == false) return false; current = startcurrent; had = 0; while (had < intersects.Count) { var PStart = intersects[current].Location; PointD StartDir = intersects[current].Direction; current = (current + 1) % intersects.Count; had++; PointD EndDir = intersects[current].Direction; var PEnd = intersects[current].Location; current = (current + 1) % intersects.Count; had++; PointD StartNorm = StartDir.Rotate(90); PointD EndNorm = EndDir.Rotate(90); if ((center - PStart).Dot(StartNorm) < 0) { // StartNorm = StartNorm * -1; } if ((center - PEnd).Dot(EndNorm) < 0) { // EndNorm = EndNorm * -1; } if (Helpers.Distance(PStart, PEnd) < drillradius * 2) { t.Errors.Add("distance closer than drillradius"); result = false; } var C1 = PStart + StartNorm * drillradius; var C2 = PEnd + EndNorm * drillradius; var DF = C2 - C1; DF.Normalize(); var DR = DF.Rotate(90); var A1 = C1 + DR * drillradius; var A2 = C2 + DR * drillradius; double AS = Helpers.AngleBetween(C1, PStart); double AE = Helpers.AngleBetween(C1, A1); double BS = Helpers.AngleBetween(C2, PEnd); double BE = Helpers.AngleBetween(C2, A2); if (AE > AS) AE -= Math.PI * 2; if (BE < BS) BE += Math.PI * 2; if (Math.Abs(AE - AS) >= Math.PI * 2) { t.Errors.Add("angle too big"); } if (Math.Abs(BE - BS) >= Math.PI * 2) { t.Errors.Add("angle too big"); } //while (AS < 0 || AE < 0) { AS += Math.PI * 2; AE += Math.PI * 2; }; //while (BS < 0 || BE < 0) { BS += Math.PI * 2; BE += Math.PI * 2; }; //if (Math.Abs(BE - BS) > Math.PI) //{ // double Dif = BE - BS; // BE = Math.PI * 2 - Dif; //} //if (Math.Abs(AE - AS) > Math.PI) //{ // double Dif = AE - AS; // AE = Math.PI * 2 - Dif; // //AE -= Math.PI * 2; //} // while (BE < BS) BE += Math.PI * 2; List<PointD> Arc1 = new List<PointD>(); List<PointD> Arc2 = new List<PointD>(); Arc1.Add(PStart); Arc2.Add(PEnd); for (double T = 0; T <= 1; T += 1.0 / 20) { double P = AS + (AE - AS) * T; PointD newP = C1 + new PointD(-Math.Cos(P) * drillradius, -Math.Sin(P) * drillradius); Arc1.Add(newP); double P2 = BS + (BE - BS) * T; PointD newP2 = C2 + new PointD(-Math.Cos(P2) * drillradius, -Math.Sin(P2) * drillradius); Arc2.Add(newP2); } // Arc1.Add(A1.ToF()); // Arc2.Add(A2.ToF()); PolyLine Middle = new PolyLine(); Middle.Vertices.Add(A1); Middle.Vertices.Add(A2); PolyLine Combined = new PolyLine(); // GeneratedArcs.Add(PL); // GeneratedArcs.Add(PL2); // GeneratedArcs.Add(Middle); Arc2.Reverse(); Combined.Vertices.AddRange(Arc1); Combined.Vertices.AddRange(Middle.Vertices); Combined.Vertices.AddRange(Arc2); GeneratedArcs.Add(Combined); //PolyLine N1 = new PolyLine(); //N1.Vertices.Add(PStart); //N1.Vertices.Add(PStart + StartNorm *4); //GeneratedArcs.Add(N1); //PolyLine N2 = new PolyLine(); //N2.Vertices.Add(PEnd); //N2.Vertices.Add(PEnd + EndNorm * 4); //GeneratedArcs.Add(N2); // var P2 = PStart - StartDir * drillradius + StartNorm * drillradius; // var P3 = PEnd - EndDir * drillradius + EndNorm * drillradius; // GP.AddBezier(PStart.ToF(), P2.ToF(), P3.ToF(), PEnd.ToF()); } return result; } public void RemoveAllTabs(bool errortabsonly = false) { if (errortabsonly) { var T = (from i in TheSet.Tabs where i.Errors.Count > 0 select i).ToList(); if (T.Count() > 0) { foreach (var bt in T) { TheSet.Tabs.Remove(bt); } } } else TheSet.Tabs.Clear(); } public void GenerateTabLocations() { RemoveAllTabs(); foreach (var a in TheSet.Instances) { if (GerberOutlines.ContainsKey(a.GerberPath) && a.GerberPath.Contains("???_negative") == false) { var g = GerberOutlines[a.GerberPath]; var TabsLocs = PolyLineSet.FindOptimalBreaktTabLocations(g.TheGerber); foreach (var b in TabsLocs) { PointD loc = b.Item1 - (b.Item2 * TheSet.MarginBetweenBoards * 0.5); loc = loc.Rotate(a.Angle); loc += new PointD(a.Center); if (loc.X >= 0 && loc.X <= TheSet.Width && loc.Y >= 0 && loc.Y <= TheSet.Height) { var BT = AddTab(loc); BT.Radius = (float)TheSet.MarginBetweenBoards + 2; } } } } } class CutUpLine { public List<List<PointD>> Lines = new List<List<PointD>>(); public void AddVertex(PointD D) { if (Lines.Count == 0) { Lines.Add(new List<PointD>()); } Lines.Last().Add(D); } public void NewLine() { if (Lines.Count > 0 && Lines.Last().Count == 0) return; Lines.Add(new List<PointD>()); } } List<CutUpLine> CutLines = new List<CutUpLine>(); class LineSeg { public PointD PStart = new PointD(); public PointD PEnd = new PointD(); public override string ToString() { return PStart.ToString() + " - " + PEnd.ToString() + String.Format(" ({0}mm)", (PEnd - PStart).Length()); } } List<LineSeg> FinalSegs = new List<LineSeg>(); void CutUpOutlines() { CutLines.Clear(); FinalSegs.Clear(); foreach (var b in TheSet.Instances) { // Polygons clips = new Polygons(); if (GerberOutlines.ContainsKey(b.GerberPath)) { var a = GerberOutlines[b.GerberPath]; foreach (var c in b.TransformedOutlines) { // PolyLine PL = new PolyLine(); // PL.FillTransformed(c, new PointD(b.Center), b.Angle); SplitPolyLineAndAddSegs(c); } } } foreach (var b in CombinedOutline) { // SplitPolyLineAndAddSegs(b); } foreach (var a in FinalSegs) { PolyLine PL = new PolyLine(); PL.Vertices.Add(a.PStart); PL.Vertices.Add(a.PEnd); GeneratedArcs.Add(PL); } } private void SplitPolyLineAndAddSegs(PolyLine PL) { int adjust = 0; if (PL.Vertices.First() == PL.Vertices.Last()) adjust = 1; List<LineSeg> Segs = new List<LineSeg>(Math.Max(1, PL.Vertices.Count - adjust + 100)); for (int i = 0; i < PL.Vertices.Count - adjust; i++) { Segs.Add(new LineSeg() { PStart = PL.Vertices[i].Copy(), PEnd = PL.Vertices[(i + 1) % PL.Vertices.Count].Copy() }); } foreach (var t in TheSet.Tabs.Where(x => x.Errors.Count == 0)) { PointD center = new PointD(t.Center); List<LineSeg> ToDelete = new List<LineSeg>(); List<LineSeg> ToAdd = new List<LineSeg>(); foreach (var s in Segs) { bool StartInside = Helpers.Distance(s.PStart, center) < t.Radius; bool EndInside = Helpers.Distance(s.PEnd, center) < t.Radius; if (StartInside && EndInside) { ToDelete.Add(s); } else { PointD I1; PointD I2; int ints = Helpers.FindLineCircleIntersections(center.X, center.Y, t.Radius, s.PStart, s.PEnd, out I1, out I2); switch (ints) { case 0: // skip; break; case 1: // adjust 1 point if (StartInside) { s.PStart = I1.Copy(); } else { s.PEnd = I1.Copy(); } break; case 2: // split and add 1 LineSeg NS1 = new LineSeg(); LineSeg NS2 = new LineSeg(); NS1.PEnd = s.PEnd.Copy(); NS1.PStart = I1.Copy(); NS2.PEnd = s.PStart.Copy(); NS2.PStart = I2.Copy(); ToAdd.Add(NS1); ToAdd.Add(NS2); ToDelete.Add(s); break; } } } foreach (var s in ToDelete) { Segs.Remove(s); } foreach (var s in ToAdd) { Segs.Add(s); } } FinalSegs.AddRange(Segs); } private void FindOutlineIntersections() { GeneratedArcs.Clear(); DrillHoles.Clear(); CutLines.Clear(); foreach (var t in TheSet.Tabs) { t.EvenOdd = 0; t.Errors.Clear(); List<TabIntersection> Intersections = new List<TabIntersection>(); float R2 = t.Radius * t.Radius; foreach (var b in TheSet.Instances) { // Polygons clips = new Polygons(); // if (b.GerberPath.Contains("???") == false) { var a = GerberOutlines[b.GerberPath]; var C = new PointD(t.Center); C.X -= b.Center.X; C.Y -= b.Center.Y; C = C.Rotate(-b.Angle); var Box2 = a.TheGerber.BoundingBox.Grow(t.Radius * 2); if (Box2.Contains(C) || b.GerberPath.Contains("???_negative") == true) { //Console.WriteLine("{0},{1}", a.TheGerber.BoundingBox, C); for (int i = 0; i < b.TransformedOutlines.Count; i++) { var c = b.TransformedOutlines[i]; // var poly = c.toPolygon(); // bool winding = Clipper.Orientation(poly); // PolyLine PL = new PolyLine(); // PL.FillTransformed(c, new PointD(b.Center), b.Angle); if (Helpers.IsInPolygon(c.Vertices, new PointD(t.Center), false)) { t.EvenOdd++; // t.Errors.Add("inside a polygon!"); // t.Valid = false; } if (TheSet.DoNotGenerateMouseBites == false) BuildDrillsForTabAndPolyLine(t, c, b.OffsetOutlines[i]); //bool inside = false; //bool newinside = false; // List<PolyLine> Lines = new List<PolyLine>(); //PolyLine Current = null; if (AddIntersectionsForTabAndPolyLine(t, Intersections, c)) { b.Tabs.Add(t); } } } } } if (t.EvenOdd % 2 == 1) { t.Errors.Add("inside a polygon!"); t.Valid = false; } foreach (var a in CombinedOutline) { AddIntersectionsForTabAndPolyLine(t, Intersections, a); } bool Succes = GenerateTabArcs(Intersections, t); ; } CutUpOutlines(); CombineGeneratedArcsAndCutlines(); } private static bool AddIntersectionsForTabAndPolyLine(BreakTab t, List<TabIntersection> Intersections, PolyLine PL) { // Polygons clips = new Polygons(); //var poly = PL.toPolygon(); //bool winding = Clipper.Orientation(poly); bool ret = false; for (int i = 0; i < PL.Vertices.Count; i++) { PointD V1 = PL.Vertices[i]; PointD V2 = PL.Vertices[(i + 1) % PL.Vertices.Count]; // if (winding == false) // { // var V3 = V1; // V1 = V2; // V2 = V3; // } PointD I1 = new PointD(); PointD I2 = new PointD(); double Len = Helpers.Distance(V1, V2); int ints = Helpers.FindLineCircleIntersections(t.Center.X, t.Center.Y, t.Radius, V1, V2, out I1, out I2); if (ints > 0) { ret = true; if (ints == 1) { TabIntersection TI = new TabIntersection(); TI.Location = I1; TI.Direction.X = (V1.X - V2.X) / Len; TI.Direction.Y = (V1.Y - V2.Y) / Len; TI.Angle = Helpers.AngleBetween(new PointD(t.Center), I1); bool addedV1 = false; bool V1Inside = Helpers.Distance(new PointD(t.Center.X, t.Center.Y), V1) < t.Radius; bool V2Inside = Helpers.Distance(new PointD(t.Center.X, t.Center.Y), V2) < t.Radius; if (Helpers.Distance(new PointD(t.Center.X, t.Center.Y), V1) < t.Radius) { addedV1 = true; TI.Start = true; } if (Helpers.Distance(new PointD(t.Center.X, t.Center.Y), V2) < t.Radius) { TI.Start = false; } Intersections.Add(TI); } if (ints == 2) { TabIntersection TI1 = new TabIntersection(); TI1.Start = true; TI1.Location = I1; TI1.Angle = Helpers.AngleBetween(new PointD(t.Center), I1); TI1.Direction.X = (V1.X - V2.X) / Len; TI1.Direction.Y = (V1.Y - V2.Y) / Len; Intersections.Add(TI1); TabIntersection TI2 = new TabIntersection(); TI2.Start = false; TI2.Location = I2; TI2.Direction.X = TI1.Direction.X; TI2.Direction.Y = TI1.Direction.Y; TI2.Angle = Helpers.AngleBetween(new PointD(t.Center), I2); Intersections.Add(TI2); } } } return ret; } private void BuildDrillsForTabAndPolyLine(BreakTab t, PolyLine PL, List<PolyLine> Offsetted) { foreach (var sub in Offsetted) { // PolyLine sub = new PolyLine(); // sub.fromPolygon(subpoly); double Len = 0; PointD last = sub.Vertices.Last(); for (int i = 0; i < sub.Vertices.Count; i++) { double dx = sub.Vertices[i].X - last.X; double dy = sub.Vertices[i].Y - last.Y; double seglen = Math.Sqrt(dx * dx + dy * dy); if (Len + seglen < 1) { Len += seglen; } else { double ndx = dx / seglen; double ndy = dy / seglen; double left = 1 - Len; double had = left; PointD place = new PointD(last.X + ndx * had, last.Y + ndy * had); if (Helpers.Distance(place, new PointD(t.Center.X, t.Center.Y)) < t.Radius) { DrillHoles.Add(place); } seglen -= left; while (seglen > 0) { double amt = Math.Min(1, seglen); seglen -= amt; had += amt; if (amt == 1) { place = new PointD(last.X + ndx * had, last.Y + ndy * had); if (Helpers.Distance(place, new PointD(t.Center.X, t.Center.Y)) < t.Radius) { DrillHoles.Add(place); } // DrillHoles.Add(new PointD(last.X + ndx * had, last.Y + ndy * had)); } else { Len = amt; } } } last = sub.Vertices[i]; } } } List<PathDefWithClosed> FinalPolygonsWithTabs = new List<PathDefWithClosed>(); private void CombineGeneratedArcsAndCutlines() { List<PathDefWithClosed> SourceLines = new List<PathDefWithClosed>(); foreach (var a in GeneratedArcs) { SourceLines.Add(new PathDefWithClosed() { Vertices = a.Vertices, Width = 0 }); } foreach (var cl in CutLines) { foreach (var l in cl.Lines) { SourceLines.Add(new PathDefWithClosed() { Vertices = l, Width = 0 }); } } FinalPolygonsWithTabs = Helpers.LineSegmentsToPolygons(SourceLines, true); } public List<string> SaveOutlineTo(string p, string combinedfilename) { List<string> R = new List<string>(); string DrillFile = Path.Combine(p, "tabdrills.TXT"); string OutlineFile = Path.Combine(p, combinedfilename + ".GKO"); R.Add(DrillFile); // R.Add(OutlineFile); ExcellonFile EF = new ExcellonFile(); EF.Tools[1] = new ExcellonTool() { ID = 1, Radius = 0.25 }; foreach (var a in DrillHoles) { EF.Tools[1].Drills.Add(a); } EF.Write(Path.Combine(p, DrillFile), 0, 0, 0, 0); GerberOutlineWriter GOW = new GerberOutlineWriter(); foreach (var a in FinalPolygonsWithTabs) { PolyLine PL = new PolyLine(); PL.Vertices = a.Vertices; // todo: check if closed/opened things need special treatment here. // width is defaulted to 0 GOW.AddPolyLine(PL); } GOW.Write(Path.Combine(p, OutlineFile)); return R; } public List<String> SaveGerbersToFolder(string BaseName, string targetfolder, ProgressLog Logger, bool SaveOutline = true, bool GenerateImages = true, bool DeleteGenerated = true, string combinedfilename = "combined") { Logger.AddString("Starting export to " + targetfolder); List<string> GeneratedFiles = TheSet.SaveTo(targetfolder, GerberOutlines, Logger); List<String> FinalFiles = new List<string>(); if (SaveOutline) { GeneratedFiles.AddRange(SaveOutlineTo(targetfolder, combinedfilename)); FinalFiles.Add(Path.Combine(targetfolder, combinedfilename + ".gko")); } // TODO: use the new Gerber.DetermineFile to actually group based on layer/type instead of extentions only! Dictionary<string, List<string>> FilesPerExt = new Dictionary<string, List<string>>(); Dictionary<string, BoardFileType> FileTypePerExt = new Dictionary<string, BoardFileType>(); foreach (var s in GeneratedFiles) { string ext = Path.GetExtension(s).ToLower(); ; if (ext == "xln") ext = "txt"; if (ext == "drl") ext = "txt"; if (FilesPerExt.ContainsKey(ext) == false) { FilesPerExt[ext] = new List<string>(); } FileTypePerExt[ext] = Gerber.FindFileType(s); FilesPerExt[ext].Add(s); } int count = 0; foreach (var a in FilesPerExt) { count++; Logger.AddString("merging *" + a.Key.ToLower(), ((float)count / (float)FilesPerExt.Keys.Count) * 0.5f + 0.3f); switch (FileTypePerExt[a.Key]) { case BoardFileType.Drill: { string Filename = Path.Combine(targetfolder, combinedfilename + a.Key); FinalFiles.Add(Filename); ExcellonFile.MergeAll(a.Value, Filename, Logger); } break; case BoardFileType.Gerber: { if (a.Key.ToLower() != ".gko") { string Filename = Path.Combine(targetfolder, combinedfilename + a.Key); FinalFiles.Add(Filename); GerberMerger.MergeAll(a.Value, Filename, Logger); } } break; } } //Logger.AddString("Writing source material zipfile", 0.80f); //string SeparateZipFile = Path.Combine(targetfolder, BaseName + ".separate_boards.zip"); //if (File.Exists(SeparateZipFile)) File.Delete(SeparateZipFile); //ZipArchive zip = ZipFile.Open(SeparateZipFile, ZipArchiveMode.Create); //foreach (string file in GeneratedFiles) //{ // zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal); //} //zip.Dispose(); //Logger.AddString("Writing combined zipfile", 0.85f); //string CombinedZipFile = Path.Combine(targetfolder, BaseName + ".combined_boards.zip"); //if (File.Exists(CombinedZipFile)) File.Delete(CombinedZipFile); //ZipArchive zip2 = ZipFile.Open(CombinedZipFile, ZipArchiveMode.Create); //foreach (string file in FinalFiles) //{ // zip2.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal); //} //zip2.Dispose(); Logger.AddString("Deleting tempfiles", 0.9f); if (DeleteGenerated) { foreach (var a in GeneratedFiles) { File.Delete(a); } } if (GenerateImages) { try { Logger.AddString("Writing board bitmaps", 0.95f); GerberImageCreator GIC = new GerberImageCreator(); GIC.AddBoardsToSet(FinalFiles); GIC.WriteImageFiles(Path.Combine(targetfolder, BaseName), 400, Gerber.DirectlyShowGeneratedBoardImages, Logger); } catch (Exception E) { Logger.AddString("Some errors while exporting board images.. but this should be no problem?"); Logger.AddString(String.Format("The exception: {0}", E.Message)); } } Logger.AddString("Done", 1); return GeneratedFiles; } public void SaveFile(string FileName) { try { XmlSerializer SerializerObj = new XmlSerializer(typeof(GerberLayoutSet)); // Create a new file stream to write the serialized object to a file TextWriter WriteFileStream = new StreamWriter(FileName); SerializerObj.Serialize(WriteFileStream, TheSet); // Cleanup WriteFileStream.Close(); } catch (Exception) { } } public void RemoveInstance(AngledThing angledThing) { if (angledThing.GetType() == typeof(GerberInstance)) { TheSet.Instances.Remove(angledThing as GerberInstance); } else { if (angledThing.GetType() == typeof(BreakTab)) { TheSet.Tabs.Remove(angledThing as BreakTab); } } } public GerberInstance AddInstance(string path, PointD coord, bool generateTransformed = false) { GerberInstance GI = new GerberInstance() { GerberPath = path, Center = coord.ToF() }; TheSet.Instances.Add(GI); if (generateTransformed) { if (GerberOutlines.ContainsKey(path)) { var GO = GerberOutlines[path]; foreach (var b in GO.TheGerber.OutlineShapes) { PolyLine PL = new PolyLine(); PL.FillTransformed(b, new PointD(GI.Center), GI.Angle); GI.TransformedOutlines.Add(PL); } GI.CreateOffsetLines(TheSet.ExtraTabDrillDistance); } } return GI; } public void LoadFile(string filename) { XmlSerializer SerializerObj = new XmlSerializer(typeof(GerberLayoutSet)); FileStream ReadFileStream = null; try { ReadFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); // Load the object saved above by using the Deserialize function GerberLayoutSet newset = (GerberLayoutSet)SerializerObj.Deserialize(ReadFileStream); if (newset != null) { foreach (var a in newset.LoadedOutlines) { AddGerberFolder(a, false); } TheSet = newset; } } catch (Exception) { } // Cleanup if (ReadFileStream != null) ReadFileStream.Close(); } public AngledThing FindOutlineUnderPoint(PointD pt) { foreach (var b in TheSet.Tabs) { if (Helpers.Distance(new PointD(b.Center), pt) <= b.Radius) { return b; } } foreach (var b in TheSet.Instances) { // Polygons clips = new Polygons(); if (GerberOutlines.ContainsKey(b.GerberPath)) { var a = GerberOutlines[b.GerberPath]; int cc = 0; foreach (var c in b.TransformedOutlines) { if (Helpers.IsInPolygon(c.Vertices, pt)) { cc++; } } if (cc % 2 == 1) return b; } } return null; } public void RectanglePack() { RectanglePacker RP = new RectanglePacker(TheSet.Width + TheSet.MarginBetweenBoards, TheSet.Height + TheSet.MarginBetweenBoards); List<Tuple<GerberInstance, double>> Instances = new List<Tuple<GerberInstance, double>>(); foreach (var a in TheSet.Instances) { if (GerberOutlines.ContainsKey(a.GerberPath)) { var OL = GerberOutlines[a.GerberPath]; var Width = OL.TheGerber.BoundingBox.BottomRight.X - OL.TheGerber.BoundingBox.TopLeft.X; var Height = OL.TheGerber.BoundingBox.BottomRight.Y - OL.TheGerber.BoundingBox.TopLeft.Y; Instances.Add(new Tuple<GerberInstance, double>(a, Math.Max(Width, Height))); } } foreach (var a in Instances.OrderByDescending(x => x.Item2)) { if (GerberOutlines.ContainsKey(a.Item1.GerberPath)) { var OL = GerberOutlines[a.Item1.GerberPath]; RectangleD RD = new RectangleD(); RD.Width = OL.TheGerber.BoundingBox.BottomRight.X - OL.TheGerber.BoundingBox.TopLeft.X; RD.Height = OL.TheGerber.BoundingBox.BottomRight.Y - OL.TheGerber.BoundingBox.TopLeft.Y; var Coord = RP.findCoords(RD.Width + TheSet.MarginBetweenBoards, RD.Height + TheSet.MarginBetweenBoards); // Console.WriteLine("empty space: {0}", RP.GetEmptySpace()); if (Coord != null) { a.Item1.Angle = 0; a.Item1.Center = (Coord - OL.TheGerber.BoundingBox.TopLeft).ToF(); // a.Item1.Center.X += 1; // a.Item1.Center.Y += 1; } else { Coord = RP.findCoords(RD.Height + TheSet.MarginBetweenBoards, RD.Width + TheSet.MarginBetweenBoards); // Console.WriteLine("empty space: {0}", RP.GetEmptySpace()); if (Coord != null) { a.Item1.Angle = 90; a.Item1.Center = (Coord - OL.TheGerber.BoundingBox.TopLeft).ToF(); a.Item1.Center.Y += (float)RD.Width; // a.Item1.Center.X += 1; // a.Item1.Center.Y += 1; } else { a.Item1.Center.X = -20; a.Item1.Center.Y = -20; } } } } } Random R = new Random(); public bool MaxRectPack(MaxRectPacker.FreeRectChoiceHeuristic strategy = MaxRectPacker.FreeRectChoiceHeuristic.RectBestAreaFit, double randomness = 0, bool allowrotation = true) { bool Succes = true; //allowrotation = true; MaxRectPacker MRP = new MaxRectPacker((int)(TheSet.Width + TheSet.MarginBetweenBoards), (int)(TheSet.Height + TheSet.MarginBetweenBoards), allowrotation); // mm is base unit for packing! List<Tuple<GerberInstance, double>> Instances = new List<Tuple<GerberInstance, double>>(); foreach (var a in TheSet.Instances) { if (GerberOutlines.ContainsKey(a.GerberPath)) { var OL = GerberOutlines[a.GerberPath]; var Width = OL.TheGerber.BoundingBox.BottomRight.X - OL.TheGerber.BoundingBox.TopLeft.X; var Height = OL.TheGerber.BoundingBox.BottomRight.Y - OL.TheGerber.BoundingBox.TopLeft.Y; Instances.Add(new Tuple<GerberInstance, double>(a, Math.Max(Width, Height) * (1 - randomness) + randomness * R.NextDouble())); } } List<MaxRectPacker.Rect> InputRects = new List<MaxRectPacker.Rect>(); List<MaxRectPacker.Rect> OutputRects = new List<MaxRectPacker.Rect>(); foreach (var a in Instances.OrderByDescending(x => x.Item2)) { if (GerberOutlines.ContainsKey(a.Item1.GerberPath)) { var OL = GerberOutlines[a.Item1.GerberPath]; MaxRectPacker.Rect RD = new MaxRectPacker.Rect() { refobject = a }; RD.width = (int)(Math.Ceiling(OL.TheGerber.BoundingBox.BottomRight.X - OL.TheGerber.BoundingBox.TopLeft.X)); RD.height = (int)(Math.Ceiling(OL.TheGerber.BoundingBox.BottomRight.Y - OL.TheGerber.BoundingBox.TopLeft.Y)); InputRects.Add(RD); var R = MRP.Insert((int)(RD.width + TheSet.MarginBetweenBoards), (int)(RD.height + TheSet.MarginBetweenBoards), strategy); if (R.height == 0) { // Console.WriteLine("{0} not packed - too big!", a.Item1.GerberPath); a.Item1.Center.X = -20; a.Item1.Center.Y = -20; return false; } else { if (R.height == (int)(RD.height + TheSet.MarginBetweenBoards)) { a.Item1.Center = (new PointD(R.x, R.y) - OL.TheGerber.BoundingBox.TopLeft).ToF(); a.Item1.Angle = 0; // regular } else { a.Item1.Center = (new PointD(R.x, R.y)).ToF();// - OL.TheGerber.TopLeft).ToF(); a.Item1.Center.X += (float)OL.TheGerber.BoundingBox.TopLeft.Y; a.Item1.Center.Y -= (float)OL.TheGerber.BoundingBox.TopLeft.X; a.Item1.Angle = 90; // a.Item1.Center.Y += RD.width; a.Item1.Center.X += RD.height; } // Console.WriteLine("{0},{1} {2},{3}", R.x, R.y, R.width, R.height); } } } //MaxRectPacker MRP2 = new MaxRectPacker((int)(TheSet.Width + 2), (int)(TheSet.Height + 2), false); // mm is base unit for packing! //MRP2.Insert(InputRects, OutputRects, MaxRectPacker.FreeRectChoiceHeuristic.RectBestAreaFit); //foreach(var a in OutputRects) //{ // Console.WriteLine("{0}", a.refobject as GerberInstance); //} return Succes; } public BreakTab AddTab(PointD center) { BreakTab BT = new BreakTab() { Radius = 3, Center = center.ToF() }; TheSet.Tabs.Add(BT); return BT; } public void MergeOverlappingTabs() { RemoveAllTabs(true); List<bool> Tabs = new List<bool>(); List<BreakTab> Removethese = new List<BreakTab>(); for (int i = 0; i < TheSet.Tabs.Count; i++) { Tabs.Add(false); } for (int i = 0; i < TheSet.Tabs.Count; i++) { PointD A = new PointD(TheSet.Tabs[i].Center); for (int j = i + 1; j < TheSet.Tabs.Count; j++) { if (Tabs[j] == false) { PointD B = new PointD(TheSet.Tabs[j].Center); if (PointD.Distance(A, B) < (TheSet.Tabs[j].Radius + TheSet.Tabs[i].Radius) * 0.75) { Tabs[j] = true; TheSet.Tabs[i].Center = ((A + B) * 0.5).ToF(); Removethese.Add(TheSet.Tabs[j]); } } } } foreach (var L in Removethese) { TheSet.Tabs.Remove(L); } } } public class AngledThing { public PointF Center = new PointF(); // float for serializer... need to investigate public float Angle; } public class GerberInstance : AngledThing { public string GerberPath; public bool Generated = false; [System.Xml.Serialization.XmlIgnore] public List<PolyLine> TransformedOutlines = new List<PolyLine>(); [System.Xml.Serialization.XmlIgnore] public List<List<PolyLine>> OffsetOutlines = new List<List<PolyLine>>(); [System.Xml.Serialization.XmlIgnore] internal float LastAngle; [System.Xml.Serialization.XmlIgnore] internal PointD LastCenter; [System.Xml.Serialization.XmlIgnore] public List<BreakTab> Tabs = new List<BreakTab>(); [System.Xml.Serialization.XmlIgnore] public PolyLineSet.Bounds BoundingBox = new PolyLineSet.Bounds(); internal void CreateOffsetLines(double extradrilldistance) { OffsetOutlines = new List<List<PolyLine>>(TransformedOutlines.Count); for (int i = 0; i < TransformedOutlines.Count; i++) { var L = new List<PolyLine>(); Polygons clips = new Polygons(); var poly = TransformedOutlines[i].toPolygon(); bool winding = Clipper.Orientation(poly); clips.Add(poly); double offset = 0.25 * 100000.0f + extradrilldistance; if (winding == false) offset *= -1; Polygons clips2 = Clipper.OffsetPolygons(clips, offset, JoinType.jtRound); foreach (var a in clips2) { PolyLine P = new PolyLine(); P.fromPolygon(a); L.Add(P); } OffsetOutlines.Add(L); } } public void RebuildTransformed(GerberOutline gerberOutline, double extra) { BoundingBox.Reset(); LastAngle = Angle; LastCenter = new PointD(Center.X, Center.Y); TransformedOutlines = new List<PolyLine>(); var GO = gerberOutline; foreach (var b in GO.TheGerber.OutlineShapes) { PolyLine PL = new PolyLine(); PL.FillTransformed(b, new PointD(Center), Angle); TransformedOutlines.Add(PL); BoundingBox.AddPolyLine(PL); } CreateOffsetLines(extra); } } public class BreakTab : AngledThing { public float Radius; public bool Valid; [System.Xml.Serialization.XmlIgnore] public List<string> Errors = new List<string>(); [System.Xml.Serialization.XmlIgnore] public int EvenOdd; } public class GerberLayoutSet { public List<string> LoadedOutlines = new List<string>(); public List<GerberInstance> Instances = new List<GerberInstance>(); public List<BreakTab> Tabs = new List<BreakTab>(); public double Width = 100; public double Height = 100; public double MarginBetweenBoards = 2; public bool ConstructNegativePolygon = false; public double FillOffset = 3; public double Smoothing = 1; public double ExtraTabDrillDistance = 0; public bool ClipToOutlines = true; public string LastExportFolder = ""; public bool DoNotGenerateMouseBites = false; public List<string> SaveTo(string OutputFolder, Dictionary<string, GerberOutline> GerberOutlines, ProgressLog Logger) { LastExportFolder = OutputFolder; List<string> GeneratedFiles = new List<string>(); List<String> UnzippedList = new List<string>(); int instanceID = 1; int current = 0; BOM MasterBom = new BOM(); BOMNumberSet set = new BOMNumberSet(); foreach (var a in Instances) { current++; BOM InstanceBom = BOM.ScanFolderForBoms(a.GerberPath); if (InstanceBom != null && InstanceBom.GetPartCount() > 0) { MasterBom.MergeBOM(InstanceBom, set, a.Center.X, a.Center.Y,0,0, a.Angle); } Logger.AddString("writing " + a.GerberPath, ((float)current / (float)Instances.Count) * 0.3f); if (a.GerberPath.Contains("???_negative") == false) { var outline = GerberOutlines[a.GerberPath]; List<String> FileList = new List<string>(); if (Directory.Exists(a.GerberPath)) { FileList = Directory.GetFiles(a.GerberPath).ToList(); } else { if (File.Exists(a.GerberPath) && (Path.GetExtension(a.GerberPath).ToLower() == ".zip" || Path.GetExtension(a.GerberPath).ToLower() == "zip")) { string BaseUnzip = Path.Combine(OutputFolder, "unzipped"); if (Directory.Exists(BaseUnzip) == false) { Directory.CreateDirectory(BaseUnzip); } using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(a.GerberPath)) { foreach (ZipEntry e in zip1) { if (e.IsDirectory == false) { string Unzipped = Path.Combine(BaseUnzip, (instanceID++).ToString() + "_" + Path.GetFileName(e.FileName)); if (File.Exists(Unzipped)) File.Delete(Unzipped); FileStream FS = new FileStream(Unzipped, FileMode.CreateNew); FileList.Add(Unzipped); UnzippedList.Add(Unzipped); e.Extract(FS); FS.Close(); } } } } } instanceID = AddFilesForInstance(OutputFolder,a.Center.X, a.Center.Y, a.Angle, FileList, instanceID, GeneratedFiles, outline, Logger); instanceID++; } } foreach (var a in UnzippedList) { try { File.Delete(a); } catch (Exception) { Logger.AddString(String.Format("warning: {0} not deleted: it was locked?", a)); } } if (MasterBom.GetPartCount() > 0) { string BomFile = Path.Combine(OutputFolder, "MergedBom.csv"); string CentroidFile = Path.Combine(OutputFolder, "MergedCentroids.csv"); MasterBom.SaveBom(BomFile); MasterBom.SaveCentroids(CentroidFile); // GeneratedFiles.Add(CentroidFile); // GeneratedFiles.Add(BomFile); } return GeneratedFiles; } private int AddFilesForInstance(string p, double x, double y, double angle, List<string> FileList, int isntid, List<string> GeneratedFiles, GerberOutline outline, ProgressLog Logger) { GerberImageCreator GIC = new GerberImageCreator(); GIC.AddBoardsToSet(FileList); foreach (var f in FileList) { var FileType = Gerber.FindFileType(f); switch (FileType) { case BoardFileType.Drill: try { double scaler = GIC.GetDrillScaler(f); ExcellonFile EF = new ExcellonFile(); EF.Load(f, scaler); string Filename = Path.Combine(p, (isntid++).ToString() + "_" + Path.GetFileName(f)); EF.Write(Filename, x,y, outline.TheGerber.TranslationSinceLoad.X, outline.TheGerber.TranslationSinceLoad.Y, angle); GeneratedFiles.Add(Filename); } catch (Exception E) { while (E != null) { Logger.AddString("Exception: " + E.Message); E = E.InnerException; } } break; case BoardFileType.Gerber: try { string ext = Path.GetExtension(f).ToLower(); string Filename = Path.Combine(p, (isntid++).ToString() + "_" + Path.GetFileName(f)); string sourcefile = f; string tempfile = ""; if (ClipToOutlines) { BoardSide Side = BoardSide.Unknown; BoardLayer Layer = BoardLayer.Unknown; Gerber.DetermineBoardSideAndLayer(f, out Side, out Layer); if (Layer == BoardLayer.Silk) { tempfile = Path.Combine(p, (isntid++).ToString() + "_" + Path.GetFileName(f)); GerberImageCreator GIC2 = new GerberImageCreator(); GIC2.AddBoardsToSet(FileList); GIC2.ClipBoard(f, tempfile,Logger); sourcefile = tempfile; } } GerberTransposer.Transform(sourcefile, Filename, x, y, outline.TheGerber.TranslationSinceLoad.X, outline.TheGerber.TranslationSinceLoad.Y, angle); GeneratedFiles.Add(Filename); if (tempfile.Length > 0) File.Delete(tempfile); } catch (Exception E) { while (E != null) { Logger.AddString("Exception: " + E.Message); E = E.InnerException; } } break; } } return isntid; } internal void ClearTransformedOutlines() { foreach (var a in Instances) { a.TransformedOutlines = new List<PolyLine>(); } } } public class GerberOutline { public ParsedGerber TheGerber; public GerberOutline(string filename) { if (filename.Length > 0) { TheGerber = PolyLineSet.LoadGerberFile(filename, true, false, new GerberParserState() { PreCombinePolygons = false }); TheGerber.FixPolygonWindings(); foreach (var a in TheGerber.OutlineShapes) { a.CheckIfHole(); } } else { TheGerber = new ParsedGerber(); } } public GerberOutline(StreamReader sr, string originalfilename) { TheGerber = PolyLineSet.LoadGerberFileFromStream(sr, originalfilename, true, false, new GerberParserState() { PreCombinePolygons = false }); TheGerber.FixPolygonWindings(); foreach (var a in TheGerber.OutlineShapes) { a.CheckIfHole(); } } public PointD GetActualCenter() { return TheGerber.BoundingBox.Middle(); } internal void BuildShapeCache() { TheGerber.BuildShapeCache(); } } }
38.345274
227
0.447854
[ "MIT" ]
fape/GerberTools
GerberLibrary/Core/GerberPanel.cs
88,848
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.MSHTMLApi { ///<summary> /// DispatchInterface HTMLOptionButtonElementEvents2 /// SupportByVersion MSHTML, 4 ///</summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class HTMLOptionButtonElementEvents2 : COMObject { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(HTMLOptionButtonElementEvents2); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public HTMLOptionButtonElementEvents2(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public HTMLOptionButtonElementEvents2(string progId) : base(progId) { } #endregion #region Properties #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onhelp(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onhelp", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onclick(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onclick", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondblclick(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondblclick", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onkeypress(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onkeypress", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onkeydown(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onkeydown", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onkeyup(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onkeyup", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmouseout(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmouseout", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmouseover(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmouseover", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmousemove(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmousemove", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmousedown(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmousedown", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmouseup(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmouseup", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onselectstart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onselectstart", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onfilterchange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onfilterchange", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondragstart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondragstart", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforeupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforeupdate", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onafterupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onafterupdate", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onerrorupdate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onerrorupdate", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onrowexit(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onrowexit", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onrowenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onrowenter", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondatasetchanged(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondatasetchanged", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondataavailable(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondataavailable", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondatasetcomplete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondatasetcomplete", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onlosecapture(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onlosecapture", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onpropertychange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onpropertychange", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onscroll(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onscroll", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onfocus(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onfocus", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onblur(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onblur", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onresize(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onresize", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondrag(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondrag", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondragend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondragend", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondragenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondragenter", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondragover(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondragover", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondragleave(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondragleave", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ondrop(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "ondrop", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforecut(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforecut", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool oncut(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "oncut", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforecopy(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforecopy", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool oncopy(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "oncopy", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforepaste(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforepaste", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onpaste(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onpaste", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool oncontextmenu(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "oncontextmenu", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onrowsdelete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onrowsdelete", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onrowsinserted(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onrowsinserted", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void oncellchange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "oncellchange", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onreadystatechange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onreadystatechange", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onlayoutcomplete(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onlayoutcomplete", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onpage(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onpage", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmouseenter(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmouseenter", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmouseleave(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmouseleave", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onactivate", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void ondeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "ondeactivate", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforedeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforedeactivate", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onbeforeactivate(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onbeforeactivate", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onfocusin(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onfocusin", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onfocusout(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onfocusout", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmove(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmove", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool oncontrolselect(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "oncontrolselect", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onmovestart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onmovestart", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onmoveend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onmoveend", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onresizestart(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onresizestart", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onresizeend(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onresizeend", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onmousewheel(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onmousewheel", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public bool onchange(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); object returnItem = Invoker.MethodReturn(this, "onchange", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onselect(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onselect", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onload(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onload", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onerror(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onerror", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pEvtObj">NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj</param> [SupportByVersionAttribute("MSHTML", 4)] public void onabort(NetOffice.MSHTMLApi.IHTMLEventObj pEvtObj) { object[] paramsArray = Invoker.ValidateParamsArray(pEvtObj); Invoker.Method(this, "onabort", paramsArray); } #endregion #pragma warning restore } }
33.966738
184
0.72022
[ "MIT" ]
Engineerumair/NetOffice
Source/MSHTML/DispatchInterfaces/HTMLOptionButtonElementEvents2.cs
31,657
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using Atma.Math.Swizzle; // ReSharper disable InconsistentNaming namespace Atma.Math { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public static double[,] Values(double2x2 m) => m.Values; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public static double[] Values1D(double2x2 m) => m.Values1D; /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public static IEnumerator<double> GetEnumerator(double2x2 m) => m.GetEnumerator(); } }
27.368421
90
0.636538
[ "MIT" ]
xposure/Atma.Math
source/Atma/Math/Mat2x2/double2x2.glm.cs
1,040
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using ZYSocket; using ZYSocket.Client; using ZYSocket.FiberStream; using ZYSocket.FiberStream.Synchronization; using ZYSocket.Share; namespace TestClient { class Program { static SocketClient client; static int id = 0; static async Task Main(string[] args) { var send = new NetSend(); client = new SocketClient(async_send:send,sync_send:send); client.BinaryInput += Client_BinaryInput; client.Disconnect += Client_Disconnect; while (true) { await connect(); var fiberRw = await client.GetFiberRw(); async Task Run() { while (true) { try { await SendTest(fiberRw); } catch { break; } } }; //var task1 = Task.Factory.StartNew(async () => // { // while (true) // { // try // { // await SendTest(fiberRw); // } // catch // { // break; // } // } // }); //var task2 = Task.Factory.StartNew(async () => //{ // while (true) // { // try // { // await SendTest(fiberRw); // } // catch // { // break; // } // } //}); //var task3 = Task.Factory.StartNew(async () => //{ // while (true) // { // try // { // await SendTest(fiberRw); // } // catch // { // break; // } // } //}); //var task4 = Task.Factory.StartNew(async () => //{ // while (true) // { // try // { // await SendTest(fiberRw); // } // catch // { // break; // } // } //}); await Task.WhenAll(Run(), Run(), Run(), Run()); } } private static async Task SendTest(IFiberRw fiberRw) { await fiberRw.Sync.Ask(() => { fiberRw.Write((++id).ToString()); }); await fiberRw.Sync.Delay(10, () => { return fiberRw.FlushAsync(); }); } static async Task connect() { var result = await client.ConnectAsync("127.0.0.1", 1002, 60000); Console.WriteLine(result); } private static void Client_Disconnect(ISocketClient client, ISockAsyncEvent socketAsync, string msg) { Console.WriteLine(msg); } static System.Diagnostics.Stopwatch stopwatch = new Stopwatch(); static int count = 0; private static async void Client_BinaryInput(ISocketClient client, ISockAsyncEvent socketAsync) { var fiberRw = await socketAsync.GetFiberRw(); client.SetConnected(); stopwatch.Start(); while (true) { try { await DataOnByLine(fiberRw); } catch { break; } } client.ShutdownBoth(); } static async ValueTask DataOnByLine(IFiberRw fiberRw) { var id = await fiberRw.ReadString(); if (System.Threading.Interlocked.Increment(ref count) >1000000) { System.Threading.Interlocked.Exchange(ref count, 0); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); stopwatch.Restart(); } // sendp(fiberRw); } static async void sendp(IFiberRw fiberRw) { await SendTest(fiberRw); } } }
25.044335
108
0.350708
[ "Apache-2.0" ]
luyikk/ZYSOCKET-V
ZYSocketFrame/MultithreadClient/Program.cs
5,086
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.Network.V20200801.Outputs { /// <summary> /// VirtualHub route table. /// </summary> [OutputType] public sealed class VirtualHubRouteTableResponse { /// <summary> /// List of all routes. /// </summary> public readonly ImmutableArray<Outputs.VirtualHubRouteResponse> Routes; [OutputConstructor] private VirtualHubRouteTableResponse(ImmutableArray<Outputs.VirtualHubRouteResponse> routes) { Routes = routes; } } }
27.290323
100
0.673759
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200801/Outputs/VirtualHubRouteTableResponse.cs
846
C#
namespace Kgb.ChessApp.Models { public enum CellType { White, Black } }
11.222222
30
0.534653
[ "MIT" ]
KostyaBaklan/Chess-KGB
Chess/App/Models/CellType.cs
103
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 SequenceStatistics : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal SequenceStatistics(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SequenceStatistics obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~SequenceStatistics() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_SequenceStatistics(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); } } public SequenceStatistics(uint dimension) : this(NQuantLibcPINVOKE.new_SequenceStatistics(dimension), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public uint size() { uint ret = NQuantLibcPINVOKE.SequenceStatistics_size(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public uint samples() { uint ret = NQuantLibcPINVOKE.SequenceStatistics_samples(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double weightSum() { double ret = NQuantLibcPINVOKE.SequenceStatistics_weightSum(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector mean() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_mean(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector variance() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_variance(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector standardDeviation() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_standardDeviation(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector errorEstimate() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_errorEstimate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector skewness() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_skewness(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector kurtosis() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_kurtosis(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector min() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_min(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public DoubleVector max() { DoubleVector ret = new DoubleVector(NQuantLibcPINVOKE.SequenceStatistics_max(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Matrix covariance() { Matrix ret = new Matrix(NQuantLibcPINVOKE.SequenceStatistics_covariance(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Matrix correlation() { Matrix ret = new Matrix(NQuantLibcPINVOKE.SequenceStatistics_correlation(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void reset() { NQuantLibcPINVOKE.SequenceStatistics_reset(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public void add(DoubleVector value, double weight) { NQuantLibcPINVOKE.SequenceStatistics_add__SWIG_0(swigCPtr, DoubleVector.getCPtr(value), weight); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public void add(DoubleVector value) { NQuantLibcPINVOKE.SequenceStatistics_add__SWIG_1(swigCPtr, DoubleVector.getCPtr(value)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public void add(QlArray value, double weight) { NQuantLibcPINVOKE.SequenceStatistics_add__SWIG_2(swigCPtr, QlArray.getCPtr(value), weight); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public void add(QlArray value) { NQuantLibcPINVOKE.SequenceStatistics_add__SWIG_3(swigCPtr, QlArray.getCPtr(value)); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
41.418301
129
0.757456
[ "BSD-3-Clause" ]
x-xing/Quantlib-SWIG
CSharp/csharp/SequenceStatistics.cs
6,337
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Dex.Cap.OnceExecutor { public abstract class BaseOnceExecutor<TContext, TResult> : IOnceExecutor<TContext, TResult> { protected abstract TContext Context { get; } public Task<TResult?> Execute(Guid idempotentKey, Func<TContext, CancellationToken, Task> modificator, Func<TContext, CancellationToken, Task<TResult>>? selector = null, CancellationToken cancellationToken = default) { if (modificator == null) throw new ArgumentNullException(nameof(modificator)); return ExecuteInTransaction(idempotentKey, async (token) => { if (!await IsAlreadyExecuted(idempotentKey, token)) { await SaveIdempotentKey(idempotentKey, token); await modificator(Context, token); await OnModificationComplete(); } var result = selector != null ? await selector(Context, token) : default; return result; }, cancellationToken); } protected abstract Task<TResult?> ExecuteInTransaction(Guid idempotentKey, Func<CancellationToken, Task<TResult?>> operation, CancellationToken cancellationToken); protected abstract Task OnModificationComplete(); protected abstract Task<bool> IsAlreadyExecuted(Guid idempotentKey, CancellationToken cancellationToken); protected abstract Task SaveIdempotentKey(Guid idempotentKey, CancellationToken cancellationToken); } }
41.35
171
0.646917
[ "MIT" ]
dex-it/dex-common
src/Dex.Cap/Dex.Cap.OnceExecutor/BaseOnceExecutor.cs
1,654
C#