max_stars_repo_path
stringlengths
4
294
max_stars_repo_name
stringlengths
5
116
max_stars_count
float64
0
82k
id
stringlengths
1
8
content
stringlengths
1
1.04M
score
float64
-0.88
3.59
int_score
int64
0
4
libutils.tests/NiceIO/ParentContaining.cs
scottbilas/advent-of-code
3
4
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using NUnit.Framework; using Unity.Coding.Utils; namespace NiceIO.Tests { [TestFixture] class ParentContaining : TestWithTempDir { [Test] public void TwoLevelsDown() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile", "somedir/needle"}); Assert.AreEqual(_tempPath.Combine("somedir"), _tempPath.Combine("somedir/dir2/myfile").ParentContaining("needle")); } [Test] public void NonExisting() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile" }); Assert.IsNull(_tempPath.Combine("somedir/dir2/myfile").ParentContaining("nonexisting")); } [Test] public void WithComplexNeedle() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile" , "needledir/", "needledir/needlefile"}); Assert.AreEqual(_tempPath, _tempPath.Combine("somedir/dir2/myfile").ParentContaining(new NPath("needledir/needlefile"))); } [Test] public void InRelativePath() { Assert.Throws<ArgumentException>(() => new NPath("this/is/relative").ParentContaining("needle")); } } }
1.703125
2
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs.cs
alexbowers/pulumi-aws
0
12
// *** 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.WafV2.Inputs { public sealed class WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs() { } } }
1.117188
1
Peeps.Monitoring.WebApp/Services/ModalService.cs
mc738/Peeps
0
20
using System; using Microsoft.AspNetCore.Components; namespace Peeps.Monitoring.WebApp.Services { public class ModalService { public event Action<string, RenderFragment> OnShow; public event Action OnClose; public void Show(string title, RenderFragment content) { // if (contentType.BaseType != typeof(ComponentBase)) // throw new ArgumentException($"{contentType.FullName} must be a Blazor Component"); // var content = new RenderFragment(x => { x.OpenComponent(1, contentType); x.CloseComponent(); }); OnShow?.Invoke(title, content); } public void Close() { OnClose?.Invoke(); } } }
1.101563
1
Ash.DefaultEC/UI/Containers/Container.cs
JonSnowbd/Nez
3
28
using System; using Microsoft.Xna.Framework; namespace Ash.UI { /// <summary> /// A group with a single child that sizes and positions the child using constraints. This provides layout similar to a /// {@link Table} with a single cell but is more lightweight. /// </summary> public class Container : Group { #region ILayout public override float MinWidth => GetMinWidth(); public override float MinHeight => GetPrefHeight(); public override float PreferredWidth => GetPrefWidth(); public override float PreferredHeight => GetPrefHeight(); public override float MaxWidth => GetMaxWidth(); public override float MaxHeight => GetMaxHeight(); #endregion Element _element; Value _minWidthValue = Value.MinWidth, _minHeightValue = Value.MinHeight; Value _prefWidthValue = Value.PrefWidth, _prefHeightValue = Value.PrefHeight; Value _maxWidthValue = Value.Zero, _maxHeightValue = Value.Zero; Value _padTop = Value.Zero, _padLeft = Value.Zero, _padBottom = Value.Zero, _padRight = Value.Zero; float _fillX, _fillY; int _align; IDrawable _background; bool _clip; bool _round = true; /// <summary> /// Creates a container with no element /// </summary> public Container() { SetTouchable(Touchable.ChildrenOnly); transform = false; } public Container(Element element) : this() { SetElement(element); } public override void Draw(Batcher batcher, float parentAlpha) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); DrawBackground(batcher, parentAlpha, 0, 0); if (_clip) { //batcher.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //if( clipBegin( padLeft, padBottom,minWidthValueh() - padLeft - padRight.get( tmaxWidth // getHeight() - padBottom - padTop.get( this ) ) ) { DrawChildren(batcher, parentAlpha); //batcher.flush(); //clipEnd(); } } else { DrawChildren(batcher, parentAlpha); } ResetTransform(batcher); } else { DrawBackground(batcher, parentAlpha, GetX(), GetY()); base.Draw(batcher, parentAlpha); } } /// <summary> /// Called to draw the background, before clipping is applied (if enabled). Default implementation draws the background drawable. /// </summary> /// <param name="batcher">Batcher.</param> /// <param name="parentAlpha">Parent alpha.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> protected void DrawBackground(Batcher batcher, float parentAlpha, float x, float y) { if (_background == null) return; _background.Draw(batcher, x, y, GetWidth(), GetHeight(), ColorExt.Create(color, (int) (color.A * parentAlpha))); } /// <summary> /// Sets the background drawable and adjusts the container's padding to match the background. /// </summary> /// <param name="background">Background.</param> public Container SetBackground(IDrawable background) { return SetBackground(background, true); } /// <summary> /// Sets the background drawable and, if adjustPadding is true, sets the container's padding to /// {@link Drawable#getBottomHeight()} , {@link Drawable#getTopHeight()}, {@link Drawable#getLeftWidth()}, and /// {@link Drawable#getRightWidth()}. /// If background is null, the background will be cleared and padding removed. /// </summary> /// <param name="background">Background.</param> /// <param name="adjustPadding">If set to <c>true</c> adjust padding.</param> public Container SetBackground(IDrawable background, bool adjustPadding) { if (_background == background) return this; _background = background; if (adjustPadding) { if (background == null) SetPad(Value.Zero); else SetPad(background.TopHeight, background.LeftWidth, background.BottomHeight, background.RightWidth); Invalidate(); } return this; } public IDrawable GetBackground() { return _background; } public override void Layout() { if (_element == null) return; float padLeft = _padLeft.Get(this), padBottom = _padBottom.Get(this); float containerWidth = GetWidth() - padLeft - _padRight.Get(this); float containerHeight = GetHeight() - padBottom - _padTop.Get(this); float minWidth = _minWidthValue.Get(_element), minHeight = _minHeightValue.Get(_element); float prefWidth = _prefWidthValue.Get(_element), prefHeight = _prefHeightValue.Get(_element); float maxWidth = _maxWidthValue.Get(_element), maxHeight = _maxHeightValue.Get(_element); float width; if (_fillX > 0) width = containerWidth * _fillX; else width = Math.Min(prefWidth, containerWidth); if (width < minWidth) width = minWidth; if (maxWidth > 0 && width > maxWidth) width = maxWidth; float height; if (_fillY > 0) height = containerHeight * _fillY; else height = Math.Min(prefHeight, containerHeight); if (height < minHeight) height = minHeight; if (maxHeight > 0 && height > maxHeight) height = maxHeight; var x = padLeft; if ((_align & AlignInternal.Right) != 0) x += containerWidth - width; else if ((_align & AlignInternal.Left) == 0) // center x += (containerWidth - width) / 2; var y = padBottom; if ((_align & AlignInternal.Top) != 0) y += containerHeight - height; else if ((_align & AlignInternal.Bottom) == 0) // center y += (containerHeight - height) / 2; if (_round) { x = Mathf.Round(x); y = Mathf.Round(y); width = Mathf.Round(width); height = Mathf.Round(height); } _element.SetBounds(x, y, width, height); if (_element is ILayout) ((ILayout) _element).Validate(); } /// <summary> /// element may be null /// </summary> /// <returns>The element.</returns> /// <param name="element">element.</param> public virtual Element SetElement(Element element) { if (element == this) throw new Exception("element cannot be the Container."); if (element == _element) return element; if (_element != null) base.RemoveElement(_element); _element = element; if (element != null) return AddElement(element); return null; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public T GetElement<T>() where T : Element { return _element as T; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public Element GetElement() { return _element; } public override bool RemoveElement(Element element) { if (element != _element) return false; SetElement(null); return true; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; _prefWidthValue = size; _prefHeightValue = size; _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; _prefWidthValue = width; _prefHeightValue = height; _maxWidthValue = width; _maxHeightValue = height; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(float size) { SetSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public new Container SetSize(float width, float height) { SetSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public Container SetWidth(Value width) { if (width == null) throw new Exception("width cannot be null."); _minWidthValue = width; _prefWidthValue = width; _maxWidthValue = width; return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public new Container SetWidth(float width) { SetWidth(new Value.Fixed(width)); return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value. /// </summary> /// <param name="height">Height.</param> public Container SetHeight(Value height) { if (height == null) throw new Exception("height cannot be null."); _minHeightValue = height; _prefHeightValue = height; _maxHeightValue = height; return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="height">Height.</param> public new Container SetHeight(float height) { SetHeight(new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; return this; } /// <summary> /// Sets the minimum size. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; return this; } public Container SetMinWidth(Value minWidth) { if (minWidth == null) throw new Exception("minWidth cannot be null."); _minWidthValue = minWidth; return this; } public Container SetMinHeight(Value minHeight) { if (minHeight == null) throw new Exception("minHeight cannot be null."); _minHeightValue = minHeight; return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(float size) { SetMinSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(float width, float height) { SetMinSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMinWidth(float minWidth) { _minWidthValue = new Value.Fixed(minWidth); return this; } public Container SetMinHeight(float minHeight) { _minHeightValue = new Value.Fixed(minHeight); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container PrefSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _prefWidthValue = size; _prefHeightValue = size; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container PrefSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _prefWidthValue = width; _prefHeightValue = height; return this; } public Container SetPrefWidth(Value prefWidth) { if (prefWidth == null) throw new Exception("prefWidth cannot be null."); _prefWidthValue = prefWidth; return this; } public Container SetPrefHeight(Value prefHeight) { if (prefHeight == null) throw new Exception("prefHeight cannot be null."); _prefHeightValue = prefHeight; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetPrefSize(float width, float height) { PrefSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values /// </summary> /// <param name="size">Size.</param> public Container SetPrefSize(float size) { PrefSize(new Value.Fixed(size)); return this; } public Container SetPrefWidth(float prefWidth) { _prefWidthValue = new Value.Fixed(prefWidth); return this; } public Container SetPrefHeight(float prefHeight) { _prefHeightValue = new Value.Fixed(prefHeight); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _maxWidthValue = width; _maxHeightValue = height; return this; } public Container SetMaxWidth(Value maxWidth) { if (maxWidth == null) throw new Exception("maxWidth cannot be null."); _maxWidthValue = maxWidth; return this; } public Container SetMaxHeight(Value maxHeight) { if (maxHeight == null) throw new Exception("maxHeight cannot be null."); _maxHeightValue = maxHeight; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(float size) { SetMaxSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(float width, float height) { SetMaxSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMaxWidth(float maxWidth) { _maxWidthValue = new Value.Fixed(maxWidth); return this; } public Container SetMaxHeight(float maxHeight) { _maxHeightValue = new Value.Fixed(maxHeight); return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value. /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(Value pad) { if (pad == null) throw new Exception("pad cannot be null."); _padTop = pad; _padLeft = pad; _padBottom = pad; _padRight = pad; return this; } public Container SetPad(Value top, Value left, Value bottom, Value right) { if (top == null) throw new Exception("top cannot be null."); if (left == null) throw new Exception("left cannot be null."); if (bottom == null) throw new Exception("bottom cannot be null."); if (right == null) throw new Exception("right cannot be null."); _padTop = top; _padLeft = left; _padBottom = bottom; _padRight = right; return this; } public Container SetPadTop(Value padTop) { if (padTop == null) throw new Exception("padTop cannot be null."); _padTop = padTop; return this; } public Container SetPadLeft(Value padLeft) { if (padLeft == null) throw new Exception("padLeft cannot be null."); _padLeft = padLeft; return this; } public Container SetPadBottom(Value padBottom) { if (padBottom == null) throw new Exception("padBottom cannot be null."); _padBottom = padBottom; return this; } public Container SetPadRight(Value padRight) { if (padRight == null) throw new Exception("padRight cannot be null."); _padRight = padRight; return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(float pad) { Value value = new Value.Fixed(pad); _padTop = value; _padLeft = value; _padBottom = value; _padRight = value; return this; } public Container SetPad(float top, float left, float bottom, float right) { _padTop = new Value.Fixed(top); _padLeft = new Value.Fixed(left); _padBottom = new Value.Fixed(bottom); _padRight = new Value.Fixed(right); return this; } public Container SetPadTop(float padTop) { _padTop = new Value.Fixed(padTop); return this; } public Container SetPadLeft(float padLeft) { _padLeft = new Value.Fixed(padLeft); return this; } public Container SetPadBottom(float padBottom) { _padBottom = new Value.Fixed(padBottom); return this; } public Container SetPadRight(float padRight) { _padRight = new Value.Fixed(padRight); return this; } /// <summary> /// Sets fillX and fillY to 1 /// </summary> public Container SetFill() { _fillX = 1f; _fillY = 1f; return this; } /// <summary> /// Sets fillX to 1 /// </summary> public Container SetFillX() { _fillX = 1f; return this; } /// <summary> /// Sets fillY to 1 /// </summary> public Container SetFillY() { _fillY = 1f; return this; } public Container SetFill(float x, float y) { _fillX = x; _fillY = y; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="x">If set to <c>true</c> x.</param> /// <param name="y">If set to <c>true</c> y.</param> public Container SetFill(bool x, bool y) { _fillX = x ? 1f : 0; _fillY = y ? 1f : 0; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="fill">If set to <c>true</c> fill.</param> public Container SetFill(bool fill) { _fillX = fill ? 1f : 0; _fillY = fill ? 1f : 0; return this; } /// <summary> /// Sets the alignment of the element within the container. Set to {@link Align#center}, {@link Align#top}, {@link Align#bottom}, /// {@link Align#left}, {@link Align#right}, or any combination of those. /// </summary> /// <param name="align">Align.</param> public Container SetAlign(Align align) { _align = (int) align; return this; } /// <summary> /// Sets the alignment of the element within the container to {@link Align#center}. This clears any other alignment. /// </summary> public Container SetAlignCenter() { _align = AlignInternal.Center; return this; } /// <summary> /// Sets {@link Align#top} and clears {@link Align#bottom} for the alignment of the element within the container. /// </summary> public Container SetTop() { _align |= AlignInternal.Top; _align &= ~AlignInternal.Bottom; return this; } /// <summary> /// Sets {@link Align#left} and clears {@link Align#right} for the alignment of the element within the container. /// </summary> public Container SetLeft() { _align |= AlignInternal.Left; _align &= ~AlignInternal.Right; return this; } /// <summary> /// Sets {@link Align#bottom} and clears {@link Align#top} for the alignment of the element within the container. /// </summary> public Container SetBottom() { _align |= AlignInternal.Bottom; _align &= ~AlignInternal.Top; return this; } /// <summary> /// Sets {@link Align#right} and clears {@link Align#left} for the alignment of the element within the container. /// </summary> public Container SetRight() { _align |= AlignInternal.Right; _align &= ~AlignInternal.Left; return this; } public float GetMinWidth() { return _minWidthValue.Get(_element) + _padLeft.Get(this) + _padRight.Get(this); } public Value GetMinHeightValue() { return _minHeightValue; } public float GetMinHeight() { return _minHeightValue.Get(_element) + _padTop.Get(this) + _padBottom.Get(this); } public Value GetPrefWidthValue() { return _prefWidthValue; } public float GetPrefWidth() { float v = _prefWidthValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinWidth); return Math.Max(GetMinWidth(), v + _padLeft.Get(this) + _padRight.Get(this)); } public Value GetPrefHeightValue() { return _prefHeightValue; } public float GetPrefHeight() { float v = _prefHeightValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinHeight); return Math.Max(GetMinHeight(), v + _padTop.Get(this) + _padBottom.Get(this)); } public Value GetMaxWidthValue() { return _maxWidthValue; } public float GetMaxWidth() { float v = _maxWidthValue.Get(_element); if (v > 0) v += _padLeft.Get(this) + _padRight.Get(this); return v; } public Value GetMaxHeightValue() { return _maxHeightValue; } public float GetMaxHeight() { float v = _maxHeightValue.Get(_element); if (v > 0) v += _padTop.Get(this) + _padBottom.Get(this); return v; } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad top value.</returns> public Value GetPadTopValue() { return _padTop; } public float GetPadTop() { return _padTop.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad left value.</returns> public Value GetPadLeftValue() { return _padLeft; } public float GetPadLeft() { return _padLeft.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad bottom value.</returns> public Value GetPadBottomValue() { return _padBottom; } public float GetPadBottom() { return _padBottom.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad right value.</returns> public Value GetPadRightValue() { return _padRight; } public float GetPadRight() { return _padRight.Get(this); } /// <summary> /// Returns {@link #getPadLeft()} plus {@link #getPadRight()}. /// </summary> /// <returns>The pad x.</returns> public float GetPadX() { return _padLeft.Get(this) + _padRight.Get(this); } /// <summary> /// Returns {@link #getPadTop()} plus {@link #getPadBottom()} /// </summary> /// <returns>The pad y.</returns> public float GetPadY() { return _padTop.Get(this) + _padBottom.Get(this); } public float GetFillX() { return _fillX; } public float GetFillY() { return _fillY; } public int GetAlign() { return _align; } /// <summary> /// If true (the default), positions and sizes are rounded to integers /// </summary> /// <param name="round">If set to <c>true</c> round.</param> public void SetRound(bool round) { _round = round; } /// <summary> /// Causes the contents to be clipped if they exceed the container bounds. Enabling clipping will set /// {@link #setTransform(bool)} to true /// </summary> /// <param name="enabled">If set to <c>true</c> enabled.</param> public void SetClip(bool enabled) { _clip = enabled; transform = enabled; Invalidate(); } public bool GetClip() { return _clip; } public override Element Hit(Vector2 point) { if (_clip) { if (GetTouchable() == Touchable.Disabled) return null; if (point.X < 0 || point.X >= GetWidth() || point.Y < 0 || point.Y >= GetHeight()) return null; } return base.Hit(point); } public override void DebugRender(Batcher batcher) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); if (_clip) { //shapes.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //bool draw = background == null ? clipBegin( 0, 0, getWidth(), getHeight() ) : clipBegin( padLeft, padBottom, // getWidth() - padLeft - padRight.get( this ), getHeight() - padBottom - padTop.get( this ) ); var draw = true; if (draw) { DebugRenderChildren(batcher, 1f); //clipEnd(); } } else { DebugRenderChildren(batcher, 1f); } ResetTransform(batcher); } else { base.DebugRender(batcher); } } } }
2.0625
2
PdfSharp/PdfSharp.Pdf.AcroForms/PdfAcroField.cs
alexiej/YATE
18
36
#region PDFsharp - A .NET library for processing PDF // // Authors: // <NAME> (mailto:<EMAIL>) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Collections; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.Internal; namespace PdfSharp.Pdf.AcroForms { /// <summary> /// Represents the base class for all interactive field dictionaries. /// </summary> public abstract class PdfAcroField : PdfDictionary { /// <summary> /// Initializes a new instance of PdfAcroField. /// </summary> internal PdfAcroField(PdfDocument document) : base(document) { } /// <summary> /// Initializes a new instance of the <see cref="PdfAcroField"/> class. Used for type transformation. /// </summary> protected PdfAcroField(PdfDictionary dict) : base(dict) { } /// <summary> /// Gets the name of this field. /// </summary> public string Name { get { string name = Elements.GetString(Keys.T); return name; } } /// <summary> /// Gets the field flags of this instance. /// </summary> public PdfAcroFieldFlags Flags { // TODO: This entry is inheritable, thus the implementation is incorrect... id:102 gh:103 get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } } internal PdfAcroFieldFlags SetFlags { get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } set { Elements.SetInteger(Keys.Ff, (int)value); } } /// <summary> /// Gets or sets the value of the field. /// </summary> public PdfItem Value { get { return Elements[Keys.V]; } set { if (ReadOnly) throw new InvalidOperationException("The field is read only."); if (value is PdfString || value is PdfName) Elements[Keys.V] = value; else throw new NotImplementedException("Values other than string cannot be set."); } } /// <summary> /// Gets or sets a value indicating whether the field is read only. /// </summary> public bool ReadOnly { get { return (Flags & PdfAcroFieldFlags.ReadOnly) != 0; } set { if (value) SetFlags |= PdfAcroFieldFlags.ReadOnly; else SetFlags &= ~PdfAcroFieldFlags.ReadOnly; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } /// <summary> /// Gets a child field by name. /// </summary> protected virtual PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return this; if (HasKids) return Fields.GetValue(name); return null; } /// <summary> /// Indicates whether the field has child fields. /// </summary> public bool HasKids { get { PdfItem item = Elements[Keys.Kids]; if (item == null) return false; if (item is PdfArray) return ((PdfArray)item).Elements.Count > 0; return false; } } /// <summary> /// Gets the names of all descendants of this field. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); if (HasKids) { PdfAcroFieldCollection fields = Fields; fields.GetDescendantNames(ref names, null); } List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal virtual void GetDescendantNames(ref List<PdfName> names, string partialName) { if (HasKids) { PdfAcroFieldCollection fields = Fields; string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (partialName != null && partialName.Length > 0) partialName += "." + t; else partialName = t; fields.GetDescendantNames(ref names, partialName); } } else { string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (!String.IsNullOrEmpty(partialName)) names.Add(new PdfName(partialName + "." + t)); else names.Add(new PdfName(t)); } } } /// <summary> /// Gets the collection of fields within this field. /// </summary> public PdfAcroField.PdfAcroFieldCollection Fields { get { if (this.fields == null) { object o = Elements.GetValue(Keys.Kids, VCF.CreateIndirect); this.fields = (PdfAcroField.PdfAcroFieldCollection)o; } return this.fields; } } PdfAcroField.PdfAcroFieldCollection fields; /// <summary> /// Holds a collection of interactive fields. /// </summary> public sealed class PdfAcroFieldCollection : PdfArray { PdfAcroFieldCollection(PdfArray array) : base(array) { } /// <summary> /// Gets the names of all fields in the collection. /// </summary> public string[] Names { get { int count = Elements.Count; string[] names = new string[count]; for (int idx = 0; idx < count; idx++) names[idx] = ((PdfDictionary)((PdfReference)Elements[idx]).Value).Elements.GetString(Keys.T); return names; } } /// <summary> /// Gets an array of all descendant names. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); GetDescendantNames(ref names, null); List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal void GetDescendantNames(ref List<PdfName> names, string partialName) { int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; Debug.Assert(field != null); if (field != null) field.GetDescendantNames(ref names, partialName); } } /// <summary> /// Gets a field from the collection. For your convenience an instance of a derived class like /// PdfTextField or PdfCheckBox is returned if PDFsharp can guess the actual type of the dictionary. /// If the actual type cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> public PdfAcroField this[int index] { get { PdfItem item = Elements[index]; Debug.Assert(item is PdfReference); PdfDictionary dict = ((PdfReference)item).Value as PdfDictionary; Debug.Assert(dict != null); PdfAcroField field = dict as PdfAcroField; if (field == null && dict != null) { // Do type transformation field = CreateAcroField(dict); //Elements[index] = field.XRef; } return field; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } internal PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return null; int dot = name.IndexOf('.'); string prefix = dot == -1 ? name : name.Substring(0, dot); string suffix = dot == -1 ? "" : name.Substring(dot + 1); int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; if (field.Name == prefix) return field.GetValue(suffix); } return null; } /// <summary> /// Create a derived type like PdfTextField or PdfCheckBox if possible. /// If the actual cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> PdfAcroField CreateAcroField(PdfDictionary dict) { string ft = dict.Elements.GetName(Keys.FT); PdfAcroFieldFlags flags = (PdfAcroFieldFlags)dict.Elements.GetInteger(Keys.Ff); switch (ft) { case "/Btn": if ((flags & PdfAcroFieldFlags.Pushbutton) != 0) return new PdfPushButtonField(dict); else if ((flags & PdfAcroFieldFlags.Radio) != 0) return new PdfRadioButtonField(dict); else return new PdfCheckBoxField(dict); case "/Tx": return new PdfTextField(dict); case "/Ch": if ((flags & PdfAcroFieldFlags.Combo) != 0) return new PdfComboBoxField(dict); else return new PdfListBoxField(dict); case "/Sig": return new PdfSignatureField(dict); default: return new PdfGenericField(dict); } } } /// <summary> /// Predefined keys of this dictionary. /// The description comes from PDF 1.4 Reference. /// </summary> public class Keys : KeysBase { /// <summary> /// (Required for terminal fields; inheritable) The type of field that this dictionary /// describes: /// Btn Button /// Tx Text /// Ch Choice /// Sig (PDF 1.3) Signature /// Note: This entry may be present in a nonterminal field (one whose descendants /// are themselves fields) in order to provide an inheritable FT value. However, a /// nonterminal field does not logically have a type of its own; it is merely a container /// for inheritable attributes that are intended for descendant terminal fields of /// any type. /// </summary> [KeyInfo(KeyType.Name | KeyType.Required)] public const string FT = "/FT"; /// <summary> /// (Required if this field is the child of another in the field hierarchy; absent otherwise) /// The field that is the immediate parent of this one (the field, if any, whose Kids array /// includes this field). A field can have at most one parent; that is, it can be included /// in the Kids array of at most one other field. /// </summary> [KeyInfo(KeyType.Dictionary)] public const string Parent = "/Parent"; /// <summary> /// (Optional) An array of indirect references to the immediate children of this field. /// </summary> [KeyInfo(KeyType.Array | KeyType.Optional, typeof(PdfAcroField.PdfAcroFieldCollection))] public const string Kids = "/Kids"; /// <summary> /// (Optional) The partial field name. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string T = "/T"; /// <summary> /// (Optional; PDF 1.3) An alternate field name, to be used in place of the actual /// field name wherever the field must be identified in the user interface (such as /// in error or status messages referring to the field). This text is also useful /// when extracting the document�s contents in support of accessibility to disabled /// users or for other purposes. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TU = "/TU"; /// <summary> /// (Optional; PDF 1.3) The mapping name to be used when exporting interactive form field /// data from the document. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TM = "/TM"; /// <summary> /// (Optional; inheritable) A set of flags specifying various characteristics of the field. /// Default value: 0. /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Ff = "/Ff"; /// <summary> /// (Optional; inheritable) The field�s value, whose format varies depending on /// the field type; see the descriptions of individual field types for further information. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string V = "/V"; /// <summary> /// (Optional; inheritable) The default value to which the field reverts when a /// reset-form action is executed. The format of this value is the same as that of V. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string DV = "/DV"; /// <summary> /// (Optional; PDF 1.2) An additional-actions dictionary defining the field�s behavior /// in response to various trigger events. This entry has exactly the same meaning as /// the AA entry in an annotation dictionary. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Optional)] public const string AA = "/AA"; // ----- Additional entries to all fields containing variable text -------------------------- /// <summary> /// (Required; inheritable) A resource dictionary containing default resources /// (such as fonts, patterns, or color spaces) to be used by the appearance stream. /// At a minimum, this dictionary must contain a Font entry specifying the resource /// name and font dictionary of the default font for displaying the field�s text. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Required)] public const string DR = "/DR"; /// <summary> /// (Required; inheritable) The default appearance string, containing a sequence of /// valid page-content graphics or text state operators defining such properties as /// the field�s text size and color. /// </summary> [KeyInfo(KeyType.String | KeyType.Required)] public const string DA = "/DA"; /// <summary> /// (Optional; inheritable) A code specifying the form of quadding (justification) /// to be used in displaying the text: /// 0 Left-justified /// 1 Centered /// 2 Right-justified /// Default value: 0 (left-justified). /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Q = "/Q"; } } }
1.25
1
Manufaktura.Controls.Legacy/Rendering/ScoreRenderingModes.cs
prepare/Ajcek_manufakturalibraries
0
44
namespace Manufaktura.Controls.Rendering { public enum ScoreRenderingModes { /// <summary> /// All system breaks are ignored (the score is displayed in single staff system). /// </summary> Panorama, /// <summary> /// Only single page is displayed /// </summary> SinglePage, /// <summary> /// All pages are displayed /// </summary> AllPages } }
0.609375
1
Singonet.ir.UI.SQL_Connection/SQL_Connection_Class.cs
ShayanFiroozi/SQL_Server_Connection_Manager
1
52
/******************************************************************* * Forever <NAME> , Forever Persia * * * * ----> Singonet.ir <---- * * * * C# Singnet.ir * * * * By <NAME> 2017 <NAME> - Iran * * EMail : <EMAIL> * * Phone : +98 936 517 5800 * * * *******************************************************************/ using System; using System.Data.SqlClient; namespace Singonet.ir.UI.SQL_Connection { public static class SQL_Connection_Class { private static frm_theme_default _frm_connection; // main sql connection for user public static SqlConnection _SQL_Connection { get; internal set; } public enum UI_Theme { Default_Theme = 0, } public static void Show_SQL_Connection_Manager(string ApplicationName,UI_Theme _UI_Theme = UI_Theme.Default_Theme) { if (string.IsNullOrEmpty(ApplicationName)==true) { throw new Exception("Invalid Application Name."); } // Theme selection if (_UI_Theme == UI_Theme.Default_Theme) { _frm_connection = new frm_theme_default(ApplicationName); _frm_connection.ShowDialog(); } } } }
1.132813
1
src/EncompassRest/Loans/Enums/RefundableType.cs
Oxymoron290/EncompassRest
87
60
using System.ComponentModel; namespace EncompassRest.Loans.Enums { /// <summary> /// RefundableType /// </summary> public enum RefundableType { /// <summary> /// Non-Refundable /// </summary> [Description("Non-Refundable")] NonRefundable = 0, /// <summary> /// Refundable /// </summary> Refundable = 1, /// <summary> /// N/A (No funds collected at or prior to funding) /// </summary> [Description("N/A (No funds collected at or prior to funding)")] NA = 2 } }
1.195313
1
source/Brimborium.SchlangangerLibrary/Contracts/Interfaces.cs
grimmborium/Brimborium.Schlanganger
0
68
using Brimborium.Functional; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Brimborium.Contracts { public interface IEntity { } public interface IDynamicEntity : IEntity { } public interface IStaticEntity : IEntity { } public interface IMetaContainer : IEntity { } public interface IMetaEntity : IEntity { } public interface IMetaAction : IEntity { } public interface IMetaProperty : IEntity { } public interface IMetaBehaviour : IEntity { } public interface IMetaValue : IEntity { } public interface IEntityAdapter { MayBe<IMetaEntity> GetMetaEntityByType(Type type); MayBe<IMetaEntity> GetMetaEntityByObject(object entity); MayBe<IMetaEntity> GetMetaEntityByIEntity<TEntity>(TEntity entity) where TEntity: IEntity; } }
1.125
1
Test.Puzzle/Puzzle3x3/Builder.cs
JeffLeBert/RubiksCubeTrainer
0
76
namespace RubiksCubeTrainer.Puzzle3x3 { public static class Builder { public static Face BuildTestFace(FaceName faceName, int offset) => new Face( faceName, new PuzzleColor[Face.Size, Face.Size] { { (PuzzleColor)offset, (PuzzleColor)(offset + 3), (PuzzleColor)(offset + 6) }, { (PuzzleColor)(offset + 1), (PuzzleColor)(offset + 4), (PuzzleColor)(offset + 7) }, { (PuzzleColor)(offset + 2), (PuzzleColor)(offset + 5), (PuzzleColor)(offset + 8) } }); } }
1.203125
1
src/WireMock.Net/Settings/SimpleCommandLineParser.cs
leolplex/WireMock.Net
700
84
using System; using System.Collections.Generic; using System.Linq; namespace WireMock.Settings { // Based on http://blog.gauffin.org/2014/12/simple-command-line-parser/ internal class SimpleCommandLineParser { private const string Sigil = "--"; private IDictionary<string, string[]> Arguments { get; } = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); public void Parse(string[] arguments) { string currentName = null; var values = new List<string>(); // Split a single argument on a space character to fix issue (e.g. Azure Service Fabric) when an argument is supplied like "--x abc" or '--x abc' foreach (string arg in arguments.SelectMany(arg => arg.Split(' '))) { if (arg.StartsWith(Sigil)) { if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } values.Clear(); currentName = arg.Substring(Sigil.Length); } else if (string.IsNullOrEmpty(currentName)) { Arguments[arg] = new string[0]; } else { values.Add(arg); } } if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } } public bool Contains(string name) { return Arguments.ContainsKey(name); } public string[] GetValues(string name, string[] defaultValue = null) { return Contains(name) ? Arguments[name] : defaultValue; } public T GetValue<T>(string name, Func<string[], T> func, T defaultValue = default(T)) { return Contains(name) ? func(Arguments[name]) : defaultValue; } public bool GetBoolValue(string name, bool defaultValue = false) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? bool.Parse(value) : defaultValue; }, defaultValue); } public bool GetBoolSwitchValue(string name) { return Contains(name); } public int? GetIntValue(string name, int? defaultValue = null) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? int.Parse(value) : defaultValue; }, defaultValue); } public string GetStringValue(string name, string defaultValue = null) { return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue); } } }
1.695313
2
Assets/ThirdParty/First Person Drifter Controller/Scripts/LockMouse.cs
fernandoramallo/oikospiel-game-tools
26
92
// by @torahhorse using UnityEngine; using System.Collections; public class LockMouse : MonoBehaviour { void Start() { LockCursor(true); } void Update() { // lock when mouse is clicked if( Input.GetMouseButtonDown(0) && Time.timeScale > 0.0f ) { LockCursor(true); } // unlock when escape is hit if ( Input.GetKeyDown(KeyCode.Escape) ) { LockCursor(Cursor.lockState == CursorLockMode.None); } } public void LockCursor(bool lockCursor) { Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None; } }
1.84375
2
src_wip/Tests.Unit.Orm/Orm/Validation/Discovery/DefaultValidationRuleDiscoveryStrategyTest.cs
brianmains/Nucleo.NET
2
100
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TypeMock.ArrangeActAssert; namespace Nucleo.Orm.Validation.Discovery { [TestClass] public class DefaultValidationRuleDiscoveryStrategyTest { protected class TestClass : IValidationRuleTarget { public ValidationRuleCollection GetValidationRules(ValidationRuleType ruleType) { return new ValidationRuleCollection { Isolate.Fake.Instance<IValidationRule>() }; } } [TestMethod] public void ValidatingNonValidatableEntityReturnsNull() { var strat = new DefaultValidationRuleDiscoveryStrategy(); var rules = strat.FindValidationRules(new object(), ValidationRuleType.Create); Assert.IsNull(rules); } [TestMethod] public void ValidatingValidatableEntityReturnsResults() { var strat = new DefaultValidationRuleDiscoveryStrategy(); var rules = strat.FindValidationRules(new TestClass(), ValidationRuleType.Create); Assert.AreEqual(1, rules.Count); } } }
1.453125
1
BookWeb.Shared/CalibreModels/BooksAuthorsLink.cs
seantrace/BookWeb
0
108
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; #nullable disable namespace BookWeb { [Table("books_authors_link")] [Index(nameof(Book), nameof(Author), IsUnique = true)] [Index(nameof(Author), Name = "books_authors_link_aidx")] [Index(nameof(Book), Name = "books_authors_link_bidx")] public partial record BooksAuthorsLink { [Key] [Column("id")] public long Id { get; set; } [Column("book")] public long Book { get; set; } [Column("author")] public long Author { get; set; } } }
0.867188
1
Xam-GLMap-Android/Additions/GLMapInfo.cs
charlenni/Xam-GLMap-Android
0
116
namespace GLMap { public partial class GLMapInfo { public GLMap.GLMapInfoState State { get { return (GLMap.GLMapInfoState)getState().Ordinal(); } } } }
0.384766
0
Deflector.Demos/Deflector.Demos/Program.cs
philiplaureano/deflectordotnet-demos
1
124
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleLibrary; namespace Deflector.Demos { class Program { static void Main(string[] args) { var targetAssembly = typeof(SampleClassWithInstanceMethod).Assembly; // Notice how modifying the sample assembly requires only one line of code var modifiedAssembly = targetAssembly.AddInterceptionHooks(); // Replace the DoSomethingElse() method call with a different method call Replace.Method<SampleClassThatCallsAnInstanceMethod>(c => c.DoSomethingElse()) .With(() => { Console.WriteLine("DoSomethingElse() method call intercepted"); }); var targetTypeName = nameof(SampleClassThatCallsAnInstanceMethod); // Use the createInstance lambda for syntactic sugar Func<string, dynamic> createInstance = typeName => { var targetType = modifiedAssembly.GetTypes().First(t => t.Name == typeName); return Activator.CreateInstance(targetType); }; // Create the modified type instance dynamic targetInstance = createInstance(targetTypeName); targetInstance.DoSomething(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
1.6875
2
KD.Dova/Extensions/ObjectExtensions.cs
Sejoslaw/KD.Dova
1
132
using KD.Dova.Core; using KD.Dova.Utils; using System.Collections.Generic; namespace KD.Dova.Extensions { internal static class ObjectExtensions { internal static JavaType[] ToJniSignatureArray(this object[] source) { List<JavaType> javaTypes = new List<JavaType>(); foreach (object obj in source) { javaTypes.Add(obj.GetType().ToJniSignature()); } return javaTypes.ToArray(); } internal static NativeValue[] ToNativeValueArray(this object[] source, JavaRuntime runtime) { List<NativeValue> values = new List<NativeValue>(); foreach (object obj in source) { values.Add(obj.ToNativeValue(runtime)); } return values.ToArray(); } internal static NativeValue ToNativeValue(this object source, JavaRuntime runtime) { JavaType jt = source.GetType().ToJniSignature(); if (jt != null) { return jt.ToNativeValue(runtime, source); } return new NativeValue(); } } }
0.796875
1
src/NTccTransaction/Persistence/TransactionManager.cs
wzl-bxg/NTcc-TransactionCore
21
140
using Microsoft.Extensions.DependencyInjection; using NTccTransaction.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace NTccTransaction { public class TransactionManager : ITransactionManager { private readonly IAmbientTransaction _ambientTransaction; private readonly IServiceScopeFactory _serviceScopeFactory; public ITransaction Current => _ambientTransaction.Transaction; public TransactionManager( IAmbientTransaction ambientTransaction, IServiceScopeFactory serviceScopeFactory) { _ambientTransaction = ambientTransaction; _serviceScopeFactory = serviceScopeFactory; } /// <summary> /// /// </summary> /// <returns></returns> public ITransaction Begin() { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="uniqueIdentity"></param> /// <returns></returns> public ITransaction Begin(object uniqueIdentity) { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationNewBegin(TransactionContext transactionContext) { var transaction = new Transaction(transactionContext); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationExistBegin(TransactionContext transactionContext) { using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); var transaction = transactionRepository.FindByXid(transactionContext.Xid); if (transaction == null) { throw new NoExistedTransactionException(); } transaction.ChangeStatus(transactionContext.Status); RegisterTransaction(transaction); return transaction; } } /// <summary> /// Commit /// </summary> public async Task CommitAsync() { var transaction = this.Current; // When confirm successfully, delete the NTccTransaction from database // The confirm action will be call from the top of stack, so delete the transaction data will not impact the excution under it using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CONFIRMING); transactionRepository.Update(transaction); try { await transaction.CommitAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception commitException) { throw new ConfirmingException("Confirm failed", commitException); } } } /// <summary> /// Rollback /// </summary> public async Task RollbackAsync() { var transaction = this.Current; using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CANCELLING); transactionRepository.Update(transaction); try { await transaction.RollbackAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception rollbackException) { throw new CancellingException("Rollback failed", rollbackException); } } } /// <summary> /// /// </summary> /// <param name="participant"></param> public void AddParticipant(IParticipant participant) { var transaction = this.Current; transaction.AddParticipant(participant); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Update(transaction); } } /// <summary> /// /// </summary> /// <returns></returns> public bool IsTransactionActive() { return Current != null; } private void RegisterTransaction(ITransaction transaction) { _ambientTransaction.RegisterTransaction(transaction); } public bool IsDelayCancelException(Exception tryingException, HashSet<Type> allDelayCancelExceptionTypes) { if (null == allDelayCancelExceptionTypes || !allDelayCancelExceptionTypes.Any()) { return false; } var tryingExceptionType = tryingException.GetType(); return allDelayCancelExceptionTypes.Any(t => t.IsAssignableFrom(tryingExceptionType)); } } }
1.296875
1
vimage/Source/Display/Graphics.cs
Torrunt/vimage
57
148
using DevIL.Unmanaged; using SFML.Graphics; using SFML.System; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Tao.OpenGl; namespace vimage { /// <summary> /// Graphics Manager. /// Loads and stores Textures and AnimatedImageDatas. /// </summary> class Graphics { private static List<Texture> Textures = new List<Texture>(); private static List<string> TextureFileNames = new List<string>(); private static List<AnimatedImageData> AnimatedImageDatas = new List<AnimatedImageData>(); private static List<string> AnimatedImageDataFileNames = new List<string>(); private static List<DisplayObject> SplitTextures = new List<DisplayObject>(); private static List<string> SplitTextureFileNames = new List<string>(); public static uint MAX_TEXTURES = 80; public static uint MAX_ANIMATIONS = 8; public static int TextureMaxSize = (int)Texture.MaximumSize; public static dynamic GetTexture(string fileName) { int index = TextureFileNames.IndexOf(fileName); int splitTextureIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return Textures[Textures.Count - 1]; } else if (splitTextureIndex >= 0) { // Texture Already Exists (as split texture) return SplitTextures[splitTextureIndex]; } else { // New Texture Texture texture = null; DisplayObject textureLarge = null; int imageID = IL.GenerateImage(); IL.BindImage(imageID); IL.Enable(ILEnable.AbsoluteOrigin); IL.SetOriginLocation(DevIL.OriginLocation.UpperLeft); bool loaded = false; using (FileStream fileStream = File.OpenRead(fileName)) loaded = IL.LoadImageFromStream(fileStream); if (loaded) { if (IL.GetImageInfo().Width > TextureMaxSize || IL.GetImageInfo().Height > TextureMaxSize) { // Image is larger than GPU's max texture size - split up textureLarge = GetCutUpTexturesFromBoundImage(TextureMaxSize / 2, fileName); } else { texture = GetTextureFromBoundImage(); if (texture == null) return null; Textures.Add(texture); TextureFileNames.Add(fileName); } // Limit amount of Textures in Memory if (Textures.Count > MAX_TEXTURES) RemoveTexture(); } IL.DeleteImages(new ImageID[] { imageID }); if (texture == null) return textureLarge; else return texture; } } private static Texture GetTextureFromBoundImage() { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; int width = IL.GetImageInfo().Width; int height = IL.GetImageInfo().Height; Texture texture = new Texture((uint)width, (uint)height); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), width, height, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, IL.GetData() ); } Texture.Bind(null); return texture; } private static DisplayObject GetCutUpTexturesFromBoundImage(int sectionSize, string fileName = "") { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; DisplayObject image = new DisplayObject(); Vector2i size = new Vector2i(IL.GetImageInfo().Width, IL.GetImageInfo().Height); Vector2u amount = new Vector2u((uint)Math.Ceiling(size.X / (float)sectionSize), (uint)Math.Ceiling(size.Y / (float)sectionSize)); Vector2i currentSize = new Vector2i(size.X, size.Y); Vector2i pos = new Vector2i(); for (int iy = 0; iy < amount.Y; iy++) { int h = Math.Min(currentSize.Y, sectionSize); currentSize.Y -= h; currentSize.X = size.X; for (int ix = 0; ix < amount.X; ix++) { int w = Math.Min(currentSize.X, sectionSize); currentSize.X -= w; Texture texture = new Texture((uint)w, (uint)h); IntPtr partPtr = Marshal.AllocHGlobal((w * h) * 4); IL.CopyPixels(pos.X, pos.Y, 0, w, h, 1, DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte, partPtr); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), w, h, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, partPtr); } Texture.Bind(null); Marshal.FreeHGlobal(partPtr); Sprite sprite = new Sprite(texture); sprite.Position = new Vector2f(pos.X, pos.Y); image.AddChild(sprite); if (fileName != "") { Textures.Add(texture); TextureFileNames.Add(fileName + "_" + ix.ToString("00") + "_" + iy.ToString("00") + "^"); } pos.X += w; } pos.Y += h; pos.X = 0; } image.Texture.Size = new Vector2u((uint)size.X, (uint)size.Y); SplitTextures.Add(image); SplitTextureFileNames.Add(fileName); return image; } public static Sprite GetSpriteFromIcon(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .ico) try { System.Drawing.Icon icon = new System.Drawing.Icon(fileName, 256, 256); System.Drawing.Bitmap iconImage = ExtractVistaIcon(icon); if (iconImage == null) iconImage = icon.ToBitmap(); Sprite iconSprite; using (MemoryStream iconStream = new MemoryStream()) { iconImage.Save(iconStream, System.Drawing.Imaging.ImageFormat.Png); Texture iconTexture = new Texture(iconStream); Textures.Add(iconTexture); TextureFileNames.Add(fileName); iconSprite = new Sprite(new Texture(iconTexture)); } return iconSprite; } catch (Exception) { } } return null; } // http://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application/1945764#1945764 // Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx // And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx public static System.Drawing.Bitmap ExtractVistaIcon(System.Drawing.Icon icoIcon) { System.Drawing.Bitmap bmpPngExtracted = null; try { byte[] srcBuf = null; using (MemoryStream stream = new MemoryStream()) { icoIcon.Save(stream); srcBuf = stream.ToArray(); } const int SizeICONDIR = 6; const int SizeICONDIRENTRY = 16; int iCount = BitConverter.ToInt16(srcBuf, 4); for (int iIndex = 0; iIndex < iCount; iIndex++) { int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex]; int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1]; int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6); if (iWidth == 0 && iHeight == 0 && iBitCount == 32) { int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8); int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12); MemoryStream destStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(destStream); writer.Write(srcBuf, iImageOffset, iImageSize); destStream.Seek(0, SeekOrigin.Begin); bmpPngExtracted = new System.Drawing.Bitmap(destStream); // This is PNG! :) break; } } } catch { return null; } return bmpPngExtracted; } public static Sprite GetSpriteFromSVG(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .svg) try { Svg.SvgDocument svg = Svg.SvgDocument.Open(fileName); System.Drawing.Bitmap bitmap = svg.Draw(); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } public static Sprite GetSpriteFromWebP(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .webp) try { var fileBytes = File.ReadAllBytes(fileName); System.Drawing.Bitmap bitmap = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(fileBytes, fileBytes.Length); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImage GetAnimatedImage(string fileName) { return new AnimatedImage(GetAnimatedImageData(fileName)); } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImageData GetAnimatedImageData(string fileName) { lock (AnimatedImageDatas) { int index = AnimatedImageDataFileNames.IndexOf(fileName); if (index >= 0) { // AnimatedImageData Already Exists // move it to the end of the array and return it AnimatedImageData data = AnimatedImageDatas[index]; string name = AnimatedImageDataFileNames[index]; AnimatedImageDatas.RemoveAt(index); AnimatedImageDataFileNames.RemoveAt(index); AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(name); return AnimatedImageDatas[AnimatedImageDatas.Count - 1]; } else { // New AnimatedImageData System.Drawing.Image image = System.Drawing.Image.FromFile(fileName); AnimatedImageData data = new AnimatedImageData(); // Store AnimatedImageData AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(fileName); // Limit amount of Animations in Memory if (AnimatedImageDatas.Count > MAX_ANIMATIONS) RemoveAnimatedImage(); // Get Frames LoadingAnimatedImage loadingAnimatedImage = new LoadingAnimatedImage(image, data); Thread loadFramesThread = new Thread(new ThreadStart(loadingAnimatedImage.LoadFrames)) { Name = "AnimationLoadThread - " + fileName, IsBackground = true }; loadFramesThread.Start(); // Wait for at least one frame to be loaded while (data.Frames == null || data.Frames.Length <= 0 || data.Frames[0] == null) { Thread.Sleep(1); } return data; } } } public static void ClearMemory(dynamic image, string file = "") { // Remove all AnimatedImages (except the one that's currently being viewed) int s = image is AnimatedImage ? 1 : 0; int a = 0; while (AnimatedImageDatas.Count > s) { if (s == 1 && (image as AnimatedImage).Data == AnimatedImageDatas[a]) a++; RemoveAnimatedImage(a); } if (image is AnimatedImage) { // Remove all Textures while (TextureFileNames.Count > 0) RemoveTexture(); } else { // Remove all Textures (except ones being used by current image) if (file == "") return; s = 0; a = 0; if (SplitTextureFileNames.Contains(file)) { for (int i = 0; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(file) == 0) s++; else if (s > 0) break; } while (TextureFileNames.Count > s) { if (TextureFileNames[a].IndexOf(file) == 0) a += s; RemoveTexture(a); } } else { while (TextureFileNames.Count > 1) { if (TextureFileNames[a] == file) a++; RemoveTexture(a); } } } } public static void RemoveTexture(int t = 0) { if (TextureFileNames[t].IndexOf('^') == TextureFileNames[t].Length - 1) { // if part of split texture - remove all parts string name = TextureFileNames[t].Substring(0, TextureFileNames[t].Length - 7); int i = t; for (i = t + 1; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(name) != 0) break; } for (int d = t; d < i; d++) { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } int splitIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(name); if (splitIndex != -1) { SplitTextures.RemoveAt(splitIndex); SplitTextureFileNames.RemoveAt(splitIndex); } } else { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } } public static void RemoveAnimatedImage(int a = 0) { AnimatedImageDatas[a].CancelLoading = true; for (int i = 0; i < AnimatedImageDatas[a].Frames.Length; i++) AnimatedImageDatas[a]?.Frames[i]?.Dispose(); AnimatedImageDatas.RemoveAt(a); AnimatedImageDataFileNames.RemoveAt(a); } } class LoadingAnimatedImage { private System.Drawing.Image Image; private ImageManipulation.OctreeQuantizer Quantizer; private AnimatedImageData Data; public LoadingAnimatedImage(System.Drawing.Image image, AnimatedImageData data) { Image = image; Data = data; } public void LoadFrames() { // Get Frame Count System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(Image.FrameDimensionsList[0]); Data.FrameCount = Image.GetFrameCount(frameDimension); Data.Frames = new Texture[Data.FrameCount]; Data.FrameDelays = new int[Data.FrameCount]; // Get Frame Delays byte[] frameDelays = null; try { System.Drawing.Imaging.PropertyItem frameDelaysItem = Image.GetPropertyItem(0x5100); frameDelays = frameDelaysItem.Value; if (frameDelays.Length == 0 || (frameDelays[0] == 0 && frameDelays.All(d => d == 0))) frameDelays = null; } catch { } int defaultFrameDelay = AnimatedImage.DEFAULT_FRAME_DELAY; if (frameDelays != null && frameDelays.Length > 1) defaultFrameDelay = (frameDelays[0] + frameDelays[1] * 256) * 10; for (int i = 0; i < Data.FrameCount; i++) { if (Data.CancelLoading) return; Image.SelectActiveFrame(frameDimension, i); Quantizer = new ImageManipulation.OctreeQuantizer(255, 8); System.Drawing.Bitmap quantized = Quantizer.Quantize(Image); MemoryStream stream = new MemoryStream(); quantized.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Data.Frames[i] = new Texture(stream); stream.Dispose(); if (Data.CancelLoading) return; Data.Frames[i].Smooth = Data.Smooth; Data.Frames[i].Mipmap = Data.Mipmap; var fd = i * 4; if (frameDelays != null && frameDelays.Length > fd) Data.FrameDelays[i] = (frameDelays[fd] + frameDelays[fd + 1] * 256) * 10; else Data.FrameDelays[i] = defaultFrameDelay; } Data.FullyLoaded = true; } } }
1.867188
2
WuHu/WuHu.WebService/Models/TournamentData.cs
bloody-orange/WuHu
1
156
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Web; using WuHu.BL.Impl; using WuHu.Domain; namespace WuHu.WebService.Models { [DataContract] public class TournamentData { public TournamentData() { } public TournamentData(Tournament tournament) { if (tournament?.TournamentId == null) { throw new ArgumentNullException(nameof(tournament.TournamentId)); } TournamentId = tournament.TournamentId.Value; Name = tournament.Name; Datetime = tournament.Datetime; Players = null; Amount = 1; } [DataMember] public int TournamentId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public DateTime Datetime { get; set; } [DataMember] [Required] public IList<Player> Players { get; set; } [DataMember] [Required] public int Amount { get; set; } } }
0.992188
1
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AllTypes.cs
tapend/tebe-cms
0
164
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using GraphQL.Types; using Squidex.Domain.Apps.Core.Assets; using Squidex.Domain.Apps.Entities.Contents.GraphQL.Types.Utils; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL.Types { public static class AllTypes { public const string PathName = "path"; public static readonly Type None = typeof(NoopGraphType); public static readonly Type NonNullTagsType = typeof(NonNullGraphType<ListGraphType<NonNullGraphType<StringGraphType>>>); public static readonly IGraphType Int = new IntGraphType(); public static readonly IGraphType DomainId = new StringGraphType(); public static readonly IGraphType Date = new InstantGraphType(); public static readonly IGraphType Json = new JsonGraphType(); public static readonly IGraphType Float = new FloatGraphType(); public static readonly IGraphType String = new StringGraphType(); public static readonly IGraphType Boolean = new BooleanGraphType(); public static readonly IGraphType AssetType = new EnumerationGraphType<AssetType>(); public static readonly IGraphType NonNullInt = new NonNullGraphType(Int); public static readonly IGraphType NonNullDomainId = new NonNullGraphType(DomainId); public static readonly IGraphType NonNullDate = new NonNullGraphType(Date); public static readonly IGraphType NonNullFloat = new NonNullGraphType(Float); public static readonly IGraphType NonNullString = new NonNullGraphType(String); public static readonly IGraphType NonNullBoolean = new NonNullGraphType(Boolean); public static readonly IGraphType NonNullAssetType = new NonNullGraphType(AssetType); public static readonly IGraphType NoopDate = new NoopGraphType(Date); public static readonly IGraphType NoopJson = new NoopGraphType(Json); public static readonly IGraphType NoopFloat = new NoopGraphType(Float); public static readonly IGraphType NoopString = new NoopGraphType(String); public static readonly IGraphType NoopBoolean = new NoopGraphType(Boolean); public static readonly IGraphType NoopTags = new NoopGraphType("TagsScalar"); public static readonly IGraphType NoopGeolocation = new NoopGraphType("GeolocationScalar"); public static readonly QueryArguments PathArguments = new QueryArguments(new QueryArgument(None) { Name = PathName, Description = "The path to the json value", DefaultValue = null, ResolvedType = String }); } }
1.21875
1
Wyrobot/Http/YouTube/YouTubeEventListener.cs
JustAeris/Wyrobot
0
172
using System; using System.Collections.Generic; using System.Threading.Tasks; using YoutubeExplode; using YoutubeExplode.Videos; namespace Wyrobot.Core.Http.YouTube { public class YouTubeEventListener { private YoutubeClient _client; public List<ChannelSubscription> Subscriptions { get; private set; } public event YouTubeEventHandler OnVideoUploaded; private YouTubeEventListener() { Subscriptions = new List<ChannelSubscription>(); } public YouTubeEventListener(YoutubeClient client) : this() { _client = client; } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, List<string> channels) { if (channels == null) throw new ArgumentNullException(nameof(channels)); foreach (var url in channels) { var uploads = await _client.Channels.GetUploadsAsync(url); Subscriptions.Add(new ChannelSubscription(guildId, channelId, broadcast, url, uploads.Count > 0 ? uploads[0] : null)); } } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, params string[] channels) { var channelsList = new List<string>(); for (var index = 0; index < channels.Length; ++index) channelsList.Add(channels[index]); await SubscribeChannels(guildId, channelId, broadcast, channelsList); } public void UnsubscribeChannel(ChannelSubscription subscription) { if (!Subscriptions.Contains(subscription)) return; Subscriptions.Remove(subscription); } public async Task PollEvents() { foreach (var subscription in Subscriptions) { var uploads = await _client.Channels.GetUploadsAsync(subscription.Url); var lastVideo = uploads.Count > 0 ? uploads[0] : null; if (lastVideo == null) continue; if (subscription.LastVideo != lastVideo) { if (OnVideoUploaded == null) continue; var channel = await _client.Channels.GetAsync(lastVideo.ChannelId); OnVideoUploaded(this, new YouTubeEventArgs(subscription.GuildId, subscription.ChannelId, subscription.Broadcast, channel, lastVideo )); subscription.LastVideo = lastVideo; } } } public class ChannelSubscription { public ulong GuildId { get; set; } public ulong ChannelId { get; set; } public string Broadcast { get; set; } public string Url { get; set; } public Video LastVideo { get; set; } public ChannelSubscription(ulong guildId, ulong channelId, string broadcast, string url, Video lastVideo = null) { GuildId = guildId; ChannelId = channelId; Broadcast = broadcast; Url = url; LastVideo = lastVideo; } } public delegate void YouTubeEventHandler(object sender, YouTubeEventArgs e); } }
1.679688
2
DigestingDuck/Pages/Ativos.xaml.cs
JorgeBeserra/DigestingDuck
2
180
using DigestingDuck.models; using Realms.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DigestingDuck.Pages { /// <summary> /// Lógica interna para Ativos.xaml /// </summary> public partial class Ativos : Page { public Ativos() { InitializeComponent(); } private void PageAtivos_Loaded(object sender, RoutedEventArgs e) { datagridAtivosBinaria.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosBinaria; datagridAtivosTurbo.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosTurbo; datagridAtivosDigital.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosDigital; } private void DatagridAtivosBinaria_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosBinaria.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosTurbo_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosTurbo.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosBinaria_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void DatagridAtivosDigital_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosDigital.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } } }
1.40625
1
src/Transports/MassTransit.KafkaIntegration/KafkaTopicAddress.cs
viktorshevchenko210/MassTransit
4,222
188
namespace MassTransit.KafkaIntegration { using System; using System.Diagnostics; [DebuggerDisplay("{" + nameof(DebuggerDisplay) + "}")] public readonly struct KafkaTopicAddress { public const string PathPrefix = "kafka"; public readonly string Topic; public readonly string Host; public readonly string Scheme; public readonly int? Port; public KafkaTopicAddress(Uri hostAddress, Uri address) { Host = default; Topic = default; Scheme = default; Port = default; var scheme = address.Scheme.ToLowerInvariant(); switch (scheme) { case "topic": ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = address.AbsolutePath; break; default: { if (string.Equals(address.Scheme, hostAddress.Scheme, StringComparison.InvariantCultureIgnoreCase)) { ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = address.AbsolutePath.Replace($"{PathPrefix}/", ""); } else throw new ArgumentException($"The address scheme is not supported: {address.Scheme}", nameof(address)); break; } } } public KafkaTopicAddress(Uri hostAddress, string topic) { ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = topic; } static void ParseLeft(Uri address, out string scheme, out string host, out int? port) { scheme = address.Scheme; host = address.Host; port = address.Port; } public static implicit operator Uri(in KafkaTopicAddress address) { var builder = new UriBuilder { Scheme = address.Scheme, Host = address.Host, Port = address.Port ?? 0, Path = $"{PathPrefix}/{address.Topic}" }; return builder.Uri; } Uri DebuggerDisplay => this; } }
1.382813
1
NGit.Test/NGit.Nls/TranslationBundleTest.cs
ashmind/ngit
1
196
/* This code is derived from jgit (http://eclipse.org/jgit). Copyright owners are documented in jgit's IP log. This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0 which accompanies this distribution, is reproduced below, and is available at http://www.eclipse.org/org/documents/edl-v10.php All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using NGit.Errors; using NGit.Nls; using Sharpen; namespace NGit.Nls { [NUnit.Framework.TestFixture] public class TranslationBundleTest { [NUnit.Framework.Test] public virtual void TestMissingPropertiesFile() { try { new NoPropertiesBundle().Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.Fail("Expected TranslationBundleLoadingException"); } catch (TranslationBundleLoadingException e) { NUnit.Framework.Assert.AreEqual(typeof(NoPropertiesBundle), e.GetBundleClass()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, e.GetLocale()); } } // pass [NUnit.Framework.Test] public virtual void TestMissingString() { try { new MissingPropertyBundle().Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.Fail("Expected TranslationStringMissingException"); } catch (TranslationStringMissingException e) { NUnit.Framework.Assert.AreEqual("nonTranslatedKey", e.GetKey()); NUnit.Framework.Assert.AreEqual(typeof(MissingPropertyBundle), e.GetBundleClass() ); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, e.GetLocale()); } } // pass [NUnit.Framework.Test] public virtual void TestNonTranslatedBundle() { NonTranslatedBundle bundle = new NonTranslatedBundle(); bundle.Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetEnglishCulture()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetGermanCulture()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); } [NUnit.Framework.Test] public virtual void TestGermanTranslation() { GermanTranslatedBundle bundle = new GermanTranslatedBundle(); bundle.Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetGermanCulture()); NUnit.Framework.Assert.AreEqual(Sharpen.Extensions.GetGermanCulture(), bundle.EffectiveLocale ()); NUnit.Framework.Assert.AreEqual("Guten Morgen {0}", bundle.goodMorning); } } }
1.25
1
src/GitVersionCore/Extensions/ExtensionMethods.git.cs
openkas/GitVersion
0
204
namespace GitVersion { static partial class ExtensionMethods { public static string GetCanonicalBranchName(this string branchName) { if (branchName.IsPullRequest()) { branchName = branchName.Replace("pull-requests/", "pull/"); branchName = branchName.Replace("pr/", "pull/"); return string.Format("refs/{0}/head", branchName); } return string.Format("refs/heads/{0}", branchName); } public static bool IsPullRequest(this string branchName) { return branchName.Contains("pull/") || branchName.Contains("pull-requests/") || branchName.Contains("pr/"); } } }
1.15625
1
test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs
WeihanLi/apm-agent-dotnet
0
212
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using Elastic.Apm.Api; using Elastic.Apm.DistributedTracing; using Elastic.Apm.Model; using Elastic.Apm.Tests.Mocks; using FluentAssertions; namespace Elastic.Apm.Tests.MockApmServer { internal static class AssertValidExtensions { internal static void AssertValid(this Service thisObj) { thisObj.Should().NotBeNull(); thisObj.Agent.AssertValid(); thisObj.Framework.AssertValid(); thisObj.Language.AssertValid(); } internal static void AssertValid(this Service.AgentC thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.Should().Be(Consts.AgentName); thisObj.Version.Should().Be(Service.GetDefaultService(new MockConfigSnapshot(new NoopLogger()), new NoopLogger()).Agent.Version); } private static void AssertValid(this Framework thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.NonEmptyAssertValid(); thisObj.Version.NonEmptyAssertValid(); thisObj.Version.Should().MatchRegex("[1-9]*.*"); } private static void AssertValid(this Language thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.Should().Be("C#"); } internal static void AssertValid(this Api.System thisObj) { thisObj.Should().NotBeNull(); thisObj.Container?.AssertValid(); } private static void AssertValid(this Container thisObj) { thisObj.Should().NotBeNull(); thisObj.Id.NonEmptyAssertValid(); } internal static void AssertValid(this Request thisObj) { thisObj.Should().NotBeNull(); thisObj.Headers?.HttpHeadersAssertValid(); thisObj.HttpVersion.HttpVersionAssertValid(); thisObj.Method.HttpMethodAssertValid(); thisObj.Socket.AssertValid(); thisObj.Url.AssertValid(); } internal static void AssertValid(this Response thisObj) { thisObj.Should().NotBeNull(); thisObj.Headers?.HttpHeadersAssertValid(); thisObj.StatusCode.HttpStatusCodeAssertValid(); } internal static void HttpStatusCodeAssertValid(this int thisObj) => thisObj.Should().BeInRange(100, 599); internal static void AssertValid(this User thisObj) { thisObj.Should().NotBeNull(); thisObj?.Id.AssertValid(); thisObj?.UserName.AssertValid(); thisObj?.Email.AssertValid(); } internal static void LabelsAssertValid(this Dictionary<string, string> thisObj) { thisObj.Should().NotBeNull(); foreach (var (key, value) in thisObj) { key.AssertValid(); value?.AssertValid(); } } private static void HttpHeadersAssertValid(this Dictionary<string, string> thisObj) { thisObj.Should().NotBeNull(); foreach (var headerNameValue in thisObj) { headerNameValue.Key.Should().NotBeNullOrEmpty(); headerNameValue.Value.Should().NotBeNull(); } } private static void HttpVersionAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should().BeOneOf("1.0", "1.1", "2.0"); } private static void HttpMethodAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); var validValues = new List<string> { "GET", "POST", "PUT", "HEAD", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH" }; thisObj.ToUpperInvariant().Should().BeOneOf(validValues, $"Given value is `{thisObj}'"); } private static void AssertValid(this Url thisObj) { thisObj.Should().NotBeNull(); thisObj.Raw?.UrlStringAssertValid(); thisObj.Protocol?.UrlProtocolAssertValid(); thisObj.Full?.UrlStringAssertValid(); thisObj.HostName?.AssertValid(); thisObj.PathName?.AssertValid(); thisObj.Search?.AssertValid(); } private static void UrlProtocolAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should().Be("HTTP"); } private static void UrlStringAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should() .Match(s => s.StartsWith("http://", StringComparison.InvariantCulture) || s.StartsWith("https://", StringComparison.InvariantCulture)); } private static void AssertValid(this Socket thisObj) { thisObj.Should().NotBeNull(); thisObj.RemoteAddress?.NonEmptyAssertValid(); } internal static void AssertValid(this SpanCountDto thisObj) => thisObj.Should().NotBeNull(); internal static void TimestampAssertValid(this long thisObj) => thisObj.Should().BeGreaterOrEqualTo(0); internal static void TraceIdAssertValid(this string thisObj) => thisObj.HexAssertValid(128 /* bits */); internal static void TransactionIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void SpanIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void ParentIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void ErrorIdAssertValid(this string thisObj) => thisObj.HexAssertValid(128 /* bits */); internal static void DurationAssertValid(this double thisObj) => thisObj.Should().BeGreaterOrEqualTo(0); internal static void NameAssertValid(this string thisObj) => thisObj.NonEmptyAssertValid(); private static void HexAssertValid(this string thisObj, int sizeInBits) { thisObj.NonEmptyAssertValid(); (sizeInBits % 8).Should().Be(0, $"sizeInBits should be divisible by 8 but sizeInBits is {sizeInBits}"); var numHexChars = sizeInBits / 8 * 2; var because = $"String should be {numHexChars} hex digits ({sizeInBits}-bits) but the actual value is `{thisObj}' (length: {thisObj.Length})"; thisObj.Length.Should().Be(numHexChars, because); // 2 hex chars per byte DistributedTracing.TraceContext.IsHex(thisObj).Should().BeTrue(because); } internal static void NonEmptyAssertValid(this string thisObj, int maxLength = 1024) { thisObj.AssertValid(); thisObj.Should().NotBeEmpty(); } internal static void AssertValid(this string thisObj, int maxLength = 1024) { thisObj.UnlimitedLengthAssertValid(); thisObj.Length.Should().BeLessOrEqualTo(maxLength); } internal static void UnlimitedLengthAssertValid(this string thisObj) => thisObj.Should().NotBeNull(); internal static void AssertValid(this CapturedException thisObj) { thisObj.Should().NotBeNull(); thisObj.Code?.AssertValid(); thisObj.StackTrace?.AssertValid(); if (string.IsNullOrEmpty(thisObj.Type)) thisObj.Message.AssertValid(); else thisObj.Message?.AssertValid(); if (string.IsNullOrEmpty(thisObj.Message)) thisObj.Type.AssertValid(); else thisObj.Type?.AssertValid(); } internal static void AssertValid(this Database thisObj) { thisObj.Should().NotBeNull(); thisObj.Instance?.AssertValid(); thisObj.Statement?.AssertValid(10_000); thisObj.Type?.AssertValid(); } internal static void AssertValid(this Http thisObj) { thisObj.Should().NotBeNull(); thisObj.Method.HttpMethodAssertValid(); thisObj.StatusCode.HttpStatusCodeAssertValid(); thisObj.Url.Should().NotBeNullOrEmpty(); } internal static void AssertValid(this Destination thisObj) { thisObj.Should().NotBeNull(); thisObj.Address.Should().NotBeNullOrEmpty(); thisObj.Address.AssertValid(); thisObj.Port?.Should().BeGreaterOrEqualTo(0); } internal static void AssertValid(this List<CapturedStackFrame> thisObj) { thisObj.Should().NotBeNull(); thisObj.Should().NotBeEmpty(); foreach (var stackFrame in thisObj) stackFrame.AssertValid(); } internal static void AssertValid(this CapturedStackFrame thisObj) { thisObj.Should().NotBeNull(); thisObj.FileName.Should().NotBeNullOrEmpty(); thisObj.LineNo.Should().BeGreaterOrEqualTo(0); thisObj.Module?.Should().NotBeEmpty(); thisObj.Function?.Should().NotBeEmpty(); } } }
1.242188
1
VideoWeb/VideoWeb.UnitTests/Controllers/ConferenceManagement/CallParticipantTests.cs
hmcts/vh-video-web
9
220
using System; using System.Linq; using System.Net; using System.Threading.Tasks; using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using VideoWeb.Common.Models; using VideoApi.Client; using VideoApi.Contract.Requests; using VideoWeb.UnitTests.Builders; using ProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails; namespace VideoWeb.UnitTests.Controllers.ConferenceManagement { public class CallParticipantTests : ConferenceManagementControllerTestBase { [SetUp] public void Setup() { TestConference = BuildConferenceForTest(true); } [Test] public async Task should_return_unauthorised_if_participant_is_not_a_witness_or_quick_link_user() { var judge = TestConference.GetJudge(); var invalidParticipants = TestConference.Participants.Where(x => !x.IsJudge() && !x.IsWitness() && !x.IsQuickLinkUser() && x.LinkedParticipants.Count == 0); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); foreach(var participant in invalidParticipants) { var result = await controller.CallParticipantAsync(TestConference.Id, participant.Id); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == participant.Id)), Times.Never); } } [Test] public async Task should_return_unauthorised_if_participant_does_not_exists() { var judge = TestConference.GetJudge(); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, Guid.NewGuid()); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.IsAny<TransferParticipantRequest>()), Times.Never); } [Test] public async Task should_return_unauthorised_if_not_judge_conference() { var participant = TestConference.Participants.First(x => !x.IsJudge()); var user = new ClaimsPrincipalBuilder() .WithUsername(participant.Username) .WithRole(AppRoles.CitizenRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, participant.Id); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("User must be either Judge or StaffMember."); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == participant.Id)), Times.Never); } [Test] public async Task should_return_video_api_error() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var responseMessage = "Could not start transfer participant"; var apiException = new VideoApiException<ProblemDetails>("Internal Server Error", (int)HttpStatusCode.InternalServerError, responseMessage, null, default, null); _mocker.Mock<IVideoApiClient>().Setup( x => x.TransferParticipantAsync(TestConference.Id, It.IsAny<TransferParticipantRequest>())).ThrowsAsync(apiException); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<ObjectResult>(); var typedResult = (ObjectResult)result; typedResult.Value.Should().Be(responseMessage); typedResult.StatusCode.Should().Be(StatusCodes.Status500InternalServerError); } [Test] public async Task should_return_accepted_when_participant_is_witness_and_judge_is_in_conference() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness() && !x.LinkedParticipants.Any()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == witness.Id && r.TransferType == TransferType.Call)), Times.Once); } [Test] public async Task should_return_accepted_when_participant_is_witness_and_has_an_interpreter_and_judge_is_in_conference() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness() && x.LinkedParticipants.Any()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == witness.Id && r.TransferType == TransferType.Call)), Times.Once); } [Test] public async Task should_return_unauthorised_when_witness_is_called_before_interpreter_joins() { var judge = TestConference.GetJudge(); var interpreterRoom = TestConference.CivilianRooms.First(); var witnessIds = TestConference.Participants .Where(p => p.IsWitness() && p.LinkedParticipants.Any()) .Select(p => p.Id).ToList(); // update room to not include interpreter interpreterRoom.Participants = interpreterRoom.Participants.Where(p => witnessIds.Contains(p)).ToList(); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var Controller = SetupControllerWithClaims(user); var result = await Controller.CallParticipantAsync(TestConference.Id, witnessIds.First()); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); } [Test] [TestCase(Role.QuickLinkObserver)] [TestCase(Role.QuickLinkParticipant)] public async Task should_return_accepted_when_participant_is_quick_link_user_and_judge_is_in_conference(Role role) { var judge = TestConference.GetJudge(); var quickLinkUser = TestConference.Participants.First(x => x.Role == role); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var Controller = SetupControllerWithClaims(user); var result = await Controller.CallParticipantAsync(TestConference.Id, quickLinkUser.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == quickLinkUser.Id && r.TransferType == TransferType.Call)), Times.Once); } } }
1.4375
1
EnvironmentAssessment.Wizard/Common/VimApi/A/AnswerFileCreateSpec.cs
octansIt/environmentassessment
1
228
namespace EnvironmentAssessment.Common.VimApi { public class AnswerFileCreateSpec : DynamicData { protected bool? _validating; public bool? Validating { get { return this._validating; } set { this._validating = value; } } } }
0.494141
0
src/MicroServices/StorageManagement/Core/StorageManagement.Application/Exceptions/ValidationException.cs
mrgrayhat/CleanMicroserviceArchitecture
4
236
using System; using System.Collections.Generic; using FluentValidation.Results; namespace StorageManagement.Application.Exceptions { public class ValidationException : Exception { public ValidationException() : base("One or more validation failures have occurred.") { Errors = new List<string>(); } public List<string> Errors { get; } public ValidationException(IEnumerable<ValidationFailure> failures) : this() { foreach (var failure in failures) { Errors.Add(failure.ErrorMessage); } } } }
1.546875
2
src/Potato.Net.Shared/Geolocation/GeolocateIp.cs
phogue/Potato
5
244
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using System.Linq; using Potato.Net.Shared.Geolocation.Maxmind; using Potato.Net.Shared.Models; namespace Potato.Net.Shared.Geolocation { /// <summary> /// Geolocation with an IP using Maxmind's library and database. /// </summary> public class GeolocateIp : IGeolocate { /// <summary> /// Used when determining a player's Country Name and Code. /// </summary> protected static CountryLookup CountryLookup = null; /// <summary> /// Loads the Maxmind GeoIP database, if available. /// </summary> static GeolocateIp() { try { String path = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "GeoIP.dat", SearchOption.AllDirectories).FirstOrDefault(); if (String.IsNullOrEmpty(path) == false) { GeolocateIp.CountryLookup = new CountryLookup(path); } } catch { GeolocateIp.CountryLookup = null; } } /// <summary> /// Validates the IP is roughly in ipv4 and gets the ip from a ip:port pair. /// </summary> /// <param name="value"></param> /// <returns></returns> protected String Ip(String value) { String ip = value; // Validate Ip has colon before trying to split. if (value != null && value.Contains(":")) { ip = value.Split(':').FirstOrDefault(); } // Validate Ip String was valid before continuing. if (string.IsNullOrEmpty(ip) == true || ip.Contains('.') == false) { ip = null; } return ip; } /// <summary> /// Fetch a location by ip /// </summary> /// <param name="value">The ip</param> /// <returns></returns> public Location Locate(String value) { Location location = null; if (GeolocateIp.CountryLookup != null) { String ip = this.Ip(value); if (ip != null) { // Try: In-case GeoIP.dat is not loaded properly try { location = new Location() { CountryName = GeolocateIp.CountryLookup.lookupCountryName(ip), CountryCode = GeolocateIp.CountryLookup.lookupCountryCode(ip) }; } catch { // Blank the location location = null; } } } return location; } } }
1.601563
2
src/Store/ArcGISRuntimeSamplesStore/Samples/Editing/EditRelatedData.xaml.cs
david-chambers/arcgis-runtime-samples-dotnet
3
252
using Esri.ArcGISRuntime.Controls; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Layers; using Esri.ArcGISRuntime.Tasks.Query; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ArcGISRuntime.Samples.Store.Samples { /// <summary> /// Demonstrates how to query and edit related records. /// </summary> /// <title>Edit Related Data</title> /// <category>Editing</category> public partial class EditRelatedData : Page { // Query is done through this relationship. Esri.ArcGISRuntime.ArcGISServices.Relationship relationship; // Editing is done through this table. ServiceFeatureTable table; public EditRelatedData() { InitializeComponent(); var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; layer.VisibleLayers = new ObservableCollection<int>(new int[] { 0 }); } /// <summary> /// Identifies graphic to highlight and query its related records. /// </summary> private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e) { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; var task = new IdentifyTask(new Uri(layer.ServiceUri)); var mapPoint = MyMapView.ScreenToLocation(e.Position); // Get current viewpoints extent from the MapView var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); var viewpointExtent = currentViewpoint.TargetGeometry.Extent; var parameter = new IdentifyParameters(mapPoint, viewpointExtent, 10, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth); // Clears map of any highlights. var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay; overlay.Graphics.Clear(); SetRelatedRecordEditor(); string message = null; try { // Performs an identify and adds graphic result into overlay. var result = await task.ExecuteAsync(parameter); if (result == null || result.Results == null || result.Results.Count < 1) return; var graphic = (Graphic)result.Results[0].Feature; overlay.Graphics.Add(graphic); // Prepares related records editor. var featureID = Convert.ToInt64(graphic.Attributes["OBJECTID"], CultureInfo.InvariantCulture); string requestID = null; if (graphic.Attributes["Service Request ID"] != null) requestID = Convert.ToString(graphic.Attributes["Service Request ID"], CultureInfo.InvariantCulture); SetRelatedRecordEditor(featureID, requestID); await QueryRelatedRecordsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Prepares related record editor for add and query. /// </summary> private void SetRelatedRecordEditor(long featureID = 0, string requestID = null) { AddButton.Tag = featureID; AddButton.IsEnabled = featureID > 0 && !string.IsNullOrWhiteSpace(requestID); RelatedRecords.Tag = requestID; if (featureID == 0) { Records.IsEnabled = false; RelatedRecords.ItemsSource = null; RelatedRecords.SelectedItem = null; } SetAttributeEditor(); } /// <summary> /// Prepares attribute editor for update or delete of existing related record. /// </summary> private void SetAttributeEditor(Feature feature = null) { if (ChoiceList.ItemsSource == null && table != null && table.ServiceInfo != null && table.ServiceInfo.Fields != null) { var rangeDomain = (RangeDomain<IComparable>)table.ServiceInfo.Fields.FirstOrDefault(f => f.Name == "rank").Domain; ChoiceList.ItemsSource = GetRangeValues((int)rangeDomain.MinValue, (int)rangeDomain.MaxValue); } AttributeEditor.Tag = feature; if (feature != null) { if (feature.Attributes.ContainsKey("rank") && feature.Attributes["rank"] != null) ChoiceList.SelectedItem = Convert.ToInt32(feature.Attributes["rank"], CultureInfo.InvariantCulture); if (feature.Attributes.ContainsKey("comments") && feature.Attributes["comments"] != null) Comments.Text = Convert.ToString(feature.Attributes["comments"], CultureInfo.InvariantCulture); AttributeEditor.Visibility = Visibility.Visible; Records.Flyout.ShowAt(Records); } else { ChoiceList.SelectedItem = null; Comments.Text = string.Empty; AttributeEditor.Visibility = Visibility.Collapsed; } } /// <summary> /// Gets exclusive values between minimum and maximum values. /// </summary> private IEnumerable<int> GetRangeValues(int min, int max) { for (int i = min; i <= max; i++) yield return i; } /// <summary> /// Gets relationship information using service metadata. /// </summary> private async Task<Esri.ArcGISRuntime.ArcGISServices.Relationship> GetRelationshipAsync() { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; if (layer == null || layer.VisibleLayers == null) return null; var id = layer.VisibleLayers.FirstOrDefault(); var details = await layer.GetDetailsAsync(id); if (details != null && details.Relationships != null) return details.Relationships.FirstOrDefault(); return null; } /// <summary> /// Queries related records for specified feature ID. /// </summary> private async Task QueryRelatedRecordsAsync() { var featureID = (Int64)AddButton.Tag; var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; var id = layer.VisibleLayers.FirstOrDefault(); var task = new QueryTask(new Uri(string.Format("{0}/{1}", layer.ServiceUri, id))); if (relationship == null) relationship = await GetRelationshipAsync(); var parameters = new RelationshipParameters(new List<long>(new long[] { featureID }), relationship.ID); parameters.OutFields = new OutFields(new string[] { "objectid" }); var result = await task.ExecuteRelationshipQueryAsync(parameters); if (result != null && result.RelatedRecordGroups != null && result.RelatedRecordGroups.ContainsKey(featureID)) { RelatedRecords.ItemsSource = result.RelatedRecordGroups[featureID]; Records.IsEnabled = true; } } /// <summary> /// Submits related record edits back to server. /// </summary> private async Task SaveEditsAsync() { if (table == null || !table.HasEdits) return; if (table is ServiceFeatureTable) { var serviceTable = (ServiceFeatureTable)table; // Pushes new graphic back to the server. var result = await serviceTable.ApplyEditsAsync(); if (result.AddResults == null || result.AddResults.Count < 1) return; var addResult = result.AddResults[0]; if (addResult.Error != null) throw addResult.Error; } } /// <summary> /// Gets related table for editing. /// </summary> private async Task<ServiceFeatureTable> GetRelatedTableAsync() { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; // Creates table based on related table ID of the visible layer in dynamic layer // using FeatureServer specifying rank and comments fields to enable editing. var id = relationship.RelatedTableID.Value; var url = layer.ServiceUri.Replace("MapServer", "FeatureServer"); url = string.Format("{0}/{1}", url, id); var table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference); table.OutFields = new OutFields(new string[] { relationship.KeyField, "rank", "comments", "submitdt" }); return table; } /// <summary> /// Displays current attribute values of related record. /// </summary> private async void RelatedRecords_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (RelatedRecords.SelectedItem == null) return; var graphic = (Graphic)RelatedRecords.SelectedItem; SetAttributeEditor(); string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture); var feature = await table.QueryAsync(featureID); SetAttributeEditor(feature); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Adds a new related record to highlighted feature. /// </summary> private async void AddButton_Click(object sender, RoutedEventArgs e) { SetAttributeEditor(); var featureID = (Int64)AddButton.Tag; var requestID = (string)RelatedRecords.Tag; string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var feature = new GeodatabaseFeature(table.Schema); feature.Attributes[relationship.KeyField] = requestID; feature.Attributes["rank"] = 5; feature.Attributes["comments"] = "Describe service requirement here."; feature.Attributes["submitdt"] = DateTime.UtcNow; var relatedFeatureID = await table.AddAsync(feature); await SaveEditsAsync(); await QueryRelatedRecordsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Updates attributes of related record. /// </summary> private async void EditButton_Click(object sender, RoutedEventArgs e) { if (AttributeEditor.Tag == null) return; var feature = (GeodatabaseFeature)AttributeEditor.Tag; string message = null; try { if (ChoiceList.SelectedItem != null) feature.Attributes["rank"] = (int)ChoiceList.SelectedItem; feature.Attributes["comments"] = Comments.Text.Trim(); await table.UpdateAsync(feature); await SaveEditsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Deletes related record. /// </summary> private async void DeleteButton_Click(object sender, RoutedEventArgs e) { if (RelatedRecords.SelectedItem == null) return; var graphic = (Graphic)RelatedRecords.SelectedItem; string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture); await table.DeleteAsync(featureID); await SaveEditsAsync(); await QueryRelatedRecordsAsync(); SetAttributeEditor(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } } }
1.40625
1
SyncPanel.cs
meyer-mcmains/musicbee-sync
0
260
using System.Windows.Forms; namespace MusicBeePlugin { public partial class SyncPanel : UserControl { public SyncPanel() { InitializeComponent(); } } }
0.734375
1
Enrollment.Parameters/Expressions/AsQueryableOperatorParameters.cs
BlaiseD/Enrollment.XPlatform
0
268
namespace Enrollment.Parameters.Expressions { public class AsQueryableOperatorParameters : IExpressionParameter { public AsQueryableOperatorParameters() { } public AsQueryableOperatorParameters(IExpressionParameter sourceOperand) { SourceOperand = sourceOperand; } public IExpressionParameter SourceOperand { get; set; } } }
0.601563
1
Advanced/Functional Programming - Exercise/09. List Of Predicates/Program.cs
tonkatawe/SoftUni-Advanced
0
276
using System; using System.Collections.Generic; using System.Linq; namespace _09._List_Of_Predicates { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); //it is maxBound var numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); var result = new List<int>(); for (int i = 1; i <= n; i++) // start 1...n { var isDivde = true; foreach (var digit in numbers) { if (i % digit != 0) { isDivde = false; break; } } if (!isDivde) { continue; } result.Add(i); } Console.WriteLine(string.Join(' ', result)); } } }
2.34375
2
src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs
rsumner31/corefx2
0
284
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() { AsyncValueTaskMethodBuilder<int> b = default; Assert.Equal(default(AsyncValueTaskMethodBuilder<int>), b); // implementation detail being verified } [Fact] public void SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = default; b.SetResult(42); ValueTask<int> vt = b.Task; Assert.True(vt.IsCompletedSuccessfully); Assert.False(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = default; ValueTask<int> vt = b.Task; b.SetResult(42); Assert.True(vt.IsCompletedSuccessfully); Assert.True(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new OperationCanceledException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = default; int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = default; var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); Assert.True(WrapsTask(b.Task)); Assert.Equal(42, b.Task.Result); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22506", TargetFrameworkMonikers.UapAot)] public void SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = default; AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = default; b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); ValueTask<int> vt = b.Task; Assert.False(WrapsTask(vt)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42, await ValueTaskReturningAsyncMethod(42)); ValueTask<int> vt = ValueTaskReturningAsyncMethod(84); Assert.Equal(yields > 0, WrapsTask(vt)); Assert.Equal(84, await vt); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) await Task.Yield(); return result; } } /// <summary>Gets whether the ValueTask has a non-null Task.</summary> private static bool WrapsTask<T>(ValueTask<T> vt) => ReferenceEquals(vt.AsTask(), vt.AsTask()); private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
1.382813
1
VirusTotal.Library/ResponseCodes/DomainResponseCode.cs
tranvanphy/VirusTotal
0
292
namespace VirusTotal.Library.ResponseCodes { public enum DomainResponseCode { /// <summary> /// The item you searched for was not present in VirusTotal's dataset. /// </summary> NotPresent = 0, /// <summary> /// The item was present and it could be retrieved. /// </summary> Present = 1 } }
0.832031
1
DeadFishStudio.Product.Infrastructure.CrossCutting/CustomExtensionsMethods.cs
luca16s/Infnet-Pos-DevOpsPresentation
0
300
using System; using DeadFishStudio.Product.Infrastructure.Data.Context; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace DeadFishStudio.Product.Infrastructure.CrossCutting { internal static class CustomExtensionsMethods { public static IServiceCollection AddCustomDbContext(this IServiceCollection services, ProductConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); services.AddEntityFrameworkSqlServer() .AddDbContext<ProductContext>(options => { options .UseLazyLoadingProxies() .UseSqlServer(configuration.ConnectionString); }); return services; } } }
1.054688
1
AtlasBotNode/SmashggHandler/Models/TournamentRoot.cs
bartdebever/AtlasBotNetwork
1
308
using System.Collections.Generic; using Newtonsoft.Json; namespace SmashggHandler.Models { public class TournamentRoot { [JsonProperty("entities")] public TournamentEntities Entities { get; set; } } public class TournamentEntities { [JsonProperty("tournament")] public Tournament Tournament { get; set; } [JsonProperty("event")] public List<Event> Events { get; set; } [JsonProperty("videogame")] public List<Videogame> Videogames { get; set; } [JsonProperty("phase")] public List<Phase> Phases { get; set; } [JsonProperty("group")] public List<Group> Groups { get; set; } } }
0.890625
1
src/DocumentProcessing/Schulteisz.Document.PdfReader/Page.cs
schulzy/HouseholdBudget
0
316
using Schulteisz.Document.Interfaces; using System; using System.Collections.Generic; namespace Schulteisz.Document.PdfReader { public class Page : IPage { private UglyToad.PdfPig.Content.Page _page; private IEnumerable<string> _lines; public Page(UglyToad.PdfPig.Content.Page page) { _page = page; } public IEnumerable<string> Lines { get { if (_lines is null) InitPages(); return _lines; } } private void InitPages() { throw new NotImplementedException(); } } }
1.023438
1
NET.Undersoft.Vegas.Sdk/Undersoft.System.Uniques/Hasher/Algorithm/xxHash32.Array.cs
undersoft-org/NET.Undersoft.Vegas.Sdk.Develop
2
324
/************************************************* Copyright (c) 2021 Undersoft System.Uniques.xxHash32.Array.cs @project: Undersoft.Vegas.Sdk @stage: Development @author: <NAME> @date: (05.06.2021) @licence MIT *************************************************/ namespace System.Uniques { using System.Diagnostics; /// <summary> /// Defines the <see cref="xxHash32" />. /// </summary> public static partial class xxHash32 { #region Methods /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe ulong ComputeHash(ArraySegment<byte> data, uint seed = 0) { Debug.Assert(data != null); return ComputeHash(data.Array, data.Offset, data.Count, seed); } /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="length">The length of the data for hashing.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe uint ComputeHash(byte[] data, int length, uint seed = 0) { Debug.Assert(data != null); Debug.Assert(length >= 0); Debug.Assert(length <= data.Length); fixed (byte* pData = &data[0]) { return UnsafeComputeHash(pData, length, seed); } } /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="offset">The offset of the data for hashing.</param> /// <param name="length">The length of the data for hashing.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe uint ComputeHash(byte[] data, int offset, int length, uint seed = 0) { Debug.Assert(data != null); Debug.Assert(length >= 0); Debug.Assert(offset < data.Length); Debug.Assert(length <= data.Length - offset); fixed (byte* pData = &data[0 + offset]) { return UnsafeComputeHash(pData, length, seed); } } #endregion } }
1.703125
2
src/Service.Registration.Grpc/Models/GetRestrictedCountriesGrpcResponse.cs
MyJetWallet/Service.Registration
0
332
using System.Collections.Generic; using System.Runtime.Serialization; namespace Service.Registration.Grpc.Models { [DataContract] public class GetRestrictedCountriesGrpcResponse { [DataMember(Order = 1)] public IEnumerable<string> RestrictedCountries { get; set; } } }
0.832031
1
src/Miru/IAppConfig.cs
MiruFx/Miru
11
340
using Microsoft.Extensions.DependencyInjection; namespace Miru { public interface IAppConfig { void ConfigureServices(IServiceCollection services); } }
0.539063
1
Source/LogBridge.Tests.Shared/When_logging_fatal_messages_with_null_parameters.cs
TorbenRahbekKoch/LogBridge
0
348
using System; using FluentAssertions; using Xunit; namespace SoftwarePassion.LogBridge.Tests.Shared { public abstract class When_logging_fatal_messages_with_null_parameters : LogTestBase { public When_logging_fatal_messages_with_null_parameters(ILogDataVerifier verifier) : base(Level.Fatal, verifier) {} [Fact] public void Verify_that_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal((string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (string)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (string)null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal((string)null, null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_value_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal((object) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_extended_properties_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal((object) null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_extended_properties_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (object) null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (object) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_value_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_extended_properties_and_null_message_and_null_formatting_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (object)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_extended_properties_and_null_message_and_null_formatting_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), null, (object)null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } } }
1.234375
1
Managed/main/MinionAssignablesProxy.cs
undancer/oni-data
1
356
using System.Collections.Generic; using System.Runtime.Serialization; using KSerialization; using UnityEngine; [AddComponentMenu("KMonoBehaviour/scripts/MinionAssignablesProxy")] public class MinionAssignablesProxy : KMonoBehaviour, IAssignableIdentity { public List<Ownables> ownables; [Serialize] private int target_instance_id = -1; private bool slotsConfigured; private static readonly EventSystem.IntraObjectHandler<MinionAssignablesProxy> OnAssignablesChangedDelegate = new EventSystem.IntraObjectHandler<MinionAssignablesProxy>(delegate(MinionAssignablesProxy component, object data) { component.OnAssignablesChanged(data); }); public IAssignableIdentity target { get; private set; } public bool IsConfigured => slotsConfigured; public int TargetInstanceID => target_instance_id; public GameObject GetTargetGameObject() { if (target == null && target_instance_id != -1) { RestoreTargetFromInstanceID(); } KMonoBehaviour kMonoBehaviour = (KMonoBehaviour)target; if (kMonoBehaviour != null) { return kMonoBehaviour.gameObject; } return null; } public float GetArrivalTime() { if (GetTargetGameObject().GetComponent<MinionIdentity>() != null) { return GetTargetGameObject().GetComponent<MinionIdentity>().arrivalTime; } if (GetTargetGameObject().GetComponent<StoredMinionIdentity>() != null) { return GetTargetGameObject().GetComponent<StoredMinionIdentity>().arrivalTime; } Debug.LogError("Could not get minion arrival time"); return -1f; } public int GetTotalSkillpoints() { if (GetTargetGameObject().GetComponent<MinionIdentity>() != null) { return GetTargetGameObject().GetComponent<MinionResume>().TotalSkillPointsGained; } if (GetTargetGameObject().GetComponent<StoredMinionIdentity>() != null) { return MinionResume.CalculateTotalSkillPointsGained(GetTargetGameObject().GetComponent<StoredMinionIdentity>().TotalExperienceGained); } Debug.LogError("Could not get minion skill points time"); return -1; } public void SetTarget(IAssignableIdentity target, GameObject targetGO) { Debug.Assert(target != null, "target was null"); if (targetGO == null) { Debug.LogWarningFormat("{0} MinionAssignablesProxy.SetTarget {1}, {2}, {3}. DESTROYING", GetInstanceID(), target_instance_id, target, targetGO); Util.KDestroyGameObject(base.gameObject); } this.target = target; target_instance_id = targetGO.GetComponent<KPrefabID>().InstanceID; base.gameObject.name = "Minion Assignables Proxy : " + targetGO.name; } protected override void OnPrefabInit() { base.OnPrefabInit(); ownables = new List<Ownables> { base.gameObject.AddOrGet<Ownables>() }; Components.MinionAssignablesProxy.Add(this); ConfigureAssignableSlots(); } [OnDeserialized] private void OnDeserialized() { } public void ConfigureAssignableSlots() { if (slotsConfigured) { return; } Ownables component = GetComponent<Ownables>(); Equipment component2 = GetComponent<Equipment>(); if (component2 != null) { foreach (AssignableSlot resource in Db.Get().AssignableSlots.resources) { if (resource is OwnableSlot) { OwnableSlotInstance slot_instance = new OwnableSlotInstance(component, (OwnableSlot)resource); component.Add(slot_instance); } else if (resource is EquipmentSlot) { EquipmentSlotInstance slot_instance2 = new EquipmentSlotInstance(component2, (EquipmentSlot)resource); component2.Add(slot_instance2); } } } slotsConfigured = true; } public void RestoreTargetFromInstanceID() { if (target_instance_id == -1 || target != null) { return; } KPrefabID instance = KPrefabIDTracker.Get().GetInstance(target_instance_id); if ((bool)instance) { IAssignableIdentity component = instance.GetComponent<IAssignableIdentity>(); if (component != null) { SetTarget(component, instance.gameObject); return; } Debug.LogWarningFormat("RestoreTargetFromInstanceID target ID {0} was found but it wasn't an IAssignableIdentity, destroying proxy object.", target_instance_id); Util.KDestroyGameObject(base.gameObject); } else { Debug.LogWarningFormat("RestoreTargetFromInstanceID target ID {0} was not found, destroying proxy object.", target_instance_id); Util.KDestroyGameObject(base.gameObject); } } protected override void OnSpawn() { base.OnSpawn(); RestoreTargetFromInstanceID(); if (target != null) { Subscribe(-1585839766, OnAssignablesChangedDelegate); Game.Instance.assignmentManager.AddToAssignmentGroup("public", this); } } protected override void OnCleanUp() { base.OnCleanUp(); Game.Instance.assignmentManager.RemoveFromAllGroups(this); GetComponent<Ownables>().UnassignAll(); GetComponent<Equipment>().UnequipAll(); Components.MinionAssignablesProxy.Remove(this); } private void OnAssignablesChanged(object data) { if (!target.IsNull()) { ((KMonoBehaviour)target).Trigger(-1585839766, data); } } private void CheckTarget() { if (target != null) { return; } KPrefabID instance = KPrefabIDTracker.Get().GetInstance(target_instance_id); if (!(instance != null)) { return; } target = instance.GetComponent<IAssignableIdentity>(); if (target == null) { return; } MinionIdentity minionIdentity = target as MinionIdentity; if ((bool)minionIdentity) { minionIdentity.ValidateProxy(); return; } StoredMinionIdentity storedMinionIdentity = target as StoredMinionIdentity; if ((bool)storedMinionIdentity) { storedMinionIdentity.ValidateProxy(); } } public List<Ownables> GetOwners() { CheckTarget(); return target.GetOwners(); } public string GetProperName() { CheckTarget(); return target.GetProperName(); } public Ownables GetSoleOwner() { CheckTarget(); return target.GetSoleOwner(); } public bool HasOwner(Assignables owner) { CheckTarget(); return target.HasOwner(owner); } public int NumOwners() { CheckTarget(); return target.NumOwners(); } public bool IsNull() { CheckTarget(); return target.IsNull(); } public static Ref<MinionAssignablesProxy> InitAssignableProxy(Ref<MinionAssignablesProxy> assignableProxyRef, IAssignableIdentity source) { if (assignableProxyRef == null) { assignableProxyRef = new Ref<MinionAssignablesProxy>(); } GameObject targetGO = ((KMonoBehaviour)source).gameObject; MinionAssignablesProxy minionAssignablesProxy = assignableProxyRef.Get(); if (minionAssignablesProxy == null) { GameObject obj = GameUtil.KInstantiate(Assets.GetPrefab(MinionAssignablesProxyConfig.ID), Grid.SceneLayer.NoLayer); minionAssignablesProxy = obj.GetComponent<MinionAssignablesProxy>(); minionAssignablesProxy.SetTarget(source, targetGO); obj.SetActive(value: true); assignableProxyRef.Set(minionAssignablesProxy); } else { minionAssignablesProxy.SetTarget(source, targetGO); } return assignableProxyRef; } }
1.453125
1
Serenity.Core/Authorization/Authorization.cs
awesomegithubusername/Serenity
1
364
using Serenity.Abstractions; using Serenity.Services; using System; namespace Serenity { /// <summary> /// Provides a common access point for authorization related services /// </summary> public static class Authorization { /// <summary> /// Returns true if user is logged in. /// </summary> /// <remarks> /// Uses the IAuthorizationService dependency. /// </remarks> public static bool IsLoggedIn { get { return Dependency.Resolve<IAuthorizationService>().IsLoggedIn; } } /// <summary> /// Returns user definition for currently logged user. /// </summary> /// <remarks> /// Uses IUserRetrieveService to get definition of current user by /// its username. /// </remarks> public static IUserDefinition UserDefinition { get { var username = Username; if (username == null) return null; return Dependency.Resolve<IUserRetrieveService>().ByUsername(username); } } /// <summary> /// Returns currently logged user ID /// </summary> /// <remarks> /// This is a shortcut to UserDefinition.UserId. /// </remarks> public static string UserId { get { var user = UserDefinition; return user == null ? null : user.Id; } } /// <summary> /// Returns currently logged username. /// </summary> /// <remarks>Uses IAuthorizationService dependency.</remarks> public static string Username { get { return Dependency.Resolve<IAuthorizationService>().Username; } } /// <summary> /// Returns true if current user has given permission. /// </summary> /// <param name="permission">Permission key (e.g. Administration)</param> public static bool HasPermission(string permission) { return Dependency.Resolve<IPermissionService>().HasPermission(permission); } /// <summary> /// Checks if there is a currently logged user and throws a validation error with /// "NotLoggedIn" error code if not. /// </summary> public static void ValidateLoggedIn() { if (!IsLoggedIn) throw new ValidationError("NotLoggedIn", null, Serenity.Core.Texts.Authorization.NotLoggedIn); } /// <summary> /// Checks if current user has given permission and throws a validation error with /// "AccessDenied" error code if not. /// </summary> /// <param name="permission"></param> public static void ValidatePermission(string permission) { if (!HasPermission(permission)) throw new ValidationError("AccessDenied", null, Serenity.Core.Texts.Authorization.AccessDenied); } } }
1.460938
1
Yuki Theme.Core/Themes/ExternalThemeManager.cs
Dragon-0609/Yuki-Theme
15
372
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Yuki_Theme.Core.Themes; public static class ExternalThemeManager { public static void LoadThemes () { string [] files = Directory.GetFiles (CLI.currentPath, "*Themes.dll"); if (files.Length > 0) AddThemesToDB (files); string path = Path.Combine (CLI.currentPath, "Themes"); if (Directory.Exists (path)) { files = Directory.GetFiles (path, "*.dll"); if (files.Length > 0) AddThemesToDB (files); } } private static void AddThemesToDB (string [] files) { foreach (string file in files) { Assembly assembly = Assembly.LoadFile (file); Type [] types = assembly.GetTypes (); Type themeHeader = types.FirstOrDefault (i => typeof (IThemeHeader).IsAssignableFrom (i) && i.IsClass); if (themeHeader != null) { IThemeHeader header = (IThemeHeader)Activator.CreateInstance (themeHeader); DefaultThemes.addHeader (header); } } } }
1.21875
1
src/VSPoll.API.UnitTest/Models/MappingTests.cs
valamistudio/vspoll
1
380
using System; using FluentAssertions; using VSPoll.API.Models.Output; using Xunit; using Entity = VSPoll.API.Persistence.Entities; namespace VSPoll.API.UnitTest.Models { public class Mapping { [Fact] public void Poll_Mapping() { Entity.Poll entity = new() { Description = "Description", EndDate = DateTime.UtcNow, Id = Guid.NewGuid(), }; var model = Poll.Of(entity); model.AllowAdd.Should().Be(entity.AllowAdd); model.Description.Should().Be(entity.Description); model.EndDate.Should().Be(entity.EndDate); model.Id.Should().Be(entity.Id); model.VotingSystem.Should().Be(entity.VotingSystem); model.ShowVoters.Should().Be(entity.ShowVoters); } [Fact] public void PollOption_Mapping() { Entity.PollOption entity = new() { Description = "Description", Id = Guid.NewGuid(), }; var model = PollOption.Of(entity); model.Description.Should().Be(entity.Description); model.Id.Should().Be(entity.Id); } [Fact] public void User_Mapping() { Entity.User entity = new() { FirstName = "First", Id = new Random().Next(), LastName = "Last", PhotoUrl = "Url", Username = "Username", }; User model = new(entity); model.FirstName.Should().Be(entity.FirstName); model.LastName.Should().Be(entity.LastName); model.PhotoUrl.Should().Be(entity.PhotoUrl); model.Username.Should().Be(entity.Username); } } }
1.335938
1
AlipaySDKNet/Response/MybankCreditGuaranteeSelleradmittanceQueryResponse.cs
alipay/alipay-sdk-net
117
388
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// MybankCreditGuaranteeSelleradmittanceQueryResponse. /// </summary> public class MybankCreditGuaranteeSelleradmittanceQueryResponse : AopResponse { /// <summary> /// 查询decision是否准入。为空表示不准入 /// </summary> [XmlElement("is_admitted")] public bool IsAdmitted { get; set; } /// <summary> /// 是否签约 /// </summary> [XmlElement("is_signed")] public bool IsSigned { get; set; } /// <summary> /// 是否解约AE提前收款,为空表示未解约 /// </summary> [XmlElement("is_unsigned")] public bool IsUnsigned { get; set; } /// <summary> /// 解约时间,为空表示无解约时间 /// </summary> [XmlElement("unsign_date")] public string UnsignDate { get; set; } } }
0.695313
1
globalvars.cs
randolphcabral/sdxs
1
396
namespace sdxs { public static class SDXS_GLOBALS { public const string C_SDXS_HDRKEY_IDENT = "X-SDxS-Ident"; public const string C_SDXS_HDRKEY_DOMAIN = "X-SDxS-Domain"; public const string C_SDXS_HDRKEY_EPHEMERAL_VAL = "X-SDxS-Ephemeral-Val"; public const string C_SDXS_HDRKEY_EPHEMERAL_SIG = "X-SDxS-Ephemeral-Sig"; public const string C_SDXS_HDRKEY_CHANNEL = "X-SDxS-Channel"; public const string C_SDXS_HDRKEY_ACTION = "X-SDxS-Action"; } }
0.275391
0
commercetools.Sdk/commercetools.Sdk.HttpApi/ApiExceptionFactory.cs
onepiecefreak3/commercetools-dotnet-core-sdk
0
404
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using commercetools.Sdk.HttpApi.Domain.Exceptions; using commercetools.Sdk.HttpApi.Extensions; using commercetools.Sdk.Serialization; using Microsoft.AspNetCore.Http; namespace commercetools.Sdk.HttpApi { /// <summary> /// Responsible for Creating HTTP Exceptions based on the status code return from unsuccessful requests /// </summary> public class ApiExceptionFactory : IApiExceptionFactory { private readonly IClientConfiguration clientConfiguration; private readonly ISerializerService serializerService; private List<HttpResponseExceptionResponsibility> responsibilities; public ApiExceptionFactory(IClientConfiguration clientConfiguration, ISerializerService serializerService) { this.clientConfiguration = clientConfiguration; this.serializerService = serializerService; this.FillResponsibilities(); } /// <summary> /// Create API Exception based on status code /// </summary> /// <param name="request">The http Request</param> /// <param name="response">The http Response</param> /// <returns>General Api Exception or any exception inherit from it based on the status code</returns> public ApiException CreateApiException(HttpRequestMessage request, HttpResponseMessage response) { ApiException apiException = null; string content = response.ExtractResponseBody(); var responsibility = this.responsibilities.FirstOrDefault(r => r.Predicate(response)); if (responsibility?.ExceptionCreator != null) { apiException = responsibility.ExceptionCreator(response); } // set the common info for all exception types if (apiException != null) { apiException.Request = request; apiException.Response = response; apiException.ProjectKey = this.clientConfiguration.ProjectKey; if (!string.IsNullOrEmpty(content) && response.Content.Headers.ContentType.MediaType == "application/json") { var errorResponse = this.serializerService.Deserialize<HttpApiErrorResponse>(content); if (errorResponse.Errors != null) { apiException.ErrorResponse = errorResponse; } } } return apiException; } /// <summary> /// Fill responsibilities which factory will use to create the exception /// each responsibility contains predicate and func, so when the http response meet the criteria of the predicate, then we use delegate Func to create the exception /// </summary> private void FillResponsibilities() { this.responsibilities = new List<HttpResponseExceptionResponsibility>(); // Add responsibilities based on status code WhenStatus(403, response => new ForbiddenException()); WhenStatus(500, response => new InternalServerErrorException()); WhenStatus(502, response => new BadGatewayException()); WhenStatus(503, response => new ServiceUnavailableException()); WhenStatus(504, response => new GatewayTimeoutException()); WhenStatus(413, response => new RequestEntityTooLargeException()); WhenStatus(404, response => new NotFoundException()); WhenStatus(409, response => new ConcurrentModificationException()); WhenStatus(401, response => { var exception = response.ExtractResponseBody().Contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(); return exception; }); WhenStatus(400, response => { if (response.ExtractResponseBody().Contains("invalid_scope")) { return new InvalidTokenException(); } else { return new ErrorResponseException(); } }); // Add the other responsibilities When(response => response.IsServiceNotAvailable(), response => new ServiceUnavailableException()); When(response => true, response => new ApiException()); } /// <summary> /// Add Responsibility when the Response meet the criteria of the predicate /// </summary> /// <param name="predicate">predicate which we check if the response message meet it's criteria</param> /// <param name="exceptionCreator">delegate function we use to create the right exception based on the status</param> private void When(Predicate<HttpResponseMessage> predicate, Func<HttpResponseMessage, ApiException> exceptionCreator) { this.AddResponsibility(predicate, exceptionCreator); } /// <summary> /// Add Responsibility when the Response status equal to the passed status /// </summary> /// <param name="status">response status code</param> /// <param name="exceptionCreator">delegate func to create the right exception</param> private void WhenStatus(int status, Func<HttpResponseMessage, ApiException> exceptionCreator) { this.AddResponsibility(response => (int)response.StatusCode == status, exceptionCreator); } /// <summary> /// Add Responsibility to responsibilities list /// </summary> /// <param name="predicate">predicate which we check if the response message meet it's criteria</param> /// <param name="exceptionCreator">delegate function we use to create the right exception based on the status</param> private void AddResponsibility(Predicate<HttpResponseMessage> predicate, Func<HttpResponseMessage, ApiException> exceptionCreator) { if (this.responsibilities == null) { return; } var responsibility = new HttpResponseExceptionResponsibility(predicate, exceptionCreator); this.responsibilities.Add(responsibility); } } }
1.414063
1
Core/Utilities/SecTime.cs
AeroNexus/AspireStudio
2
412
using System; using System.Text; namespace Aspire.Core.Utilities { public struct SecTime { private int mSec, mUSec; static SecTime infinite = new SecTime(-1, 0); public static SecTime Infinite { get { return infinite; } } public SecTime(int sec, int uSec) { mSec = sec; mUSec = uSec; } public SecTime(double seconds) { mSec = (int)seconds; mUSec = (int)((seconds-mSec)*1000000); } public SecTime(SecTime rhs) { mSec = rhs.mSec; mUSec = rhs.mUSec; } public int this[int i] { get { return i == 0 ? mSec : mUSec; } set { if (i == 0) mSec = value; else if (i == 1) mUSec = value; } } public override bool Equals(object obj) { if (obj == null) return false; return ((SecTime)obj).mSec == mSec && ((SecTime)obj).mUSec == mUSec; } public override int GetHashCode() { return mSec+mUSec; } static public SecTime Milliseconds(int ms) { return new SecTime(0, ms * 1000); } public static SecTime operator+(SecTime lhs, SecTime rhs) { SecTime result; result.mUSec = lhs.mUSec + rhs.mUSec; if (result.mUSec > 1000000) { result.mUSec -= 1000000; result.mSec = lhs.mSec + 1 + rhs.mSec; } else result.mSec = lhs.mSec + rhs.mSec; return result; } public static SecTime operator+(SecTime lhs, int rhs) { SecTime result; result.mUSec = lhs.mUSec; result.mSec = lhs.mSec + rhs; return result; } public static SecTime operator-(SecTime lhs, SecTime rhs) { SecTime result; result.mUSec = lhs.mUSec - rhs.mUSec; if (result.mUSec > 0) result.mSec = lhs.mSec - rhs.mSec; else { result.mUSec += 1000000; result.mSec = lhs.mSec - 1 - rhs.mSec; } return result; } public static SecTime operator-(SecTime lhs, int rhs) { SecTime result; result.mUSec = lhs.mUSec; result.mSec = lhs.mSec - rhs; return result; } public static bool operator>(SecTime lhs, int rhsUsec) { return lhs.mSec >= 0 || lhs.mUSec > rhsUsec; } public static bool operator<(SecTime lhs, SecTime rhs) { if (lhs.mSec < rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec < rhs.mUSec) return true; return false; } public static bool operator<=(SecTime lhs, SecTime rhs) { if (lhs.mSec < rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec <= rhs.mUSec) return true; return false; } public static bool operator>(SecTime lhs, SecTime rhs) { if (lhs.mSec > rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec > rhs.mUSec) return true; return false; } public static bool operator>=(SecTime lhs, SecTime rhs) { if (lhs.mSec > rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec >= rhs.mUSec) return true; return false; } public static bool operator<(SecTime lhs, int rhsUsec) { return lhs.mSec <= 0 || lhs.mUSec < rhsUsec; } public bool IsInfinite { get { return mSec == -1; } } public int Seconds { get { return mSec; } set { mSec = value; } } public int USeconds { get { return mUSec; } set { mUSec = value; } } public void Set(int seconds, int microSeconds) { mSec = seconds; mUSec = microSeconds; } public double ToDouble { get { return mUSec*0.000001 + mSec; } } public int ToMicroSeconds { get { return mSec*1000000+mUSec; } } public int ToMilliSeconds { get { return mSec*1000+mUSec/1000; } } public override string ToString() { int dSec = mSec; int dUsec = mUSec; var sb = new StringBuilder(); if ( dSec < 0 ) { dSec++; if ( dSec == 0) sb.Append('-'); dUsec = 1000000 - dUsec; } sb.AppendFormat("{0}.{1,6:D6}", dSec, dUsec); return sb.ToString(); } } }
1.632813
2
src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs
madmonkey/Ocelot
6,073
420
namespace Ocelot.Multiplexer { using Ocelot.Configuration; public interface IResponseAggregatorFactory { IResponseAggregator Get(Route route); } }
0.482422
0
Dorothy/Game/World.cs
IppClub/Dorothy-Xna
1
428
using Dorothy.Core; using Microsoft.Xna.Framework; using Dorothy.Cameras; namespace Dorothy.Game { public class World : DrawComponent { public const float B2FACTOR = 100.0f; private int _velocityIterations = 8; private int _positionIterations = 6; private float _deltaTime; private Box2D.World _world; public int VelocityIterations { set { _velocityIterations = value; } get { return _velocityIterations; } } public int PositionIterations { set { _positionIterations = value; } get { return _positionIterations; } } public float DeltaTime { set { _deltaTime = value; } get { return _deltaTime; } } public bool IsRunning { set { this.Enable = value; } get { return this.Enable; } } public Box2D.World B2World { get { return _world; } } public static float B2Value(float value) { return value / B2FACTOR; } public static Vector2 B2Value(Vector2 value) { return new Vector2(value.X / B2FACTOR, value.Y / B2FACTOR); } public static Vector2 B2Value(ref Vector2 value) { return new Vector2(value.X / B2FACTOR, value.Y / B2FACTOR); } public static float GameValue(float value) { return value * B2FACTOR; } public static Vector2 GameValue(Vector2 value) { return new Vector2(value.X * B2FACTOR, value.Y * B2FACTOR); } public static Vector2 GameValue(ref Vector2 value) { return new Vector2(value.X * B2FACTOR, value.Y * B2FACTOR); } public World(Vector2 gravity) : base(oSceneManager.CurrentScene.Controller) { _world = new Box2D.World(gravity, true); _world.ContactListener = new ContactListener(); _deltaTime = oGame.TargetFrameInterval / 1000.0f; oSceneManager.CurrentScene.Root.Add(this); base.Enable = true; } public override void Update() { _world.Step(_deltaTime, _velocityIterations, _positionIterations); } protected override void GetReady() { base.GetReady(); if (_world.DebugDraw != null) { _world.DrawDebugData(); } } public override void Draw() { } } }
1.78125
2
Source/RCStatic.cs
Jagerente/RCFixed
2
436
using System; public static class RCStatic { }
0.148438
0
WaterPreview/WaterPreview/Controllers/HomeController.cs
Kate605690919/Water-Preview
0
444
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using WaterPreview.Base; using WaterPreview.Other; using WaterPreview.Other.Attribute; using WaterPreview.Other.Client; using WaterPreview.Redis; using WaterPreview.Service; using WaterPreview.Service.Interface; using WaterPreview.Service.Service; namespace WaterPreview.Controllers { public class HomeController : Controller { private IAccountService accountService; private IRoleService roleService; private IUserInnerRoleService userInnerRoleService; public HomeController() { accountService = new AccountService(); roleService = new RoleService(); userInnerRoleService = new UserInnerRoleService(); } [AllowAnonymous] public ActionResult Login() { ViewBag.Exception = false; return View(); } [HttpPost] [AllowAnonymous] public JsonResult Login(string userName, string password) { JsonResult result= new JsonResult(); User_t user = accountService.GetAccountByName(userName); if (user.Usr_UId == new Guid() || user.Usr_Password != <PASSWORD>(password)) { ViewBag.Exception = true; result.Data = false; return result; } password = <PASSWORD>(password); Response.Headers.Add("username", user.Usr_Name); Response.Headers.Add("useruid", user.Usr_UId.ToString()); //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Value = user.Usr_UId.ToString(); //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Domain = ConfigurationManager.AppSettings["DomainName"]; //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Expires = DateTime.Now.AddDays(1); //Response.Cookies["username"].Value = user.Usr_Name; //Response.Cookies["username"].Domain = ConfigurationManager.AppSettings["DomainName"]; //Response.Cookies["username"].Expires = DateTime.Now.AddDays(1); HttpClientCrant client = new HttpClientCrant(); client.Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant(userName,password); UserContext.account = user; //return RedirectToAction("index"); //return View("index"); var userInnerRoles = userInnerRoleService.GetByUid(user.Usr_UId); List<InnerRole_t> roleLists = new List<InnerRole_t>(); foreach (var item in userInnerRoles) { var role = roleService.GetRoles(item.UIr_IrUId); if(role != null) { roleLists.Add(role); } } var names = new List<String>(); foreach (var item in roleLists) { var name = item.Ir_Name; names.Add(name); } //var roles = new List<String>(); RoleHelper.Role personalRole = new RoleHelper.Role(); foreach (var item in names) { switch (item) { case "总查看员": RoleHelper.GetAllPermission(personalRole); break; case "流量计查看员": RoleHelper.GetFlowMeterViewPermission(personalRole); break; case "流量计管理员": RoleHelper.GetClientManagePermission(personalRole); break; case "压力计查看员": RoleHelper.GetPressureMeterViewPermission(personalRole); break; case "压力计管理员": RoleHelper.GetPressureMeterManagePermission(personalRole); break; case "水质计查看员": RoleHelper.GetQualityMeterViewPermission(personalRole); break; case "水质计管理员": RoleHelper.GetQualityMeterManagePermission(personalRole); break; case "区域查看员": RoleHelper.GetAreaViewPermission(personalRole); break; case "区域管理员": RoleHelper.GetAreaManagePermission(personalRole); break; case "客户查看员": RoleHelper.GetClientViewPermission(personalRole); break; case "客户管理员": RoleHelper.GetClientManagePermission(personalRole); break; case "职员查看员": result.Data = RoleHelper.GetStaffViewPermission(personalRole); break; case "职员管理员": RoleHelper.GetStaffManagePermission(personalRole); break; case "职位查看员": RoleHelper.GetRolesViewPermission(personalRole); break; case "职位管理员": RoleHelper.GetRolesManagePermission(personalRole); break; } } result.Data = personalRole; return result; } [Login(IsCheck=true)] [AllowAnonymous] public ActionResult Index() { return View(); } public JsonResult LogOut() { JsonResult result = new JsonResult(); User_t account = UserContext.account; try { //清除token和账号uid对应缓存 DBHelper.SetExpire(ConfigurationManager.AppSettings["tokenByUserUid"] + UserContext.account.Usr_UId); DBHelper.SetExpire("token-" + UserContext.access_token); UserContext.access_token = UserContext.access_token != null ? "" : UserContext.access_token; //清除用户信息上下文 account = account != null && account.Usr_UId != new Guid() ? account : new User_t(); //清除可能的cookie HttpCookie cookiename = Request.Cookies["username"]; if (cookiename != null) { cookiename.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookiename); } HttpCookie cookieuid = Request.Cookies["useruid"]; if (cookieuid != null) { cookieuid.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookieuid); } result.Data = true; } catch { result.Data = false; } return result; } } }
1.140625
1
source/FastRsync/Core/ChunkSignatureChecksumComparer.cs
Gwynneth/FastRsyncNet
108
452
using System.Collections.Generic; namespace FastRsync.Core { class ChunkSignatureChecksumComparer : IComparer<ChunkSignature> { public int Compare(ChunkSignature x, ChunkSignature y) { var comparison = x.RollingChecksum.CompareTo(y.RollingChecksum); return comparison == 0 ? x.StartOffset.CompareTo(y.StartOffset) : comparison; } } }
1.015625
1
Assets/XLua/Gen/Minecraft_Assets_AsyncAssetWrap.cs
Jin-Yuhan/MinecraftClone-Unity
60
460
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class MinecraftAssetsAsyncAssetWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Minecraft.Assets.AsyncAsset); Utils.BeginObjectRegister(type, L, translator, 0, 3, 5, 0); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Initialize", _m_Initialize); Utils.RegisterFunc(L, Utils.METHOD_IDX, "UpdateLoadingState", _m_UpdateLoadingState); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Unload", _m_Unload); Utils.RegisterFunc(L, Utils.GETTER_IDX, "IsDone", _g_get_IsDone); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Progress", _g_get_Progress); Utils.RegisterFunc(L, Utils.GETTER_IDX, "AssetName", _g_get_AssetName); Utils.RegisterFunc(L, Utils.GETTER_IDX, "AssetBundle", _g_get_AssetBundle); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Asset", _g_get_Asset); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "WaitAll", _m_WaitAll_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { var gen_ret = new Minecraft.Assets.AsyncAsset(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Initialize(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<System.Type>(L, 3)&& translator.Assignable<Minecraft.Assets.IAssetBundle>(L, 4)) { string _name = LuaAPI.lua_tostring(L, 2); System.Type _type = (System.Type)translator.GetObject(L, 3, typeof(System.Type)); Minecraft.Assets.IAssetBundle _assetBundle = (Minecraft.Assets.IAssetBundle)translator.GetObject(L, 4, typeof(Minecraft.Assets.IAssetBundle)); gen_to_be_invoked.Initialize( _name, _type, _assetBundle ); return 0; } if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<UnityEngine.Object>(L, 3)&& translator.Assignable<Minecraft.Assets.IAssetBundle>(L, 4)) { string _name = LuaAPI.lua_tostring(L, 2); UnityEngine.Object _asset = (UnityEngine.Object)translator.GetObject(L, 3, typeof(UnityEngine.Object)); Minecraft.Assets.IAssetBundle _assetBundle = (Minecraft.Assets.IAssetBundle)translator.GetObject(L, 4, typeof(Minecraft.Assets.IAssetBundle)); gen_to_be_invoked.Initialize( _name, _asset, _assetBundle ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset.Initialize!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_UpdateLoadingState(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); { var gen_ret = gen_to_be_invoked.UpdateLoadingState( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Unload(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Unload( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_WaitAll_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count >= 0&& (LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, 1) || translator.Assignable<Minecraft.Assets.AsyncAsset>(L, 1))) { Minecraft.Assets.AsyncAsset[] _assets = translator.GetParams<Minecraft.Assets.AsyncAsset>(L, 1); var gen_ret = Minecraft.Assets.AsyncAsset.WaitAll( _assets ); translator.PushAny(L, gen_ret); return 1; } if(gen_param_count == 1&& translator.Assignable<System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>>(L, 1)) { System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset> _assets = (System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>)translator.GetObject(L, 1, typeof(System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>)); var gen_ret = Minecraft.Assets.AsyncAsset.WaitAll( _assets ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset.WaitAll!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_IsDone(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushboolean(L, gen_to_be_invoked.IsDone); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Progress(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushnumber(L, gen_to_be_invoked.Progress); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_AssetName(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushstring(L, gen_to_be_invoked.AssetName); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_AssetBundle(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); translator.PushAny(L, gen_to_be_invoked.AssetBundle); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Asset(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); translator.Push(L, gen_to_be_invoked.Asset); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } } }
1.117188
1
samples/TenantManagementService.Host/Migrations/PermissionManagementDb/PermissionManagementDbContextModelSnapshot.cs
linfx/linfx
0
468
// <auto-generated /> using LinFx.Extensions.EntityFrameworkCore; using LinFx.Extensions.PermissionManagement.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace TenantManagementService.Migrations.PermissionManagementDb { [DbContext(typeof(PermissionManagementDbContext))] partial class PermissionManagementDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_DatabaseProvider", EfDatabaseProvider.Sqlite) .HasAnnotation("ProductVersion", "5.0.10"); modelBuilder.Entity("LinFx.Extensions.PermissionManagement.PermissionGrant", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64) .HasColumnType("TEXT"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("TEXT"); b.Property<string>("ProviderName") .IsRequired() .HasMaxLength(64) .HasColumnType("TEXT"); b.Property<string>("TenantId") .HasMaxLength(36) .HasColumnType("TEXT") .HasColumnName("TenantId"); b.HasKey("Id"); b.ToTable("Core_PermissionGrant"); }); #pragma warning restore 612, 618 } } }
1.21875
1
Source/NXL2019_luciano/NXL2019_luciano.Build.cs
TheTarrasque/UnrealEngine-Paintball
0
476
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; public class NXL2019_luciano : ModuleRules { public NXL2019_luciano(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "ProceduralMeshComponent", "RuntimeMeshComponent", "RHI", "RenderCore", "PixelShader", "ComputeShader" }); } }
0.800781
1
Src/MultiSafepay/Model/RefundResult.cs
narendrakongara1987/.Net
42
484
using Newtonsoft.Json; namespace MultiSafepay.Model { public class RefundResult { [JsonProperty("transaction_id")] public string TransactionId { get; set; } } }
0.664063
1
Assets/Scripts/DeliveryTargtSpawner.cs
thibaudio/ld47
0
492
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeliveryTargtSpawner : MonoBehaviour { public GameEvent TargetSpawn; public float WarningTime; public GameObject TargetPrefab; public Transform OrbitTarget; public float DelayMin; public float DelayMax; public float MinY; public float MaxY; private float _cd = 0; private bool _warned = false; private int _targetToSpawn = 0; private ObjectPool _pool; private void Awake() { _pool = new ObjectPool(transform, TargetPrefab, 5); } public void OnPackageCollected() { _targetToSpawn++; } private void Update() { if(_cd <= 0) { if (_targetToSpawn > 0) { _cd = Random.Range(DelayMin, DelayMax); _warned = false; } else return; } _cd -= Time.deltaTime; if (_cd <= WarningTime && !_warned) { TargetSpawn.Raise(); _warned = true; } if (_cd <= 0) { GameObject go = _pool.Get(); Vector3 position = transform.position; position.y += Random.Range(MinY, MaxY); go.transform.position = transform.position; go.transform.rotation = transform.rotation; go.GetComponent<Orbit>().Target = OrbitTarget; _targetToSpawn--; } } }
1.40625
1
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/ServiceServiceGrpc.cs
skuruppu/google-cloud-dotnet
1
500
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/service_service.proto // </auto-generated> // Original file comments: // Copyright 2019 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Cloud.Monitoring.V3 { /// <summary> /// The Stackdriver Monitoring Service-Oriented Monitoring API has endpoints for /// managing and querying aspects of a workspace's services. These include the /// `Service`'s monitored resources, its Service-Level Objectives, and a taxonomy /// of categorized Health Metrics. /// </summary> public static partial class ServiceMonitoringService { static readonly string __ServiceName = "google.monitoring.v3.ServiceMonitoringService"; static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceRequest> __Marshaller_google_monitoring_v3_CreateServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.Service> __Marshaller_google_monitoring_v3_Service = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.Service.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceRequest> __Marshaller_google_monitoring_v3_GetServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesRequest> __Marshaller_google_monitoring_v3_ListServicesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServicesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Marshaller_google_monitoring_v3_ListServicesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServicesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest> __Marshaller_google_monitoring_v3_UpdateServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest> __Marshaller_google_monitoring_v3_DeleteServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Marshaller_google_monitoring_v3_ServiceLevelObjective = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ServiceLevelObjective.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_CreateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "CreateService", __Marshaller_google_monitoring_v3_CreateServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_GetService = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "GetService", __Marshaller_google_monitoring_v3_GetServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Method_ListServices = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>( grpc::MethodType.Unary, __ServiceName, "ListServices", __Marshaller_google_monitoring_v3_ListServicesRequest, __Marshaller_google_monitoring_v3_ListServicesResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_UpdateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "UpdateService", __Marshaller_google_monitoring_v3_UpdateServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteService = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteService", __Marshaller_google_monitoring_v3_DeleteServiceRequest, __Marshaller_google_protobuf_Empty); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_CreateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "CreateServiceLevelObjective", __Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_GetServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "GetServiceLevelObjective", __Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Method_ListServiceLevelObjectives = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>( grpc::MethodType.Unary, __ServiceName, "ListServiceLevelObjectives", __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest, __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_UpdateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "UpdateServiceLevelObjective", __Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteServiceLevelObjective", __Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest, __Marshaller_google_protobuf_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.ServiceServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of ServiceMonitoringService</summary> [grpc::BindServiceMethod(typeof(ServiceMonitoringService), "BindService")] public abstract partial class ServiceMonitoringServiceBase { /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for ServiceMonitoringService</summary> public partial class ServiceMonitoringServiceClient : grpc::ClientBase<ServiceMonitoringServiceClient> { /// <summary>Creates a new client for ServiceMonitoringService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ServiceMonitoringServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for ServiceMonitoringService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ServiceMonitoringServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ServiceMonitoringServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ServiceMonitoringServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateService, null, options, request); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateService, null, options, request); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetService, null, options, request); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetService, null, options, request); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServices(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListServices, null, options, request); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServicesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListServices, null, options, request); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateService, null, options, request); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateService, null, options, request); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteService, null, options, request); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteService, null, options, request); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateServiceLevelObjective, null, options, request); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateServiceLevelObjective, null, options, request); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetServiceLevelObjective, null, options, request); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetServiceLevelObjective, null, options, request); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServiceLevelObjectives(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListServiceLevelObjectives, null, options, request); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServiceLevelObjectivesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListServiceLevelObjectives, null, options, request); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override ServiceMonitoringServiceClient NewInstance(ClientBaseConfiguration configuration) { return new ServiceMonitoringServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(ServiceMonitoringServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateService, serviceImpl.CreateService) .AddMethod(__Method_GetService, serviceImpl.GetService) .AddMethod(__Method_ListServices, serviceImpl.ListServices) .AddMethod(__Method_UpdateService, serviceImpl.UpdateService) .AddMethod(__Method_DeleteService, serviceImpl.DeleteService) .AddMethod(__Method_CreateServiceLevelObjective, serviceImpl.CreateServiceLevelObjective) .AddMethod(__Method_GetServiceLevelObjective, serviceImpl.GetServiceLevelObjective) .AddMethod(__Method_ListServiceLevelObjectives, serviceImpl.ListServiceLevelObjectives) .AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl.UpdateServiceLevelObjective) .AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl.DeleteServiceLevelObjective).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, ServiceMonitoringServiceBase serviceImpl) { serviceBinder.AddMethod(__Method_CreateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.CreateService)); serviceBinder.AddMethod(__Method_GetService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.GetService)); serviceBinder.AddMethod(__Method_ListServices, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>(serviceImpl.ListServices)); serviceBinder.AddMethod(__Method_UpdateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.UpdateService)); serviceBinder.AddMethod(__Method_DeleteService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteService)); serviceBinder.AddMethod(__Method_CreateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.CreateServiceLevelObjective)); serviceBinder.AddMethod(__Method_GetServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.GetServiceLevelObjective)); serviceBinder.AddMethod(__Method_ListServiceLevelObjectives, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>(serviceImpl.ListServiceLevelObjectives)); serviceBinder.AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.UpdateServiceLevelObjective)); serviceBinder.AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteServiceLevelObjective)); } } } #endregion
1.101563
1
Pc/ReflowController/ReflowControllerDeviceSerial.cs
DerekGn/AVRReflowController
0
508
using Google.Protobuf; using RJCP.IO.Ports; using System; using System.IO; using System.Linq; namespace ReflowController { internal class ReflowControllerDeviceSerial : IReflowControllerDevice, IDisposable { private const int TcInputStateMask = 0x4; private object _lock = new object(); private SerialPortStream _serialPortStream; private SerialError _lastError; private SerialData _serialData; public ThermoCoupleStatus GetThermoCoupleStatus() { var response = SendRequest(new Request() { Command = Request.Types.RequestType.Tcstate }); var isOpen = (response.TcState & TcInputStateMask) > 0; var temp = (response.TcState >> 3) * 0.25; return new ThermoCoupleStatus(temp, isOpen); } public void Ping() { SendRequest(new Request() { Command = Request.Types.RequestType.Ping }); } public void SetRelayState(bool state) { SendRequest(new Request() { Command = state ? Request.Types.RequestType.Relayon : Request.Types.RequestType.Relayoff }); } public void StartProfile() { SendRequest(new Request() { Command = Request.Types.RequestType.Startprofile }); } public void StopProfile() { SendRequest(new Request() { Command = Request.Types.RequestType.Stopprofile }); } public ProfileStage GetProfileStage() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getprofilestage }).Stage; } public ReflowProfile GetReflowProfile() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getprofile }).Profile; } public void SetReflowProfile(ReflowProfile reflowProfile) { SendRequest(new Request() { Command = Request.Types.RequestType.Setprofile, Profile = reflowProfile }); } public Pid GetPid() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getpid }).PidGains; } public void SetPid(Pid pid) { SendRequest(new Request() { Command = Request.Types.RequestType.Setpid, PidGains = pid }); } public void Open(string port) { if (!SerialPortStream.GetPortNames().Contains(port)) { throw new ReflowControllerException($"Port does not exist: {port}" ); } if (_serialPortStream == null) { _serialPortStream = new SerialPortStream(port); _serialPortStream.Open(); } else throw new ReflowControllerException("Device aplready open"); } public void Close() { lock (_lock) { if (_serialPortStream != null) { _serialPortStream.Close(); _serialPortStream.Dispose(); _serialPortStream = null; } } } private Response SendRequest(Request request) { lock(_lock) { var requestBytes = request.ToByteArray(); _serialPortStream.Write(requestBytes, 0, requestBytes.Length); byte[] readBuffer = new byte[64]; int readLen = 0; if (_lastError == SerialError.NoError) { readLen = _serialPortStream.Read(readBuffer, 0, 64); } else { throw new ReflowControllerException(_lastError.ToString()); } Response response = Deserialise(readBuffer, readLen); if (response.Result == Response.Types.ResultType.Fail) { throw new ReflowControllerException($"ReflowController Error Code: {response.ErrorCode}"); } return response; } } private Response Deserialise(byte[] readBuffer, int readLen) { using (MemoryStream stream = new MemoryStream()) { stream.Write(readBuffer, 0, readLen); stream.Seek(0, SeekOrigin.Begin); return Response.Parser.ParseFrom(stream); } } private void ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { _lastError = e.EventType; } private void DataReceived(object sender, SerialDataReceivedEventArgs e) { _serialData = e.EventType; } private void PinChanged(object sender, SerialPinChangedEventArgs e) { } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } #endregion } }
1.21875
1
DataBinding/ConsoleApp1/SocketService/MainWindow.xaml.cs
TommyMerlin/CSharpLearning
0
516
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Net; using System.Net.Sockets; namespace SocketService { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } // 创建IP地址 IPAddress ip; // 创建TCP监听对象 TcpListener listener; private void Window_Loaded(object sender, RoutedEventArgs e) { } private void BtnStart_Click(object sender, RoutedEventArgs e) { ip = IPAddress.Parse(txtboxIP.Text); listener = new TcpListener(ip, Convert.ToInt32(txtboxPort.Text)); listener.Start(); txtboxInfo.Text = "服务器监听启动 " + DateTime.Now.ToString() + "\r\n" + txtboxInfo.Text; } } }
1.429688
1
Assets/Game/InGame/Components/ProjectileComponent.cs
grofit/ecsrx.schmup
1
524
using EcsRx.Components; using UnityEngine; namespace Game.InGame.Components { public class ProjectileComponent : IComponent { public Vector3 StartingPosition { get; set; } public Vector3 Direction { get; set; } public float Lifetime { get; set; } public float ElapsedTime { get; set; } public int Damage { get; set; } } }
0.777344
1
src/SuperMassive/Helpers/AssemblyHelper.cs
PulsarBlow/SuperMassive
6
532
namespace SuperMassive { using System.Reflection; /// <summary> /// Provides helping methods for manipulating assemblies /// </summary> public static class AssemblyHelper { /// <summary> /// Returns the file version of the executing assembly /// </summary> /// <returns>The file version of the executing assembly</returns> public static string? GetFileVersion() { return GetFileVersion(typeof(AssemblyHelper).Assembly); } /// <summary> /// Returns the file version of a given assembly /// </summary> /// <param name="assembly">Assembly used to get the file version</param> /// <returns>The file version of the assembly</returns> public static string? GetFileVersion(Assembly assembly) { return assembly .GetCustomAttribute<AssemblyFileVersionAttribute>()? .Version; } /// <summary> /// Returns the informational version of the executing assembly. /// </summary> /// <returns>The informational version of the assembly</returns> public static string? GetInformationalVersion() { return GetInformationalVersion(typeof(AssemblyHelper).Assembly); } /// <summary> /// Returns the informational version of the given assembly. /// </summary> /// <param name="assembly">Assembly used to get the informational version</param> /// <returns>The informational version of the assembly</returns> public static string? GetInformationalVersion(Assembly assembly) { return assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>()? .InformationalVersion; } } }
1.757813
2
BrawlLib/Modeling/Triangle Converter/Deque/Deque.cs
ilazoja/BrawlCrate
102
540
#region License /* Copyright (c) 2006 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * <NAME> * Email: <EMAIL> */ #endregion using System; using System.Collections; using System.Diagnostics; namespace BrawlLib.Modeling.Triangle_Converter.Deque { /// <summary> /// Represents a simple double-ended-queue collection of objects. /// </summary> [Serializable()] public class Deque : ICollection, IEnumerable, ICloneable { #region Deque Members #region Fields // The node at the front of the deque. private Node front; // The node at the back of the deque. private Node back; // The number of elements in the deque. private int count; // The version of the deque. private long version; #endregion #region Construction /// <summary> /// Initializes a new instance of the Deque class. /// </summary> public Deque() { } /// <summary> /// Initializes a new instance of the Deque class that contains /// elements copied from the specified collection. /// </summary> /// <param name="col"> /// The ICollection to copy elements from. /// </param> public Deque(ICollection col) { #region Require if (col == null) { throw new ArgumentNullException("col"); } #endregion foreach (object obj in col) { PushBack(obj); } } #endregion #region Methods /// <summary> /// Removes all objects from the Deque. /// </summary> public virtual void Clear() { count = 0; front = back = null; version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Determines whether or not an element is in the Deque. /// </summary> /// <param name="obj"> /// The Object to locate in the Deque. /// </param> /// <returns> /// <b>true</b> if <i>obj</i> if found in the Deque; otherwise, /// <b>false</b>. /// </returns> public virtual bool Contains(object obj) { foreach (object o in this) { if (o == null && obj == null) { return true; } if (o.Equals(obj)) { return true; } } return false; } /// <summary> /// Inserts an object at the front of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushFront(object obj) { // The new node to add to the front of the deque. Node newNode = new Node(obj) { // Link the new node to the front node. The current front node at // the front of the deque is now the second node in the deque. Next = front }; // If the deque isn't empty. if (Count > 0) { // Link the current front to the new node. front.Previous = newNode; } // Make the new node the front of the deque. front = newNode; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if (Count == 1) { // The front and back nodes are the same. back = front; } version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Inserts an object at the back of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushBack(object obj) { // The new node to add to the back of the deque. Node newNode = new Node(obj) { // Link the new node to the back node. The current back node at // the back of the deque is now the second to the last node in the // deque. Previous = back }; // If the deque is not empty. if (Count > 0) { // Link the current back node to the new node. back.Next = newNode; } // Make the new node the back of the deque. back = newNode; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if (Count == 1) { // The front and back nodes are the same. front = back; } version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Removes and returns the object at the front of the Deque. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopFront() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the front of the deque. object obj = front.Value; // Move the front back one node. front = front.Next; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if (Count > 0) { // Tie off the previous link in the front node. front.Previous = null; } // Else the deque is empty. else { // Indicate that there is no back node. back = null; } version++; #region Invariant AssertValid(); #endregion return obj; } /// <summary> /// Removes and returns the object at the back of the Deque. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopBack() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the back of the deque. object obj = back.Value; // Move back node forward one node. back = back.Previous; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if (Count > 0) { // Tie off the next link in the back node. back.Next = null; } // Else the deque is empty. else { // Indicate that there is no front node. front = null; } version++; #region Invariant AssertValid(); #endregion return obj; } /// <summary> /// Returns the object at the front of the Deque without removing it. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekFront() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return front.Value; } /// <summary> /// Returns the object at the back of the Deque without removing it. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekBack() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return back.Value; } /// <summary> /// Copies the Deque to a new array. /// </summary> /// <returns> /// A new array containing copies of the elements of the Deque. /// </returns> public virtual object[] ToArray() { object[] array = new object[Count]; int index = 0; foreach (object obj in this) { array[index] = obj; index++; } return array; } /// <summary> /// Returns a synchronized (thread-safe) wrapper for the Deque. /// </summary> /// <param name="deque"> /// The Deque to synchronize. /// </param> /// <returns> /// A synchronized wrapper around the Deque. /// </returns> public static Deque Synchronized(Deque deque) { #region Require if (deque == null) { throw new ArgumentNullException("deque"); } #endregion return new SynchronizedDeque(deque); } [Conditional("DEBUG")] private void AssertValid() { int n = 0; Node current = front; while (current != null) { n++; current = current.Next; } Debug.Assert(n == Count); if (Count > 0) { Debug.Assert(front != null && back != null, "Front/Back Null Test - Count > 0"); Node f = front; Node b = back; while (f.Next != null && b.Previous != null) { f = f.Next; b = b.Previous; } Debug.Assert(f.Next == null && b.Previous == null, "Front/Back Termination Test"); Debug.Assert(f == back && b == front, "Front/Back Equality Test"); } else { Debug.Assert(front == null && back == null, "Front/Back Null Test - Count == 0"); } } #endregion #region Node Class // Represents a node in the deque. [Serializable()] private class Node { private readonly object value; private Node previous; private Node next; public Node(object value) { this.value = value; } public object Value => value; public Node Previous { get => previous; set => previous = value; } public Node Next { get => next; set => next = value; } } #endregion #region DequeEnumerator Class [Serializable()] private class DequeEnumerator : IEnumerator { private readonly Deque owner; private Node currentNode; private object current; private bool moveResult; private readonly long version; public DequeEnumerator(Deque owner) { this.owner = owner; currentNode = owner.front; version = owner.version; } #region IEnumerator Members public void Reset() { #region Require if (version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion currentNode = owner.front; moveResult = false; } public object Current { get { #region Require if (!moveResult) { throw new InvalidOperationException( "The enumerator is positioned before the first " + "element of the Deque or after the last element."); } #endregion return current; } } public bool MoveNext() { #region Require if (version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion if (currentNode != null) { current = currentNode.Value; currentNode = currentNode.Next; moveResult = true; } else { moveResult = false; } return moveResult; } #endregion } #endregion #region SynchronizedDeque Class // Implements a synchronization wrapper around a deque. [Serializable()] private class SynchronizedDeque : Deque { #region SynchronziedDeque Members #region Fields // The wrapped deque. private readonly Deque deque; // The object to lock on. private readonly object root; #endregion #region Construction public SynchronizedDeque(Deque deque) { #region Require if (deque == null) { throw new ArgumentNullException("deque"); } #endregion this.deque = deque; root = deque.SyncRoot; } #endregion #region Methods public override void Clear() { lock (root) { deque.Clear(); } } public override bool Contains(object obj) { bool result; lock (root) { result = deque.Contains(obj); } return result; } public override void PushFront(object obj) { lock (root) { deque.PushFront(obj); } } public override void PushBack(object obj) { lock (root) { deque.PushBack(obj); } } public override object PopFront() { object obj; lock (root) { obj = deque.PopFront(); } return obj; } public override object PopBack() { object obj; lock (root) { obj = deque.PopBack(); } return obj; } public override object PeekFront() { object obj; lock (root) { obj = deque.PeekFront(); } return obj; } public override object PeekBack() { object obj; lock (root) { obj = deque.PeekBack(); } return obj; } public override object[] ToArray() { object[] array; lock (root) { array = deque.ToArray(); } return array; } public override object Clone() { object clone; lock (root) { clone = deque.Clone(); } return clone; } public override void CopyTo(Array array, int index) { lock (root) { deque.CopyTo(array, index); } } public override IEnumerator GetEnumerator() { IEnumerator e; lock (root) { e = deque.GetEnumerator(); } return e; } #endregion #region Properties public override int Count { get { lock (root) { return deque.Count; } } } public override bool IsSynchronized => true; #endregion #endregion } #endregion #endregion #region ICollection Members /// <summary> /// Gets a value indicating whether access to the Deque is synchronized /// (thread-safe). /// </summary> public virtual bool IsSynchronized => false; /// <summary> /// Gets the number of elements contained in the Deque. /// </summary> public virtual int Count => count; /// <summary> /// Copies the Deque elements to an existing one-dimensional Array, /// starting at the specified array index. /// </summary> /// <param name="array"> /// The one-dimensional Array that is the destination of the elements /// copied from Deque. The Array must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in array at which copying begins. /// </param> public virtual void CopyTo(Array array, int index) { #region Require if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", index, "Index is less than zero."); } if (array.Rank > 1) { throw new ArgumentException("Array is multidimensional."); } if (index >= array.Length) { throw new ArgumentException("Index is equal to or greater " + "than the length of array."); } if (Count > array.Length - index) { throw new ArgumentException( "The number of elements in the source Deque is greater " + "than the available space from index to the end of the " + "destination array."); } #endregion int i = index; foreach (object obj in this) { array.SetValue(obj, i); i++; } } /// <summary> /// Gets an object that can be used to synchronize access to the Deque. /// </summary> public virtual object SyncRoot => this; #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that can iterate through the Deque. /// </summary> /// <returns> /// An IEnumerator for the Deque. /// </returns> public virtual IEnumerator GetEnumerator() { return new DequeEnumerator(this); } #endregion #region ICloneable Members /// <summary> /// Creates a shallow copy of the Deque. /// </summary> /// <returns> /// A shallow copy of the Deque. /// </returns> public virtual object Clone() { Deque clone = new Deque(this) { version = version }; return clone; } #endregion } }
1.695313
2
Web/Db/Enums/PpeTypes.cs
WeAreBeep/FrontlineUkraine
0
548
using System.Collections.Generic; using System.Collections.Immutable; using Web.Snippets.System; namespace Web.Db { public enum PpeTypes { [EnumText("Type IIR Surgical Masks")] TypeIIRSurgicalMasks = 1, [EnumText("FFP1 Respirator Masks")] FFP1RespiratorMasks, [EnumText("FFP2 Respirator Masks")] FFP2RespiratorMasks, [EnumText("FFP3 Respirator Masks")] FFP3RespiratorMasks, Gowns, Aprons, Gloves, Scrubs, SafetyGlasses, FaceVisors, AlcoholHandGel, [EnumText("Other...")] Other, // Domestic - Sanitary [EnumText("Sanitary Towels (Tampons/Pads)")] DomesticSanitarySanitaryTowels, [EnumText("Nappies Size 0 (1-2.5kg, 2-5lbs")] DomesticSanitaryNappiesSize0, [EnumText("Nappies Size 1 (2 -5kg, 5-11lbs")] DomesticSanitaryNappiesSize1, [EnumText("Nappies Size 2 (3-6kg, 7-14lbs")] DomesticSanitaryNappiesSize2, [EnumText("Nappies Size 3 (4-9kg, 8-20lbs")] DomesticSanitaryNappiesSize3, [EnumText("Nappies Size 4 (7-18kg, 15-40lbs")] DomesticSanitaryNappiesSize4, [EnumText("Nappies Size 5 (11-25kg, 24-55lbs")] DomesticSanitaryNappiesSize5, [EnumText("Nappies Size 6 (16kg +, 35lbs +)")] DomesticSanitaryNappiesSize6, [EnumText("Breast pads (for breastfeeding mothers)")] DomesticSanitaryBreastPads, [EnumText("Hairbrushes")] DomesticSanitaryHairbrushes, [EnumText("Liquid soap/ Shampoo")] DomesticSanitaryLiquidSoap, [EnumText("Wet wipes (adults/children)")] DomesticSanitaryWetWipes, [EnumText("Toothbrushes")] DomesticSanitaryToothbrushes, [EnumText("Toothpaste")] DomesticSanitaryToothpaste, [EnumText("Towels")] DomesticSanitaryTowels, [EnumText("Toilet paper")] DomesticSanitaryToiletPaper, [EnumText("Pocket tissues")] DomesticSanitaryPocketTissues, [EnumText("Shaving gels and razors")] DomesticSanitaryShavingGelRazors, [EnumText("Other sanitary products")] DomesticSanitaryOther, // Domestic - Non perishable food/ drink [EnumText("Protein bars")] DomesticNonPerishableFoodDrinkProteinBars, [EnumText("Canned food")] DomesticNonPerishableFoodDrinkCannedFood, [EnumText("Dry food (i.e.: rice, pasta, nuts, dried fruit) / Fast cooking grains (couscous)")] DomesticNonPerishableFoodDrinkDryFood, [EnumText("Instant food (i.e.: Cup-a-soups)")] DomesticNonPerishableFoodDrinkInstantFood, [EnumText("Baby food (i.e.: powdered milk, ready-meal pouches)")] DomesticNonPerishableFoodDrinkBabyFood, [EnumText("Energy drinks")] DomesticNonPerishableFoodDrinkEnergyDrinks, [EnumText("Other (please specify)")] DomesticNonPerishableOther, // Domestic - Other [EnumText("Foil survival blankets")] DomesticOtherFoilSurvivalBlankets, [EnumText("Thermal clothing (new)")] DomesticOtherThermalClothingNew, [EnumText("Sleeping bags")] DomesticOtherSleepingBags, [EnumText("Bed (Hospital use)")] DomesticOtherBedHospital, [EnumText("Large/medium-sized backpacks")] DomesticOtherLargeOrMediumBackpacks, [EnumText("Power banks and charging cables")] DomesticOtherPowerBanksAndChargingCables, [EnumText("Torches with batteries/ Head torches (in sealed packs)")] DomesticOtherTorches, [EnumText("Electricity generators")] DomesticOtherElectricityGenerators, [EnumText("Boot driers")] DomesticOtherBootDriers, [EnumText("Hot water bottles")] DomesticOtherHotWaterBottles, [EnumText("Insulated flasks")] DomesticOtherInsulatedFlasks, [EnumText("Disposable tableware (cup, plates, cutlery)")] DomesticOtherDisposableTableware, [EnumText("Cooking stoves (without gas)")] DomesticOtherCookingStoves, [EnumText("Bin bags")] DomesticOtherBinBags, [EnumText("Other basics")] DomesticOtherOther, // (Non Drug) Medical Supplies - Equipment [EnumText("PATIENT MONITOR, w/CO2 IBP ECG NIBP TEMP, SPO2, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentPatientMonitor, [EnumText("ANAESTHESIA MACHINE, closed-circuit, trolley, w/acc")] NonDrugMedicalSuppliesMedicalEquipmentAnaesthesiaMachine, [EnumText("ECG RECORDER, portable, 12 leads, with printer and access")] NonDrugMedicalSuppliesMedicalEquipmentECGRecorder, [EnumText("DEFIBRILLATOR, AED, w/access")] NonDrugMedicalSuppliesMedicalEquipmentDefibrillator, [EnumText("SYRINGE PUMP, single-channel, AC and battery-powered, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentSyringePump, [EnumText("INFUSION PUMP, LCD, flow 0.1-1500mL/h, 220V, batt., w/acc")] NonDrugMedicalSuppliesMedicalEquipmentInfusionPump, [EnumText("EXAMINATION LIGHT, Led, overhead, mobile, adjustable, on wheels")] NonDrugMedicalSuppliesMedicalEquipmentExaminationLightLed, [EnumText("PUMP, SUCTION, FOOT-OPERATED, with tubes and connector")] NonDrugMedicalSuppliesMedicalEquipmentFootOperatedSuctionPump, [EnumText("PATIENT VENTILATOR, intensive care, for adult and paediatric, with breathing circuits and patient interface (TYPE 2)")] NonDrugMedicalSuppliesMedicalEquipmentPatientVentilator, [EnumText("SCANNER, ULTRASOUND, mobile, w/access")] NonDrugMedicalSuppliesMedicalEquipmentMobileUltrasoundScanner, [EnumText("SELF-INFLATING BAG SET, self-refilling, capacity > 1500 m adult + 3 masks (S, M, L)")] NonDrugMedicalSuppliesMedicalEquipmentSelfInflatingBagSet, [EnumText("CAPNOMETER portable, EtCO2/RR monitoring, AAA battery, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentCapnometer, [EnumText("X-RAY UNIT BASIC, mobile")] NonDrugMedicalSuppliesMedicalEquipmentXRayUnit, [EnumText("SURGICAL DRILL, cordless +accessories + drill bit")] NonDrugMedicalSuppliesMedicalEquipmentSurgicalDrill, [EnumText("DERMATOME, ELECTRICAL with battery + access.")] NonDrugMedicalSuppliesMedicalEquipmentDermatome, [EnumText("LEG TRACTION SPLINT, pre-hospital care and transport")] NonDrugMedicalSuppliesMedicalEquipmentLegTractionSplint, [EnumText("OTHER (please specify)")] NonDrugMedicalSuppliesMedicalEquipmentOther, // (Non Drug) Medical Supplies - Consumables [EnumText("Medical tourniquets")] NonDrugMedicalSuppliesConsumablesMedicalTourniquets, [EnumText("First aid kits (bandages, plasters, antiseptic creams, burn gels, micropore tape)")] NonDrugMedicalSuppliesConsumablesFirstAidKits, [EnumText("Viral bacterial filters & circuits for mechanical ventilation")] NonDrugMedicalSuppliesConsumablesViralBacteriaFilter, [EnumText("CENTRAL VENOUS CATHETERS, Y and straight needle, triple lumen")] NonDrugMedicalSuppliesConsumablesCentralVenousCatheters, [EnumText("SET, INTRAOSSEOUS INFUSION KIT, w/ needles and IV set")] NonDrugMedicalSuppliesConsumablesSetIntraosseousInfusionKit, [EnumText("SET, INFUSION, adult, sterile, s.u.")] NonDrugMedicalSuppliesConsumablesSetInfusionAdult, [EnumText("SET, INFUSION, paediatric, precision, sterile, s.u.")] NonDrugMedicalSuppliesConsumablesSetInfusionPaediatric, [EnumText("DRAIN, THORACIC, INSERTION-SET, complete, sterile, disposable")] NonDrugMedicalSuppliesConsumablesDrainThoracicInsertionSet, [EnumText("Insulin syringes/needles")] NonDrugMedicalSuppliesConsumablesInsulinSyringes, [EnumText("Syringe pens for diabetics")] NonDrugMedicalSuppliesConsumablesSyringePensDiabetics, [EnumText("Glucometers with test strips")] NonDrugMedicalSuppliesConsumablesGlucometers, [EnumText("X-ray cartridges")] NonDrugMedicalSuppliesConsumablesXRayCartridges, [EnumText("[(Non Drug) Medical Supplies - Consumables] OTHER (please specify)")] NonDrugMedicalSuppliesConsumablesOther, // (Non Drug) Medical Supplies - Surgical Instruments & Fixators [EnumText("SET, GENERAL SURGERY INSTRUMENTS, BASIC SURGERY")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsBasicSurgery, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DRESSING")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDressing, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, CRANIOTOMY,")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsCraniotomy, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, LAPAROTOMY, + caesarean")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsLaparotomyAndCaesarean, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DPC (suture)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDPCSuture, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DEBRIDEMENT")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDebridement, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, SKIN GRAFT")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsSkinGraft, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, FINE (paediatrics)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsFinePaediatrics, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, THORACOTOMY, complementary")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsThoracotomyComplementary, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, AMPUTATION")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsAmputation, [EnumText("SET, ORTHO.SURGERY INSTRUMENTS, BASIC BONE SURGERY")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgery, [EnumText("SET, ORTHO.SURGERY INSTRUMENTS, BASIC BONE SURGERY, curettes")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgeryCurettes, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, BONE WIRING and KIRSHNER")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBoneWiringAndKirshner, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, PLASTER CASTS REMOVAL")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsPlasterCastsRemoval, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, TRACTION, + 10 bows")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsTractionPlusTenBows, [EnumText("SET, EXTERNAL FIXATION, LARGE, FIXATORS & INSTRUMENTS")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetExternalFixationLargeFixatorsAndInstruments, [EnumText("OTHER (please specify)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther } public static class PpeTypesEnumExtension { private static List<PpeTypes> OTHER_PPE_TYPES = new List<PpeTypes> { PpeTypes.Other, PpeTypes.DomesticSanitaryOther, PpeTypes.DomesticNonPerishableOther, PpeTypes.DomesticOtherOther, PpeTypes.NonDrugMedicalSuppliesConsumablesOther, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentOther, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther }; public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticSanitary = new HashSet<PpeTypes> { PpeTypes.DomesticSanitarySanitaryTowels, PpeTypes.DomesticSanitaryNappiesSize0, PpeTypes.DomesticSanitaryNappiesSize1, PpeTypes.DomesticSanitaryNappiesSize2, PpeTypes.DomesticSanitaryNappiesSize3, PpeTypes.DomesticSanitaryNappiesSize4, PpeTypes.DomesticSanitaryNappiesSize5, PpeTypes.DomesticSanitaryNappiesSize6, PpeTypes.DomesticSanitaryBreastPads, PpeTypes.DomesticSanitaryHairbrushes, PpeTypes.DomesticSanitaryLiquidSoap, PpeTypes.DomesticSanitaryWetWipes, PpeTypes.DomesticSanitaryToothbrushes, PpeTypes.DomesticSanitaryToothpaste, PpeTypes.DomesticSanitaryTowels, PpeTypes.DomesticSanitaryToiletPaper, PpeTypes.DomesticSanitaryPocketTissues, PpeTypes.DomesticSanitaryShavingGelRazors, PpeTypes.DomesticSanitaryOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticNonPerishableFoodDrink = new HashSet<PpeTypes> { PpeTypes.DomesticNonPerishableFoodDrinkProteinBars, PpeTypes.DomesticNonPerishableFoodDrinkCannedFood, PpeTypes.DomesticNonPerishableFoodDrinkDryFood, PpeTypes.DomesticNonPerishableFoodDrinkInstantFood, PpeTypes.DomesticNonPerishableFoodDrinkBabyFood, PpeTypes.DomesticNonPerishableFoodDrinkEnergyDrinks, PpeTypes.DomesticNonPerishableOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticOther = new HashSet<PpeTypes> { PpeTypes.DomesticOtherFoilSurvivalBlankets, PpeTypes.DomesticOtherThermalClothingNew, PpeTypes.DomesticOtherSleepingBags, PpeTypes.DomesticOtherBedHospital, PpeTypes.DomesticOtherLargeOrMediumBackpacks, PpeTypes.DomesticOtherPowerBanksAndChargingCables, PpeTypes.DomesticOtherTorches, PpeTypes.DomesticOtherElectricityGenerators, PpeTypes.DomesticOtherBootDriers, PpeTypes.DomesticOtherHotWaterBottles, PpeTypes.DomesticOtherInsulatedFlasks, PpeTypes.DomesticOtherDisposableTableware, PpeTypes.DomesticOtherCookingStoves, PpeTypes.DomesticOtherBinBags, PpeTypes.DomesticOtherOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesEquip = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentPatientMonitor, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentAnaesthesiaMachine, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentECGRecorder, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentDefibrillator, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSyringePump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentInfusionPump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentExaminationLightLed, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentFootOperatedSuctionPump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentPatientVentilator, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentMobileUltrasoundScanner, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSelfInflatingBagSet, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentCapnometer, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentXRayUnit, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSurgicalDrill, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentDermatome, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentLegTractionSplint, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesConsumable = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesConsumablesMedicalTourniquets, PpeTypes.NonDrugMedicalSuppliesConsumablesFirstAidKits, PpeTypes.NonDrugMedicalSuppliesConsumablesViralBacteriaFilter, PpeTypes.NonDrugMedicalSuppliesConsumablesCentralVenousCatheters, PpeTypes.NonDrugMedicalSuppliesConsumablesSetIntraosseousInfusionKit, PpeTypes.NonDrugMedicalSuppliesConsumablesSetInfusionAdult, PpeTypes.NonDrugMedicalSuppliesConsumablesSetInfusionPaediatric, PpeTypes.NonDrugMedicalSuppliesConsumablesDrainThoracicInsertionSet, PpeTypes.NonDrugMedicalSuppliesConsumablesInsulinSyringes, PpeTypes.NonDrugMedicalSuppliesConsumablesSyringePensDiabetics, PpeTypes.NonDrugMedicalSuppliesConsumablesGlucometers, PpeTypes.NonDrugMedicalSuppliesConsumablesXRayCartridges, PpeTypes.NonDrugMedicalSuppliesConsumablesOther, }.ToImmutableHashSet(); public static ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesSurgicalInstrumentsAndFixators = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsBasicSurgery, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDressing, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsCraniotomy, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsLaparotomyAndCaesarean, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDPCSuture, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDebridement, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsSkinGraft, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsFinePaediatrics, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsThoracotomyComplementary, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsAmputation, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgery, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgeryCurettes, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBoneWiringAndKirshner, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsPlasterCastsRemoval, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsTractionPlusTenBows, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetExternalFixationLargeFixatorsAndInstruments, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesPpe = new HashSet<PpeTypes> { PpeTypes.TypeIIRSurgicalMasks, PpeTypes.FFP1RespiratorMasks, PpeTypes.FFP2RespiratorMasks, PpeTypes.FFP3RespiratorMasks, PpeTypes.Gowns, PpeTypes.Aprons, PpeTypes.Gloves, PpeTypes.Scrubs, PpeTypes.SafetyGlasses, PpeTypes.FaceVisors, PpeTypes.AlcoholHandGel, PpeTypes.Other, }.ToImmutableHashSet(); public static readonly List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> DomesticCategories = new List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> { (Name: "SANITARY PRODUCTS", CategorySet: CategoryDomesticSanitary), (Name: "NON-PERISHABLE FOOD/DRINK", CategorySet: CategoryDomesticNonPerishableFoodDrink), (Name: "OTHER BASICS / SHELTER EQUIPMENT", CategorySet: CategoryDomesticOther), }; public static readonly List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> NonDrugMedicalSuppliesCategory = new List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> { (Name: "MEDICAL EQUIPMENT", CategorySet: CategoryNonDrugMedicalSuppliesEquip), (Name: "CONSUMABLES", CategorySet: CategoryNonDrugMedicalSuppliesConsumable), (Name: "SURGICAL INSTRUMENTS & FIXATORS", CategorySet: CategoryNonDrugMedicalSuppliesSurgicalInstrumentsAndFixators), (Name: "PPE", CategorySet: CategoryNonDrugMedicalSuppliesPpe), }; public static bool IsOther(this PpeTypes ppeType) { return PpeTypesEnumExtension.OTHER_PPE_TYPES.Contains(ppeType); } } }
0.875
1
MonkeyWorks/Unmanaged/Headers/Winnt.cs
NetSPI/MonkeyWorks
52
556
using System; using System.Runtime.InteropServices; using WORD = System.UInt16; using LONG = System.UInt32; using DWORD = System.UInt32; using QWORD = System.UInt64; using ULONGLONG = System.UInt64; using LARGE_INTEGER = System.UInt64; using PSID = System.IntPtr; using PVOID = System.IntPtr; using LPVOID = System.IntPtr; using DWORD_PTR = System.IntPtr; using SIZE_T = System.IntPtr; namespace MonkeyWorks.Unmanaged.Headers { sealed class Winnt { //Token //http://www.pinvoke.net/default.aspx/advapi32.openprocesstoken public const DWORD STANDARD_RIGHTS_REQUIRED = 0x000F0000; public const DWORD STANDARD_RIGHTS_READ = 0x00020000; public const DWORD TOKEN_ASSIGN_PRIMARY = 0x0001; public const DWORD TOKEN_DUPLICATE = 0x0002; public const DWORD TOKEN_IMPERSONATE = 0x0004; public const DWORD TOKEN_QUERY = 0x0008; public const DWORD TOKEN_QUERY_SOURCE = 0x0010; public const DWORD TOKEN_ADJUST_PRIVILEGES = 0x0020; public const DWORD TOKEN_ADJUST_GROUPS = 0x0040; public const DWORD TOKEN_ADJUST_DEFAULT = 0x0080; public const DWORD TOKEN_ADJUST_SESSIONID = 0x0100; public const DWORD TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); public const DWORD TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID); public const DWORD TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY); //TOKEN_PRIVILEGES //https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx public const DWORD SE_PRIVILEGE_ENABLED = 0x2; public const DWORD SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1; public const DWORD SE_PRIVILEGE_REMOVED = 0x4; public const DWORD SE_PRIVILEGE_USED_FOR_ACCESS = 0x3; public const Int32 ANYSIZE_ARRAY = 1; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa446619(v=vs.85).aspx public const String SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; public const String SE_BACKUP_NAME = "SeBackupPrivilege"; public const String SE_DEBUG_NAME = "SeDebugPrivilege"; public const String SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; public const String SE_TCB_NAME = "SeTcbPrivilege"; public const QWORD SE_GROUP_ENABLED = 0x00000004L; public const QWORD SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002L; public const QWORD SE_GROUP_INTEGRITY = 0x00000020L; public const QWORD SE_GROUP_INTEGRITY_32 = 0x00000020; public const QWORD SE_GROUP_INTEGRITY_ENABLED = 0x00000040L; public const QWORD SE_GROUP_LOGON_ID = 0xC0000000L; public const QWORD SE_GROUP_MANDATORY = 0x00000001L; public const QWORD SE_GROUP_OWNER = 0x00000008L; public const QWORD SE_GROUP_RESOURCE = 0x20000000L; public const QWORD SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010L; //https://msdn.microsoft.com/en-us/library/windows/desktop/aa446583%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 public const DWORD DISABLE_MAX_PRIVILEGE = 0x1; public const DWORD SANDBOX_INERT = 0x2; public const DWORD LUA_TOKEN = 0x4; public const DWORD WRITE_RESTRICTED = 0x8; private const DWORD EXCEPTION_MAXIMUM_PARAMETERS = 15; [Flags] // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx public enum MEMORY_PROTECTION_CONSTANTS : uint { PAGE_NOACCESS = 0x01, PAGE_READONLY = 0x02, PAGE_READWRITE = 0x04, PAGE_WRITECOPY = 0x08, PAGE_EXECUTE = 0x10, PAGE_EXECUTE_READ = 0x20, PAGE_EXECUTE_READWRITE = 0x40, PAGE_EXECUTE_WRITECOPY = 0x80, PAGE_GUARD = 0x100, PAGE_NOCACHE = 0x200, PAGE_WRITECOMBINE = 0x400, PAGE_TARGETS_INVALID = 0x40000000, PAGE_TARGETS_NO_UPDATE = 0x40000000 } [Flags] //https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx public enum TokenPrivileges : uint { SE_PRIVILEGE_NONE = 0x0, SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1, SE_PRIVILEGE_ENABLED = 0x2, SE_PRIVILEGE_REMOVED = 0x4, SE_PRIVILEGE_USED_FOR_ACCESS = 0x3 } [Flags] public enum ACCESS_MASK : uint { DELETE = 0x00010000, READ_CONTROL = 0x00020000, WRITE_DAC = 0x00040000, WRITE_OWNER = 0x00080000, SYNCHRONIZE = 0x00100000, STANDARD_RIGHTS_REQUIRED = 0x000F0000, STANDARD_RIGHTS_READ = 0x00020000, STANDARD_RIGHTS_WRITE = 0x00020000, STANDARD_RIGHTS_EXECUTE = 0x00020000, STANDARD_RIGHTS_ALL = 0x001F0000, SPECIFIC_RIGHTS_ALL = 0x0000FFF, ACCESS_SYSTEM_SECURITY = 0x01000000, MAXIMUM_ALLOWED = 0x02000000, GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000, GENERIC_EXECUTE = 0x20000000, GENERIC_ALL = 0x10000000, DESKTOP_READOBJECTS = 0x00000001, DESKTOP_CREATEWINDOW = 0x00000002, DESKTOP_CREATEMENU = 0x00000004, DESKTOP_HOOKCONTROL = 0x00000008, DESKTOP_JOURNALRECORD = 0x00000010, DESKTOP_JOURNALPLAYBACK = 0x00000020, DESKTOP_ENUMERATE = 0x00000040, DESKTOP_WRITEOBJECTS = 0x00000080, DESKTOP_SWITCHDESKTOP = 0x00000100, WINSTA_ENUMDESKTOPS = 0x00000001, WINSTA_READATTRIBUTES = 0x00000002, WINSTA_ACCESSCLIPBOARD = 0x00000004, WINSTA_CREATEDESKTOP = 0x00000008, WINSTA_WRITEATTRIBUTES = 0x00000010, WINSTA_ACCESSGLOBALATOMS = 0x00000020, WINSTA_EXITWINDOWS = 0x00000040, WINSTA_ENUMERATE = 0x00000100, WINSTA_READSCREEN = 0x00000200, WINSTA_ALL_ACCESS = 0x0000037F }; [StructLayout(LayoutKind.Sequential)] public struct CONTEXT { public CONTEXT_FLAGS ContextFlags; // Retrieved by CONTEXT_DEBUG_REGISTERS public uint Dr0; public uint Dr1; public uint Dr2; public uint Dr3; public uint Dr6; public uint Dr7; // Retrieved by CONTEXT_FLOATING_POINT public _FLOATING_SAVE_AREA FloatSave; // Retrieved by CONTEXT_SEGMENTS public uint SegGs; public uint SegFs; public uint SegEs; public uint SegDs; // Retrieved by CONTEXT_INTEGER public uint Edi; public uint Esi; public uint Ebx; public uint Edx; public uint Ecx; public uint Eax; // Retrieved by CONTEXT_CONTROL public uint Ebp; public uint Eip; public uint SegCs; public uint EFlags; public uint Esp; public uint SegSs; // Retrieved by CONTEXT_EXTENDED_REGISTERS [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)] public byte[] ExtendedRegisters; } [StructLayout(LayoutKind.Sequential)] public struct CONTEXT64 { public ulong P1Home; public ulong P2Home; public ulong P3Home; public ulong P4Home; public ulong P5Home; public ulong P6Home; public CONTEXT_FLAGS64 ContextFlags; public uint MxCsr; public ushort SegCs; public ushort SegDs; public ushort SegEs; public ushort SegFs; public ushort SegGs; public ushort SegSs; public uint EFlags; public ulong Dr0; public ulong Dr1; public ulong Dr2; public ulong Dr3; public ulong Dr6; public ulong Dr7; public ulong Rax; public ulong Rcx; public ulong Rdx; public ulong Rbx; public ulong Rsp; public ulong Rbp; public ulong Rsi; public ulong Rdi; public ulong R8; public ulong R9; public ulong R10; public ulong R11; public ulong R12; public ulong R13; public ulong R14; public ulong R15; public ulong Rip; public _XMM_SAVE_AREA32 FltSave; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] public _M128A[] VectorRegister; public ulong VectorControl; public ulong DebugControl; public ulong LastBranchToRip; public ulong LastBranchFromRip; public ulong LastExceptionToRip; public ulong LastExceptionFromRip; } [Flags] public enum CONTEXT_FLAGS : uint { CONTEXT_i386 = 0x10000, CONTEXT_i486 = 0x10000, // same as i386 CONTEXT_CONTROL = CONTEXT_i386 | 0x0001, // SS:SP, CS:IP, FLAGS, BP CONTEXT_INTEGER = CONTEXT_i386 | 0x0002, // AX, BX, CX, DX, SI, DI CONTEXT_SEGMENTS = CONTEXT_i386 | 0x0004, // DS, ES, FS, GS CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x0008, // 387 state CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x0010, // DB 0-3,6,7 CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x0020, // cpu specific extensions CONTEXT_FULL = 65543,//CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS, CONTEXT_ALL = 65599//CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS } [Flags] public enum CONTEXT_FLAGS64 : uint { CONTEXT_AMD64 = 0x100000, CONTEXT_CONTROL = CONTEXT_AMD64 | 0x01, // SS:SP, CS:IP, FLAGS, BP CONTEXT_INTEGER = CONTEXT_AMD64 | 0x02, // AX, BX, CX, DX, SI, DI CONTEXT_SEGMENTS = CONTEXT_AMD64 | 0x04, // DS, ES, FS, GS CONTEXT_FLOATING_POINT = CONTEXT_AMD64 | 0x08, // 387 state CONTEXT_DEBUG_REGISTERS = CONTEXT_AMD64 | 0x10, // DB 0-3,6,7 CONTEXT_EXTENDED_REGISTERS = CONTEXT_AMD64 | 0x20, // cpu specific extensions CONTEXT_FULL = 1048587,//CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS, CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS } [StructLayout(LayoutKind.Sequential)] public struct _EXCEPTION_POINTERS { public System.IntPtr ExceptionRecord; public System.IntPtr ContextRecord; } [StructLayout(LayoutKind.Sequential)] public struct _EXCEPTION_RECORD { public DWORD ExceptionCode; public DWORD ExceptionFlags; public System.IntPtr hExceptionRecord; public PVOID ExceptionAddress; public DWORD NumberParameters; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)] public DWORD[] ExceptionInformation; } [StructLayout(LayoutKind.Sequential)] public struct _FLOATING_SAVE_AREA { public DWORD ControlWord; public DWORD StatusWord; public DWORD TagWord; public DWORD ErrorOffset; public DWORD ErrorSelector; public DWORD DataOffset; public DWORD DataSelector; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)] public byte[] RegisterArea; public DWORD Cr0NpxState; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct _IMAGE_BASE_RELOCATION { public DWORD VirtualAdress; public DWORD SizeOfBlock; } [Flags] public enum RelocationTypes : ushort { IMAGE_REL_BASED_ABSOLUTE = 0, IMAGE_REL_BASED_HIGH = 1, IMAGE_REL_BASED_LOW = 2, IMAGE_REL_BASED_HIGHLOW = 3, IMAGE_REL_BASED_HIGHADJ = 4, IMAGE_REL_BASED_MIPS_JMPADDR = 5, IMAGE_REL_BASED_ARM_MOV32 = 5, IMAGE_REL_BASED_SECTION = 6, IMAGE_REL_BASED_REL32 = 7, IMAGE_REL_BASED_THUMB_MOV32 = 7, IMAGE_REL_BASED_IA64_IMM64 = 9, IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, IMAGE_REL_BASED_DIR64 = 10 } [Flags] public enum TypeOffset : ushort { IMAGE_REL_BASED_ABSOLUTE = 0, IMAGE_REL_BASED_HIGH = 1, IMAGE_REL_BASED_LOW = 2, IMAGE_REL_BASED_HIGHLOW = 3, IMAGE_REL_BASED_HIGHADJ = 4, IMAGE_REL_BASED_MIPS_JMPADDR = 5, IMAGE_REL_BASED_ARM_MOV32A = 5, IMAGE_REL_BASED_ARM_MOV32 = 5, IMAGE_REL_BASED_SECTION = 6, IMAGE_REL_BASED_REL = 7, IMAGE_REL_BASED_ARM_MOV32T = 7, IMAGE_REL_BASED_THUMB_MOV32 = 7, IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, IMAGE_REL_BASED_IA64_IMM64 = 9, IMAGE_REL_BASED_DIR64 = 10, IMAGE_REL_BASED_HIGH3ADJ = 11 } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct _IMAGE_DATA_DIRECTORY { public DWORD VirtualAddress; public DWORD Size; }; [StructLayout(LayoutKind.Sequential, Pack = 1)] //https://www.nirsoft.net/kernel_struct/vista/IMAGE_DOS_HEADER.html public struct _IMAGE_DOS_HEADER { public WORD e_magic; public WORD e_cblp; public WORD e_cp; public WORD e_crlc; public WORD e_cparhdr; public WORD e_minalloc; public WORD e_maxalloc; public WORD e_ss; public WORD e_sp; public WORD e_csum; public WORD e_ip; public WORD e_cs; public WORD e_lfarlc; public WORD e_ovno; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public WORD[] e_res; public WORD e_oemid; public WORD e_oeminfo; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public WORD[] e_res2; public LONG e_lfanew; }; [StructLayout(LayoutKind.Sequential, Pack = 1)] //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_nt_headers public struct _IMAGE_NT_HEADERS { public DWORD Signature; public _IMAGE_FILE_HEADER FileHeader; public _IMAGE_OPTIONAL_HEADER OptionalHeader; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct _IMAGE_NT_HEADERS64 { public DWORD Signature; public _IMAGE_FILE_HEADER FileHeader; public _IMAGE_OPTIONAL_HEADER64 OptionalHeader; } [StructLayout(LayoutKind.Sequential, Pack = 1)] //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_file_header public struct _IMAGE_FILE_HEADER { public IMAGE_FILE_MACHINE Machine; public WORD NumberOfSections; public DWORD TimeDateStamp; public DWORD PointerToSymbolTable; public DWORD NumberOfSymbols; public WORD SizeOfOptionalHeader; public CHARACTERISTICS Characteristics; } [Flags] public enum IMAGE_FILE_MACHINE : ushort { IMAGE_FILE_MACHINE_I386 = 0x014c, IMAGE_FILE_MACHINE_IA64 = 0x0200, IMAGE_FILE_MACHINE_AMD64 = 0x8664, } [Flags] public enum CHARACTERISTICS : ushort { IMAGE_FILE_RELOCS_STRIPPED = 0x0001, IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002, IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004, IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008, IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010, IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020, IMAGE_FILE_BYTES_REVERSED_LO = 0x0080, IMAGE_FILE_32BIT_MACHINE = 0x0100, IMAGE_FILE_DEBUG_STRIPPED = 0x0200, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400, IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800, IMAGE_FILE_SYSTEM = 0x1000, IMAGE_FILE_DLL = 0x2000, IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000, IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 } [StructLayout(LayoutKind.Sequential, Pack = 1)] //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_optional_header public struct _IMAGE_OPTIONAL_HEADER { public MAGIC Magic; public Byte MajorLinkerVersion; public Byte MinorLinkerVersion; public DWORD SizeOfCode; public DWORD SizeOfInitializedData; public DWORD SizeOfUninitializedData; public DWORD AddressOfEntryPoint; public DWORD BaseOfCode; public DWORD BaseOfData; public DWORD ImageBase; public DWORD SectionAlignment; public DWORD FileAlignment; public WORD MajorOperatingSystemVersion; public WORD MinorOperatingSystemVersion; public WORD MajorImageVersion; public WORD MinorImageVersion; public WORD MajorSubsystemVersion; public WORD MinorSubsystemVersion; public DWORD Win32VersionValue; public DWORD SizeOfImage; public DWORD SizeOfHeaders; public DWORD CheckSum; public SUBSYSTEM Subsystem; public DLL_CHARACTERISTICS DllCharacteristics; public DWORD SizeOfStackReserve; public DWORD SizeOfStackCommit; public DWORD SizeOfHeapReserve; public DWORD SizeOfHeapCommit; public DWORD LoaderFlags; public DWORD NumberOfRvaAndSizes; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public Winnt._IMAGE_DATA_DIRECTORY[] ImageDataDirectory; }; //https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_optional_header [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct _IMAGE_OPTIONAL_HEADER64 { public MAGIC Magic; public Byte MajorLinkerVersion; public Byte MinorLinkerVersion; public DWORD SizeOfCode; public DWORD SizeOfInitializedData; public DWORD SizeOfUninitializedData; public DWORD AddressOfEntryPoint; public DWORD BaseOfCode; public ULONGLONG ImageBase; public DWORD SectionAlignment; public DWORD FileAlignment; public WORD MajorOperatingSystemVersion; public WORD MinorOperatingSystemVersion; public WORD MajorImageVersion; public WORD MinorImageVersion; public WORD MajorSubsystemVersion; public WORD MinorSubsystemVersion; public DWORD Win32VersionValue; public DWORD SizeOfImage; public DWORD SizeOfHeaders; public DWORD CheckSum; public SUBSYSTEM Subsystem; public DLL_CHARACTERISTICS DllCharacteristics; public ULONGLONG SizeOfStackReserve; public ULONGLONG SizeOfStackCommit; public ULONGLONG SizeOfHeapReserve; public ULONGLONG SizeOfHeapCommit; public DWORD LoaderFlags; public DWORD NumberOfRvaAndSizes; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public Winnt._IMAGE_DATA_DIRECTORY[] ImageDataDirectory; }; [Flags] public enum MAGIC : ushort { IMAGE_NT_OPTIONAL_HDR_MAGIC = 0x00, IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b, IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b, IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107 } [Flags] public enum SUBSYSTEM : ushort { //IMAGE_SUBSYSTEM_UNKNOWN = 0, IMAGE_SUBSYSTEM_NATIVE = 1, IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, IMAGE_SUBSYSTEM_OS2_CUI = 5, IMAGE_SUBSYSTEM_POSIX_CUI = 7, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, IMAGE_SUBSYSTEM_EFI_ROM = 13, IMAGE_SUBSYSTEM_XBOX = 14, IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16 } [Flags] public enum DLL_CHARACTERISTICS : ushort { Reserved1 = 0x0001, Reserved2 = 0x0002, Reserved4 = 0x0004, Reserved8 = 0x0008, IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040, IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY = 0x0080, IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100, IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200, IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400, IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800, Reserved1000 = 0x1000, IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000, Reserved4000 = 0x4000, IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct _IMAGE_SECTION_HEADER { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public Char[] Name; public DWORD VirtualSize; public DWORD VirtualAddress; public DWORD SizeOfRawData; public DWORD PointerToRawData; public DWORD PointerToRelocations; public DWORD PointerToLinenumbers; public WORD NumberOfRelocations; public WORD NumberOfLinenumbers; public DWORD Characteristics; }; [StructLayout(LayoutKind.Sequential)] public struct _LUID { public DWORD LowPart; public DWORD HighPart; } [StructLayout(LayoutKind.Sequential)] public struct _LUID_AND_ATTRIBUTES { public _LUID Luid; public DWORD Attributes; } [StructLayout(LayoutKind.Sequential)] public struct _M128A { public UInt64 High; public Int64 Low; } [StructLayout(LayoutKind.Sequential)] public struct _MEMORY_BASIC_INFORMATION { public DWORD BaseAddress; public DWORD AllocationBase; public DWORD AllocationProtect; public DWORD RegionSize; public DWORD State; public DWORD Protect; public DWORD Type; } [StructLayout(LayoutKind.Sequential)] public struct _MEMORY_BASIC_INFORMATION64 { public ULONGLONG BaseAddress; public ULONGLONG AllocationBase; public DWORD AllocationProtect; public DWORD __alignment1; public ULONGLONG RegionSize; public DWORD State; public MEMORY_PROTECTION_CONSTANTS Protect; public DWORD Type; public DWORD __alignment2; } //https://msdn.microsoft.com/en-us/library/ms809762.aspx [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct _IMAGE_IMPORT_DESCRIPTOR { public DWORD Characteristics; public DWORD TimeDateStamp; public DWORD ForwarderChain; public DWORD Name; public DWORD FirstThunk; } public const Int32 PRIVILEGE_SET_ALL_NECESSARY = 1; [StructLayout(LayoutKind.Sequential)] public struct _PRIVILEGE_SET { public DWORD PrivilegeCount; public DWORD Control; [MarshalAs(UnmanagedType.ByValArray, SizeConst = (Int32)ANYSIZE_ARRAY)] public _LUID_AND_ATTRIBUTES[] Privilege; } //PRIVILEGE_SET, * PPRIVILEGE_SET [StructLayout(LayoutKind.Sequential)] public struct _SID_AND_ATTRIBUTES { public PSID Sid; public DWORD Attributes; } //SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES [StructLayout(LayoutKind.Sequential)] public struct _SID_AND_ATTRIBUTES_MIDL { public Ntifs._SID Sid; public DWORD Attributes; } //SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES [Flags] public enum _SECURITY_IMPERSONATION_LEVEL : int { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3 }; [StructLayout(LayoutKind.Sequential)] public struct _SID_IDENTIFIER_AUTHORITY { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)] public Byte[] Value; } [Flags] public enum _SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown, SidTypeComputer, SidTypeLabel } [Flags] public enum TOKEN_ELEVATION_TYPE { TokenElevationTypeDefault = 1, TokenElevationTypeFull, TokenElevationTypeLimited } [Flags] public enum _TOKEN_INFORMATION_CLASS { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, TokenSecurityAttributes, TokenIsRestricted, MaxTokenInfoClass } [StructLayout(LayoutKind.Sequential)] public struct _TOKEN_MANDATORY_LABEL { public _SID_AND_ATTRIBUTES Label; } [StructLayout(LayoutKind.Sequential)] public struct _TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; public _LUID_AND_ATTRIBUTES Privileges; } [StructLayout(LayoutKind.Sequential)] public struct _TOKEN_PRIVILEGES_ARRAY { public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)] public _LUID_AND_ATTRIBUTES[] Privileges; } [StructLayout(LayoutKind.Sequential)] internal struct _TOKEN_STATISTICS { public Winnt._LUID TokenId; public Winnt._LUID AuthenticationId; public LARGE_INTEGER ExpirationTime; public _TOKEN_TYPE TokenType; public _SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; public DWORD DynamicCharged; public DWORD DynamicAvailable; public DWORD GroupCount; public DWORD PrivilegeCount; public Winnt._LUID ModifiedId; } [Flags] public enum _TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } [StructLayout(LayoutKind.Sequential)] public struct _XMM_SAVE_AREA32 { public WORD ControlWord; public WORD StatusWord; public byte TagWord; public byte Reserved1; public WORD ErrorOpcode; public DWORD ErrorOffset; public WORD ErrorSelector; public WORD Reserved2; public DWORD DataOffset; public WORD DataSelector; public WORD Reserved3; public WORD MxCsr; public WORD MxCsr_Mask; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public _M128A[] FloatRegisters; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public _M128A[] XmmRegisters; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] public byte[] Reserved4; } } }
1.09375
1
Game-Blocket/Assets/Scripts/Player/PlayerVariables.cs
HyFabi/Blocket
14
564
using System; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; public class PlayerVariables : MonoBehaviour{ public static PlayerVariables Singleton { get; private set; } public static Gamemode Gamemode { get => gamemode; set { switch(value){ case Gamemode.SURVIVAL: break; case Gamemode.CREATIVE: break; } gamemode = value; } } private static Gamemode gamemode; private void Awake() => Singleton = this; #region Static Resources public GameObject playerModel, playerLogic; public SpriteRenderer holdingItemPlaceholder; #endregion #region Dyniamic Variables private ushort _health, _maxHealth, _maxArmor, _maxStrength, _armor, _strength; public Inventory inventory; #endregion #region Statistics Variables [HideInInspector] public uint healthGained, healthLost; #endregion #region References public Light2D playerLight; #endregion #region Properties public ushort Health { get => _health; set { _health = value; if(UIInventory.Singleton?.heartStat != null) UIInventory.Singleton.heartStat.text = $"{_health}/{_maxHealth}"; PlayerHealth.Singleton.CurrentHealth = _health; } } public ushort MaxHealth { get => _maxHealth; set { _maxHealth = value; if (UIInventory.Singleton?.heartStat != null) UIInventory.Singleton.heartStat.text = $"{_health}/{_maxHealth}"; PlayerHealth.Singleton.maxHealth = _maxHealth; PlayerHealth.Singleton.InitiateSprites(); } } public ushort MaxArmor { get => _maxArmor; set { _maxArmor = value; UIInventory.Singleton.shieldStat.text = $"{_armor}/{_maxArmor}";} } public ushort Armor { get => _armor; set { _armor = value; UIInventory.Singleton.shieldStat.text = $"{_armor}/{_maxArmor}"; } } public ushort Strength { get => _strength; set { _strength = value; UIInventory.Singleton.swordStat.text = $"{_strength}/{_maxStrength}"; } } public ushort MaxStrength { get => _maxStrength; set { _maxStrength = value; UIInventory.Singleton.swordStat.text = $"{_strength}/{_maxStrength}"; } } private CharacterRace race = CharacterRace.HUMAN; public CharacterRace Race { get=> race; set => race = value; } #endregion /// <summary>For configuring the health of the player</summary> /// <param name="add">If you want to loose health: make it below 0</param> public void AddHealth(byte add) { if(add == 0) return; if(add > 0) healthGained += add; else healthLost -= add; Health += add; if(Health <= 0) Death(); } public void Death() { //TODO } public void ReloadItemInHand(){ holdingItemPlaceholder.sprite = Inventory.Singleton.SelectedItemObj?.itemImage; } public void Init(){ MaxHealth = GameManager.PlayerProfileNow.maxHealth; Health = GameManager.PlayerProfileNow.health != 0 ? GameManager.PlayerProfileNow.health : MaxHealth; Armor = GameManager.PlayerProfileNow.armor; healthGained = GameManager.PlayerProfileNow.healthGained; healthLost = GameManager.PlayerProfileNow.healthLost; } } public enum Gamemode{ SURVIVAL, CREATIVE } public enum CharacterRace { MAGICIAN, HUMAN }
1.703125
2
srcs/PokemonCardTraderBot.Database/Generic/IEntity.cs
Tusquito/PokemonCardTraderBot
0
572
namespace PokemonCardTraderBot.Database.Generic { public interface IEntity { } }
0.480469
0
src/xunit.performance.api/Profilers/Etw/Helper.cs
Bhaskers-Blu-Org2/xunit-performance
150
580
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Diagnostics.Tracing.Parsers; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Xunit.Performance.Api.Native.Windows; using System; using System.Collections.Generic; namespace Microsoft.Xunit.Performance.Api.Profilers.Etw { /// <summary> /// Provides a basic interface for ETW Tracing operations. /// </summary> internal static class Helper { static Helper() { AvailablePreciseMachineCounters = TraceEventProfileSources.GetInfo(); CanEnableKernelProvider = TraceEventSession.IsElevated() == true; } /// <summary> /// Collection of available precise machine counters. /// </summary> public static IReadOnlyDictionary<string, ProfileSourceInfo> AvailablePreciseMachineCounters { get; } /// <summary> /// Indicates whether an ETW kernel session can be enabled. /// </summary> public static bool CanEnableKernelProvider { get; } /// <summary> /// Enable the PMC machine wide, for ETW capture. /// </summary> /// <param name="profileSourceInfos">Collection of PMC to be enabled.</param> public static void SetPreciseMachineCounters(IReadOnlyCollection<ProfileSourceInfo> profileSourceInfos) { if (profileSourceInfos == null) throw new ArgumentNullException(nameof(profileSourceInfos)); if (!Kernel32.IsWindows8OrGreater()) throw new InvalidOperationException("System Tracing is only supported on Windows 8 and above."); var profileSourceIDs = new List<int>(); var profileSourceIntervals = new List<int>(); foreach (var psi in profileSourceInfos) { if (AvailablePreciseMachineCounters.TryGetValue(psi.Name, out var profInfo)) { profileSourceIDs.Add(profInfo.ID); profileSourceIntervals.Add(Math.Min(profInfo.MaxInterval, Math.Max(profInfo.MinInterval, psi.Interval))); } } if (profileSourceIDs.Count > 0) { // // FIXME: This function changes the -pmcsources intervals machine wide. // Maybe we should undo/revert these changes! // TraceEventProfileSources.Set(profileSourceIDs.ToArray(), profileSourceIntervals.ToArray()); } } /// <summary> /// Creates a ETW kernel session data object. /// </summary> /// <param name="kernelFileName">Name of the etl file where the kernel session events will be written to.</param> /// <param name="bufferSizeMB">Sizeof of the internal buffer to be used by the kernel session.</param> /// <returns>A new Session data object.</returns> public static Session MakeKernelSession(string kernelFileName, int bufferSizeMB) { return new Session(new SessionData(KernelTraceEventParser.KernelSessionName, kernelFileName) { BufferSizeMB = bufferSizeMB }); } /// <summary> /// Determines whether a kernel session is needed. /// </summary> /// <param name="kernelProvider">Provider data that will be traced.</param> /// <returns>True if a kernel session is needed, False otherwise.</returns> public static bool NeedSeparateKernelSession(KernelProvider kernelProvider) { if (kernelProvider == null) throw new ArgumentNullException(nameof(kernelProvider)); // CPU counters need the special kernel session return ((kernelProvider.Flags & (KernelTraceEventParser.Keywords.Profile | KernelTraceEventParser.Keywords.PMCProfile)) != KernelTraceEventParser.Keywords.None); } } }
1.117188
1
6.0.0/aspnet-core/src/dgCube.Core/YoYoAbpefCoreConsts.cs
PowerDG/dgCubeInit
1
588
namespace dgCube { public class YoYoAbpefCoreConsts { public static class SchemaNames { public const string Basic = "Basic"; public const string ABP = "ABP"; public const string CMS = "CMS"; } /// <summary> /// 实体长度单位 /// </summary> public static class EntityLengthNames { public const int Length8 = 8; public const int Length16 = 16; public const int Length32 = 32; public const int Length64 = 65; public const int Length128 = 128; public const int Length256 = 256; public const int Length512 = 512; public const int Length1024 = 1024; } } }
0.589844
1
HandSchool.Core/Models/TaskResp.cs
yang-er/HandSchool
28
596
using System; namespace HandSchool.Models { /// <summary> /// 一个任务返回值的包装类 /// </summary> public readonly struct TaskResp { /// <summary> /// 消息为空的“真” /// </summary> public static readonly TaskResp True = new TaskResp(true); /// <summary> /// 消息为空的“假” /// </summary> public static readonly TaskResp False = new TaskResp(false); public TaskResp(bool isSuccess, object msg = null) { IsSuccess = isSuccess; Msg = msg; } public bool IsSuccess {get;} public object Msg { get; } public override string ToString() { return Msg?.ToString() ?? string.Empty; } } }
0.960938
1
third_party/libSBML-5.10.0-Source/src/bindings/csharp/csharp-files/ListOfReactions.cs
0u812/roadrunner
0
604
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace libsbmlcs { using System; using System.Runtime.InteropServices; /** * @sbmlpackage{core} * @htmlinclude pkg-marker-core.html Implementation of SBML's %ListOfReactions construct. * * * * * The various ListOf___ @if conly structures @else classes@endif in SBML * are merely containers used for organizing the main components of an SBML * model. In libSBML's implementation, ListOf___ * @if conly data structures @else classes@endif are derived from the * intermediate utility @if conly structure @else class@endif ListOf, which * is not defined by the SBML specifications but serves as a useful * programmatic construct. ListOf is itself is in turn derived from SBase, * which provides all of the various ListOf___ * @if conly data structures @else classes@endif with common features * defined by the SBML specification, such as 'metaid' attributes and * annotations. * * The relationship between the lists and the rest of an SBML model is * illustrated by the following (for SBML Level&nbsp;2 Version&nbsp;4): * * @htmlinclude listof-illustration.html * * Readers may wonder about the motivations for using the ListOf___ * containers in SBML. A simpler approach in XML might be to place the * components all directly at the top level of the model definition. The * choice made in SBML is to group them within XML elements named after * %ListOf<em>Classname</em>, in part because it helps organize the * components. More importantly, the fact that the container classes are * derived from SBase means that software tools can add information @em about * the lists themselves into each list container's 'annotation'. * * @see ListOfFunctionDefinitions * @see ListOfUnitDefinitions * @see ListOfCompartmentTypes * @see ListOfSpeciesTypes * @see ListOfCompartments * @see ListOfSpecies * @see ListOfParameters * @see ListOfInitialAssignments * @see ListOfRules * @see ListOfConstraints * @see ListOfReactions * @see ListOfEvents * * @if conly * @note In the C API for libSBML, functions that in other language APIs * would be inherited by the various ListOf___ structures not shown in the * pages for the individual ListOf___'s. Instead, the functions are defined * on ListOf_t. <strong>Please consult the documentation for ListOf_t for * the many common functions available for manipulating ListOf___ * structures</strong>. The documentation for the individual ListOf___ * structures (ListOfCompartments_t, ListOfReactions_t, etc.) does not reveal * all of the functionality available. @endif * * */ public class ListOfReactions : ListOf { private HandleRef swigCPtr; internal ListOfReactions(IntPtr cPtr, bool cMemoryOwn) : base(libsbmlPINVOKE.ListOfReactions_SWIGUpcast(cPtr), cMemoryOwn) { //super(libsbmlPINVOKE.ListOfReactionsUpcast(cPtr), cMemoryOwn); swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(ListOfReactions obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } internal static HandleRef getCPtrAndDisown (ListOfReactions obj) { HandleRef ptr = new HandleRef(null, IntPtr.Zero); if (obj != null) { ptr = obj.swigCPtr; obj.swigCMemOwn = false; } return ptr; } ~ListOfReactions() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; libsbmlPINVOKE.delete_ListOfReactions(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } /** * Creates a new ListOfReactions object. * * The object is constructed such that it is valid for the given SBML * Level and Version combination. * * @param level the SBML Level * * @param version the Version within the SBML Level */ public ListOfReactions(long level, long version) : this(libsbmlPINVOKE.new_ListOfReactions__SWIG_0(level, version), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates a new ListOfReactions object. * * The object is constructed such that it is valid for the SBML Level and * Version combination determined by the SBMLNamespaces object in @p * sbmlns. * * @param sbmlns an SBMLNamespaces object that is used to determine the * characteristics of the ListOfReactions object to be created. */ public ListOfReactions(SBMLNamespaces sbmlns) : this(libsbmlPINVOKE.new_ListOfReactions__SWIG_1(SBMLNamespaces.getCPtr(sbmlns)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates and returns a deep copy of this ListOfReactions instance. * * @return a (deep) copy of this ListOfReactions. */ public new ListOfReactions clone() { IntPtr cPtr = libsbmlPINVOKE.ListOfReactions_clone(swigCPtr); ListOfReactions ret = (cPtr == IntPtr.Zero) ? null : new ListOfReactions(cPtr, true); return ret; } /** * Returns the libSBML type code for the objects contained in this ListOf * (i.e., Reaction objects, if the list is non-empty). * * * * * LibSBML attaches an identifying code to every kind of SBML object. These * are integer constants known as <em>SBML type codes</em>. The names of all * the codes begin with the characters &ldquo;<code>SBML_</code>&rdquo;. * @if clike The set of possible type codes for core elements is defined in * the enumeration #SBMLTypeCode_t, and in addition, libSBML plug-ins for * SBML Level&nbsp;3 packages define their own extra enumerations of type * codes (e.g., #SBMLLayoutTypeCode_t for the Level&nbsp;3 Layout * package).@endif@if java In the Java language interface for libSBML, the * type codes are defined as static integer constants in the interface class * {@link libsbmlConstants}. @endif@if python In the Python language * interface for libSBML, the type codes are defined as static integer * constants in the interface class @link libsbml@endlink.@endif@if csharp In * the C# language interface for libSBML, the type codes are defined as * static integer constants in the interface class * @link libsbmlcs.libsbml@endlink.@endif Note that different Level&nbsp;3 * package plug-ins may use overlapping type codes; to identify the package * to which a given object belongs, call the <code>getPackageName()</code> * method on the object. * * * * @return the SBML type code for objects contained in this list: * @link libsbmlcs.libsbml.SBML_REACTION SBML_REACTION@endlink (default). * * @see getElementName() * @see getPackageName() */ public new int getItemTypeCode() { int ret = libsbmlPINVOKE.ListOfReactions_getItemTypeCode(swigCPtr); return ret; } /** * Returns the XML element name of this object * * For ListOfReactions, the XML element name is @c 'listOfReactions'. * * @return the name of this element, i.e., @c 'listOfReactions'. */ public new string getElementName() { string ret = libsbmlPINVOKE.ListOfReactions_getElementName(swigCPtr); return ret; } /** * Get a Reaction from the ListOfReactions. * * @param n the index number of the Reaction to get. * * @return the nth Reaction in this ListOfReactions. * * @see size() */ public new Reaction get(long n) { IntPtr cPtr = libsbmlPINVOKE.ListOfReactions_get__SWIG_0(swigCPtr, n); Reaction ret = (cPtr == IntPtr.Zero) ? null : new Reaction(cPtr, false); return ret; } /** * Get a Reaction from the ListOfReactions based on its identifier. * * @param sid a string representing the identifier of the Reaction to get. * * @return Reaction in this ListOfReactions with the given @p sid or @c * null if no such Reaction exists. * * @see get(long n) * @see size() */ public new Reaction get(string sid) { IntPtr cPtr = libsbmlPINVOKE.ListOfReactions_get__SWIG_2(swigCPtr, sid); Reaction ret = (cPtr == IntPtr.Zero) ? null : new Reaction(cPtr, false); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } /** * Removes the nth item from this ListOfReactions items and returns a * pointer to it. * * The caller owns the returned item and is responsible for deleting it. * * @param n the index of the item to remove * * @see size() */ public new Reaction remove(long n) { IntPtr cPtr = libsbmlPINVOKE.ListOfReactions_remove__SWIG_0(swigCPtr, n); Reaction ret = (cPtr == IntPtr.Zero) ? null : new Reaction(cPtr, true); return ret; } /** * Removes item in this ListOfReactions items with the given identifier. * * The caller owns the returned item and is responsible for deleting it. * If none of the items in this list have the identifier @p sid, then * null is returned. * * @param sid the identifier of the item to remove * * @return the item removed. As mentioned above, the caller owns the * returned item. */ public new Reaction remove(string sid) { IntPtr cPtr = libsbmlPINVOKE.ListOfReactions_remove__SWIG_1(swigCPtr, sid); Reaction ret = (cPtr == IntPtr.Zero) ? null : new Reaction(cPtr, true); if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
1.101563
1
src/Toe.SPIRV/Reflection/Nodes/EnqueueMarker.cs
gleblebedev/Toe.SPIRV
8
612
using System; using System.Collections.Generic; using System.Linq; using Toe.SPIRV.Instructions; using Toe.SPIRV.Reflection.Types; using Toe.SPIRV.Spv; namespace Toe.SPIRV.Reflection.Nodes { public partial class EnqueueMarker : Node { public EnqueueMarker() { } public EnqueueMarker(SpirvTypeBase resultType, Node queue, Node numEvents, Node waitEvents, Node retEvent, string debugName = null) { this.ResultType = resultType; this.Queue = queue; this.NumEvents = numEvents; this.WaitEvents = waitEvents; this.RetEvent = retEvent; DebugName = debugName; } public override Op OpCode => Op.OpEnqueueMarker; public Node Queue { get; set; } public Node NumEvents { get; set; } public Node WaitEvents { get; set; } public Node RetEvent { get; set; } public SpirvTypeBase ResultType { get; set; } public override SpirvTypeBase GetResultType() { return ResultType; } public override IEnumerable<Node> GetInputNodes() { yield return Queue; yield return NumEvents; yield return WaitEvents; yield return RetEvent; } public EnqueueMarker WithDecoration(Spv.Decoration decoration) { AddDecoration(decoration); return this; } public override void SetUp(Instruction op, SpirvInstructionTreeBuilder treeBuilder) { base.SetUp(op, treeBuilder); SetUp((OpEnqueueMarker)op, treeBuilder); } public EnqueueMarker SetUp(Action<EnqueueMarker> setup) { setup(this); return this; } private void SetUp(OpEnqueueMarker op, SpirvInstructionTreeBuilder treeBuilder) { ResultType = treeBuilder.ResolveType(op.IdResultType); Queue = treeBuilder.GetNode(op.Queue); NumEvents = treeBuilder.GetNode(op.NumEvents); WaitEvents = treeBuilder.GetNode(op.WaitEvents); RetEvent = treeBuilder.GetNode(op.RetEvent); SetUpDecorations(op, treeBuilder); } /// <summary>Returns a string that represents the EnqueueMarker object.</summary> /// <returns>A string that represents the EnqueueMarker object.</returns> /// <filterpriority>2</filterpriority> public override string ToString() { return $"EnqueueMarker({ResultType}, {Queue}, {NumEvents}, {WaitEvents}, {RetEvent}, {DebugName})"; } } }
1.265625
1
Startup.cs
arkadiusz-gorecki/Web-HR-application
0
620
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using job_application_project.EntityFramework; using Microsoft.EntityFrameworkCore; using Swashbuckle.AspNetCore.Swagger; using System.Reflection; using System.IO; namespace job_application_project { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); var connection = Configuration["DatabaseConnectionString"]; services.AddDbContext<DataContext>(options => options.UseSqlServer(connection)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //This line adds Swagger generation services to our container. services.AddSwaggerGen(c => { //The generated Swagger JSON file will have these properties. c.SwaggerDoc("v1", new Info { Title = "Swagger XML Api Demo", Version = "v1", }); //Locate the XML file being generated by ASP.NET... var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //... and tell Swagger to use those XML comments. c.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); //This line enables the app to use Swagger, with the configuration in the ConfigureServices method. app.UseSwagger(); //This line enables Swagger UI, which provides us with a nice, simple UI with which we can view our API calls. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML Api Demo v1"); }); } } }
1.1875
1
_no_namespace/ApproachCommand.cs
SinsofSloth/RF5-global-metadata
1
628
public class ApproachCommand : ToolActionCommandBase // TypeDefIndex: 6257 { // Properties public float Force { get; } // Methods // RVA: 0x227A620 Offset: 0x227A721 VA: 0x227A620 public float get_Force() { } // RVA: 0x227A640 Offset: 0x227A741 VA: 0x227A640 public void .ctor(ActionCommandDataTable actionCommandData, AS_ToolController controller) { } // RVA: 0x227A6A0 Offset: 0x227A7A1 VA: 0x227A6A0 Slot: 8 public override void DoAction() { } // RVA: 0x227A8D0 Offset: 0x227A9D1 VA: 0x227A8D0 private bool IsCanBreak(HumanController character) { } }
0.710938
1
Entity/Models/IdentifyRequest.cs
SinanBarut26/EsriRestLibrary
0
636
namespace Entity.Models { public class IdentifyRequest { public IdentifyRequest() { geometryType = "esriGeometryPolygon"; sr = ""; layers = "4"; layerDefs = ""; time = ""; layerTimeOptions = ""; tolerance = "0"; imageDisplay = "600;550;96"; returnGeometry = "true"; maxAllowableOffset = ""; geometryPrecision = ""; dynamicLayers = ""; returnZ = "false"; returnM = "false"; gdbVersion = ""; f = "json"; } public string geometry { get; set; } public string geometryType { get; set; } public string sr { get; set; } public string layers { get; set; } public string layerDefs { get; set; } public string time { get; set; } public string layerTimeOptions { get; set; } public string tolerance { get; set; } public string mapExtent { get; set; } public string imageDisplay { get; set; } public string returnGeometry { get; set; } public string maxAllowableOffset { get; set; } public string geometryPrecision { get; set; } public string dynamicLayers { get; set; } public string returnZ { get; set; } public string returnM { get; set; } public string gdbVersion { get; set; } public string f { get; set; } } }
0.832031
1
src/A6k.Messaging.Kafka.Tests/KafkaOptionsTests.cs
AndyPook/A6k.Messaging
0
644
using Xunit; namespace A6k.Messaging.Kafka.Tests { public class KafkaOptionsTests { [Fact] public void BootstrapServers_ViaProp() { var options = new KafkaOptions(); options.BootstrapServers = "bs"; Assert.Equal("bs", options.Configuration["bootstrap.servers"]); } [Fact] public void BootstrapServers_Configuration() { var options = new KafkaOptions(); options.Configuration["bootstrap.servers"] = "bs"; Assert.Equal("bs", options.BootstrapServers); } [Fact] public void GroupId_ViaProp() { var options = new KafkaOptions(); options.GroupId = "grp"; Assert.Equal("grp", options.Configuration["group.id"]); } [Fact] public void GroupId_Configuration() { var options = new KafkaOptions(); options.Configuration["group.id"] = "grp"; Assert.Equal("grp", options.GroupId); } } }
1.09375
1
Program.cs
mukai1011/XDInitialSeedSorter
0
652
using System.Text.Json; using Pastel; using PokemonPRNG.LCG32.GCLCG; using PokemonXD; public class Program { public static void Main(string[] args) { // apply silent flag bool flagSilent = (args.Contains("--silent") || args.Contains("-s")); if (flagSilent) { Console.SetOut(TextWriter.Null); } Directory.SetCurrentDirectory(AppContext.BaseDirectory); ConsoleExtensions.Enable(); XDConnecter pkmnXD; try { pkmnXD = new XDConnecter(JsonSerializer.Deserialize<Setting>(File.ReadAllText("setting.json"))); } catch (Exception e) { Console.Error.WriteLine(e); Console.Error.WriteLine("接続できませんでした。setting.jsonを確認してください。"); return; } // apply silent flag for stderr if (flagSilent) { Console.SetError(TextWriter.Null); } long count = 1; TimeSpan waitingTime; UInt32 currentSeed = 0; UInt32 targetSeed = 0; do { do { Console.WriteLine(""); Console.WriteLine("--- Attempt: {0} ---", count); Console.WriteLine(""); waitingTime = pkmnXD.GetShortestWaitingTime(); count++; } while (waitingTime > TimeSpan.Parse("03:00:00")); Console.WriteLine("Suitable seed is found!"); if (waitingTime > TimeSpan.Parse("00:05:00")) { try { currentSeed = 0; targetSeed = 0; pkmnXD.InvokeRoughConsumption(waitingTime - TimeSpan.Parse("00:05:00")); currentSeed = pkmnXD.GetCurrentSeed(); targetSeed = pkmnXD.GetWaitingTimes(currentSeed).OrderBy(pair => pair.Value).First().Key; break; } catch (Exception e) { Console.WriteLine(e); // never supposed to be here // nothing to do but reset... } } } while (!pkmnXD.IsLeftEnough(currentSeed, targetSeed)); pkmnXD.Dispose(); // always show this message if (flagSilent) { StreamWriter stdOut = new StreamWriter(Console.OpenStandardOutput()); Console.SetOut(stdOut); stdOut.AutoFlush = true; } Console.WriteLine("{{\"currentSeed\":{0},\"targetSeed\":{1}}}", currentSeed, targetSeed); } }
1.773438
2
ferramentas/Roles.cs
fdamiao/lawyerBox
0
660
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeblawyersBox.ferramentas { public enum Roles { Adminitrador, Advogados, super } }
0.585938
1
src/Systems/Menu/InputMenu.cs
ZerethjiN/GalacticPewPew
1
668
using AlizeeEngine; using SFML.Window; class InputMenuSystem: ClodoBehaviour { public override void OnUpdate() { Entities.ForEach( (Window win) => { win.affichage.DispatchEvents(); if (win.affichage.HasFocus()) { Entities.ForEach( (Input input) => { /* Appuis des touches du menu */ Entities.ForEach( (DeplacementMenu cursor) => { cursor.NextTimer += Time.deltaTime; if (cursor.NextTimer > cursor.NextCooldown) { if (input.IsKeyPressed(Clavier.Touche.Z) && cursor.Position > 0) cursor.Position--; else if (input.IsKeyPressed(Clavier.Touche.S) && cursor.Position < cursor.NbElements) cursor.Position++; cursor.Clicked = input.IsKeyPressed(Clavier.Touche.Enter); Joystick.Update(); if (Joystick.IsConnected(0)) { if (Joystick.GetAxisPosition(0, Joystick.Axis.PovY) > 25 && cursor.Position > 0) { cursor.Position--; } else if (Joystick.GetAxisPosition(0, Joystick.Axis.PovY) < -25 && cursor.Position < cursor.NbElements) { cursor.Position++; } cursor.Clicked = Joystick.IsButtonPressed(0, 1); } cursor.NextTimer = 0; } }); }); } }); } }
1.578125
2
Microsoft.Toolkit.Uwp.UI.Controls.Graph/AadLogin/AadLogin.cs
nschonni/WindowsCommunityToolkit
3
676
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.Identity.Client; using Microsoft.Toolkit.Services.MicrosoftGraph; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation; using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls.Graph { /// <summary> /// The AAD Login Control leverages MSAL libraries to support basic AAD sign-in processes for Microsoft Graph and beyond. /// </summary> [TemplatePart(Name = "RootGrid", Type = typeof(Grid))] [TemplatePart(Name = "ContentPresenter", Type = typeof(ContentPresenter))] public partial class AadLogin : Button { /// <summary> /// Initializes a new instance of the <see cref="AadLogin"/> class. /// </summary> public AadLogin() { DefaultStyleKey = typeof(AadLogin); } /// <summary> /// Override default OnApplyTemplate to capture child controls /// </summary> protected async override void OnApplyTemplate() { ApplyTemplate(); AutomationProperties.SetName(this, SignInDefaultText); Click -= AadLogin_Clicked; Click += AadLogin_Clicked; GraphService.IsAuthenticatedChanged -= GraphService_StateChanged; GraphService.IsAuthenticatedChanged += GraphService_StateChanged; if (GraphService.IsAuthenticated) { CurrentUserId = (await GraphService.User.GetProfileAsync(new MicrosoftGraphUserFields[1] { MicrosoftGraphUserFields.Id })).Id; } } private async void AadLogin_Clicked(object sender, RoutedEventArgs e) { if (!GraphService.IsAuthenticated) { IsEnabled = false; Flyout = null; await SignInAsync(); IsEnabled = true; } else { Flyout = GenerateMenuItems(); } } private async void GraphService_StateChanged(object sender, EventArgs e) { if (GraphService.IsAuthenticated) { CurrentUserId = (await GraphService.User.GetProfileAsync(new MicrosoftGraphUserFields[1] { MicrosoftGraphUserFields.Id })).Id; } else { CurrentUserId = string.Empty; } } /// <summary> /// This method is used to prompt to login screen. /// </summary> /// <returns>True if sign in successfully, otherwise false</returns> public async Task<bool> SignInAsync() { if (await GraphService.TryLoginAsync()) { AutomationProperties.SetName(this, string.Empty); Flyout = GenerateMenuItems(); SignInCompleted?.Invoke(this, new SignInEventArgs() { GraphClient = GraphService.GraphProvider }); return true; } return false; } /// <summary> /// This method is used to sign out the currently signed on user /// </summary> /// <returns>Success or failure</returns> public async Task<bool> SignOutAsync() { var result = await GraphService.Logout(); SignOutCompleted?.Invoke(this, EventArgs.Empty); return result; } private MenuFlyout GenerateMenuItems() { MenuFlyout menuFlyout = new MenuFlyout(); if (AllowSignInAsDifferentUser) { MenuFlyoutItem signinanotherItem = new MenuFlyoutItem { Text = SignInAnotherUserDefaultText }; AutomationProperties.SetName(signinanotherItem, SignInAnotherUserDefaultText); signinanotherItem.Click += async (object sender, RoutedEventArgs e) => { try { if (await GraphService.ConnectForAnotherUserAsync()) { var graphClient = GraphService.GraphProvider; SignInCompleted?.Invoke(this, new SignInEventArgs() { GraphClient = graphClient }); CurrentUserId = (await GraphService.User.GetProfileAsync(new MicrosoftGraphUserFields[1] { MicrosoftGraphUserFields.Id })).Id; } } catch (MsalServiceException ex) { // Swallow error in case of authentication cancellation. if (ex.ErrorCode != "authentication_canceled" && ex.ErrorCode != "access_denied") { throw ex; } } }; menuFlyout.Items.Add(signinanotherItem); } MenuFlyoutItem signoutItem = new MenuFlyoutItem { Text = SignOutDefaultText }; AutomationProperties.SetName(signoutItem, SignOutDefaultText); signoutItem.Click += async (object sender, RoutedEventArgs e) => await SignOutAsync(); menuFlyout.Items.Add(signoutItem); return menuFlyout; } } }
1.320313
1
Developers/UtilityLibrary/UtilityLibrary/Menus/PopupMenu.cs
ewosp/sycorax
1
684
using System; using System.IO; using System.Drawing; using System.Reflection; using System.Drawing.Text; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Diagnostics; using System.Text; using UtilityLibrary.Menus; using UtilityLibrary.Win32; using UtilityLibrary.Collections; using UtilityLibrary.General; namespace UtilityLibrary.Menus { #region Helper Classes internal class FocusCatcher : NativeWindow { public FocusCatcher(IntPtr hParent) { CreateParams cp = new CreateParams(); // Any old title will do as it will not be shown cp.Caption = "NativeFocusCatcher"; // Set the position off the screen so it will not be seen cp.X = -1; cp.Y = -1; cp.Height = 0; cp.Width = 0; // As a top-level window it has no parent cp.Parent = hParent; // Create as a child of the specified parent cp.Style = unchecked((int)(uint)Win32.WindowStyles.WS_CHILD + (int)(uint)Win32.WindowStyles.WS_VISIBLE); // Create the actual window CreateHandle(cp); } } #endregion [ToolboxItem(false)] [DefaultProperty("MenuCommands")] public class PopupMenu : NativeWindow { #region Enumerations // Enumeration of Indexes into positioning constants array protected enum PI { BorderTop = 0, BorderLeft = 1, BorderBottom = 2, BorderRight = 3, ImageGapTop = 4, ImageGapLeft = 5, ImageGapBottom = 6, ImageGapRight = 7, TextGapLeft = 8, TextGapRight = 9, SubMenuGapLeft = 10, SubMenuWidth = 11, SubMenuGapRight = 12, SeparatorHeight = 13, SeparatorWidth = 14, ShortcutGap = 15, ShadowWidth = 16, ShadowHeight = 17, ExtraWidthGap = 18, ExtraHeightGap = 19, ExtraRightGap = 20, ExtraReduce = 21 } // Indexes into the menu images strip protected enum ImageIndex { Check = 0, Radio = 1, SubMenu = 2, CheckSelected = 3, RadioSelected = 4, SubMenuSelected = 5, Expansion = 6, ImageError = 7 } #endregion #region Class Variables // Class constants for sizing/positioning each style protected static readonly int[,] position = { {2, 1, 0, 1, 4, 3, 4, 5, 4, 4, 2, 6, 5, 3, 1, 10, 3, 3, 2, 2, 0, 0}, // IDE {1, 0, 1, 2, 2, 1, 3, 4, 3, 3, 2, 8, 5, 4, 5, 10, 0, 0, 2, 2, 2, 5} // Plain }; // Other class constants protected static readonly int selectionDelay = 400; // Class fields protected static ImageList menuImages = null; protected static bool supportsLayered = false; // Class constants that are marked as 'readonly' are allowed computed initialization protected readonly int WM_DISMISS = (int)Msg.WM_USER + 1; protected readonly int imageWidth = SystemInformation.SmallIconSize.Width; protected readonly int imageHeight = SystemInformation.SmallIconSize.Height; // Instance fields protected Timer timer; protected bool layered; protected Font textFont; protected int popupItem; protected int trackItem; protected int borderGap; protected int returnDir; protected int extraSize; protected bool exitLoop; protected bool mouseOver; protected bool grabFocus; protected bool popupDown; protected bool popupRight; protected bool excludeTop; protected Point screenPos; protected IntPtr oldFocus; protected VisualStyle style; protected Size currentSize; protected int excludeOffset; protected Point lastMousePos; protected Point currentPoint; protected bool showInfrequent; protected PopupMenu childMenu; protected Point leftScreenPos; protected Direction direction; protected Point aboveScreenPos; protected PopupMenu parentMenu; protected ArrayList drawCommands; internal FocusCatcher focusCatcher; protected MenuControl parentControl; protected MenuCommand returnCommand; protected MenuCommandCollection menuCommands; #endregion #region Constructors static PopupMenu() { // Create a strip of images by loading an embedded bitmap resource menuImages = ResourceUtil.LoadImageListResource(Type.GetType("UtilityLibrary.Menus.PopupMenu"), "UtilityLibrary.Resources.ImagesMenu", "MenuControlImages", new Size(16,16), true, new Point(0,0)); // We need to know if the OS supports layered windows supportsLayered = (OSFeature.Feature.GetVersionPresent(OSFeature.LayeredWindows) != null); } public PopupMenu() { // Create collection objects drawCommands = new ArrayList(); menuCommands = new MenuCommandCollection(); // Default the properties returnDir = 0; extraSize = 0; popupItem = -1; trackItem = -1; childMenu = null; exitLoop = false; popupDown = true; mouseOver = false; grabFocus = false; excludeTop = true; popupRight = true; parentMenu = null; excludeOffset = 0; focusCatcher = null; parentControl = null; returnCommand = null; oldFocus = IntPtr.Zero; showInfrequent = false; style = VisualStyle.IDE; lastMousePos = new Point(-1,-1); direction = Direction.Horizontal; textFont = SystemInformation.MenuFont; // Create and initialise the timer object (but do not start it running!) timer = new Timer(); timer.Interval = selectionDelay; timer.Tick += new EventHandler(OnTimerExpire); } #endregion #region Overrides protected override void WndProc(ref Message m) { // WM DISMISS is not a constant and so cannot be in a switch if (m.Msg == WM_DISMISS) OnWM_DISMISS(); else { // Want to notice when the window is maximized Msg cmsg = (Msg)m.Msg; Debug.WriteLine(cmsg.ToString()); // Want to notice when the window is maximized switch(m.Msg) { case (int)Msg.WM_PAINT: OnWM_PAINT(ref m); break; case (int)Msg.WM_ACTIVATEAPP: OnWM_ACTIVATEAPP(ref m); break; case (int)Msg.WM_MOUSEMOVE: OnWM_MOUSEMOVE(ref m); break; case (int)Msg.WM_MOUSELEAVE: OnWM_MOUSELEAVE(); break; case (int)Msg.WM_LBUTTONUP: case (int)Msg.WM_MBUTTONUP: case (int)Msg.WM_RBUTTONUP: OnWM_XBUTTONUP(ref m); break; case (int)Msg.WM_MOUSEACTIVATE: OnWM_MOUSEACTIVATE(ref m); break; case (int)Msg.WM_SETCURSOR: OnWM_SETCURSOR(ref m); break; default: base.WndProc(ref m); break; } } } #endregion #region Properties [Category("Appearance")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public MenuCommandCollection MenuCommands { get { return menuCommands; } set { menuCommands.Clear(); menuCommands = value; } } [Category("Appearance")] [DefaultValue(VisualStyle.IDE)] public VisualStyle Style { get { return style; } set { if ( style != value) style = value; } } [Category("Appearance")] public Font Font { get { return textFont; } set { if (textFont != value) textFont = value; } } [Category("Behaviour")] [DefaultValue(false)] public bool ShowInfrequent { get { return showInfrequent; } set { if ( showInfrequent != value) showInfrequent = value; } } #endregion #region Methods public MenuCommand TrackPopup(Point screenPos) { return TrackPopup(screenPos, false); } public MenuCommand TrackPopup(Point screenPos, bool selectFirst) { // No point in showing PopupMenu if there are no entries if ( menuCommands.VisibleItems()) { // We are being called as a popup window and not from a MenuControl instance // and so we need to the focus during the lifetime of the popup and then return // focus back again when we are dismissed. Otherwise keyboard input will still go // to the control that has it when the popup is created. grabFocus = true; // Default the drawing direction direction = Direction.Horizontal; // Remember screen positions this.screenPos = screenPos; aboveScreenPos = screenPos; leftScreenPos = screenPos; return InternalTrackPopup(selectFirst); } else return null; } public void Dismiss() { if (this.Handle != IntPtr.Zero) { // Prevent the timer from expiring timer.Stop(); // Kill any child menu if ( childMenu != null) childMenu.Dismiss(); // Finish processing messages exitLoop = true; // Hide ourself WindowsAPI.ShowWindow(this.Handle, (short)Win32.ShowWindowStyles.SW_HIDE); // Cause our own message loop to exit WindowsAPI.PostMessage(this.Handle, WM_DISMISS, 0, 0); } } #endregion #region Implementation internal MenuCommand TrackPopup(Point screenPos, Point aboveScreenPos, Direction direction, MenuCommandCollection menuCollection, int borderGap, bool selectFirst, MenuControl parentControl, ref int returnDir) { // Remember which direction the MenuControl is drawing in direction = direction; // Remember the MenuControl that initiated us parentControl = parentControl; // Remember the gap in drawing the top border borderGap = borderGap; // Remember any currect menu item collection MenuCommandCollection oldCollection = menuCommands; // Use the passed in collection of menu commands menuCommands = menuCollection; // Remember screen positions screenPos = screenPos; aboveScreenPos = aboveScreenPos; leftScreenPos = screenPos; MenuCommand ret = InternalTrackPopup(selectFirst); // Restore to original collection menuCommands = oldCollection; // Remove reference no longer required parentControl = null; // Return the direction key that caused dismissal returnDir = returnDir; return ret; } protected MenuCommand InternalTrackPopup(Point screenPosTR, Point screenPosTL, MenuCommandCollection menuCollection, PopupMenu parentMenu, bool selectFirst, MenuControl parentControl, bool popupRight, bool popupDown, ref int returnDir) { // Default the drawing direction direction = Direction.Horizontal; // Remember the MenuControl that initiated us parentControl = parentControl; // We have a parent popup menu that should be consulted about operation parentMenu = parentMenu; // Remember any currect menu item collection MenuCommandCollection oldCollection = menuCommands; // Use the passed in collection of menu commands menuCommands = menuCollection; // Remember screen positions screenPos = screenPosTR; aboveScreenPos = screenPosTR; leftScreenPos = screenPosTL; // Remember display directions popupRight = popupRight; popupDown = popupDown; MenuCommand ret = InternalTrackPopup(selectFirst); // Restore to original collection menuCommands = oldCollection; // Remove references no longer required parentControl = null; parentMenu = null; // Return the direction key that caused dismissal returnDir = returnDir; return ret; } protected MenuCommand InternalTrackPopup(bool selectFirst) { // MenuCommand to return as method result returnCommand = null; // No item is being tracked trackItem = -1; // Flag to indicate when to exit the message loop exitLoop = false; // Assume the mouse does not start over our window mouseOver = false; // Direction of key press if this caused dismissal returnDir = 0; // Flag to indicate if the message should be dispatched bool leaveMsg = false; // Create and show the popup window (without taking the focus) CreateAndShowWindow(); // Create an object for storing windows message information Win32.MSG msg = new Win32.MSG(); // Draw everything now... //RefreshAllCommands(); // Pretend user pressed key down to get the first valid item selected if (selectFirst) ProcessKeyDown(); // Process messages until exit condition recognised while(! exitLoop) { // Suspend thread until a windows message has arrived if (WindowsAPI.WaitMessage()) { // Take a peek at the message details without removing from queue while(! exitLoop && WindowsAPI.PeekMessage(ref msg, 0, 0, 0, (int)Win32.PeekMessageFlags.PM_NOREMOVE)) { // Leave messages for children IntPtr hParent = WindowsAPI.GetParent(msg.hwnd); bool child = hParent == Handle; bool combolist = IsComboBoxList(msg.hwnd); // Mouse was pressed in a window of this application if ((msg.message == (int)Msg.WM_LBUTTONDOWN) || (msg.message == (int)Msg.WM_MBUTTONDOWN) || (msg.message == (int)Msg.WM_RBUTTONDOWN) || (msg.message == (int)Msg.WM_NCLBUTTONDOWN) || (msg.message == (int)Msg.WM_NCMBUTTONDOWN) || (msg.message == (int)Msg.WM_NCRBUTTONDOWN)) { // Is the mouse event for this popup window? if (msg.hwnd != this.Handle) { // Let the parent chain of PopupMenu's decide if they want it if (!ParentWantsMouseMessage(ref msg)&& !child && !combolist) { // No, then we need to exit the popup menu tracking exitLoop = true; // DO NOT process the message, leave it on the queue // and let the real destination window handle it. leaveMsg = true; // Is a parent control specified? if ( parentControl != null) { // Is the mouse event destination the parent control? if (msg.hwnd == parentControl.Handle) { // Then we want to consume the message so it does not get processed // by the parent control. Otherwise, pressing down will cause this // popup to disappear but the message will then get processed by // the parent and cause a popup to reappear again. When we actually // want the popup to disappear and nothing more. leaveMsg = false; } } } } } else { // Mouse move occured if (msg.message == (int)Msg.WM_MOUSEMOVE) { // Is the mouse event for this popup window? if (msg.hwnd != this.Handle) { // Do we still think the mouse is over our window? if ( mouseOver) { // Process mouse leaving situation OnWM_MOUSELEAVE(); } // Let the parent chain of PopupMenu's decide if they want it if (!ParentWantsMouseMessage(ref msg) && !child && !combolist) { // Eat the message to prevent the destination getting it Win32.MSG eat = new Win32.MSG(); WindowsAPI.GetMessage(ref eat, 0, 0, 0); // Do not attempt to pull a message off the queue as it has already // been eaten by us in the above code leaveMsg = true; } } } else { // Was the alt key pressed? if (msg.message == (int)Msg.WM_SYSKEYDOWN) { // Alt key pressed on its own if((int)msg.wParam == (int)Win32.VirtualKeys.VK_MENU) // ALT key { // Then we should dimiss ourself exitLoop = true; } } // Was a key pressed? if (msg.message == (int)Msg.WM_KEYDOWN) { switch((int)msg.wParam) { case (int)Win32.VirtualKeys.VK_UP: ProcessKeyUp(); break; case (int)Win32.VirtualKeys.VK_DOWN: ProcessKeyDown(); break; case (int)Win32.VirtualKeys.VK_LEFT: ProcessKeyLeft(); break; case (int)Win32.VirtualKeys.VK_RIGHT: if(ProcessKeyRight()) { // Do not attempt to pull a message off the queue as the // ProcessKeyRight has eaten the message for us leaveMsg = true; } break; case (int)Win32.VirtualKeys.VK_RETURN: // Is an item currently selected if ( trackItem != -1) { DrawCommand dc = drawCommands[ trackItem] as DrawCommand; // Does this item have a submenu? if (dc.SubMenu) { // Consume the keyboard message to prevent the submenu immediately // processing the same message again. Remember this routine is called // after PeekMessage but the message is still on the queue at this point Win32.MSG eat = new Win32.MSG(); WindowsAPI.GetMessage(ref eat, 0, 0, 0); // Handle the submenu OperateSubMenu( trackItem, false); // Do not attempt to pull a message off the queue as it has already // been eaten by us in the above code leaveMsg = true; } else { // Is this item the expansion command? if (dc.Expansion) { RegenerateExpansion(); } else { // Define the selection to return to caller returnCommand = dc.MenuCommand; // Finish processing messages exitLoop = true; } } } break; case (int)Win32.VirtualKeys.VK_ESCAPE: // User wants to exit the menu, so set the flag to exit the message loop but // let the message get processed. This way the key press is thrown away. exitLoop = true; break; default: // Any other key is treated as a possible mnemonic int selectItem = ProcessMnemonicKey((char)msg.wParam); if (selectItem != -1) { DrawCommand dc = drawCommands[selectItem] as DrawCommand; // Define the selection to return to caller returnCommand = dc.MenuCommand; // Finish processing messages exitLoop = true; } break; } } } } // Should the message we pulled from the queue? if (!leaveMsg) { if (WindowsAPI.GetMessage(ref msg, 0, 0, 0)) { WindowsAPI.TranslateMessage(ref msg); WindowsAPI.DispatchMessage(ref msg); } } else leaveMsg = false; } } } // Do we have a focus we need to restore? if ( oldFocus != IntPtr.Zero) ReturnTheFocus(); // Need to unset this window as the parent of the comboboxes // -- if any -- otherwise the combobox use in an toolbar would get "sick" UnsetComboBoxesParent(); // Hide the window from view before killing it, as sometimes there is a // short delay between killing it and it disappearing because of the time // it takes for the destroy messages to get processed WindowsAPI.ShowWindow(this.Handle, (short)Win32.ShowWindowStyles.SW_HIDE); // Commit suicide DestroyHandle(); // Was a command actually selected? if (( parentMenu == null) && ( returnCommand != null)) { // Pulse the selected event for the command returnCommand.OnClick(EventArgs.Empty); } return returnCommand; } protected void CreateAndShowWindow() { // Decide if we need layered windows layered = ( supportsLayered && ( style == VisualStyle.IDE)); // Don't use layered windows because we would need to do more work // to paint the comboboxes layered = false; // Process the menu commands to determine where each one needs to be // drawn and return the size of the window needed to display it. Size winSize = GenerateDrawPositions(); Point screenPos = CorrectPositionForScreen(winSize); CreateParams cp = new CreateParams(); // Any old title will do as it will not be shown cp.Caption = "NativePopupMenu"; // Define the screen position/size cp.X = screenPos.X; cp.Y = screenPos.Y; cp.Height = winSize.Height; cp.Width = winSize.Width; // As a top-level window it has no parent cp.Parent = IntPtr.Zero; // Appear as a top-level window cp.Style = unchecked((int)(uint)Win32.WindowStyles.WS_POPUP | (int)(uint)Win32.WindowStyles.WS_CLIPCHILDREN); // Set styles so that it does not have a caption bar and is above all other // windows in the ZOrder, i.e. TOPMOST cp.ExStyle = (int)Win32.WindowExStyles.WS_EX_TOPMOST + (int)Win32.WindowExStyles.WS_EX_TOOLWINDOW; // OS specific style if (layered) { // If not on NT then we are going to use alpha blending on the shadow border // and so we need to specify the layered window style so the OS can handle it cp.ExStyle += (int)Win32.WindowExStyles.WS_EX_LAYERED; } // Is this the plain style of appearance? if ( style == VisualStyle.Plain) { // We want the tradiditonal 3D border cp.Style += unchecked((int)(uint)Win32.WindowStyles.WS_DLGFRAME); } // Create the actual window this.CreateHandle(cp); // Update the window clipping region if (!layered) SetWindowRegion(winSize); // Make sure comboboxes are the children of this window SetComboBoxesParent(); // Show the window without activating it (i.e. do not take focus) WindowsAPI.ShowWindow(this.Handle, (short)Win32.ShowWindowStyles.SW_SHOWNOACTIVATE); if (layered) { // Remember the correct screen drawing details currentPoint = screenPos; currentSize = winSize; // Update the image for display UpdateLayeredWindow(); // Must grab the focus immediately if ( grabFocus) GrabTheFocus(); } } void SetComboBoxesParent() { foreach(MenuCommand command in menuCommands) { // no need for recursion, comboboxes are only // on the first level if ( command.ComboBox != null) { WindowsAPI.SetParent(command.ComboBox.Handle, Handle); } } } void UnsetComboBoxesParent() { foreach(MenuCommand command in menuCommands) { // no need for recursion, comboboxes are only // on the first level if ( command.ComboBox != null) { command.ComboBox.Visible = false; WindowsAPI.SetParent(command.ComboBox.Handle, IntPtr.Zero); } } } bool IsComboBoxList(IntPtr hWnd) { STRINGBUFFER className; WindowsAPI.GetClassName(hWnd, out className, 80); if ( className.szText == "ComboLBox" ) return true; return false; } protected void UpdateLayeredWindow() { UpdateLayeredWindow( currentPoint, currentSize); } protected void UpdateLayeredWindow(Point point, Size size) { // Create bitmap for drawing onto Bitmap memoryBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); using(Graphics g = Graphics.FromImage(memoryBitmap)) { Rectangle area = new Rectangle(0, 0, size.Width, size.Height); // Draw the background area DrawBackground(g, area); // Draw the actual menu items DrawAllCommands(g); // Get hold of the screen DC IntPtr hDC = WindowsAPI.GetDC(IntPtr.Zero); // Create a memory based DC compatible with the screen DC IntPtr memoryDC = WindowsAPI.CreateCompatibleDC(hDC); // Get access to the bitmap handle contained in the Bitmap object IntPtr hBitmap = memoryBitmap.GetHbitmap(Color.FromArgb(0)); // Select this bitmap for updating the window presentation IntPtr oldBitmap = WindowsAPI.SelectObject(memoryDC, hBitmap); // New window size Win32.SIZE ulwsize; ulwsize.cx = size.Width; ulwsize.cy = size.Height; // New window position Win32.POINT topPos; topPos.x = point.X; topPos.y = point.Y; // Offset into memory bitmap is always zero Win32.POINT pointSource; pointSource.x = 0; pointSource.y = 0; // We want to make the entire bitmap opaque Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION(); blend.BlendOp = (byte)Win32.AlphaFlags.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = 255; blend.AlphaFormat = (byte)Win32.AlphaFlags.AC_SRC_ALPHA; // Tell operating system to use our bitmap for painting WindowsAPI.UpdateLayeredWindow(Handle, hDC, ref topPos, ref ulwsize, memoryDC, ref pointSource, 0, ref blend, (int)Win32.UpdateLayeredWindowsFlags.ULW_ALPHA); // Put back the old bitmap handle WindowsAPI.SelectObject(memoryDC, oldBitmap); // Cleanup resources WindowsAPI.ReleaseDC(IntPtr.Zero, hDC); WindowsAPI.DeleteObject(hBitmap); WindowsAPI.DeleteDC(memoryDC); } } protected void SetWindowRegion(Size winSize) { // Style specific handling if ( style == VisualStyle.IDE) { int shadowHeight = position[(int) style, (int)PI.ShadowHeight]; int shadowWidth = position[(int) style, (int)PI.ShadowWidth]; // Create a new region object Region drawRegion = new Region(); // Can draw anywhere drawRegion.MakeInfinite(); // Remove the area above the right hand shadow drawRegion.Xor(new Rectangle(winSize.Width - shadowWidth, 0, shadowWidth, shadowHeight)); // When drawing upwards from a vertical menu we need to allow a connection between the // MenuControl selection box and the PopupMenu shadow if (!(( direction == Direction.Vertical) && ! excludeTop)) { // Remove the area left of the bottom shadow drawRegion.Xor(new Rectangle(0, winSize.Height - shadowHeight, shadowWidth, shadowHeight)); } // Define a region to prevent drawing over exposed corners of shadows using(Graphics g = Graphics.FromHwnd(this.Handle)) WindowsAPI.SetWindowRgn(this.Handle, drawRegion.GetHrgn(g), false); } } protected Point CorrectPositionForScreen(Size winSize) { int screenWidth = SystemInformation.WorkingArea.Width; int screenHeight = SystemInformation.WorkingArea.Height; // Default to excluding menu border from top excludeTop = true; excludeOffset = 0; // Calculate the downward position first if ( popupDown) { // Ensure the end of the menu is not off the bottom of the screen if ((screenPos.Y + winSize.Height) > screenHeight) { // If the parent control exists then try and position upwards instead if (( parentControl != null) && ( parentMenu == null)) { // Is there space above the required position? if (( aboveScreenPos.Y - winSize.Height) > 0) { // Great...do that instead screenPos.Y = aboveScreenPos.Y - winSize.Height; // Reverse direction of drawing this and submenus popupDown = false; // Remember to exclude border from bottom of menu and not the top excludeTop = false; // Inform parent it needs to redraw the selection upwards parentControl.DrawSelectionUpwards(); } } // Did the above logic still fail? if ((screenPos.Y + winSize.Height) > screenHeight) { // If not a top level PopupMenu then.. if ( parentMenu != null) { // Reverse direction of drawing this and submenus popupDown = false; // Is there space above the required position? if (( aboveScreenPos.Y - winSize.Height) > 0) screenPos.Y = aboveScreenPos.Y - winSize.Height; else screenPos.Y = 0; } else screenPos.Y = screenHeight - winSize.Height - 1; } } } else { // Ensure the end of the menu is not off the top of the screen if ((screenPos.Y - winSize.Height) < 0) { // Reverse direction popupDown = true; // Is there space below the required position? if ((screenPos.Y + winSize.Height) > screenHeight) screenPos.Y = screenHeight - winSize.Height - 1; } else screenPos.Y -= winSize.Height; } // Calculate the across position next if ( popupRight) { // Ensure that right edge of menu is not off right edge of screen if ((screenPos.X + winSize.Width) > screenWidth) { // If not a top level PopupMenu then... if ( parentMenu != null) { // Reverse direction popupRight = false; // Adjust across position screenPos.X = leftScreenPos.X - winSize.Width; if (screenPos.X < 0) screenPos.X = 0; } else { // Find new position of X coordinate int newX = screenWidth - winSize.Width - 1; // Modify the adjust needed when drawing top/bottom border excludeOffset = screenPos.X - newX; // Use new position for popping up menu screenPos.X = newX; } } } else { // Start by using the left screen pos instead screenPos.X = leftScreenPos.X; // Ensure the left edge of the menu is not off the left of the screen if ((screenPos.X - winSize.Width) < 0) { // Reverse direction popupRight = true; // Is there space below the required position? if (( screenPos.X + winSize.Width) > screenWidth) screenPos.X = screenWidth - winSize.Width - 1; else screenPos.X = screenPos.X; } else screenPos.X -= winSize.Width; } return screenPos; } protected void RegenerateExpansion() { // Remove all existing draw commands drawCommands.Clear(); // Move into the expanded mode showInfrequent = true; // Generate new ones Size newSize = GenerateDrawPositions(); // Find the new screen location for the window Point newPos = CorrectPositionForScreen(newSize); // Update the window clipping region if (!layered) { SetWindowRegion(newSize); // Alter size and location of window WindowsAPI.MoveWindow(this.Handle, newPos.X, newPos.Y, newSize.Width, newSize.Height, true); } else { // Remember the correct screen drawing details currentPoint = newPos; currentSize = newSize; // Update the image for display UpdateLayeredWindow(); } // Lets repaint everything RefreshAllCommands(); } protected Size GenerateDrawPositions() { // Create a collection of drawing objects drawCommands = new ArrayList(); // Calculate the minimum cell width and height int cellMinHeight = position[(int) style, (int)PI.ImageGapTop] + imageHeight + position[(int) style, (int)PI.ImageGapBottom]; int cellMinWidth = position[(int) style, (int)PI.ImageGapLeft] + imageWidth + position[(int) style, (int)PI.ImageGapRight] + position[(int) style, (int)PI.TextGapLeft] + position[(int) style, (int)PI.TextGapRight] + position[(int) style, (int)PI.SubMenuGapLeft] + position[(int) style, (int)PI.SubMenuWidth] + position[(int) style, (int)PI.SubMenuGapRight]; // Find cell height needed to draw text int textHeight = textFont.Height; // If height needs to be more to handle image then use image height if (textHeight < cellMinHeight) textHeight = cellMinHeight; // Make sure no column in the menu is taller than the screen int screenHeight = SystemInformation.WorkingArea.Height; // Define the starting positions for calculating cells int xStart = position[(int) style, (int)PI.BorderLeft]; int yStart = position[(int) style, (int)PI.BorderTop]; int yPosition = yStart; // Largest cell for column defaults to minimum cell width int xColumnMaxWidth = cellMinWidth; int xPreviousColumnWidths = 0; int xMaximumColumnHeight = 0; // Track the row/col of each cell int row = 0; int col = 0; // Are there any infrequent items bool infrequent = false; // Get hold of the DC for the desktop IntPtr hDC = WindowsAPI.GetDC(IntPtr.Zero); // Contains the collection of items in the current column ArrayList columnItems = new ArrayList(); using(Graphics g = Graphics.FromHdc(hDC)) { // Handle any extra text drawing if ( menuCommands.ExtraText.Length > 0) { // Calculate the column width needed to show this text SizeF dimension = g.MeasureString( menuCommands.ExtraText, menuCommands.ExtraFont); // Always add 1 to ensure that rounding is up and not down int extraHeight = (int)dimension.Height + 1; // Find the total required as the text requirement plus style specific spacers extraSize = extraHeight + position[(int) style, (int)PI.ExtraRightGap] + position[(int) style, (int)PI.ExtraWidthGap] * 2; // Push first column of items across from the extra text xStart += extraSize; // Add this extra width to the total width of the window xPreviousColumnWidths = extraSize; } foreach(MenuCommand command in menuCommands) { // Give the command a chance to update its state command.OnUpdate(EventArgs.Empty); // Ignore items that are marked as hidden if (!command.Visible) continue; // If this command has menu items (and so it a submenu item) then check // if any of the submenu items are visible. If none are visible then there // is no point in showing this submenu item if ((command.MenuCommands.Count > 0) && (!command.MenuCommands.VisibleItems())) continue; // Ignore infrequent items unless flag set to show them if (command.Infrequent && ! showInfrequent) { infrequent = true; continue; } int cellWidth = 0; int cellHeight = 0; // Shift across to the next column? if (command.Break) { // Move row/col tracking to the next column row = 0; col++; // Apply cell width to the current column entries ApplySizeToColumnList(columnItems, xColumnMaxWidth); // Move cell position across to start of separator position xStart += xColumnMaxWidth; // Get width of the separator area int xSeparator = position[(int) style, (int)PI.SeparatorWidth]; DrawCommand dcSep = new DrawCommand(new Rectangle(xStart, 0, xSeparator, 0), false); // Add to list of items for drawing drawCommands.Add(dcSep); // Move over the separator xStart += xSeparator; // Reset cell position to top of column yPosition = yStart; // Accumulate total width of previous columns xPreviousColumnWidths += xColumnMaxWidth + xSeparator; // Largest cell for column defaults to minimum cell width xColumnMaxWidth = cellMinWidth; } // Is this a horizontal separator? if (command.Text == "-") { cellWidth = cellMinWidth; cellHeight = position[(int) style, (int)PI.SeparatorHeight]; } else { // Use precalculated height cellHeight = textHeight; // Calculate the text width portion of the cell SizeF dimension = g.MeasureString(command.Text, textFont); // Always add 1 to ensure that rounding is up and not down cellWidth = cellMinWidth + (int)dimension.Width + 1; // Does the menu command have a shortcut defined? if (command.Shortcut != Shortcut.None) { // Find the width of the shortcut text dimension = g.MeasureString(GetShortcutText(command.Shortcut), textFont); // Add to the width of the cell cellWidth += position[(int) style, (int)PI.ShortcutGap] + (int)dimension.Width + 1; } // If this is a combobox, then add the combobox dimension if ( command.ComboBox != null ) { cellWidth += command.ComboBox.Width; } } // If the new cell expands past the end of the screen... if ((yPosition + cellHeight) >= screenHeight) { // .. then need to insert a column break // Move row/col tracking to the next column row = 0; col++; // Apply cell width to the current column entries ApplySizeToColumnList(columnItems, xColumnMaxWidth); // Move cell position across to start of separator position xStart += xColumnMaxWidth; // Get width of the separator area int xSeparator = position[(int) style, (int)PI.SeparatorWidth]; DrawCommand dcSep = new DrawCommand(new Rectangle(xStart, yStart, xSeparator, 0), false); // Add to list of items for drawing drawCommands.Add(dcSep); // Move over the separator xStart += xSeparator; // Reset cell position to top of column yPosition = yStart; // Accumulate total width of previous columns xPreviousColumnWidths += xColumnMaxWidth + xSeparator; // Largest cell for column defaults to minimum cell width xColumnMaxWidth = cellMinWidth; } // Create a new position rectangle (the width will be reset later once the // width of the column has been determined but the other values are correct) Rectangle cellRect = new Rectangle(xStart, yPosition, cellWidth, cellHeight); // Create a drawing object DrawCommand dc = new DrawCommand(command, cellRect, row, col); // Add to list of items for drawing drawCommands.Add(dc); // Add to list of items in this column columnItems.Add(dc); // Remember the biggest cell width in this column if (cellWidth > xColumnMaxWidth) xColumnMaxWidth = cellWidth; // Move down to start of next cell in column yPosition += cellHeight; // Remember the tallest column in the menu if (yPosition > xMaximumColumnHeight) xMaximumColumnHeight = yPosition; row++; } // Check if we need to add an infrequent expansion item if (infrequent) { // Create a minimum size cell Rectangle cellRect = new Rectangle(xStart, yPosition, cellMinWidth, cellMinHeight); // Create a draw command to represent the drawing of the expansion item DrawCommand dc = new DrawCommand(cellRect, true); // Must be last item drawCommands.Add(dc); // Add to list of items in this column columnItems.Add(dc); yPosition += cellMinHeight; // Remember the tallest column in the menu if (yPosition > xMaximumColumnHeight) xMaximumColumnHeight = yPosition; } // Apply cell width to the current column entries ApplySizeToColumnList(columnItems, xColumnMaxWidth); } // Must remember to release the HDC resource! WindowsAPI.ReleaseDC(IntPtr.Zero, hDC); // Find width/height of window int windowWidth = position[(int) style, (int)PI.BorderLeft] + xPreviousColumnWidths + xColumnMaxWidth + position[(int) style, (int)PI.BorderRight]; int windowHeight = position[(int) style, (int)PI.BorderTop] + xMaximumColumnHeight + position[(int) style, (int)PI.BorderBottom]; // Define the height of the vertical separators ApplyVerticalSeparators(xMaximumColumnHeight); // Style specific modification of window size int xAdd = position[(int) style, (int)PI.ShadowHeight]; int yAdd = position[(int) style, (int)PI.ShadowWidth]; if ( style == VisualStyle.Plain) { xAdd += SystemInformation.Border3DSize.Width * 2; yAdd += SystemInformation.Border3DSize.Height * 2; } return new Size(windowWidth + xAdd, windowHeight + yAdd); } protected void ApplyVerticalSeparators(int sepHeight) { // Each vertical separator needs to be the same height, this has already // been calculated and passed in from the tallest column in the menu foreach(DrawCommand dc in drawCommands) { if (dc.VerticalSeparator) { // Grab the current drawing rectangle Rectangle cellRect = dc.DrawRect; // Modify the height to that requested dc.DrawRect = new Rectangle(cellRect.Left, cellRect.Top, cellRect.Width, sepHeight); } } } protected void ApplySizeToColumnList(ArrayList columnList, int cellWidth) { // Each cell in the same column needs to be the same width, this has already // been calculated and passed in as the widest cell in the column foreach(DrawCommand dc in columnList) { // Grab the current drawing rectangle Rectangle cellRect = dc.DrawRect; // Modify the width to that requested dc.DrawRect = new Rectangle(cellRect.Left, cellRect.Top, cellWidth, cellRect.Height); } // Clear collection out ready for reuse columnList.Clear(); } protected void RefreshAllCommands() { Win32.RECT rectRaw = new Win32.RECT(); // Grab the screen rectangle of the window WindowsAPI.GetWindowRect(this.Handle, ref rectRaw); // Convert from screen to client sizing Rectangle rectWin = new Rectangle(0, 0, rectRaw.right - rectRaw.left, rectRaw.bottom - rectRaw.top); using(Graphics g = Graphics.FromHwnd(this.Handle)) { // Draw the background area DrawBackground(g, rectWin); // Draw the actual menu items DrawAllCommands(g); } } protected void DrawBackground(Graphics g, Rectangle rectWin) { Rectangle main = new Rectangle(0, 0, rectWin.Width - 1 - position[(int) style, (int)PI.ShadowWidth], rectWin.Height - 1 - position[(int) style, (int)PI.ShadowHeight]); // Style specific drawing switch( style) { case VisualStyle.IDE: // Calculate some common values int imageColWidth = position[(int) style, (int)PI.ImageGapLeft] + imageWidth + position[(int) style, (int)PI.ImageGapRight]; int xStart = position[(int) style, (int)PI.BorderLeft]; int yStart = position[(int) style, (int)PI.BorderTop]; int yHeight = main.Height - yStart - position[(int) style, (int)PI.BorderBottom] - 1; // Paint the main area background g.FillRectangle(SystemBrushes.ControlLightLight, main); // Draw single line border around the main area Pen mainBorder = SystemPens.ControlDark; g.DrawRectangle(mainBorder, main); // Should the border be drawn with part of the border missing? if ( borderGap > 0) { Pen mainControl = SystemPens.ControlLight; // Remove the appropriate section of the border if ( direction == Direction.Horizontal) { if ( excludeTop) g.DrawLine(mainControl, main.Left + 1 + excludeOffset, main.Top, main.Left + borderGap + excludeOffset - 1, main.Top); else g.DrawLine(mainControl, main.Left + 1 + excludeOffset, main.Bottom, main.Left + borderGap + excludeOffset - 1, main.Bottom); } else { if ( excludeTop) g.DrawLine(mainControl, main.Left, main.Top + 1 + excludeOffset, main.Left, main.Top + borderGap + excludeOffset - 1); else g.DrawLine(mainControl, main.Left, main.Bottom - 1 - excludeOffset, main.Left, main.Bottom - borderGap - excludeOffset - 1); } } // Draw the first image column Rectangle imageRect = new Rectangle(xStart, yStart, imageColWidth, yHeight); g.FillRectangle(SystemBrushes.ControlLight, imageRect); // Draw image column after each vertical separator foreach(DrawCommand dc in drawCommands) { if (dc.Separator && dc.VerticalSeparator) { // Recalculate starting position (but height remains the same) imageRect.X = dc.DrawRect.Right; g.FillRectangle(SystemBrushes.ControlLight, imageRect); } } // Draw shadow around borders int rightLeft = main.Right + 1; int rightTop = main.Top + position[(int) style, (int)PI.ShadowHeight]; int rightBottom = main.Bottom + 1; int leftLeft = main.Left + position[(int) style, (int)PI.ShadowWidth]; int xExcludeStart = main.Left + excludeOffset; int xExcludeEnd = main.Left + excludeOffset + borderGap; SolidBrush shadowBrush; if (layered) shadowBrush = new SolidBrush(Color.FromArgb(64, 0, 0, 0)); else shadowBrush = new SolidBrush(SystemColors.ControlDark); if (( borderGap > 0) && (! excludeTop) && ( direction == Direction.Horizontal)) { int rightright = rectWin.Width; if (xExcludeStart >= leftLeft) g.FillRectangle(shadowBrush, leftLeft, rightBottom, xExcludeStart - leftLeft, position[(int) style, (int)PI.ShadowHeight]); if (xExcludeEnd <= rightright) g.FillRectangle(shadowBrush, xExcludeEnd, rightBottom, rightright - xExcludeEnd, position[(int) style, (int)PI.ShadowHeight]); } else { if (( direction == Direction.Vertical) && (! excludeTop)) leftLeft = 0; g.FillRectangle(shadowBrush, leftLeft, rightBottom, rightLeft, position[(int) style, (int)PI.ShadowHeight]); } g.FillRectangle(shadowBrush, rightLeft, rightTop, position[(int) style, (int)PI.ShadowWidth], rightBottom - rightTop); shadowBrush.Dispose(); if (( borderGap > 0) && (! excludeTop) && ( direction == Direction.Horizontal)) { g.FillRectangle( SystemBrushes.ControlLight, new Rectangle(xExcludeStart, rightBottom - 1, xExcludeEnd - xExcludeStart, position[(int) style, (int)PI.ShadowHeight] + 1)); // Draw lines connecting the selected MenuControl item to the submenu Pen connectPen = SystemPens.ControlDark; g.DrawLine(connectPen, xExcludeStart, rightBottom - 1, xExcludeStart, rectWin.Height); g.DrawLine(connectPen, xExcludeEnd, rightBottom - 1, xExcludeEnd, rectWin.Height); } break; case VisualStyle.Plain: // Paint the main area background g.FillRectangle( SystemBrushes.Control, rectWin); break; } // Is there an extra title text to be drawn? if ( menuCommands.ExtraText.Length > 0) DrawColumn(g, main); } protected void DrawColumn(Graphics g, Rectangle main) { // Create the rectangle that encloses the drawing Rectangle rectText = new Rectangle(main.Left, main.Top, extraSize - position[(int) style, (int)PI.ExtraRightGap], main.Height); Brush backBrush = null; bool disposeBack = true; if ( menuCommands.ExtraBackBrush != null) { backBrush = menuCommands.ExtraBackBrush; disposeBack = false; rectText.Width++; } else backBrush = new SolidBrush( menuCommands.ExtraBackColor); // Fill background using brush g.FillRectangle(backBrush, rectText); // Do we need to dispose of the brush? if (disposeBack) backBrush.Dispose(); // Adjust rectangle for drawing the text into rectText.X += position[(int) style, (int)PI.ExtraWidthGap]; rectText.Y += position[(int) style, (int)PI.ExtraHeightGap]; rectText.Width -= position[(int) style, (int)PI.ExtraWidthGap] * 2; rectText.Height -= position[(int) style, (int)PI.ExtraHeightGap] * 2; // For Plain style we need to take into account the border sizes if ( style == VisualStyle.Plain) rectText.Height -= SystemInformation.Border3DSize.Height * 2; // Draw the text into this rectangle StringFormat format = new StringFormat(); format.FormatFlags = StringFormatFlags.DirectionVertical | StringFormatFlags.NoClip | StringFormatFlags.NoWrap; format.Alignment = StringAlignment.Near; format.LineAlignment = StringAlignment.Center; Brush textBrush = null; bool disposeText = true; if ( menuCommands.ExtraTextBrush != null) { textBrush = menuCommands.ExtraTextBrush; disposeText = false; } else textBrush = new SolidBrush( menuCommands.ExtraTextColor); // Draw string from bottom of area towards the top using the given Font/Brush TextUtil.DrawReverseString(g, menuCommands.ExtraText, menuCommands.ExtraFont, rectText, textBrush, format); // Do we need to dispose of the brush? if (disposeText) textBrush.Dispose(); } internal void DrawSingleCommand(Graphics g, DrawCommand dc, bool hotCommand) { Rectangle drawRect = dc.DrawRect; MenuCommand mc = dc.MenuCommand; // Remember some often used values int textGapLeft = position[(int) style, (int)PI.TextGapLeft]; int imageGapLeft = position[(int) style, (int)PI.ImageGapLeft]; int imageGapRight = position[(int) style, (int)PI.ImageGapRight]; int imageLeft = drawRect.Left + imageGapLeft; // Calculate some common values int imageColWidth = imageGapLeft + imageWidth + imageGapRight; int subMenuWidth = position[(int) style, (int)PI.SubMenuGapLeft] + position[(int) style, (int)PI.SubMenuWidth] + position[(int) style, (int)PI.SubMenuGapRight]; int subMenuX = drawRect.Right - position[(int) style, (int)PI.SubMenuGapRight] - position[(int) style, (int)PI.SubMenuWidth]; // Text drawing rectangle needs to know the right most position for drawing // to stop. This is the width of the window minus the relevant values int shortCutX = subMenuX - position[(int) style, (int)PI.SubMenuGapLeft] - position[(int) style, (int)PI.TextGapRight]; // Is this item an expansion command? if (dc.Expansion) { Rectangle box = drawRect; // In IDE style the box is next to the image column if ( style == VisualStyle.IDE) { // Reduce the box to take into account the column box.X += imageColWidth; box.Width -= imageColWidth; } // Find centre for drawing the image int xPos = box.Left + ((box.Width - imageHeight) / 2);; int yPos = box.Top + ((box.Height - imageHeight) / 2); switch( style) { case VisualStyle.IDE: g.FillRectangle(SystemBrushes.ControlLightLight, box); break; case VisualStyle.Plain: g.FillRectangle(SystemBrushes.Control, box); break; } // Should the item look selected if (hotCommand) { switch( style) { case VisualStyle.IDE: Rectangle selectArea = new Rectangle(drawRect.Left + 1, drawRect.Top, drawRect.Width - 3, drawRect.Height - 1); // Draw the selection area white, because we are going to use an alpha brush g.FillRectangle( Brushes.White, selectArea ); using (SolidBrush selectBrush = new SolidBrush(Color.FromArgb(70,ColorUtil.VSNetBorderColor))) { // Draw the selection area g.FillRectangle(selectBrush, selectArea); // Draw a border around the selection area g.DrawRectangle( ColorUtil.VSNetBorderPen, selectArea ); } break; case VisualStyle.Plain: // Shrink the box to provide a small border box.Inflate(-2, -2); // Grab common values Color baseColor = SystemColors.Control; using (Pen lightPen = new Pen(SystemColors.ControlLightLight), darkPen = new Pen(SystemColors.ControlDarkDark)) { g.DrawLine(lightPen, box.Right, box.Top, box.Left, box.Top); g.DrawLine(lightPen, box.Left, box.Top, box.Left, box.Bottom); g.DrawLine(darkPen, box.Left, box.Bottom, box.Right, box.Bottom); g.DrawLine(darkPen, box.Right, box.Bottom, box.Right, box.Top); } break; } } else { switch( style) { case VisualStyle.IDE: // Fill the entire drawing area with white g.FillRectangle( SystemBrushes.ControlLightLight, new Rectangle(drawRect.Left + 1, drawRect.Top, drawRect.Width - 1, drawRect.Height)); Rectangle imageCol = new Rectangle(drawRect.Left, drawRect.Top, imageColWidth, drawRect.Height); // Draw the image column background g.FillRectangle(SystemBrushes.Control, imageCol); break; case VisualStyle.Plain: g.FillRectangle(SystemBrushes.Control, new Rectangle(drawRect.Left, drawRect.Top, drawRect.Width, drawRect.Height)); break; } } // Always draw the expansion bitmap g.DrawImage(menuImages.Images[(int)ImageIndex.Expansion], xPos, yPos); } else { // Is this item a separator? if (dc.Separator) { if (dc.VerticalSeparator) { switch( style) { case VisualStyle.IDE: // Draw the separator as a single line using (Pen separatorPen = new Pen(SystemColors.ControlDark)) g.DrawLine(separatorPen, drawRect.Left, drawRect.Top, drawRect.Left, drawRect.Bottom); break; case VisualStyle.Plain: Color baseColor = SystemColors.Control; ButtonBorderStyle bsInset = ButtonBorderStyle.Inset; ButtonBorderStyle bsNone = ButtonBorderStyle.Inset; Rectangle sepRect = new Rectangle(drawRect.Left + 1, drawRect.Top, 2, drawRect.Height); // Draw the separator as two lines using Inset style ControlPaint.DrawBorder(g, sepRect, baseColor, 1, bsInset, baseColor, 0, bsNone, baseColor, 1, bsInset, baseColor, 0, bsNone); break; } } else { switch( style) { case VisualStyle.IDE: // Draw the image column background Rectangle imageCol = new Rectangle(drawRect.Left, drawRect.Top, imageColWidth, drawRect.Height); g.FillRectangle( ColorUtil.VSNetBackgroundBrush, drawRect); g.FillRectangle( ColorUtil.VSNetControlBrush, imageCol); // Draw a separator using (Pen separatorPen = new Pen(Color.FromArgb(75, SystemColors.MenuText))) { // Draw the separator as a single line g.DrawLine(separatorPen, drawRect.Left + imageColWidth + textGapLeft, drawRect.Top + 1, drawRect.Right-4, drawRect.Top + 1); } break; case VisualStyle.Plain: Color baseColor = SystemColors.Control; ButtonBorderStyle bsInset = ButtonBorderStyle.Inset; ButtonBorderStyle bsNone = ButtonBorderStyle.Inset; Rectangle sepRect = new Rectangle(drawRect.Left + 2, drawRect.Top + 1, drawRect.Width - 4, 2); // Draw the separator as two lines using Inset style ControlPaint.DrawBorder(g, sepRect, baseColor, 0, bsNone, baseColor, 1, bsInset, baseColor, 0, bsNone, baseColor, 1, bsInset); break; } } } else { // Should the command be drawn selected? if (hotCommand && mc.ComboBox == null ) { switch( style) { case VisualStyle.IDE: Rectangle selectArea = new Rectangle(drawRect.Left + 1, drawRect.Top, drawRect.Width - 3, drawRect.Height - 1); // Draw the selection area white, because we are going to use an alpha brush g.FillRectangle(Brushes.White, selectArea); using (SolidBrush selectBrush = new SolidBrush(Color.FromArgb(70, ColorUtil.VSNetBorderColor))) { // Draw the selection area g.FillRectangle(selectBrush, selectArea); // Draw a border around the selection area g.DrawRectangle( ColorUtil.VSNetBorderPen, selectArea); } break; case VisualStyle.Plain: g.FillRectangle( ColorUtil.VSNetBorderBrush, drawRect); break; } } else { switch( style) { case VisualStyle.IDE: // Fill the entire drawing area with white g.FillRectangle( ColorUtil.VSNetBackgroundBrush, new Rectangle(drawRect.Left + 1, drawRect.Top, drawRect.Width - 1, drawRect.Height)); Rectangle imageCol = new Rectangle(drawRect.Left, drawRect.Top, imageColWidth, drawRect.Height); // Draw the image column background g.FillRectangle( ColorUtil.VSNetControlBrush, imageCol ); // If this is a combobox item, make sure to position the combobox a couple // of pixel after the icon area if ( mc.ComboBox != null ) { // Combobox will paint itself mc.ComboBox.Left = drawRect.Left+imageColWidth + 2; mc.ComboBox.Top = drawRect.Top + (drawRect.Height - mc.ComboBox.Height)/2; } break; case VisualStyle.Plain: g.FillRectangle(SystemBrushes.Control, new Rectangle(drawRect.Left, drawRect.Top, drawRect.Width, drawRect.Height)); break; } } int leftPos = drawRect.Left + imageColWidth + textGapLeft; // Calculate text drawing rectangle Rectangle strRect = new Rectangle(leftPos, drawRect.Top, shortCutX - leftPos, drawRect.Height); // Left align the text drawing on a single line centered vertically // and process the & character to be shown as an underscore on next character StringFormat format = new StringFormat(); format.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.NoWrap; format.Alignment = StringAlignment.Near; format.LineAlignment = StringAlignment.Center; format.HotkeyPrefix = HotkeyPrefix.Show; SolidBrush textBrush; // Create brush depending on enabled state if (mc.Enabled) { if (!hotCommand || ( style == VisualStyle.IDE)) textBrush = new SolidBrush(SystemColors.MenuText); else textBrush = new SolidBrush(SystemColors.HighlightText); } else textBrush = new SolidBrush(SystemColors.GrayText); // Helper values used when drawing grayed text in plain style Rectangle rectDownRight = strRect; rectDownRight.Offset(1,1); if (mc.Enabled || ( style == VisualStyle.IDE)) g.DrawString(mc.Text, textFont, textBrush, strRect, format); else { // Draw grayed text by drawing white string offset down and right g.DrawString(mc.Text, textFont, SystemBrushes.HighlightText, rectDownRight, format); // And then draw in corret color offset up and left g.DrawString(mc.Text, textFont, textBrush, strRect, format); } if (mc.Shortcut != Shortcut.None) { // Right align the shortcut drawing format.Alignment = StringAlignment.Far; if (mc.Enabled || ( style == VisualStyle.IDE)) { // Draw the shortcut text g.DrawString(GetShortcutText(mc.Shortcut), textFont, textBrush, strRect, format); } else { // Draw grayed text by drawing white string offset down and right g.DrawString(GetShortcutText(mc.Shortcut), textFont, SystemBrushes.HighlightText, rectDownRight, format ); // And then draw in corret color offset up and left g.DrawString(GetShortcutText(mc.Shortcut), textFont, textBrush, strRect, format); } } // The image offset from top of cell is half the space left after // subtracting the height of the image from the cell height int imageTop = drawRect.Top + (drawRect.Height - imageHeight) / 2; Image image = null; // Should a check mark be drawn? if (mc.Checked) { switch( style) { case VisualStyle.IDE: Pen boxPen; if (mc.Enabled) boxPen = ColorUtil.VSNetBorderPen; else boxPen = SystemPens.GrayText; // Draw the box around the checkmark area g.DrawRectangle(boxPen, new Rectangle(imageLeft - 1, imageTop - 1, imageHeight + 2, imageWidth + 2)); break; case VisualStyle.Plain: break; } // Grab either tick or radio button image if (mc.RadioCheck) { if (hotCommand && ( style == VisualStyle.Plain)) image = menuImages.Images[(int)ImageIndex.RadioSelected]; else image = menuImages.Images[(int)ImageIndex.Radio]; } else { if (hotCommand && ( style == VisualStyle.Plain)) image = menuImages.Images[(int)ImageIndex.CheckSelected]; else image = menuImages.Images[(int)ImageIndex.Check]; } } else { try { // Is there an image available to be drawn? if ((mc.ImageList != null) && (mc.ImageIndex >= 0)) image = mc.ImageList.Images[mc.ImageIndex]; else if ( mc.Image != null) image = mc.Image; } catch(Exception) { // User supplied ImageList/ImageIndex are invalid, use an error image instead image = menuImages.Images[(int)ImageIndex.ImageError]; } } // Is there an image to be drawn? if (image != null) { if (mc.Enabled) { if ((hotCommand) && (!mc.Checked) && ( style == VisualStyle.IDE)) { // Draw a disabled icon offset down and right ControlPaint.DrawImageDisabled(g, image, imageLeft + 1, imageTop + 1, SystemColors.HighlightText); // Draw an enabled icon offset up and left g.DrawImage(image, imageLeft - 1, imageTop - 1); } else { // Draw an enabled icon g.DrawImage(image, imageLeft, imageTop); } } else { // Draw a image disabled ControlPaint.DrawImageDisabled(g, image, imageLeft, imageTop, SystemColors.HighlightText); } } // Does the menu have a submenu defined? if (dc.SubMenu) { // Is the item enabled? if (mc.Enabled) { int subMenuIndex = (int)ImageIndex.SubMenu; if (hotCommand && ( style == VisualStyle.Plain)) subMenuIndex = (int)ImageIndex.SubMenuSelected; // Draw the submenu arrow g.DrawImage(menuImages.Images[subMenuIndex], subMenuX, imageTop); } else { // Draw a image disabled ControlPaint.DrawImageDisabled(g, menuImages.Images[(int)ImageIndex.SubMenu], subMenuX, imageTop, SystemColors.HighlightText); } } } } } protected void DrawAllCommands(Graphics g) { for(int i=0; i< drawCommands.Count; i++) { // Grab some commonly used values DrawCommand dc = drawCommands[i] as DrawCommand; // Draw this command only DrawSingleCommand(g, dc, (i == trackItem)); } } protected string GetShortcutText(Shortcut shortcut) { // Get the key code char keycode = (char)((int)shortcut & 0x0000FFFF); // The type converter does not work for numeric values as it returns // Alt+D0 instad of Alt+0. So check for numeric keys and construct the // return string ourself. if ((keycode >= '0') && (keycode <= '9')) { string display = ""; // Get the modifier int modifier = (int)((int)shortcut & 0xFFFF0000); if ((modifier & 0x00010000) != 0) display += "Shift+"; if ((modifier & 0x00020000) != 0) display += "Ctrl+"; if ((modifier & 0x00040000) != 0) display += "Alt+"; display += keycode; return display; } return TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString((Keys)shortcut); } protected bool ProcessKeyUp() { int newItem = trackItem; int startItem = newItem; for(int i=0; i< drawCommands.Count; i++) { // Move to previous item newItem--; // Have we looped all the way around all the choices if (newItem == startItem) return false; // Check limits if (newItem < 0) newItem = drawCommands.Count - 1; DrawCommand dc = drawCommands[newItem] as DrawCommand; // Can we select this item? if (!dc.Separator && dc.Enabled) { // If a change has occured if (newItem != trackItem) { // Modify the display of the two items SwitchSelection( trackItem, newItem, false, false); return true; } } } return false; } protected bool ProcessKeyDown() { int newItem = trackItem; int startItem = newItem; for(int i=0; i< drawCommands.Count; i++) { // Move to previous item newItem++; // Check limits if (newItem >= drawCommands.Count) newItem = 0; DrawCommand dc = drawCommands[newItem] as DrawCommand; // Can we select this item? if (!dc.Separator && dc.Enabled) { // If a change has occured if (newItem != trackItem) { // Modify the display of the two items SwitchSelection( trackItem, newItem, false, false); return true; } } } return false; } protected void ProcessKeyLeft() { if ( trackItem != -1) { // Get the col this item is in DrawCommand dc = drawCommands[ trackItem] as DrawCommand; // Grab the current column/row values int col = dc.Col; int row = dc.Row; // If not in the first column then move left one if (col > 0) { int newItem = -1; int newRow = -1; int findCol = col - 1; DrawCommand newDc = null; for(int i=0; i< drawCommands.Count; i++) { DrawCommand listDc = drawCommands[i] as DrawCommand; // Interesting in cells in the required column if (listDc.Col == findCol) { // Is this Row nearer to the one required than those found so far? if ((listDc.Row <= row) && (listDc.Row > newRow) && !listDc.Separator && listDc.Enabled) { // Remember this item newRow = listDc.Row; newDc = listDc; newItem = i; } } } if (newDc != null) { // Track the new item // Modify the display of the two items SwitchSelection( trackItem, newItem, false, false); return; } } // Are we the first submenu of a parent control? bool autoLeft = ( parentMenu == null) && ( parentControl != null); // Do we have a parent menu? if (( parentMenu != null) || autoLeft) { // Tell the parent on return that nothing was selected returnCommand = null; // Finish processing messages timer.Stop(); exitLoop = true; if (autoLeft) returnDir = -1; } } } protected bool ProcessKeyRight() { // Are we the first submenu of a parent control? bool autoRight = ( parentControl != null); bool checkKeys = false; bool ret = false; // Is an item currently selected? if ( trackItem != -1) { DrawCommand dc = drawCommands[ trackItem] as DrawCommand; // Does this item have a submenu? if (dc.SubMenu) { // Consume the keyboard message to prevent the submenu immediately // processing the same message again. Remember this routine is called // after PeekMessage but the message is still on the queue at this point Win32.MSG msg = new Win32.MSG(); WindowsAPI.GetMessage(ref msg, 0, 0, 0); // Handle the submenu OperateSubMenu( trackItem, true); ret = true; } else { // Grab the current column/row values int col = dc.Col; int row = dc.Row; // If not in the first column then move left one int newItem = -1; int newRow = -1; int findCol = col + 1; DrawCommand newDc = null; for(int i=0; i< drawCommands.Count; i++) { DrawCommand listDc = drawCommands[i] as DrawCommand; // Interesting in cells in the required column if (listDc.Col == findCol) { // Is this Row nearer to the one required than those found so far? if ((listDc.Row <= row) && (listDc.Row > newRow) && !listDc.Separator && listDc.Enabled) { // Remember this item newRow = listDc.Row; newDc = listDc; newItem = i; } } } if (newDc != null) { // Track the new item // Modify the display of the two items SwitchSelection( trackItem, newItem, false, false); } else checkKeys = true; } } else { if ( parentMenu != null) { if (!ProcessKeyDown()) checkKeys = true; } else checkKeys = true; } // If we have a parent control and nothing to move right into if (autoRight && checkKeys) { returnCommand = null; // Finish processing messages timer.Stop(); exitLoop = true; returnDir = 1; } return ret; } protected int ProcessMnemonicKey(char key) { // Check against each draw command mnemonic for(int i=0; i< drawCommands.Count; i++) { DrawCommand dc = drawCommands[i] as DrawCommand; if (dc.Enabled) { // Does the character match? if (key == dc.Mnemonic) return i; } } // No match found return -1; } protected bool ParentWantsMouseMessage(ref Win32.MSG msg) { Win32.POINT screenPos; screenPos.x = (int)((uint)msg.lParam & 0x0000FFFFU); screenPos.y = (int)(((uint)msg.lParam & 0xFFFF0000U) >> 16); // Convert the mouse position to screen coordinates WindowsAPI.ClientToScreen(msg.hwnd, ref screenPos); // Special case the MOUSEMOVE so if we are part of a MenuControl // then we should always allow mousemoves to be processed if ((msg.message == (int)Msg.WM_MOUSEMOVE) && ( parentControl != null)) { Win32.RECT rectRaw = new Win32.RECT(); // Grab the screen rectangle of the parent control WindowsAPI.GetWindowRect( parentControl.Handle, ref rectRaw); if ((screenPos.x >= rectRaw.left) && (screenPos.x <= rectRaw.right) && (screenPos.y >= rectRaw.top) && (screenPos.y <= rectRaw.bottom)) return true; } if ( parentMenu != null) return parentMenu.WantMouseMessage(screenPos); else return false; } protected bool WantMouseMessage(Win32.POINT screenPos) { Win32.RECT rectRaw = new Win32.RECT(); // Grab the screen rectangle of the window WindowsAPI.GetWindowRect(this.Handle, ref rectRaw); bool want = ((screenPos.x >= rectRaw.left) && (screenPos.x <= rectRaw.right) && (screenPos.y >= rectRaw.top) && (screenPos.y <= rectRaw.bottom)); if (!want && ( parentMenu != null)) want = parentMenu.WantMouseMessage(screenPos); return want; } protected void SwitchSelection(int oldItem, int newItem, bool mouseChange, bool reverting) { bool updateWindow = false; // Create a graphics object for drawing with using(Graphics g = Graphics.FromHwnd(this.Handle)) { // Deselect the old draw command if (oldItem != -1) { DrawCommand dc = drawCommands[oldItem] as DrawCommand; // Draw old item not selected if (layered) updateWindow = true; else DrawSingleCommand(g, drawCommands[oldItem] as DrawCommand, false); } if (newItem != -1) { // Stop the timer as a new selection has occured timer.Stop(); // Do we have a child menu? if (!reverting && ( childMenu != null)) { // Start timer to test if it should be dismissed timer.Start(); } DrawCommand dc = drawCommands[newItem] as DrawCommand; // Select the new draw command if (!dc.Separator && dc.Enabled) { // Draw the newly selected item if (layered) updateWindow = true; else DrawSingleCommand(g, dc, true); // Only is mouse movement caused the selection change... if (!reverting && mouseChange) { //...should we start a timer to test for sub menu displaying timer.Start(); } } else { // Cannot become selected newItem = -1; } } // Remember the new selection trackItem = newItem; if (layered && updateWindow) { // Update the image for display UpdateLayeredWindow(); } } } protected void OnTimerExpire(object sender, EventArgs e) { // Prevent it expiring again timer.Stop(); bool showPopup = true; // Is a popup menu already being displayed? if ( childMenu != null) { // If the submenu popup is for a different item? if ( popupItem != trackItem) { // Then need to kill the submenu WindowsAPI.PostMessage( childMenu.Handle, WM_DISMISS, 0, 0); } else showPopup = false; } // Should we show the popup for this item if (showPopup) { // Check an item really is selected if ( trackItem != -1) { DrawCommand dc = drawCommands[ trackItem] as DrawCommand; // Does this item have a submenu? if (dc.SubMenu) OperateSubMenu( trackItem, false); else { if (dc.Expansion) RegenerateExpansion(); } } } } protected void OperateSubMenu(int popupItem, bool selectFirst) { popupItem = popupItem; childMenu = new PopupMenu(); DrawCommand dc = drawCommands[popupItem] as DrawCommand; // Find screen coordinate of Top right of item cell Win32.POINT screenPosTR; screenPosTR.x = dc.DrawRect.Right; screenPosTR.y = dc.DrawRect.Top; WindowsAPI.ClientToScreen(this.Handle, ref screenPosTR); // Find screen coordinate of top left of item cell Win32.POINT screenPosTL; screenPosTL.x = dc.DrawRect.Left; screenPosTL.y = dc.DrawRect.Top; WindowsAPI.ClientToScreen(this.Handle, ref screenPosTL); // Ensure the child has the same properties as ourself childMenu.Style = this.Style; childMenu.Font = this.Font; // Record keyboard direction int returnDir = 0; returnCommand = childMenu.InternalTrackPopup(new Point(screenPosTR.x, screenPosTR.y), new Point(screenPosTL.x, screenPosTL.y), dc.MenuCommand.MenuCommands, this, selectFirst, parentControl, popupRight, popupDown, ref returnDir); popupItem = -1;; childMenu = null; if (( returnCommand != null) || (returnDir != 0)) { // Finish processing messages timer.Stop(); exitLoop = true; returnDir = returnDir; } } protected void GrabTheFocus() { oldFocus = WindowsAPI.GetFocus(); // Is the focus on a control/window? if ( oldFocus != IntPtr.Zero) { IntPtr hParent = WindowsAPI.GetParent( oldFocus); // Did we find a parent window? if (hParent != IntPtr.Zero) { // Create a new destination for the focus focusCatcher = new FocusCatcher(hParent); // Park focus at the temporary window WindowsAPI.SetFocus( focusCatcher.Handle); // Kill any capturing of the mouse WindowsAPI.ReleaseCapture(); } } grabFocus = false; } protected void ReturnTheFocus() { // Restore focus to origin WindowsAPI.SetFocus( oldFocus); // Did we use an temporary parking location? if ( focusCatcher != null) { // Kill it focusCatcher.DestroyHandle(); focusCatcher = null; } // Reset state oldFocus = IntPtr.Zero; } protected void OnWM_PAINT(ref Message m) { // Paint message occurs after the window is created and we have // entered the message loop. So this is a good place to handle focus if ( grabFocus) GrabTheFocus(); Win32.PAINTSTRUCT ps = new Win32.PAINTSTRUCT(); // Have to call BeginPaint whenever processing a WM PAINT message IntPtr hDC = WindowsAPI.BeginPaint(m.HWnd, ref ps); Win32.RECT rectRaw = new Win32.RECT(); // Grab the screen rectangle of the window WindowsAPI.GetWindowRect(this.Handle, ref rectRaw); // Convert to a client size rectangle Rectangle rectWin = new Rectangle(0, 0, rectRaw.right - rectRaw.left, rectRaw.bottom - rectRaw.top); // Create a graphics object for drawing using(Graphics g = Graphics.FromHdc(hDC)) { // Create bitmap for drawing onto Bitmap memoryBitmap = new Bitmap(rectWin.Width, rectWin.Height); using(Graphics h = Graphics.FromImage(memoryBitmap)) { // Draw the background area DrawBackground(h, rectWin); // Draw the actual menu items DrawAllCommands(h); } // Blit bitmap onto the screen g.DrawImageUnscaled(memoryBitmap, 0, 0); } // Don't forget to end the paint operation! WindowsAPI.EndPaint(m.HWnd, ref ps); } protected void OnWM_ACTIVATEAPP(ref Message m) { // Another application has been activated, so we need to kill ourself timer.Stop(); exitLoop = true; } protected void SubMenuMovement() { // Cancel timer to prevent auto closing of an open submenu timer.Stop(); // Has the selected item changed since child menu shown? if ( popupItem != trackItem) { // Need to put it back again SwitchSelection( trackItem, popupItem, false, true); } // Are we a submenu? if ( parentMenu != null) { // Inform parent that we have movement and so do not // use a timer to close us up parentMenu.SubMenuMovement(); } } protected void OnWM_MOUSEMOVE(ref Message m) { // Are we a submenu? if ( parentMenu != null) { // Inform parent that we have movement and so do not // use a timer to close us up parentMenu.SubMenuMovement(); } // Is the first time we have noticed a mouse movement over our window if (! mouseOver) { // Crea the structure needed for WindowsAPI call Win32.TRACKMOUSEEVENTS tme = new Win32.TRACKMOUSEEVENTS(); // Fill in the structure tme.cbSize = 16; tme.dwFlags = (uint)Win32.TrackerEventFlags.TME_LEAVE; tme.hWnd = this.Handle; tme.dwHoverTime = 0; // Request that a message gets sent when mouse leaves this window WindowsAPI.TrackMouseEvent(ref tme); // Yes, we know the mouse is over window mouseOver = true; } // Extract the mouse position int xPos = (int)((uint)m.LParam & 0x0000FFFFU); int yPos = (int)(((uint)m.LParam & 0xFFFF0000U) >> 16); Point pos = new Point(xPos, yPos); // Has mouse position really changed since last time? if ( lastMousePos != pos) { for(int i=0; i< drawCommands.Count; i++) { DrawCommand dc = drawCommands[i] as DrawCommand; if (dc.DrawRect.Contains(pos)) { // Is there a change in selected item? if ( trackItem != i) { // Modify the display of the two items SwitchSelection( trackItem, i, true, false); } } } // Remember for next time around lastMousePos = pos; } } protected void OnWM_MOUSELEAVE() { // Deselect the old draw command if not showing a child menu if (( trackItem != -1) && ( childMenu == null)) { // Modify the display of the two items SwitchSelection( trackItem, -1, false, false); } // Reset flag so that next mouse move start monitor for mouse leave message mouseOver = false; // No point having a last mouse position lastMousePos = new Point(-1,-1); } protected void OnWM_XBUTTONUP(ref Message m) { // Extract the mouse position int xPos = (int)((uint)m.LParam & 0x0000FFFFU); int yPos = (int)(((uint)m.LParam & 0xFFFF0000U) >> 16); Point pos = new Point(xPos, yPos); for(int i=0; i< drawCommands.Count; i++) { DrawCommand dc = drawCommands[i] as DrawCommand; if (dc.DrawRect.Contains(pos)) { // Is there a change in selected item? if ( trackItem != i) { // Modify the display of the two items SwitchSelection( trackItem, i, false, false); } } } // Is an item selected? if ( trackItem != -1) { DrawCommand dc = drawCommands[ trackItem] as DrawCommand; // Does this item have a submenu? if (dc.SubMenu) { // If we are not already showing this submenu... if ( popupItem != trackItem) { // Is a submenu for a different item showing? if ( childMenu != null) { // Inform the child menu it is no longer needed WindowsAPI.PostMessage( childMenu.Handle, WM_DISMISS, 0, 0); } // Handle the submenu OperateSubMenu( trackItem, false); } } else { if (dc.Expansion) RegenerateExpansion(); else { // Kill any child menus open if ( childMenu != null) { // Inform the child menu it is no longer needed WindowsAPI.PostMessage( childMenu.Handle, WM_DISMISS, 0, 0); } // Define the selection to return to caller returnCommand = dc.MenuCommand; // Finish processing messages timer.Stop(); exitLoop = true; } } } } protected void OnWM_MOUSEACTIVATE(ref Message m) { // Do not allow then mouse down to activate the window, but eat // the message as we still want the mouse down for processing m.Result = (IntPtr)Win32.MouseActivateFlags.MA_NOACTIVATE; } protected void OnWM_SETCURSOR(ref Message m) { // Always use the arrow cursor WindowsAPI.SetCursor(WindowsAPI.LoadCursor(IntPtr.Zero, (uint)Win32.CursorType.IDC_ARROW)); } protected void OnWM_DISMISS() { // Pass on to any child menu of ours if ( childMenu != null) { // Inform the child menu it is no longer needed WindowsAPI.PostMessage( childMenu.Handle, WM_DISMISS, 0, 0); } // Define the selection to return to caller returnCommand = null; // Finish processing messages timer.Stop(); exitLoop = true; // Hide ourself WindowsAPI.ShowWindow(this.Handle, (short)Win32.ShowWindowStyles.SW_HIDE); // Kill ourself DestroyHandle(); } #endregion } }
1.453125
1
src/NavyCOOLPublishing/COOLTool.Services/Models.Input/DeleteRequest.cs
CredentialEngine/NavyCOOL
0
692
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace COOLTool.Services.Models.Input { public class DeleteRequest { /// <summary> /// CTID of document to be deleted /// </summary> public string CTID { get; set; } /// <summary> /// Identifier for Organization which Owns the data being published /// 2017-12-13 - this will be the CTID for the owning org. /// </summary> public string PublishForOrganizationIdentifier { get; set; } /// <summary> /// Leave blank for default /// </summary> public string Community { get; set; } } }
0.902344
1
AlexaSkillsKit.Sample.Dialog.AzureFunc/Handlers/DefaultHandler.cs
BizLogr/AlexaAppKit.Net
228
700
using AlexaSkillsKit.Sample.Dialog.AzureFunc.Helpers.Builder; using AlexaSkillsKit.Sample.Dialog.AzureFunc.Helpers.Log; using AlexaSkillsKit.Slu; using AlexaSkillsKit.Speechlet; using System.Threading.Tasks; namespace AlexaSkillsKit.Sample.Dialog.AzureFunc.Handlers { public class DefaultHandler : IntentHandler { private static readonly string HelpIndexAttribute = "Index"; private static readonly string[] HelpResponces = new[] { "Say something", "Are you still here?", "What can I help you?", "WTF?" }; public DefaultHandler(ISpeechletResponseBuilder responseBuilder, ILogHelper logHelper) : base(responseBuilder, logHelper) { } private static int GetIntAttribute(Session session, string key, int defaultValue = 0) { string value = session.Attributes.TryGetValue(key, out value) ? value : string.Empty; int result = int.TryParse(value, out result) ? result : 0; return result; } private static void SetIntAttribute(Session session, string key, int value) { session.Attributes[key] = $"{value}"; } public async override Task<ISpeechletResponseBuilder> HandleIntentAsync(Intent intent, IntentRequest.DialogStateEnum dialogState, Session session) { await logHelper.Log($"Something unrecognized sayd"); var index = GetIntAttribute(session, HelpIndexAttribute); SetIntAttribute(session, HelpIndexAttribute, (index + 1) / HelpResponces.Length); return responseBuilder.Say(HelpResponces[index]).KeepSession(); } } }
1.203125
1
CSCore/Codecs/CodecFactory.cs
gvdbq/CsCoreClone
2
708
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using CSCore.Codecs.AAC; using CSCore.Codecs.AIFF; using CSCore.Codecs.DDP; using CSCore.Codecs.FLAC; using CSCore.Codecs.MP1; using CSCore.Codecs.MP2; using CSCore.Codecs.MP3; using CSCore.Codecs.WAV; using CSCore.Codecs.WMA; using CSCore.MediaFoundation; namespace CSCore.Codecs { /// <summary> /// Helps to choose the right decoder for different codecs. /// </summary> public class CodecFactory { // ReSharper disable once InconsistentNaming private static readonly CodecFactory _instance = new CodecFactory(); private readonly Dictionary<object, CodecFactoryEntry> _codecs; private CodecFactory() { _codecs = new Dictionary<object, CodecFactoryEntry>(); Register("mp3", new CodecFactoryEntry(s => { try { return new DmoMp3Decoder(s); } catch (Exception) { if (Mp3MediafoundationDecoder.IsSupported) return new Mp3MediafoundationDecoder(s); throw; } }, "mp3", "mpeg3")); Register("wave", new CodecFactoryEntry(s => { IWaveSource res = new WaveFileReader(s); if (res.WaveFormat.WaveFormatTag != AudioEncoding.Pcm && res.WaveFormat.WaveFormatTag != AudioEncoding.IeeeFloat && res.WaveFormat.WaveFormatTag != AudioEncoding.Extensible) { res.Dispose(); res = new MediaFoundationDecoder(s); } return res; }, "wav", "wave")); Register("flac", new CodecFactoryEntry(s => new FlacFile(s), "flac", "fla")); Register("aiff", new CodecFactoryEntry(s => new AiffReader(s), "aiff", "aif", "aifc")); if (AacDecoder.IsSupported) { Register("aac", new CodecFactoryEntry(s => new AacDecoder(s), "aac", "adt", "adts", "m2ts", "mp2", "3g2", "3gp2", "3gp", "3gpp", "m4a", "m4v", "mp4v", "mp4", "mov")); } if (WmaDecoder.IsSupported) { Register("wma", new CodecFactoryEntry(s => new WmaDecoder(s), "asf", "wm", "wmv", "wma")); } if (Mp1Decoder.IsSupported) { Register("mp1", new CodecFactoryEntry(s => new Mp1Decoder(s), "mp1", "m2ts")); } if (Mp2Decoder.IsSupported) { Register("mp2", new CodecFactoryEntry(s => new Mp1Decoder(s), "mp2", "m2ts")); } if (DDPDecoder.IsSupported) { Register("ddp", new CodecFactoryEntry(s => new DDPDecoder(s), "mp2", "m2ts", "m4a", "m4v", "mp4v", "mp4", "mov", "asf", "wm", "wmv", "wma", "avi", "ac3", "ec3")); } } /// <summary> /// Gets the default singleton instance of the <see cref="CodecFactory" /> class. /// </summary> public static CodecFactory Instance { get { return _instance; } } /// <summary> /// Gets the file filter in English. This filter can be used e.g. in combination with an OpenFileDialog. /// </summary> public static string SupportedFilesFilterEn { get { return Instance.GenerateFilter(); } } /// <summary> /// Registers a new codec. /// </summary> /// <param name="key"> /// The key which gets used internally to save the <paramref name="codec" /> in a /// <see cref="Dictionary{TKey,TValue}" />. This is typically the associated file extension. For example: the mp3 codec /// uses the string "mp3" as its key. /// </param> /// <param name="codec"><see cref="CodecFactoryEntry" /> which provides information about the codec.</param> public void Register(object key, CodecFactoryEntry codec) { var keyString = key as string; if (keyString != null) key = keyString.ToLower(); if (_codecs.ContainsKey(key) != true) _codecs.Add(key, codec); } /// <summary> /// Returns a fully initialized <see cref="IWaveSource" /> instance which is able to decode the specified file. If the /// specified file can not be decoded, this method throws an <see cref="NotSupportedException" />. /// </summary> /// <param name="filename">Filename of the specified file.</param> /// <returns>Fully initialized <see cref="IWaveSource" /> instance which is able to decode the specified file.</returns> /// <exception cref="NotSupportedException">The codec of the specified file is not supported.</exception> public IWaveSource GetCodec(string filename) { if(String.IsNullOrEmpty(filename)) throw new ArgumentNullException("filename"); if (!File.Exists(filename)) throw new FileNotFoundException("File not found.", filename); string extension = Path.GetExtension(filename).Remove(0, 1); //get the extension without the "dot". //remove the dot in front of the file extension. foreach (var codecEntry in _codecs) { try { if (codecEntry.Value.FileExtensions.Any(x => x.Equals(extension, StringComparison.OrdinalIgnoreCase))) return codecEntry.Value.GetCodecAction(File.OpenRead(filename)); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } return Default(filename); } /// <summary> /// Returns a fully initialized <see cref="IWaveSource" /> instance which is able to decode the audio source behind the /// specified <paramref name="uri" />. /// If the specified audio source can not be decoded, this method throws an <see cref="NotSupportedException" />. /// </summary> /// <param name="uri">Uri which points to an audio source.</param> /// <returns>Fully initialized <see cref="IWaveSource" /> instance which is able to decode the specified audio source.</returns> /// <exception cref="NotSupportedException">The codec of the specified audio source is not supported.</exception> public IWaveSource GetCodec(Uri uri) { if (uri == null) throw new ArgumentNullException("uri"); try { if (uri.IsFile) { return GetCodec(uri.LocalPath); } return OpenWebStream(uri.ToString()); } catch (IOException) { throw; } catch (Exception e) { throw new NotSupportedException("Codec not supported.", e); } } internal IWaveSource GetCodec(Stream stream, object key) { return _codecs[key].GetCodecAction(stream); } private IWaveSource OpenWebStream(string url) { try { return Default(url); } catch (Exception) { try { #pragma warning disable 618 return new Mp3WebStream(url, false); #pragma warning restore 618 } catch (Exception) { Debug.WriteLine("No mp3 webstream."); } throw; //better throw the exception of the MediaFoundationDecoder. We just try to use the Mp3WebStream class since a few mp3 streams are not supported by the mediafoundation. } } private static IWaveSource Default(string url) { return new MediaFoundationDecoder(url); } /// <summary> /// Returns all the common file extensions of all supported codecs. Note that some of these file extensions belong to /// more than one codec. /// That means that it can be possible that some files with the file extension abc can be decoded but other a few files /// with the file extension abc can't be decoded. /// </summary> /// <returns>Supported file extensions.</returns> public string[] GetSupportedFileExtensions() { var extensions = new List<string>(); foreach (CodecFactoryEntry item in _codecs.Select(x => x.Value)) { foreach (string e in item.FileExtensions) { if (!extensions.Contains(e)) extensions.Add(e); } } return extensions.ToArray(); } private string GenerateFilter() { var stringBuilder = new StringBuilder(); stringBuilder.Append("Supported Files|"); stringBuilder.Append(String.Concat(GetSupportedFileExtensions().Select(x => "*." + x + ";").ToArray())); stringBuilder.Remove(stringBuilder.Length - 1, 1); return stringBuilder.ToString(); } } }
1.46875
1
tracer/test/Datadog.Trace.TestHelpers.SharedSource/VerifyHelper.cs
DataDog/dd-trace-csharp
13
716
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using VerifyTests; using VerifyXunit; namespace Datadog.Trace.TestHelpers { public static class VerifyHelper { private static readonly Regex LocalhostRegex = new(@"localhost\:\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex LoopBackRegex = new(@"127.0.0.1\:\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex KeepRateRegex = new(@"_dd.tracer_kr: \d\.\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex ProcessIdRegex = new(@"process_id: \d+\.0", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// <summary> /// With <see cref="Verify"/>, parameters are used as part of the filename. /// This method produces a "sanitised" version to remove problematic values /// </summary> /// <param name="path">The path to sanitise</param> /// <returns>The sanitised path</returns> public static string SanitisePathsForVerify(string path) { // TODO: Make this more robust return path .Replace(@"\", "_") .Replace("/", "_") .Replace("?", "-"); } public static VerifySettings GetSpanVerifierSettings(params object[] parameters) { var settings = new VerifySettings(); VerifierSettings.DerivePathInfo( (sourceFile, projectDirectory, type, method) => { return new(directory: Path.Combine(projectDirectory, "..", "snapshots")); }); if (parameters.Length > 0) { settings.UseParameters(parameters); } settings.ModifySerialization(_ => { _.IgnoreMember<MockSpan>(s => s.Duration); _.IgnoreMember<MockSpan>(s => s.Start); _.MemberConverter<MockSpan, Dictionary<string, string>>(x => x.Tags, ScrubStackTraceForErrors); }); settings.AddRegexScrubber(LocalhostRegex, "localhost:00000"); settings.AddRegexScrubber(LoopBackRegex, "localhost:00000"); settings.AddRegexScrubber(KeepRateRegex, "_dd.tracer_kr: 1.0"); settings.AddRegexScrubber(ProcessIdRegex, "process_id: 0"); return settings; } public static SettingsTask VerifySpans(IReadOnlyCollection<MockSpan> spans, VerifySettings settings) { // Ensure a static ordering for the spans var orderedSpans = spans .OrderBy(x => GetRootSpanName(x, spans)) .ThenBy(x => GetSpanDepth(x, spans)) .ThenBy(x => x.Start) .ThenBy(x => x.Duration); return Verifier.Verify(orderedSpans, settings); static string GetRootSpanName(MockSpan span, IReadOnlyCollection<MockSpan> allSpans) { while (span.ParentId is not null) { span = allSpans.First(x => x.SpanId == span.ParentId.Value); } return span.Resource; } static int GetSpanDepth(MockSpan span, IReadOnlyCollection<MockSpan> allSpans) { var depth = 0; while (span.ParentId is not null) { span = allSpans.First(x => x.SpanId == span.ParentId.Value); depth++; } return depth; } } public static void AddRegexScrubber(this VerifySettings settings, Regex regex, string replacement) { settings.AddScrubber(builder => ReplaceRegex(builder, regex, replacement)); } public static void AddSimpleScrubber(this VerifySettings settings, string oldValue, string newValue) { settings.AddScrubber(builder => ReplaceSimple(builder, oldValue, newValue)); } public static Dictionary<string, string> ScrubStackTraceForErrors( MockSpan span, Dictionary<string, string> tags) { return tags .Select( kvp => kvp.Key switch { Tags.ErrorStack => new KeyValuePair<string, string>(kvp.Key, ScrubStackTrace(kvp.Value)), _ => kvp }) .OrderBy(x => x.Key) .ToDictionary(x => x.Key, x => x.Value); } private static void ReplaceRegex(StringBuilder builder, Regex regex, string replacement) { var value = builder.ToString(); var result = regex.Replace(value, replacement); if (value.Equals(result, StringComparison.Ordinal)) { return; } builder.Clear(); builder.Append(result); } private static void ReplaceSimple(StringBuilder builder, string oldValue, string newValue) { var value = builder.ToString(); var result = value.Replace(oldValue, newValue); if (value.Equals(result, StringComparison.Ordinal)) { return; } builder.Clear(); builder.Append(result); } private static string ScrubStackTrace(string stackTrace) { // keep the message + the first (scrubbed) location var sb = new StringBuilder(); using StringReader reader = new(Scrubbers.ScrubStackTrace(stackTrace)); string line; while ((line = reader.ReadLine()) is not null) { if (line.StartsWith("at ")) { // add the first line of the stack trace sb.Append(line); break; } sb .Append(line) .Append('\n'); } return sb.ToString(); } } }
1.335938
1
src/KsWare.Presentation.Core/(Utils)/(Extensions)/DispatcherExtension.cs
KsWare/master
0
724
//OBSOLETE. Use DispatcherSlim //using System; //using System.Collections.Generic; //using System.Diagnostics.CodeAnalysis; //using System.Linq; //using System.Security.Permissions; //using System.Text; //using System.Threading; //using System.Windows.Threading; // // //[module: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope="namespace", Target="System.Windows.Threading")] //namespace System.Windows.Threading { // // /// <summary> // /// Provides additional functionality for <see cref="Dispatcher"/> // /// </summary> // public static class DispatcherExtension { // // /// <summary> Gets a value indicating whether the caller must call an invoke method when making method calls to the UI because the caller is on a different thread than the one the UI was created on. // /// </summary> // public static bool IsInvokeRequired(this Dispatcher dispatcher) { // return dispatcher.Thread.ManagedThreadId != Thread.CurrentThread.ManagedThreadId; // } // // /// <summary> // /// Executes a delegate on the application dispatcher. // /// </summary> // /// <param name="dispatcher">The dispatcher.</param> // /// <param name="method">The method to execute</param> // /// <param name="args">The method arguments</param> // /// <returns></returns> // public static object InvokeIfRequired(this Dispatcher dispatcher, Delegate method, params object[] args) { // if(IsInvokeRequired(dispatcher)) return dispatcher.Invoke(method, args); // return method.DynamicInvoke(args); // } // // /// <summary> Processes all Dispatcher messages currently in the dispatcher queue. // /// </summary> // /// <param name="dispatcher">The dispatcher.</param> // [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] // public static void DoEvents(this Dispatcher dispatcher) { // DispatcherFrame frame = new DispatcherFrame(); // dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame); // Dispatcher.PushFrame(frame); // } // // private static object ExitFrame(object frame) { // ((DispatcherFrame)frame).Continue = false; // return null; // } // // } //}
1.6875
2
LogicMonitor.Api/Settings/RecipientGroup.cs
tdicks/LogicMonitor.Api
0
732
using System.Collections.Generic; using System.Runtime.Serialization; namespace LogicMonitor.Api.Settings { /// <summary> /// An external alert destination /// </summary> [DataContract] public class RecipientGroup : DescribedItem, IHasEndpoint { /// <summary> /// The group name /// </summary> [DataMember(Name = "groupName")] public string GroupName { get; set; } /// <summary> /// The recipients /// </summary> [DataMember(Name = "recipients")] public List<AlertRecipient> Recipients { get; set; } /// <summary> /// The endpoint /// </summary> /// <returns></returns> public string Endpoint() => "setting/recipientgroups"; } }
0.859375
1
src/Disqord.Rest/Entities/Core/Guild/IRole.cs
Anu6is/Disqord
0
740
namespace Disqord { public partial interface IRole : ISnowflakeEntity, IMentionable, IDeletable { string Name { get; } Color Color { get; } bool IsHoisted { get; } int Position { get; } GuildPermissions Permissions { get; } bool IsManaged { get; } bool IsMentionable { get; } Snowflake GuildId { get; } } }
0.589844
1
src/BuildScriptGenerator/DotNetCore/DotnetCoreConstants.cs
samruddhikhandale/Oryx
34
748
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // -------------------------------------------------------------------------------------------- namespace Microsoft.Oryx.BuildScriptGenerator.DotNetCore { public static class DotNetCoreConstants { public const string PlatformName = "dotnet"; public const string CSharpProjectFileExtension = "csproj"; public const string FSharpProjectFileExtension = "fsproj"; public const string GlobalJsonFileName = "global.json"; public const string NetCoreApp10 = "netcoreapp1.0"; public const string NetCoreApp11 = "netcoreapp1.1"; public const string NetCoreApp20 = "netcoreapp2.0"; public const string NetCoreApp21 = "netcoreapp2.1"; public const string NetCoreApp22 = "netcoreapp2.2"; public const string NetCoreApp30 = "netcoreapp3.0"; public const string NetCoreApp31 = "netcoreapp3.1"; public const string AspNetCorePackageReference = "Microsoft.AspNetCore"; public const string AspNetCoreAllPackageReference = "Microsoft.AspNetCore.All"; public const string AspNetCoreAppPackageReference = "Microsoft.AspNetCore.App"; public const string ProjectFileLanguageDetectorProperty = "ProjectFile"; public const string DotNetSdkName = "Microsoft.NET.Sdk"; public const string DotNetWebSdkName = "Microsoft.NET.Sdk.Web"; public const string ProjectSdkAttributeValueXPathExpression = "string(/Project/@Sdk)"; public const string ProjectSdkElementNameAttributeValueXPathExpression = "string(/Project/Sdk/@Name)"; public const string TargetFrameworkElementXPathExpression = "/Project/PropertyGroup/TargetFramework"; public const string AssemblyNameXPathExpression = "/Project/PropertyGroup/AssemblyName"; public const string OutputTypeXPathExpression = "/Project/PropertyGroup/OutputType"; public const string PackageReferenceXPathExpression = "/Project/ItemGroup/PackageReference"; public const string DefaultMSBuildConfiguration = "Release"; public const string ProjectBuildPropertyKey = "project"; public const string ProjectBuildPropertyKeyDocumentation = "Relative path of the project file to build."; public const string AzureBlazorWasmRazorLangVersionXPathExpression = "/Project/PropertyGroup/RazorLangVersion"; public const string AzureBlazorWasmPackageReference = "Microsoft.AspNetCore.Components.WebAssembly"; public const string AzureFunctionsVersionElementXPathExpression = "/Project/PropertyGroup/AzureFunctionsVersion"; public const string AzureFunctionsPackageReference = "Microsoft.NET.Sdk.Functions"; public const string StorageSdkMetadataRuntimeVersionElementName = "Runtime_version"; public const string StorageSdkMetadataSdkVersionElementName = "Version"; public const string InstallBlazorWebAssemblyAOTWorkloadCommand = "dotnet workload install wasm-tools"; public static readonly string DefaultDotNetCoreSdkVersionsInstallDir = $"/opt/{PlatformName}"; } }
1.039063
1
src/_Workflow/Framework.Workflow.BLL/ParameterizedObjectValidators/_Base/ParameterizedObjectValidator.cs
Luxoft/BSSFramework.Workflow
0
756
using System; using System.Linq; using Framework.Core; using Framework.DomainDriven.BLL; using Framework.Validation; using Framework.Workflow.Domain; using Framework.Workflow.Domain.Definition; using Framework.Workflow.Domain.Runtime; namespace Framework.Workflow.BLL { public abstract class ParameterizedObjectValidator<TDomainObject, TDomainObjectDefinition, TParameterInstance, TParameterDefinition> : BLLContextContainer<IWorkflowBLLContext> where TDomainObject : PersistentDomainObjectBase, IDefinitionDomainObject<TDomainObjectDefinition>, IParametersContainer<TParameterInstance> where TDomainObjectDefinition : PersistentDomainObjectBase, IParametersContainer<TParameterDefinition> where TParameterInstance : ParameterInstance<TParameterDefinition>, IWorkflowInstanceElement where TParameterDefinition : Parameter { protected readonly ITargetSystemService TargetSystemService; private readonly string _parameterTypeName = typeof(TDomainObjectDefinition).Name.ToStartLowerCase(); protected ParameterizedObjectValidator(IWorkflowBLLContext context, ITargetSystemService targetSystemService) : base (context) { if (targetSystemService == null) throw new ArgumentNullException(nameof(targetSystemService)); this.TargetSystemService = targetSystemService; } protected abstract object CreateParameterizedObject(TDomainObject domainObject); public ValidationResult GetValidateResult(TDomainObject domainObject) { if (domainObject == null) throw new ArgumentNullException(nameof(domainObject)); var mergeResult = domainObject.Definition.Parameters.GetMergeResult(domainObject.Parameters, definition => definition, instance => instance.Definition); var validateParametersResult = mergeResult.ToValidationResult( list => ValidationResult.FromCondition(!list.Any(), () => $"Unexpected {this._parameterTypeName} parameters: {list.Join(", ", v => v.Definition.Name)}"), list => ValidationResult.FromCondition(!list.Any(), () => $"Missing {this._parameterTypeName} parameters: {list.Join(", ", v => v.Name)}")); var validateParametersValueResult = TryResult.Catch(() => this.Context.AnonymousObjectValidator.GetDynamicValidateResult(this.CreateParameterizedObject(domainObject))) .Match(res => res, error => ValidationResult.CreateError(new Framework.Validation.ValidationException(error.Message, error))); return (validateParametersResult + validateParametersValueResult); } } }
1.226563
1
GitPulseAnalytics/Models/PullRequest.cs
quanyincoder/GitPulseAnalytics
0
764
using System; namespace GitPulseAnalytics.Models { /// <summary> /// Pull request. /// </summary> public class PullRequest { /// <summary> /// Pull request ID /// </summary> public long Id { get; set; } /// <summary> /// Url of the pull request. /// </summary> public string Url { get; set; } /// <summary> /// Sequence number of the pull request. /// </summary> public long Number { get; set; } /// <summary> /// Current state of the pull request. /// </summary> public string State { get; set; } /// <summary> /// Title of the pull request. /// </summary> public string Title { get; set; } /// <summary> /// Title of the pull request. /// </summary> public string Body { get; set; } /// <summary> /// GitHub user who made the pull request. /// </summary> public GitHubUser User { get; set; } /// <summary> /// Time the pull request was created. /// </summary> public DateTime CreatedAt { get; set; } /// <summary> /// Time the pull request was updated. /// </summary> public DateTime? UpdatedAt { get; set; } /// <summary> /// Time the pull request was closed. /// </summary> public DateTime? ClosedAt { get; set; } /// <summary> /// Time the pull request was merged. /// </summary> public DateTime? MergedAt { get; set; } /// <summary> /// Head branch. /// </summary> public Branch Head { get; set; } /// <summary> /// Base branch. /// </summary> public Branch Base { get; set; } } }
1.078125
1
src/DocumentDbTests/Bugs/Bug_365_compiled_query_with_constant_fails.cs
juchom/marten
0
772
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Marten.Linq; using Marten.Services; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace DocumentDbTests.Bugs { public class Bug_365_compiled_query_with_constant_fails: BugIntegrationContext { public class Route { public Guid ID { get; set; } public DateTime Date { get; private set; } public RouteStatus Status { get; private set; } public void Plan(DateTime date) { if (date < DateTime.Today.AddDays(1)) { throw new InvalidOperationException("Route can only plan from tomorrow."); } Status = RouteStatus.Planned; Date = date; } } public enum RouteStatus { Created, Planned, Driving, Stopped } public Bug_365_compiled_query_with_constant_fails() { StoreOptions(_ => { _.Schema.For<Route>(); }); theStore.Options.Providers.StorageFor<Route>().ShouldNotBeNull(); } public class RoutesPlannedAfter: ICompiledQuery<Route, IEnumerable<Route>> { public DateTime DateTime { get; } public RoutesPlannedAfter(DateTime dateTime) { DateTime = dateTime; } public Expression<Func<IMartenQueryable<Route>, IEnumerable<Route>>> QueryIs() { return query => query.Where(route => route.Status == RouteStatus.Planned && route.Date > DateTime); } } [Fact] public void Index_was_outside_the_bounds_of_the_array() { AddRoutes(30); var from = DateTime.Today.AddDays(5); using (var session = theStore.QuerySession()) { var routes = session.Query(new RoutesPlannedAfter(from)).ToList(); var all = session.Query<Route>(); routes.Count.ShouldBe(all.Count(route => route.Status == RouteStatus.Planned && route.Date > from)); } } private void AddRoutes(int number) { using (var session = theStore.OpenSession()) { for (var index = 0; index < number; index++) { var route = new Route(); if (index % 2 == 0) { route.Plan(DateTime.Today.AddDays(index + 1)); } session.Store(route); } session.SaveChanges(); } } } }
1.476563
1
Classes/InterfacesAndPolymorphism/MailService.cs
ejrach/exercises-mosh
0
780
using System; using System.Collections.Generic; using System.Text; namespace InterfacesAndPolymorphism { public class MailService { public void Send(Mail mail) { Console.WriteLine("Sending email..."); } } }
1.039063
1
NetCasbin.UnitTest/Fixtures/TestModelFixture.cs
ChangeTheCode/Casbin.NET
0
788
using System; using System.IO; using System.Text; using NetCasbin.Persist.FileAdapter; namespace NetCasbin.UnitTest.Fixtures { public class TestModelFixture { internal readonly Lazy<string> _abacModelText = LazyReadTestFile("abac_model.conf"); internal readonly Lazy<string> _basicModelText = LazyReadTestFile("basic_model.conf"); internal readonly Lazy<string> _basicWithRootModelText = LazyReadTestFile("basic_with_root_model.conf"); internal readonly Lazy<string> _basicWithoutResourceModelText = LazyReadTestFile("basic_without_resources_model.conf"); internal readonly Lazy<string> _basicWithoutUserModelText = LazyReadTestFile("basic_without_users_model.conf"); internal readonly Lazy<string> _ipMatchModelText = LazyReadTestFile("ipmatch_model.conf"); internal readonly Lazy<string> _keyMatchModelText = LazyReadTestFile("keymatch_model.conf"); internal readonly Lazy<string> _keyMatch2ModelText = LazyReadTestFile("keymatch2_model.conf"); internal readonly Lazy<string> _priorityModelText = LazyReadTestFile("priority_model.conf"); internal readonly Lazy<string> _rbacModelText = LazyReadTestFile("rbac_model.conf"); internal readonly Lazy<string> _rbacWithDenyModelText = LazyReadTestFile("rbac_with_deny_model.conf"); internal readonly Lazy<string> _rbacWithNotDenyModelText = LazyReadTestFile("rbac_with_not_deny_model.conf"); internal readonly Lazy<string> _rbacWithDomainsModelText = LazyReadTestFile("rbac_with_domains_model.conf"); internal readonly Lazy<string> _rbacWithResourceRoleModelText = LazyReadTestFile("rbac_with_resource_roles_model.conf"); internal readonly Lazy<string> _basicPolicyText = LazyReadTestFile("basic_Policy.csv"); internal readonly Lazy<string> _basicWithoutResourcePolicyText = LazyReadTestFile("basic_without_resources_Policy.csv"); internal readonly Lazy<string> _basicWithoutUserPolicyText = LazyReadTestFile("basic_without_users_Policy.csv"); internal readonly Lazy<string> _ipMatchPolicyText = LazyReadTestFile("ipmatch_Policy.csv"); internal readonly Lazy<string> _keyMatchPolicyText = LazyReadTestFile("keymatch_Policy.csv"); internal readonly Lazy<string> _keyMatch2PolicyText = LazyReadTestFile("keymatch2_Policy.csv"); internal readonly Lazy<string> _priorityPolicyText = LazyReadTestFile("priority_Policy.csv"); internal readonly Lazy<string> _priorityIndeterminatePolicyText = LazyReadTestFile("priority_indeterminate_policy.csv"); internal readonly Lazy<string> _rbacPolicyText = LazyReadTestFile("rbac_Policy.csv"); internal readonly Lazy<string> _rbacWithDenyPolicyText = LazyReadTestFile("rbac_with_deny_Policy.csv"); internal readonly Lazy<string> _rbacWithDomainsPolicyText = LazyReadTestFile("rbac_with_domains_Policy.csv"); internal readonly Lazy<string> _rbacWithResourceRolePolicyText = LazyReadTestFile("rbac_with_resource_roles_Policy.csv"); public Model.Model GetBasicTestModel() { return GetNewTestModel(_basicModelText, _basicPolicyText); } public Model.Model GetBasicWithoutResourceTestModel() { return GetNewTestModel(_basicWithoutResourceModelText, _basicWithoutResourcePolicyText); } public Model.Model GetBasicWithoutUserTestModel() { return GetNewTestModel(_basicWithoutUserModelText, _basicWithoutUserPolicyText); } public Model.Model GetNewkeyMatchTestModel() { return GetNewTestModel(_keyMatchModelText, _keyMatchPolicyText); } public Model.Model GetNewkeyMatch2TestModel() { return GetNewTestModel(_keyMatch2ModelText, _keyMatch2PolicyText); } public Model.Model GetNewPriorityTestModel() { return GetNewTestModel(_priorityModelText, _priorityPolicyText); } public Model.Model GetNewRbacTestModel() { return GetNewTestModel(_rbacModelText, _rbacPolicyText); } public Model.Model GetNewRbacWithDenyTestModel() { return GetNewTestModel(_rbacWithDenyModelText, _rbacWithDenyPolicyText); } public Model.Model GetNewRbacWithDomainsTestModel() { return GetNewTestModel(_rbacWithDomainsModelText, _rbacWithDomainsPolicyText); } public Model.Model GetNewRbacWithResourceRoleTestModel() { return GetNewTestModel(_rbacWithResourceRoleModelText, _rbacWithResourceRolePolicyText); } public Model.Model GetNewTestModel(Lazy<string> modelText) { return CoreEnforcer.NewModel(modelText.Value); } public Model.Model GetNewTestModel(Lazy<string> modelText, Lazy<string> policyText) { var model = CoreEnforcer.NewModel(modelText.Value); return LoadModelFromMemory(model, policyText.Value); } private static Model.Model LoadModelFromMemory(Model.Model model, string policy) { model.ClearPolicy(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(policy))) { var fileAdapter = new DefaultFileAdapter(ms); fileAdapter.LoadPolicy(model); } model.RefreshPolicyStringSet(); return model; } private static Lazy<string> LazyReadTestFile(string fileName) { return new Lazy<string>(() => File.ReadAllText(Path.Combine("examples", fileName))); } } }
1.101563
1
src/Framework/Data/Core/Data.Core/SqlQueryable/NetSqlQueryable6.cs
GHCoder-SSC/NetModular
1
796
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using NetModular.Lib.Data.Abstractions; using NetModular.Lib.Data.Abstractions.Entities; using NetModular.Lib.Data.Abstractions.Enums; using NetModular.Lib.Data.Abstractions.Pagination; using NetModular.Lib.Data.Abstractions.SqlQueryable; using NetModular.Lib.Data.Abstractions.SqlQueryable.GroupByQueryable; using NetModular.Lib.Data.Core.SqlQueryable.GroupByQueryable; using NetModular.Lib.Data.Core.SqlQueryable.Internal; using NetModular.Lib.Utils.Core; using NetModular.Lib.Utils.Core.Extensions; namespace NetModular.Lib.Data.Core.SqlQueryable { internal class NetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> : NetSqlQueryableAbstract, INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> where TEntity : IEntity, new() where TEntity2 : IEntity, new() where TEntity3 : IEntity, new() where TEntity4 : IEntity, new() where TEntity5 : IEntity, new() where TEntity6 : IEntity, new() { public NetSqlQueryable(IDbSet dbSet, QueryBody queryBody, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> onExpression, JoinType joinType = JoinType.Left, string tableName = null) : base(dbSet, queryBody) { Check.NotNull(onExpression, nameof(onExpression), "请输入连接条件"); var t6 = new QueryJoinDescriptor { Type = joinType, Alias = "T6", EntityDescriptor = EntityDescriptorCollection.Get<TEntity6>(), On = onExpression, }; t6.TableName = tableName.NotNull() ? tableName : t6.EntityDescriptor.TableName; QueryBody.JoinDescriptors.Add(t6); QueryBody.WhereDelegateType = typeof(Func<,,,,,,>).MakeGenericType(typeof(TEntity), typeof(TEntity2), typeof(TEntity3), typeof(TEntity4), typeof(TEntity5), typeof(TEntity6), typeof(bool)); } private NetSqlQueryable(IDbSet dbSet, QueryBody queryBody) : base(dbSet, queryBody) { } #region ==UseUow== public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> UseUow(IUnitOfWork uow) { QueryBody.UseUow(uow); return this; } #endregion public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> OrderBy(string colName) { return Order(new Sort(colName)); } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> OrderByDescending(string colName) { return Order(new Sort(colName, SortType.Desc)); } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> OrderBy<TKey>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TKey>> expression) { QueryBody.SetOrderBy(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> OrderByDescending<TKey>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TKey>> expression) { QueryBody.SetOrderBy(expression, SortType.Desc); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Order(Sort sort) { QueryBody.SetOrderBy(sort); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Order<TKey>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TKey>> expression, SortType sortType) { QueryBody.SetOrderBy(expression, sortType); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Where(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> expression) { QueryBody.SetWhere(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Where(string whereSql) { QueryBody.SetWhere(whereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereIf(bool condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> expression) { if (condition) Where(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereIf(bool condition, string whereSql) { if (condition) Where(whereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereIf(bool condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> ifExpression, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> elseExpression) { Where(condition ? ifExpression : elseExpression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereIf(bool condition, string ifWhereSql, string elseWhereSql) { Where(condition ? ifWhereSql : elseWhereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(string condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> expression) { if (condition.NotNull()) Where(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(string condition, string whereSql) { if (condition.NotNull()) Where(whereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(string condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> ifExpression, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> elseExpression) { Where(condition.NotNull() ? ifExpression : elseExpression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(string condition, string ifWhereSql, string elseWhereSql) { Where(condition.NotNull() ? ifWhereSql : elseWhereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(object condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> expression) { if (condition != null) Where(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(object condition, string whereSql) { if (condition != null) Where(whereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(object condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> ifExpression, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> elseExpression) { Where(condition != null ? ifExpression : elseExpression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotNull(object condition, string ifWhereSql, string elseWhereSql) { Where(condition != null ? ifWhereSql : elseWhereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotEmpty(Guid condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> expression) { if (condition.NotEmpty()) Where(expression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotEmpty(Guid condition, string whereSql) { if (condition.NotEmpty()) Where(whereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotEmpty(Guid condition, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> ifExpression, Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, bool>> elseExpression) { Where(condition.NotEmpty() ? ifExpression : elseExpression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotEmpty(Guid condition, string ifWhereSql, string elseWhereSql) { Where(condition.NotEmpty() ? ifWhereSql : elseWhereSql); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> WhereNotIn<TKey>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TKey>> key, IEnumerable<TKey> list) { QueryBody.SetWhereNotIn(key, list); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Limit(int skip, int take) { QueryBody.SetLimit(skip, take); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Select<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> selectExpression) { QueryBody.SetSelect(selectExpression); return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7> LeftJoin<TEntity7>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7, bool>> onExpression, string tableName = null) where TEntity7 : IEntity, new() { return new NetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7>(Db, QueryBody, onExpression, JoinType.Left, tableName); } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7> InnerJoin<TEntity7>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7, bool>> onExpression, string tableName = null) where TEntity7 : IEntity, new() { return new NetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7>(Db, QueryBody, onExpression, JoinType.Inner, tableName); } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7> RightJoin<TEntity7>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7, bool>> onExpression, string tableName = null) where TEntity7 : IEntity, new() { return new NetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TEntity7>(Db, QueryBody, onExpression, JoinType.Right, tableName); } public TResult Max<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.Max<TResult>(expression); } public Task<TResult> MaxAsync<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.MaxAsync<TResult>(expression); } public TResult Min<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.Min<TResult>(expression); } public Task<TResult> MinAsync<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.MinAsync<TResult>(expression); } public TResult Sum<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.Sum<TResult>(expression); } public Task<TResult> SumAsync<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.SumAsync<TResult>(expression); } public TResult Avg<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.Avg<TResult>(expression); } public Task<TResult> AvgAsync<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return base.AvgAsync<TResult>(expression); } public IGroupByQueryable6<TResult, TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> GroupBy<TResult>(Expression<Func<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6, TResult>> expression) { return new GroupByQueryable6<TResult, TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6>(Db, QueryBody, QueryBuilder, expression); } public new IList<TEntity> ToList() { return ToList<TEntity>(); } public new Task<IList<TEntity>> ToListAsync() { return ToListAsync<TEntity>(); } public new IList<TEntity> Pagination(Paging paging = null) { return Pagination<TEntity>(paging); } public new Task<IList<TEntity>> PaginationAsync(Paging paging = null) { return PaginationAsync<TEntity>(paging); } public new TEntity First() { return First<TEntity>(); } public new Task<TEntity> FirstAsync() { return FirstAsync<TEntity>(); } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> IncludeDeleted() { QueryBody.FilterDeleted = false; return this; } public INetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6> Copy() { return new NetSqlQueryable<TEntity, TEntity2, TEntity3, TEntity4, TEntity5, TEntity6>(Db, QueryBody.Copy()); } } }
1.359375
1