content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using UnityEngine;
using System.Collections;
using PubNubMessaging.Core;
namespace PubNubMessaging.Tests
{
public class TestCoroutineRunIntegerationPHBError: MonoBehaviour
{
public IEnumerator Start ()
{
CommonIntergrationTests common = new CommonIntergrationTests ();
string url = "http://pubsub.pubnub.com";
string[] multiChannel = {"testChannel"};
//Inducing Error by setting wrong request type
CurrentRequestType crt = CurrentRequestType.PresenceHeartbeat;
string expectedMessage = "404 Nothing";
string expectedChannels = string.Join (",", multiChannel);
ResponseType respType = ResponseType.PresenceHeartbeat;
IEnumerator ienum = common.TestCoroutineRunError(url, 20, -1, multiChannel, false,
false, this.name, expectedMessage, expectedChannels, true, false, false, 0, crt, respType);
yield return StartCoroutine(ienum);
UnityEngine.Debug.Log (string.Format("{0}: After StartCoroutine", this.name));
yield return new WaitForSeconds (CommonIntergrationTests.WaitTimeBetweenCalls);
}
}
}
| 36.666667 | 107 | 0.669421 | [
"Unlicense"
] | MatthewValverde/android-ar-simple | Assets/PubNub/PubnubIntegrationTests/TestCoroutineRunIntegerationPHBError.cs | 1,212 | C# |
namespace Zu.ChromeDevTools.BackgroundService
{
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Represents an adapter for the BackgroundService domain to simplify the command interface.
/// </summary>
public class BackgroundServiceAdapter
{
private readonly ChromeSession m_session;
public BackgroundServiceAdapter(ChromeSession session)
{
m_session = session ?? throw new ArgumentNullException(nameof(session));
}
/// <summary>
/// Gets the ChromeSession associated with the adapter.
/// </summary>
public ChromeSession Session
{
get { return m_session; }
}
/// <summary>
/// Enables event updates for the service.
/// </summary>
public async Task<StartObservingCommandResponse> StartObserving(StartObservingCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<StartObservingCommand, StartObservingCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Disables event updates for the service.
/// </summary>
public async Task<StopObservingCommandResponse> StopObserving(StopObservingCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<StopObservingCommand, StopObservingCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Set the recording state for the service.
/// </summary>
public async Task<SetRecordingCommandResponse> SetRecording(SetRecordingCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<SetRecordingCommand, SetRecordingCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Clears all stored data for the service.
/// </summary>
public async Task<ClearEventsCommandResponse> ClearEvents(ClearEventsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
return await m_session.SendCommand<ClearEventsCommand, ClearEventsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
}
/// <summary>
/// Called when the recording state for the service has been updated.
/// </summary>
public void SubscribeToRecordingStateChangedEvent(Action<RecordingStateChangedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
/// <summary>
/// Called with all existing backgroundServiceEvents when enabled, and all new
/// events afterwards if enabled and recording.
/// </summary>
public void SubscribeToBackgroundServiceEventReceivedEvent(Action<BackgroundServiceEventReceivedEvent> eventCallback)
{
m_session.Subscribe(eventCallback);
}
}
} | 50.388889 | 250 | 0.706174 | [
"Apache-2.0"
] | DoctorDump/AsyncChromeDriver | ChromeDevToolsClient/BackgroundService/BackgroundServiceAdapter.cs | 3,628 | C# |
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Raritan Inc. All rights reserved.
//
// This file was generated by IdlC from Sensor.idl.
using System;
using System.Linq;
using LightJson;
using Com.Raritan.Idl;
using Com.Raritan.JsonRpc;
using Com.Raritan.Util;
#pragma warning disable 0108, 0219, 0414, 1591
namespace Com.Raritan.JsonRpc.sensors.Sensor_4_0_0 {
public class TypeSpecChangedEvent_ValObjCodec : Com.Raritan.JsonRpc.idl.Event_ValObjCodec {
public static new void Register() {
ValueObjectCodec.RegisterCodec(Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpecChangedEvent.typeInfo, new TypeSpecChangedEvent_ValObjCodec());
}
public override void EncodeValObj(LightJson.JsonObject json, ValueObject vo) {
base.EncodeValObj(json, vo);
var inst = (Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpecChangedEvent)vo;
json["oldTypeSpec"] = inst.oldTypeSpec.Encode();
json["newTypeSpec"] = inst.newTypeSpec.Encode();
}
public override ValueObject DecodeValObj(ValueObject vo, LightJson.JsonObject json, Agent agent) {
Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpecChangedEvent inst;
if (vo == null) {
inst = new Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpecChangedEvent();
} else {
inst = (Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpecChangedEvent)vo;
}
base.DecodeValObj(vo, json, agent);
inst.oldTypeSpec = Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpec.Decode(json["oldTypeSpec"], agent);
inst.newTypeSpec = Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpec.Decode(json["newTypeSpec"], agent);
return inst;
}
}
}
| 36.6 | 145 | 0.734062 | [
"BSD-3-Clause"
] | gregoa/raritan-pdu-json-rpc-sdk | pdu-dotnet-api/_idlc_gen/dotnet/Com/Raritan/JsonRpc/sensors/Sensor_4_0_0/TypeSpecChangedEvent_ValObjCodec.cs | 1,647 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FxController : MonoBehaviour
{
public int idPool = -1;
public float timeLife = 2;
ParticleSystem fx;
void Awake()
{
fx = GetComponent<ParticleSystem>();
}
void OnEnable()
{
StartCoroutine(Play());
}
IEnumerator Play()
{
if (fx != null) fx.Play();
yield return new WaitForSeconds(timeLife);
ObjectsPool.Despawn(idPool, gameObject);
yield return null;
}
}
| 18.862069 | 50 | 0.61426 | [
"MIT"
] | FlamperDM/AbstractGame | Assets/MY ASSETS/Scripts/FxController.cs | 549 | C# |
namespace VSCC.Roll20.Macros.Logic
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Documents;
using VSCC.Roll20.Macros.Basic;
public class MacroConditionGreaterN : MacroAction
{
private readonly MacroAction[] _backend = new MacroAction[2];
public override string Name => this.Translate("Macro_LogicGreaterN_Name");
public override string Category => this.Translate("Macro_Category_LogicMath");
public override MacroAction[] Params => this._backend;
public override Type[] ParamTypes => new Type[] { typeof(int), typeof(int) };
public override Type ReturnType => typeof(bool);
public override string[] CreateFormattedText() => new string[] { this.Params[0].CreateFullInnerText(), this.Params[1].CreateFullInnerText() };
public override string CreateFullInnerText() => this.Translate("Macro_LogicGreaterN_FullInnerText", this.Params[0].CreateFullInnerText(), this.Params[1].CreateFullInnerText());
public override IEnumerable<Inline> CreateInnerText()
{
yield return new Hyperlink(new Run()) { Tag = 0 };
yield return new Run(this.Translate("Macro_LogicGreaterN_Text_0"));
yield return new Hyperlink(new Run()) { Tag = 1 };
}
public override void Deserialize(BinaryReader br)
{
this.Params[0] = MacroSerializer.ReadMacroAction(br);
this.Params[1] = MacroSerializer.ReadMacroAction(br);
}
public override object Execute(Macro m, List<string> errors) => (int)this.Params[0].Execute(m, errors) > (int)this.Params[1].Execute(m, errors);
public override void Serialize(BinaryWriter bw)
{
MacroSerializer.WriteMacroAction(bw, this.Params[0]);
MacroSerializer.WriteMacroAction(bw, this.Params[1]);
}
public override void SetDefaults()
{
this.Params[0] = new MacroActionNumberConstant();
this.Params[1] = new MacroActionNumberConstant();
this.Params[0].SetDefaults();
this.Params[1].SetDefaults();
}
}
}
| 38.245614 | 184 | 0.653211 | [
"MIT"
] | skyloutyr/VSCC | VSCC/Roll20/Macros/Logic/Math/MacroConditionGreaterN.cs | 2,182 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the worklink-2018-09-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WorkLink.Model
{
/// <summary>
/// This is the response object from the DisassociateWebsiteCertificateAuthority operation.
/// </summary>
public partial class DisassociateWebsiteCertificateAuthorityResponse : AmazonWebServiceResponse
{
}
} | 31.216216 | 106 | 0.744589 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/WorkLink/Generated/Model/DisassociateWebsiteCertificateAuthorityResponse.cs | 1,155 | C# |
using Ordering.Domain.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ordering.Domain.Entities
{
public class Order: EntityBase
{
public string UserName { get; set; }
public decimal TotalPrice { get; set; }
// BillingAddress
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string AddressLine { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
// Payment
public string CardName { get; set; }
public string CardNumber { get; set; }
public string Expiration { get; set; }
public string CVV { get; set; }
public int PaymentMethod { get; set; }
}
}
| 28.6875 | 48 | 0.619826 | [
"MIT"
] | DimdungPasang/Microservices | src/Services/Ordering/Ordering.Domain/Entities/Order.cs | 920 | C# |
using Model = ToHModels;
using Entity = ToHDL.Entities;
namespace ToHDL
{
/// <summary>
/// To parse entities from DB to models used in BL and vice versa
/// </summary>
public interface IMapper
{
Model.Hero ParseHero(Entity.Hero hero);
Entity.Hero ParseHero(Model.Hero hero);
Model.SuperPower ParseSuperPower(Entity.Superpower superpower);
Entity.Superpower ParseSuperPower(Model.SuperPower superPower);
}
} | 29.0625 | 71 | 0.683871 | [
"MIT"
] | 210215-USF-NET/ConnorAgnone-code | 2-sql/TourOfHeroes/ToHDL/IMapper.cs | 465 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP160R1FieldElement
: AbstractFpFieldElement
{
public static readonly BigInteger Q = SecP160R1Curve.q;
protected internal readonly uint[] x;
public SecP160R1FieldElement(BigInteger x)
{
if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0)
throw new ArgumentException("value invalid for SecP160R1FieldElement", "x");
this.x = SecP160R1Field.FromBigInteger(x);
}
public SecP160R1FieldElement()
{
this.x = Nat160.Create();
}
protected internal SecP160R1FieldElement(uint[] x)
{
this.x = x;
}
public override bool IsZero
{
get { return Nat160.IsZero(x); }
}
public override bool IsOne
{
get { return Nat160.IsOne(x); }
}
public override bool TestBitZero()
{
return Nat160.GetBit(x, 0) == 1;
}
public override BigInteger ToBigInteger()
{
return Nat160.ToBigInteger(x);
}
public override string FieldName
{
get { return "SecP160R1Field"; }
}
public override int FieldSize
{
get { return Q.BitLength; }
}
public override ECFieldElement Add(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R1Field.Add(x, ((SecP160R1FieldElement)b).x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement AddOne()
{
uint[] z = Nat160.Create();
SecP160R1Field.AddOne(x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R1Field.Subtract(x, ((SecP160R1FieldElement)b).x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R1Field.Multiply(x, ((SecP160R1FieldElement)b).x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Divide(ECFieldElement b)
{
// return multiply(b.invert());
uint[] z = Nat160.Create();
Mod.Invert(SecP160R1Field.P, ((SecP160R1FieldElement)b).x, z);
SecP160R1Field.Multiply(z, x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Negate()
{
uint[] z = Nat160.Create();
SecP160R1Field.Negate(x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Square()
{
uint[] z = Nat160.Create();
SecP160R1Field.Square(x, z);
return new SecP160R1FieldElement(z);
}
public override ECFieldElement Invert()
{
// return new SecP160R1FieldElement(ToBigInteger().modInverse(Q));
uint[] z = Nat160.Create();
Mod.Invert(SecP160R1Field.P, x, z);
return new SecP160R1FieldElement(z);
}
// D.1.4 91
/**
* return a sqrt root - the routine verifies that the calculation returns the right value - if
* none exists it returns null.
*/
public override ECFieldElement Sqrt()
{
/*
* Raise this element to the exponent 2^158 - 2^29
*
* Breaking up the exponent's binary representation into "repunits", we get:
* { 129 1s } { 29 0s }
*
* Therefore we need an addition chain containing 129 (the length of the repunit) We use:
* 1, 2, 4, 8, 16, 32, 64, 128, [129]
*/
uint[] x1 = this.x;
if (Nat160.IsZero(x1) || Nat160.IsOne(x1))
{
return this;
}
uint[] x2 = Nat160.Create();
SecP160R1Field.Square(x1, x2);
SecP160R1Field.Multiply(x2, x1, x2);
uint[] x4 = Nat160.Create();
SecP160R1Field.SquareN(x2, 2, x4);
SecP160R1Field.Multiply(x4, x2, x4);
uint[] x8 = x2;
SecP160R1Field.SquareN(x4, 4, x8);
SecP160R1Field.Multiply(x8, x4, x8);
uint[] x16 = x4;
SecP160R1Field.SquareN(x8, 8, x16);
SecP160R1Field.Multiply(x16, x8, x16);
uint[] x32 = x8;
SecP160R1Field.SquareN(x16, 16, x32);
SecP160R1Field.Multiply(x32, x16, x32);
uint[] x64 = x16;
SecP160R1Field.SquareN(x32, 32, x64);
SecP160R1Field.Multiply(x64, x32, x64);
uint[] x128 = x32;
SecP160R1Field.SquareN(x64, 64, x128);
SecP160R1Field.Multiply(x128, x64, x128);
uint[] x129 = x64;
SecP160R1Field.Square(x128, x129);
SecP160R1Field.Multiply(x129, x1, x129);
uint[] t1 = x129;
SecP160R1Field.SquareN(t1, 29, t1);
uint[] t2 = x128;
SecP160R1Field.Square(t1, t2);
return Nat160.Eq(x1, t2) ? new SecP160R1FieldElement(t1) : null;
}
public override bool Equals(object obj)
{
return Equals(obj as SecP160R1FieldElement);
}
public override bool Equals(ECFieldElement other)
{
return Equals(other as SecP160R1FieldElement);
}
public virtual bool Equals(SecP160R1FieldElement other)
{
if (this == other)
return true;
if (null == other)
return false;
return Nat160.Eq(x, other.x);
}
public override int GetHashCode()
{
return Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 5);
}
}
}
#pragma warning restore
#endif
| 31.519231 | 103 | 0.523032 | [
"Apache-2.0"
] | Cl0udG0d/Asteroid | Assets/Import/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecP160R1FieldElement.cs | 6,556 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// Created by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2020 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core)
// Version 5.500.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace Krypton.Toolkit
{
[DebuggerDisplay("({_visualOrientation} {_optimisedVisible})")]
internal class VisualShadowBase : NativeWindow, IDisposable
{
#region Instance Fields
private readonly ShadowValues _shadowValues;
private readonly VisualOrientation _visualOrientation;
private bool _optimisedVisible;
private Bitmap _shadowClip;
#endregion
#region Identity
/// <summary>
/// Create a shadow thingy
/// </summary>
/// <param name="shadowValues">What value will be used</param>
/// <param name="visualOrientation">What orientation for the shadow placement</param>
public VisualShadowBase(ShadowValues shadowValues, VisualOrientation visualOrientation)
{
_shadowValues = shadowValues;
_visualOrientation = visualOrientation;
// Update form properties so we do not have a border and do not show
// in the task bar. We draw the background in Magenta and set that as
// the transparency key so it is a see through window.
CreateParams cp = new CreateParams
{
// Define the screen position/size
X = -2,
Y = -2,
Height = 2,
Width = 2,
Parent = IntPtr.Zero,//_ownerHandle,
Style = unchecked((int) (PI.WS_.DISABLED | PI.WS_.POPUP)),
ExStyle = PI.WS_EX_.LAYERED | PI.WS_EX_.NOACTIVATE | PI.WS_EX_.TRANSPARENT | PI.WS_EX_.NOPARENTNOTIFY
};
_shadowClip = new Bitmap(1, 1);
// Make the default transparent color transparent for myBitmap.
_shadowClip.MakeTransparent();
// Create the actual window
CreateHandle(cp);
}
/// <summary>
/// Make sure the resources are disposed of gracefully.
/// </summary>
public void Dispose()
{
DestroyHandle();
_shadowClip.Dispose();
}
#endregion
#region Public
/// <summary>
/// Show the window without activating it (i.e. do not take focus)
/// </summary>
public bool Visible
{
get => _optimisedVisible;
set
{
if ( _optimisedVisible != value )
{
_optimisedVisible = value;
if (!value)
{
PI.ShowWindow(Handle, PI.ShowWindowCommands.SW_HIDE);
}
}
}
}
/// <summary>
///
/// </summary>
public Rectangle TargetRect { get; private set; }
#endregion
#region Implementation
/// <summary>
/// Calculate the new position, but DO NOT Move
/// </summary>
/// <param name="clientLocation">screen location of parent</param>
/// <param name="windowBounds"></param>
/// <returns>true, if the position has changed</returns>
/// <remarks>
/// Move operations have to be done as a single operation to reduce flickering
/// </remarks>
public bool CalcPositionShadowForm(Point clientLocation, Rectangle windowBounds)
{
Rectangle rect = CalcRectangle(windowBounds);
rect.Offset(clientLocation);
rect.Offset(_shadowValues.Offset);
if (TargetRect != rect)
{
TargetRect = rect;
return true;
}
return false;
}
/// <summary>
/// Also invalidates to perform a redraw
/// </summary>
/// <param name="sourceBitmap">This will be a single bitmap that would represent all the shadows</param>
/// <param name="windowBounds"></param>
public void ReCalcShadow(Bitmap sourceBitmap, Rectangle windowBounds)
{
Rectangle clipRect = CalcRectangle(windowBounds);
if (clipRect.Width > 0
&& clipRect.Height > 0)
{
_shadowClip = sourceBitmap.Clone(clipRect, sourceBitmap.PixelFormat);
}
else
{
_shadowClip = new Bitmap(1, 1);
_shadowClip.MakeTransparent();
}
UpdateShadowLayer();
}
internal void UpdateShadowLayer()
{
// The Following is also in
// $:\Krypton-NET-4.7\Source\Krypton Components\Krypton.Navigator\Dragging\DropDockingIndicatorsRounded.cs
// Does this bitmap contain an alpha channel?
if (_shadowClip.PixelFormat != PixelFormat.Format32bppArgb)
{
throw new ApplicationException("The bitmap must be 32bpp with alpha-channel.");
}
// Must have a visible rectangle to render
if (TargetRect.Width <= 0 || TargetRect.Height <= 0)
{
return;
}
// Get device contexts
IntPtr screenDc = PI.GetDC(IntPtr.Zero);
IntPtr memDc = PI.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr hOldBitmap = IntPtr.Zero;
try
{
// Get handle to the new bitmap and select it into the current
// device context.
hBitmap = _shadowClip.GetHbitmap(Color.FromArgb(0));
hOldBitmap = PI.SelectObject(memDc, hBitmap);
// Set parameters for layered window update.
PI.SIZE newSize = new PI.SIZE(_shadowClip.Width, _shadowClip.Height);
PI.POINT sourceLocation = new PI.POINT(0, 0);
PI.POINT newLocation = new PI.POINT(TargetRect.Left, TargetRect.Top);
PI.BLENDFUNCTION blend = new PI.BLENDFUNCTION
{
BlendOp = PI.AC_SRC_OVER,
BlendFlags = 0,
SourceConstantAlpha = (byte)(255 * _shadowValues.Opacity/100.0),
AlphaFormat = PI.AC_SRC_ALPHA
};
// Update the window.
PI.UpdateLayeredWindow(
Handle, // Handle to the layered window
screenDc, // Handle to the screen DC
ref newLocation, // New screen position of the layered window
ref newSize, // New size of the layered window
memDc, // Handle to the layered window surface DC
ref sourceLocation, // Location of the layer in the DC
0, // Color key of the layered window
ref blend, // Transparency of the layered window
PI.ULW_ALPHA // Use blend as the blend function
);
}
finally
{
// Release device context.
PI.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
PI.SelectObject(memDc, hOldBitmap);
PI.DeleteObject(hBitmap);
}
PI.DeleteDC(memDc);
}
}
/// <summary>
/// Q: Why go to this trouble and not just have a "Huge bitmap"
/// A: Memory for a 4K screen can eat a lot for a 32bit per pixel shader !
/// </summary>
/// <param name="windowBounds"></param>
/// <returns></returns>
private Rectangle CalcRectangle(Rectangle windowBounds)
{
int extraWidth = _shadowValues.ExtraWidth;
int w = windowBounds.Width + extraWidth*2;
int h = windowBounds.Height + extraWidth*2;
int top;
int left;
int bottom;
int right;
switch (_visualOrientation)
{
case VisualOrientation.Top:
top = 0;
left = 0;
bottom = Math.Abs(_shadowValues.Offset.Y)+ extraWidth;
right = w;
break;
case VisualOrientation.Left:
top = Math.Abs(_shadowValues.Offset.Y) + extraWidth;
left = 0;
bottom = h;
right = Math.Abs(_shadowValues.Offset.X) + extraWidth;
break;
case VisualOrientation.Bottom:
top = windowBounds.Height - (Math.Abs(_shadowValues.Offset.Y) + extraWidth);
left = Math.Abs(_shadowValues.Offset.X) + extraWidth;
bottom = h;
right = windowBounds.Width - (Math.Abs(_shadowValues.Offset.X) + extraWidth);
break;
case VisualOrientation.Right:
top = Math.Abs(_shadowValues.Offset.Y) + extraWidth;
left = windowBounds.Width - (Math.Abs(_shadowValues.Offset.X) + extraWidth);
bottom = h;
right = w;
break;
default:
throw new ArgumentOutOfRangeException();
}
return Rectangle.FromLTRB(left, top, right, bottom);
}
#endregion
}
}
| 37.471698 | 164 | 0.519537 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-NET-Core | Source/Truncated Namespaces/Source/Krypton Components/Krypton.Toolkit/Controls Visuals/VisualShadowBase.cs | 9,932 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V251.Segment{
///<summary>
/// Represents an HL7 OM2 message segment.
/// This segment has the following fields:<ol>
///<li>OM2-1: Sequence Number - Test/Observation Master File (NM)</li>
///<li>OM2-2: Units of Measure (CE)</li>
///<li>OM2-3: Range of Decimal Precision (NM)</li>
///<li>OM2-4: Corresponding SI Units of Measure (CE)</li>
///<li>OM2-5: SI Conversion Factor (TX)</li>
///<li>OM2-6: Reference (Normal) Range - Ordinal and Continuous Observations (RFR)</li>
///<li>OM2-7: Critical Range for Ordinal and Continuous Observations (RFR)</li>
///<li>OM2-8: Absolute Range for Ordinal and Continuous Observations (RFR)</li>
///<li>OM2-9: Delta Check Criteria (DLT)</li>
///<li>OM2-10: Minimum Meaningful Increments (NM)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class OM2 : AbstractSegment {
/**
* Creates a OM2 (Numeric Observation) segment object that belongs to the given
* message.
*/
public OM2(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(NM), false, 1, 4, new System.Object[]{message}, "Sequence Number - Test/Observation Master File");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Units of Measure");
this.add(typeof(NM), false, 0, 10, new System.Object[]{message}, "Range of Decimal Precision");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Corresponding SI Units of Measure");
this.add(typeof(TX), false, 1, 60, new System.Object[]{message}, "SI Conversion Factor");
this.add(typeof(RFR), false, 0, 250, new System.Object[]{message}, "Reference (Normal) Range - Ordinal and Continuous Observations");
this.add(typeof(RFR), false, 0, 205, new System.Object[]{message}, "Critical Range for Ordinal and Continuous Observations");
this.add(typeof(RFR), false, 1, 250, new System.Object[]{message}, "Absolute Range for Ordinal and Continuous Observations");
this.add(typeof(DLT), false, 0, 250, new System.Object[]{message}, "Delta Check Criteria");
this.add(typeof(NM), false, 1, 20, new System.Object[]{message}, "Minimum Meaningful Increments");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Sequence Number - Test/Observation Master File(OM2-1).
///</summary>
public NM SequenceNumberTestObservationMasterFile
{
get{
NM ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Units of Measure(OM2-2).
///</summary>
public CE UnitsOfMeasure
{
get{
CE ret = null;
try
{
IType t = this.GetField(2, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Range of Decimal Precision(OM2-3).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public NM GetRangeOfDecimalPrecision(int rep)
{
NM ret = null;
try
{
IType t = this.GetField(3, rep);
ret = (NM)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Range of Decimal Precision (OM2-3).
///</summary>
public NM[] GetRangeOfDecimalPrecision() {
NM[] ret = null;
try {
IType[] t = this.GetField(3);
ret = new NM[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (NM)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Range of Decimal Precision (OM2-3).
///</summary>
public int RangeOfDecimalPrecisionRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(3);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Corresponding SI Units of Measure(OM2-4).
///</summary>
public CE CorrespondingSIUnitsOfMeasure
{
get{
CE ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns SI Conversion Factor(OM2-5).
///</summary>
public TX SIConversionFactor
{
get{
TX ret = null;
try
{
IType t = this.GetField(5, 0);
ret = (TX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Reference (Normal) Range - Ordinal and Continuous Observations(OM2-6).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public RFR GetReferenceNormalRangeOrdinalAndContinuousObservations(int rep)
{
RFR ret = null;
try
{
IType t = this.GetField(6, rep);
ret = (RFR)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Reference (Normal) Range - Ordinal and Continuous Observations (OM2-6).
///</summary>
public RFR[] GetReferenceNormalRangeOrdinalAndContinuousObservations() {
RFR[] ret = null;
try {
IType[] t = this.GetField(6);
ret = new RFR[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (RFR)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Reference (Normal) Range - Ordinal and Continuous Observations (OM2-6).
///</summary>
public int ReferenceNormalRangeOrdinalAndContinuousObservationsRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(6);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Critical Range for Ordinal and Continuous Observations(OM2-7).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public RFR GetCriticalRangeForOrdinalAndContinuousObservations(int rep)
{
RFR ret = null;
try
{
IType t = this.GetField(7, rep);
ret = (RFR)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Critical Range for Ordinal and Continuous Observations (OM2-7).
///</summary>
public RFR[] GetCriticalRangeForOrdinalAndContinuousObservations() {
RFR[] ret = null;
try {
IType[] t = this.GetField(7);
ret = new RFR[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (RFR)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Critical Range for Ordinal and Continuous Observations (OM2-7).
///</summary>
public int CriticalRangeForOrdinalAndContinuousObservationsRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(7);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Absolute Range for Ordinal and Continuous Observations(OM2-8).
///</summary>
public RFR AbsoluteRangeForOrdinalAndContinuousObservations
{
get{
RFR ret = null;
try
{
IType t = this.GetField(8, 0);
ret = (RFR)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Delta Check Criteria(OM2-9).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public DLT GetDeltaCheckCriteria(int rep)
{
DLT ret = null;
try
{
IType t = this.GetField(9, rep);
ret = (DLT)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Delta Check Criteria (OM2-9).
///</summary>
public DLT[] GetDeltaCheckCriteria() {
DLT[] ret = null;
try {
IType[] t = this.GetField(9);
ret = new DLT[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (DLT)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Delta Check Criteria (OM2-9).
///</summary>
public int DeltaCheckCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(9);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Minimum Meaningful Increments(OM2-10).
///</summary>
public NM MinimumMeaningfulIncrements
{
get{
NM ret = null;
try
{
IType t = this.GetField(10, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
}} | 37.64554 | 141 | 0.656357 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V251/Segment/OM2.cs | 16,037 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using commercetools.Sdk.Domain.Errors;
using Type = System.Type;
namespace commercetools.Sdk.Serialization
{
internal class ErrorConverter : JsonConverterDecoratorTypeRetrieverBase<Error>
{
public override string PropertyName => "code";
public override Type DefaultType => typeof(GeneralError);
public ErrorConverter(IDecoratorTypeRetriever<Error> decoratorTypeRetriever) : base(decoratorTypeRetriever)
{
}
}
} | 29.684211 | 115 | 0.748227 | [
"Apache-2.0"
] | commercetools/commercetools-dotnet-core-sdk | commercetools.Sdk/commercetools.Sdk.Serialization/JsonConverters/ErrorConverter.cs | 566 | C# |
using Xunit;
using Chapter4;
using static Chapter4.Utilities;
using cb = Chapter4.Q4_4CheckBalanced<int>;
using cbTweak = Chapter4.Q4_4CheckBalancedTweak<int>;
namespace Tests.Chapter4
{
public class Q4_4
{
[FactAttribute]
private void checkBalancedTest()
{
TreeBinaryNode<int> tree = CreateBinarySearchTree<TreeBinaryNode<int>>(15); //Differ by 0
TreeBinaryNode<int> tree2 = CreateBinarySearchTree<TreeBinaryNode<int>>(13); //Differ by 1
TreeBinaryNode<int> tree3 = new TreeBinaryNode<int>(100, tree, new TreeBinaryNode<int>(700));
TreeBinaryNode<int> tree4 = new TreeBinaryNode<int>(1);
//Without Tweaks
Assert.True(cb.isBalanced(tree));
Assert.True(cb.isBalanced(tree2));
Assert.False(cb.isBalanced(tree3));
Assert.True(cb.isBalanced(tree4));
//With Tweaks
Assert.True(cbTweak.isBalanced(tree));
Assert.True(cbTweak.isBalanced(tree2));
Assert.False(cbTweak.isBalanced(tree3));
Assert.True(cbTweak.isBalanced(tree4));
}
[FactAttribute]
private void checkBalancedNullTest()
{
Assert.True(cb.isBalanced(null));
Assert.True(cbTweak.isBalanced(null));
}
}
} | 33.2 | 105 | 0.623494 | [
"MIT"
] | LuigiAndrea/ctci | test/chapter4/Q4.4-check-balanced-test.cs | 1,328 | C# |
#region License
// Copyright (c) 2019 Ewout van der Linden
// https://github.com/IonKiwi/Json/blob/master/LICENSE
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace IonKiwi.Json.MetaData {
public interface IJsonCustomMemberTypeProvider {
Type? ProvideMemberType(string member);
}
}
| 21.733333 | 54 | 0.782209 | [
"Apache-2.0"
] | IonKiwi/Json | IonKiwi.Json/MetaData/IJsonCustomMemberTypeProvider.cs | 328 | C# |
namespace CoEvent.Data.Interfaces
{
public interface ISubscriptionService : IUpdatableService<Models.Subscription>
{
/// <summary>
/// Get the subscription for the specified 'id'.
/// Validates whether the current user is authorized to view the subscription.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Models.Subscription Get(int id);
}
}
| 31 | 86 | 0.617512 | [
"MIT"
] | FosolSolutions/coevent.api | libs/Data/Interfaces/ISubscriptionService.cs | 436 | C# |
// <copyright file="ITableNameConvention.cs" company="Berkeleybross">
// Copyright (c) Berkeleybross. All rights reserved.
// </copyright>
namespace PeregrineDb.Schema
{
using System;
/// <summary>
/// Defines how to get the table name from a specific type.
/// </summary>
public interface ITableNameConvention
{
/// <summary>
/// Gets the table name from the <paramref name="type"/>.
/// The table name should be properly escaped
/// (Probably by calling <see cref="ISqlNameEscaper.EscapeTableName(string)"/>.
/// </summary>
string GetTableName(Type type);
}
} | 30.428571 | 87 | 0.638498 | [
"MIT"
] | berkeleybross/Dapper.MicroCRUD | src/PeregrineDb/Schema/ITableNameConvention.cs | 639 | C# |
namespace Edelstein.Protocol.Gameplay.Users.Inventories.Modify
{
public enum BodyPart : short
{
Hair = 0,
Cap = 1,
FaceAcc = 2,
EyeAcc = 3,
EarAcc = 4,
Clothes = 5,
Pants = 6,
Shoes = 7,
Gloves = 8,
Cape = 9,
Shield = 10,
Weapon = 11,
Ring1 = 12,
Ring2 = 13,
PetWear = 14,
Ring3 = 15,
Ring4 = 16,
Pendant = 17,
TamingMob = 18,
Saddle = 19,
MobEquip = 20,
PetRingLabel = 21,
PetAbilItem = 22,
PetAbilMeso = 23,
PetAbilHpConsume = 24,
PetAbilMechanicConsume = 25,
PetAbilSweepForDrop = 26,
PetAbilLongRange = 27,
PetAbilPickupOthers = 28,
PetRingQuote = 29,
PetWear2 = 30,
PetRingLabel2 = 31,
PetRingQuote2 = 32,
PetAbilItem2 = 33,
PetAbilMeso2 = 34,
PetAbilSweepForDrop2 = 35,
PetAbilLongRange2 = 36,
PetAbilPickupOthers2 = 37,
PetWear3 = 38,
PetRingLabel3 = 39,
PetRingQuote3 = 40,
PetAbilItem3 = 41,
PetAbilMeso3 = 42,
PetAbilSweepForDrop3 = 43,
PetAbilLongRange3 = 44,
PetAbilPickupOthers3 = 45,
PetAbilIgnoreItems1 = 46,
PetAbilIgnoreItems2 = 47,
PetAbilIgnoreItems3 = 48,
Medal = 49,
Belt = 50,
Shoulder = 51,
Nothing3 = 54,
Nothing2 = 55,
Nothing1 = 56,
Nothing0 = 57,
Ext0 = 59,
ExtPendant1 = 59,
Ext1 = 60,
Ext2 = 61,
Ext3 = 62,
Ext4 = 63,
Ext5 = 64,
Ext6 = 65,
Sticker = 100,
DragonCap = 1000,
DragonPendant = 1001,
DragonWing = 1002,
DragonShoes = 1003,
MechanicEngine = 1100,
MechanicArm = 1101,
MechanicLeg = 1102,
MechanicFrame = 1103,
MechanicTransistor = 1104,
}
}
| 21.912088 | 63 | 0.495486 | [
"MIT"
] | R3DIANCE/Edelstein | src/protocol/Edelstein.Protocol.Gameplay/Users/Inventories/Modify/BodyPart.cs | 1,996 | C# |
#region Copyright (c) 2006-2014 nHydrate.org, All Rights Reserved
// -------------------------------------------------------------------------- *
// NHYDRATE.ORG *
// Copyright (c) 2006-2014 All Rights reserved *
// *
// *
// 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 nHydrate.Generator.Common.EventArgs;
using nHydrate.Generator.Common.GeneratorFramework;
using System.Linq;
namespace nHydrate.Generator.EFDAL.Generators.EFSSDL
{
[GeneratorItem("SSDLGenerator", typeof (EFDALProjectGenerator))]
public class SSDLGenerator : EFDALProjectItemGenerator
{
#region Class Members
private const string RELATIVE_OUTPUT_LOCATION = @"\";
#endregion
#region Overrides
public override int FileCount
{
get { return 1; }
}
public override void Generate()
{
//Sql Server
if ((_model.SupportedPlatforms & SupportedDatabaseConstants.SqlServer) == SupportedDatabaseConstants.SqlServer)
{
{
var template = new SSDLTemplate(_model);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemGeneratedEventArgs(fullFileName, template.FileContent, ProjectName, this, true);
eventArgs.Properties.Add("BuildAction", 3);
OnProjectItemGenerated(this, eventArgs);
}
if (_model.Database.Tables.Any(x => x.IsTenant && x.Generated))
{
var template = new SSDLAdminTemplate(_model);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemGeneratedEventArgs(fullFileName, template.FileContent, ProjectName, this, true);
eventArgs.Properties.Add("BuildAction", 3);
OnProjectItemGenerated(this, eventArgs);
}
else
{
//If this is not a tenant model then remove the admin SSDL file
var template = new SSDLAdminTemplate(_model);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemDeletedEventArgs(fullFileName, ProjectName, this);
OnProjectItemDeleted(this, eventArgs);
}
}
//MySql
if ((_model.SupportedPlatforms & SupportedDatabaseConstants.MySql) == SupportedDatabaseConstants.MySql)
{
var template = new SSDLMySqlTemplate(_model);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemGeneratedEventArgs(fullFileName, template.FileContent, ProjectName, this, true);
eventArgs.Properties.Add("BuildAction", 3);
OnProjectItemGenerated(this, eventArgs);
}
var gcEventArgs = new ProjectItemGenerationCompleteEventArgs(this);
OnGenerationComplete(this, gcEventArgs);
}
#endregion
}
} | 51.197917 | 132 | 0.545066 | [
"MIT"
] | giannik/nHydrate | Source/nHydrate.Generator.EFDAL/Generators/EFSSDL/SSDLGenerator.cs | 4,915 | C# |
using ProjectServices.Application.Interfaces.Serialization.Serializers;
using FluentValidation;
using FluentValidation.Validators;
namespace ProjectServices.Application.Validators.Extensions
{
public static class ValidatorExtensions
{
public static IRuleBuilderOptions<T, string> MustBeJson<T>(this IRuleBuilder<T, string> ruleBuilder, IPropertyValidator<T, string> validator) where T : class
{
return ruleBuilder.SetValidator(validator);
}
}
} | 35.285714 | 165 | 0.757085 | [
"MIT"
] | NguyenDuyCuong/projectservices | src/Application/Validators/Extensions/ValidatorExtensions.cs | 496 | C# |
using System.Runtime.Serialization;
namespace DiabloSharp.DataTransferObjects
{
[DataContract]
internal class EraProfileDto
{
[DataMember(Name = "eraId")]
public long Id { get; set; }
[DataMember(Name = "paragonLevel")]
public long ParagonLevel { get; set; }
[DataMember(Name = "paragonLevelHardcore")]
public long ParagonLevelHardcore { get; set; }
[DataMember(Name = "kills")]
public AccountKillsDto Kills { get; set; }
[DataMember(Name = "timePlayed")]
public TimePlayedDto TimePlayed { get; set; }
[DataMember(Name = "highestHardcoreLevel")]
public long HighestHardcoreLevel { get; set; }
}
} | 27.461538 | 54 | 0.628852 | [
"MIT"
] | leardev/DiabloSharp | src/DiabloSharp/DataTransferObjects/EraProfileDto.cs | 714 | C# |
using System.Threading.Tasks;
using NServiceBus;
public class Startup :
IWantToRunWhenEndpointStartsAndStops
{
public Task Start(IMessageSession session)
{
var myMessage = new MyMessage();
return session.SendLocal(myMessage);
}
public Task Stop(IMessageSession session)
{
return Task.CompletedTask;
}
} | 21.882353 | 47 | 0.66129 | [
"Apache-2.0"
] | A-Franklin/docs.particular.net | samples/logging/hostcustom/Host_7/Sample/Startup.cs | 356 | C# |
using System;
namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Use this attribute to change the name of the <see cref="ModelDescription"/> generated for a type.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)]
public sealed class ModelNameAttribute : Attribute
{
public ModelNameAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
}
| 30.526316 | 136 | 0.675862 | [
"Apache-2.0"
] | Faithlife/newrelic-dotnet-agent | tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs | 580 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 由 MSBuild WriteCodeFragment 类生成。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("5e843403-338f-46ff-a09c-da4a56c7ea9a")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("5e843403-338f-46ff-a09c-da4a56c7ea9a")]
[assembly: System.Reflection.AssemblyTitleAttribute("5e843403-338f-46ff-a09c-da4a56c7ea9a")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
| 50.117647 | 94 | 0.653756 | [
"MIT"
] | NMSAzulX/RoslynPerfomanceTest | RoslynPerfomance/RoslynTest/bin/Release/netcoreapp2.0/5e843403-338f-46ff-a09c-da4a56c7ea9a/obj/Release/netcoreapp2.0/BenchmarkDotNet.Autogenerated.AssemblyInfo.cs | 862 | C# |
namespace asshcii.game
{
public class GameState
{
}
}
| 8.375 | 26 | 0.597015 | [
"MIT"
] | projektir/asshcii | game/GameState.cs | 67 | C# |
namespace InterfaceAndPolymorphism
{
public class Message
{
}
} | 12.666667 | 35 | 0.671053 | [
"MIT"
] | tuvshinot/csharp | csharp/InterfaceAndPolymorphism/Message.cs | 78 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesis-2013-12-02.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.Kinesis
{
/// <summary>
/// Configuration for accessing Amazon Kinesis service
/// </summary>
public partial class AmazonKinesisConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.5.0.18");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonKinesisConfig()
{
this.AuthenticationServiceName = "kinesis";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "kinesis";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2013-12-02";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 25.8875 | 105 | 0.584259 | [
"Apache-2.0"
] | atpyatt/aws-sdk-net | sdk/src/Services/Kinesis/Generated/AmazonKinesisConfig.cs | 2,071 | C# |
/*
HashLib4CSharp Library
Copyright (c) 2020 Ugochukwu Mmaduekwe
GitHub Profile URL <https://github.com/Xor-el>
Distributed under the MIT software license, see the accompanying LICENSE file
or visit http://www.opensource.org/licenses/mit-license.php.
Acknowledgements:
This library was sponsored by Sphere 10 Software (https://www.sphere10.com)
for the purposes of supporting the XXX (https://YYY) project.
*/
using System;
using HashLib4CSharp.Base;
using HashLib4CSharp.Interfaces;
using HashLib4CSharp.Utils;
namespace HashLib4CSharp.Crypto
{
internal sealed class Grindahl256 : BlockHash, ICryptoNotBuiltIn, ITransformBlock
{
private static readonly uint[] Table0 = new uint[256];
private static readonly uint[] Table1 = new uint[256];
private static readonly uint[] Table2 = new uint[256];
private static readonly uint[] Table3 = new uint[256];
private static readonly uint[] MasterTable =
{
0xC66363A5, 0xF87C7C84,
0xEE777799, 0xF67B7B8D, 0xFFF2F20D, 0xD66B6BBD, 0xDE6F6FB1, 0x91C5C554,
0x60303050, 0x02010103, 0xCE6767A9, 0x562B2B7D, 0xE7FEFE19, 0xB5D7D762,
0x4DABABE6, 0xEC76769A, 0x8FCACA45, 0x1F82829D, 0x89C9C940, 0xFA7D7D87,
0xEFFAFA15, 0xB25959EB, 0x8E4747C9, 0xFBF0F00B, 0x41ADADEC, 0xB3D4D467,
0x5FA2A2FD, 0x45AFAFEA, 0x239C9CBF, 0x53A4A4F7, 0xE4727296, 0x9BC0C05B,
0x75B7B7C2, 0xE1FDFD1C, 0x3D9393AE, 0x4C26266A, 0x6C36365A, 0x7E3F3F41,
0xF5F7F702, 0x83CCCC4F, 0x6834345C, 0x51A5A5F4, 0xD1E5E534, 0xF9F1F108,
0xE2717193, 0xABD8D873, 0x62313153, 0x2A15153F, 0x0804040C, 0x95C7C752,
0x46232365, 0x9DC3C35E, 0x30181828, 0x379696A1, 0x0A05050F, 0x2F9A9AB5,
0x0E070709, 0x24121236, 0x1B80809B, 0xDFE2E23D, 0xCDEBEB26, 0x4E272769,
0x7FB2B2CD, 0xEA75759F, 0x1209091B, 0x1D83839E, 0x582C2C74, 0x341A1A2E,
0x361B1B2D, 0xDC6E6EB2, 0xB45A5AEE, 0x5BA0A0FB, 0xA45252F6, 0x763B3B4D,
0xB7D6D661, 0x7DB3B3CE, 0x5229297B, 0xDDE3E33E, 0x5E2F2F71, 0x13848497,
0xA65353F5, 0xB9D1D168, 0x00000000, 0xC1EDED2C, 0x40202060, 0xE3FCFC1F,
0x79B1B1C8, 0xB65B5BED, 0xD46A6ABE, 0x8DCBCB46, 0x67BEBED9, 0x7239394B,
0x944A4ADE, 0x984C4CD4, 0xB05858E8, 0x85CFCF4A, 0xBBD0D06B, 0xC5EFEF2A,
0x4FAAAAE5, 0xEDFBFB16, 0x864343C5, 0x9A4D4DD7, 0x66333355, 0x11858594,
0x8A4545CF, 0xE9F9F910, 0x04020206, 0xFE7F7F81, 0xA05050F0, 0x783C3C44,
0x259F9FBA, 0x4BA8A8E3, 0xA25151F3, 0x5DA3A3FE, 0x804040C0, 0x058F8F8A,
0x3F9292AD, 0x219D9DBC, 0x70383848, 0xF1F5F504, 0x63BCBCDF, 0x77B6B6C1,
0xAFDADA75, 0x42212163, 0x20101030, 0xE5FFFF1A, 0xFDF3F30E, 0xBFD2D26D,
0x81CDCD4C, 0x180C0C14, 0x26131335, 0xC3ECEC2F, 0xBE5F5FE1, 0x359797A2,
0x884444CC, 0x2E171739, 0x93C4C457, 0x55A7A7F2, 0xFC7E7E82, 0x7A3D3D47,
0xC86464AC, 0xBA5D5DE7, 0x3219192B, 0xE6737395, 0xC06060A0, 0x19818198,
0x9E4F4FD1, 0xA3DCDC7F, 0x44222266, 0x542A2A7E, 0x3B9090AB, 0x0B888883,
0x8C4646CA, 0xC7EEEE29, 0x6BB8B8D3, 0x2814143C, 0xA7DEDE79, 0xBC5E5EE2,
0x160B0B1D, 0xADDBDB76, 0xDBE0E03B, 0x64323256, 0x743A3A4E, 0x140A0A1E,
0x924949DB, 0x0C06060A, 0x4824246C, 0xB85C5CE4, 0x9FC2C25D, 0xBDD3D36E,
0x43ACACEF, 0xC46262A6, 0x399191A8, 0x319595A4, 0xD3E4E437, 0xF279798B,
0xD5E7E732, 0x8BC8C843, 0x6E373759, 0xDA6D6DB7, 0x018D8D8C, 0xB1D5D564,
0x9C4E4ED2, 0x49A9A9E0, 0xD86C6CB4, 0xAC5656FA, 0xF3F4F407, 0xCFEAEA25,
0xCA6565AF, 0xF47A7A8E, 0x47AEAEE9, 0x10080818, 0x6FBABAD5, 0xF0787888,
0x4A25256F, 0x5C2E2E72, 0x381C1C24, 0x57A6A6F1, 0x73B4B4C7, 0x97C6C651,
0xCBE8E823, 0xA1DDDD7C, 0xE874749C, 0x3E1F1F21, 0x964B4BDD, 0x61BDBDDC,
0x0D8B8B86, 0x0F8A8A85, 0xE0707090, 0x7C3E3E42, 0x71B5B5C4, 0xCC6666AA,
0x904848D8, 0x06030305, 0xF7F6F601, 0x1C0E0E12, 0xC26161A3, 0x6A35355F,
0xAE5757F9, 0x69B9B9D0, 0x17868691, 0x99C1C158, 0x3A1D1D27, 0x279E9EB9,
0xD9E1E138, 0xEBF8F813, 0x2B9898B3, 0x22111133, 0xD26969BB, 0xA9D9D970,
0x078E8E89, 0x339494A7, 0x2D9B9BB6, 0x3C1E1E22, 0x15878792, 0xC9E9E920,
0x87CECE49, 0xAA5555FF, 0x50282878, 0xA5DFDF7A, 0x038C8C8F, 0x59A1A1F8,
0x09898980, 0x1A0D0D17, 0x65BFBFDA, 0xD7E6E631, 0x844242C6, 0xD06868B8,
0x824141C3, 0x299999B0, 0x5A2D2D77, 0x1E0F0F11, 0x7BB0B0CB, 0xA85454FC,
0x6DBBBBD6, 0x2C16163A
};
private uint[] _state;
private uint[] _temp;
static unsafe Grindahl256()
{
fixed (uint* ptrTable0 = Table0, ptrTable1 = Table1, ptrTable2 = Table2,
ptrTable3 = Table3, ptrMasterTable = MasterTable)
{
PointerUtils.MemMove(ptrTable0, ptrMasterTable, MasterTable.Length * sizeof(uint));
CalcTable(1, ptrTable1);
CalcTable(2, ptrTable2);
CalcTable(3, ptrTable3);
}
}
internal Grindahl256()
: base(32, 4)
{
_state = new uint[13];
_temp = new uint[13];
}
public override IHash Clone() =>
new Grindahl256
{
_state = ArrayUtils.Clone(_state),
_temp = ArrayUtils.Clone(_temp),
Buffer = Buffer.Clone(),
ProcessedBytesCount = ProcessedBytesCount,
BufferSize = BufferSize
};
public override void Initialize()
{
ArrayUtils.ZeroFill(_state);
ArrayUtils.ZeroFill(_temp);
base.Initialize();
}
protected override unsafe byte[] GetResult()
{
var result = new byte[HashSize];
fixed (uint* statePtr = &_state[5])
{
fixed (byte* resultPtr = result)
{
Converters.be32_copy(statePtr, 0, resultPtr, 0,
result.Length);
}
}
return result;
}
protected override unsafe void Finish()
{
var paddingSize = 12 - (int)(ProcessedBytesCount & 3);
var msgLength = (ProcessedBytesCount >> 2) + 1;
Span<byte> pad = stackalloc byte[paddingSize];
pad[0] = 0x80;
msgLength = Converters.be2me_64(msgLength);
Converters.ReadUInt64AsBytesLE(msgLength, pad.Slice(paddingSize - 8));
TransformByteSpan(pad.Slice(0, paddingSize - 4));
fixed (byte* padPtr = pad)
{
_state[0] = Converters.ReadBytesAsUInt32LE(padPtr, paddingSize - 4);
_state[0] = Converters.be2me_32(_state[0]);
}
InjectMsg(true);
for (var i = 0; i < 8; i++) InjectMsg(true);
}
protected override unsafe void TransformBlock(void* data,
int dataLength, int index)
{
_state[0] = Converters.ReadBytesAsUInt32LE((byte*)data, index);
_state[0] = Converters.be2me_32(_state[0]);
InjectMsg(false);
}
private static unsafe void CalcTable(int i, uint* result)
{
for (var j = 0; j < 256; j++) result[j] = (MasterTable[j] >> (i * 8)) | (MasterTable[j] << (32 - i * 8));
}
private void InjectMsg(bool fullProcess)
{
_state[12] = _state[12] ^ 0x01;
if (fullProcess)
_temp[0] = Table0[(byte)(_state[12] >> 24)] ^ Table1
[(byte)(_state[11] >> 16)] ^ Table2[(byte)(_state[9] >> 8)
] ^ Table3[(byte)_state[3]];
_temp[1] = Table0[(byte)(_state[0] >> 24)] ^ Table1
[(byte)(_state[12] >> 16)] ^ Table2[(byte)(_state[10] >> 8)
] ^ Table3[(byte)_state[4]];
_temp[2] = Table0[(byte)(_state[1] >> 24)] ^ Table1
[(byte)(_state[0] >> 16)] ^ Table2[(byte)(_state[11] >> 8)
] ^ Table3[(byte)_state[5]];
_temp[3] = Table0[(byte)(_state[2] >> 24)] ^ Table1
[(byte)(_state[1] >> 16)] ^ Table2[(byte)(_state[12] >> 8)
] ^ Table3[(byte)_state[6]];
_temp[4] = Table0[(byte)(_state[3] >> 24)] ^ Table1
[(byte)(_state[2] >> 16)] ^ Table2[(byte)(_state[0] >> 8)
] ^ Table3[(byte)_state[7]];
_temp[5] = Table0[(byte)(_state[4] >> 24)] ^ Table1
[(byte)(_state[3] >> 16)] ^ Table2[(byte)(_state[1] >> 8)
] ^ Table3[(byte)_state[8]];
_temp[6] = Table0[(byte)(_state[5] >> 24)] ^ Table1
[(byte)(_state[4] >> 16)] ^ Table2[(byte)(_state[2] >> 8)
] ^ Table3[(byte)_state[9]];
_temp[7] = Table0[(byte)(_state[6] >> 24)] ^ Table1
[(byte)(_state[5] >> 16)] ^ Table2[(byte)(_state[3] >> 8)
] ^ Table3[(byte)_state[10]];
_temp[8] = Table0[(byte)(_state[7] >> 24)] ^ Table1
[(byte)(_state[6] >> 16)] ^ Table2[(byte)(_state[4] >> 8)
] ^ Table3[(byte)_state[11]];
_temp[9] = Table0[(byte)(_state[8] >> 24)] ^ Table1
[(byte)(_state[7] >> 16)] ^ Table2[(byte)(_state[5] >> 8)
] ^ Table3[(byte)_state[12]];
_temp[10] = Table0[(byte)(_state[9] >> 24)] ^ Table1
[(byte)(_state[8] >> 16)] ^ Table2[(byte)(_state[6] >> 8)
] ^ Table3[(byte)_state[0]];
_temp[11] = Table0[(byte)(_state[10] >> 24)] ^ Table1
[(byte)(_state[9] >> 16)] ^ Table2[(byte)(_state[7] >> 8)
] ^ Table3[(byte)_state[1]];
_temp[12] = Table0[(byte)(_state[11] >> 24)] ^ Table1
[(byte)(_state[10] >> 16)] ^ Table2[(byte)(_state[8] >> 8)
] ^ Table3[(byte)_state[2]];
// Swap memory pointers
var t = _temp;
_temp = _state;
_state = t;
}
}
} | 42.556962 | 117 | 0.581499 | [
"MIT"
] | Xor-el/HashLib4CSharp | HashLib4CSharp/src/Crypto/Grindahl256.cs | 10,086 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
[RequireComponent(typeof(Ball))]
public class DragLaunch : MonoBehaviour
{
private Ball _ball;
private Vector3 _startPosition;
private Vector3 _endPosition;
private float _startTime;
private float _endTime;
// Use this for initialization
void Start()
{
_ball = GetComponent<Ball>();
}
public void MoveStart(float distance)
{
if (!_ball.InPlay)
{
var xPos = Mathf.Clamp(_ball.transform.position.x + distance, -0.5f, 0.5f);
var yPos = _ball.transform.position.y;
var zPos = _ball.transform.position.z;
_ball.transform.position = new Vector3(xPos, yPos, zPos);
}
}
public void DragStart()
{
if (!_ball.InPlay)
{
_startPosition = Input.mousePosition;
_startTime = Time.time;
}
}
public void DragEnd()
{
if (!_ball.InPlay)
{
_endPosition = Input.mousePosition;
_endTime = Time.time;
float dragDuration = _endTime - _startTime;
float launchSpeedX = (_endPosition.x - _startPosition.x) / dragDuration;
float launchSpeedZ = (_endPosition.y - _startPosition.y) / dragDuration;
var launchVelocity = new Vector3(launchSpeedX / 300, 0, launchSpeedZ / 100);
_ball.Launch(launchVelocity);
}
}
}
| 26.964912 | 88 | 0.611581 | [
"MIT"
] | MartinZikmund/UnityDeveloper2DCourse | BowlerMaster/Assets/Scripts/DragLaunch.cs | 1,539 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using static CVApp.ViewModels.Language.LanguageViewModels;
namespace CVApp.Common.Services.Contracts
{
public interface ILanguageService
{
Task<int> SaveFormData(LanguageInputViewModel model, string userName);
Task<LanguageEditViewModel> EditDeleteForm(int id, string userName);
Task Update(LanguageEditViewModel model);
Task Delete(LanguageEditViewModel model);
Task<IEnumerable<LanguageOutViewModel>> GetLanguageInfo(int resumeId);
}
}
| 28 | 78 | 0.758929 | [
"MIT"
] | EvaSRGitHub/CV-asp.net-mvc | src/CVApp.Common/CVApp.Common/Services/Contracts/ILanguageService.cs | 562 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.WindowsAzure.Storage.Table;
#if PUBLICSTORAGE
namespace Microsoft.Azure.WebJobs.Storage.Table
#else
namespace Microsoft.Azure.WebJobs.Host.Storage.Table
#endif
{
/// <summary>Defines an operation on a table.</summary>
#if PUBLICSTORAGE
public interface IStorageTableOperation
#else
internal interface IStorageTableOperation
#endif
{
/// <summary>Gets the type of operation to perform.</summary>
/// <remarks>
/// When <see cref="OperationType"/> is <see cref="TableOperationType.Retrieve"/>, returns
/// <see langword="null"/>.
/// </remarks>
TableOperationType OperationType { get; }
/// <summary>Gets the entity on which to operate.</summary>
/// <remarks>
/// When <see cref="OperationType"/> is <see cref="TableOperationType.Retrieve"/>, returns
/// <see langword="null"/>.
/// </remarks>
ITableEntity Entity { get; }
/// <summary>Gets the partition key of the entity to retrieve.</summary>
/// <remarks>
/// When <see cref="OperationType"/> is not <see cref="TableOperationType.Retrieve"/>, returns
/// <see langword="null"/>.
/// </remarks>
string RetrievePartitionKey { get; }
/// <summary>Gets the row key of the entity to retrieve.</summary>
/// <remarks>
/// When <see cref="OperationType"/> is not <see cref="TableOperationType.Retrieve"/>, returns
/// <see langword="null"/>.
/// </remarks>
string RetrieveRowKey { get; }
/// <summary>Gets the resolver to resolve the entity to retrieve.</summary>
/// <remarks>
/// When <see cref="OperationType"/> is not <see cref="TableOperationType.Retrieve"/>, returns
/// <see langword="null"/>.
/// </remarks>
IEntityResolver RetrieveEntityResolver { get; }
}
}
| 36.263158 | 102 | 0.626512 | [
"MIT"
] | Azure-App-Service/azure-webjobs-sdk | src/Microsoft.Azure.WebJobs.Storage/Table/IStorageTableOperation.cs | 2,069 | C# |
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Permissions;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Vanjaro.Common.Engines.UIEngine.AngularBootstrap;
using Vanjaro.Common.Entities.Apps;
namespace Vanjaro.UXManager.Extensions.Menu.LogoAndTitle.Factories
{
public class AppFactory
{
private const string ModuleRuntimeVersion = "1.0.0";
internal static string GetAllowedRoles(string Identifier)
{
AngularView template = GetViews().Where(t => t.Identifier == Identifier).FirstOrDefault();
if (template != null)
{
return template.AccessRoles;
}
return string.Empty;
}
public static List<AngularView> GetViews()
{
List<AngularView> Views = new List<AngularView>();
AngularView roles = new AngularView
{
AccessRoles = "user",
UrlPaths = new List<string> {
"setting"
},
IsDefaultTemplate = true,
TemplatePath = "setting/setting.html",
Identifier = Identifier.setting_setting.ToString(),
Defaults = new Dictionary<string, string> { }
};
Views.Add(roles);
return Views;
}
public static string GetAccessRoles(UserInfo UserInfo)
{
List<string> AccessRoles = new List<string>();
if (UserInfo.UserID > 0)
{
AccessRoles.Add("user");
}
else
{
AccessRoles.Add("anonymous");
}
if (UserInfo.UserID > -1 && (UserInfo.IsInRole("Administrators")))
{
AccessRoles.Add("admin");
}
if (UserInfo.IsSuperUser)
{
AccessRoles.Add("host");
}
if (TabPermissionController.HasTabPermission("EDIT"))
{
AccessRoles.Add("editpage");
}
return string.Join(",", AccessRoles);
}
public static AppInformation GetAppInformation()
{
return new AppInformation(ExtensionInfo.Name, ExtensionInfo.FriendlyName, ExtensionInfo.GUID, GetRuntimeVersion, "http://www.mandeeps.com/store", "http://www.mandeeps.com/Activation", 14, 7, new List<string> { "Domain", "Server" }, false);
}
public AppInformation AppInformation => GetAppInformation();
public static string GetRuntimeVersion
{
get
{
try
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
catch { }
return ModuleRuntimeVersion;
}
}
public enum Identifier
{
setting_setting
}
public static dynamic GetLocalizedEnumOption(Type EnumType)
{
Array data = System.Enum.GetNames(EnumType);
List<dynamic> list = new List<dynamic>();
dynamic item = null;
foreach (string name in data)
{
int value = (int)Enum.Parse(EnumType, name);
item = new ExpandoObject();
item.Key = name;
item.Value = value;
list.Add(item);
}
return list;
}
}
} | 30.704348 | 251 | 0.526763 | [
"MIT"
] | Bradinz/Vanjaro.Platform | DesktopModules/Vanjaro/UXManager/Extensions/Menu/LogoAndTitle/Factories/AppFactory.cs | 3,533 | C# |
namespace Jellyfish.Network;
public class KeyPair
{
public string Address { get; init; } = string.Empty;
public string PrivateKey { get; init; } = string.Empty;
}
| 21.625 | 59 | 0.693642 | [
"MIT"
] | defichaininfo/Jellyfish.NET | Jellyfish.NET/Network/KeyPair.cs | 175 | C# |
// <copyright file="PasswordControlTestsChrome.cs" company="Automate The Planet Ltd.">
// Copyright 2020 Automate The Planet 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.
// </copyright>
// <author>Anton Angelov</author>
// <site>https://bellatrix.solutions/</site>
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bellatrix.Web.Tests.Controls
{
[TestClass]
[Browser(BrowserType.Chrome, Lifecycle.ReuseIfStarted)]
[AllureSuite("Password Control")]
public class PasswordControlTestsChrome : MSTest.WebTest
{
public override void TestInit() => App.NavigationService.NavigateToLocalPage(ConfigurationService.GetSection<TestPagesSettings>().PasswordLocalPage);
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void PasswordSet_When_UseSetPasswordMethod_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
passwordElement.SetPassword("bellatrix");
Assert.AreEqual("bellatrix", passwordElement.GetPassword());
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetPasswordReturnsCorrectPassword_When_DefaultPasswordIsSet_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword3");
Assert.AreEqual("password for stars", passwordElement.GetPassword());
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void AutoCompleteReturnsFalse_When_NoAutoCompleteAttributeIsPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
Assert.AreEqual(false, passwordElement.IsAutoComplete);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void AutoCompleteReturnsFalse_When_AutoCompleteAttributeExistsAndIsSetToOff_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword5");
Assert.AreEqual(false, passwordElement.IsAutoComplete);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void AutoCompleteReturnsTrue_When_AutoCompleteAttributeExistsAndIsSetToOn_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword4");
Assert.AreEqual(true, passwordElement.IsAutoComplete);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetReadonlyReturnsFalse_When_ReadonlyAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword4");
Assert.AreEqual(false, passwordElement.IsReadonly);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetReadonlyReturnsTrue_When_ReadonlyAttributeIsPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword6");
Assert.AreEqual(true, passwordElement.IsReadonly);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetMaxLengthReturnsNull_When_MaxLengthAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
var maxLength = passwordElement.MaxLength;
Assert.IsNull(maxLength);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetMinLengthReturnsNull_When_MinLengthAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
Assert.IsNull(passwordElement.MinLength);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetSizeReturnsDefault20_When_SizeAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
// Specifies the width of an <input> element, in characters. Default value is 20
Assert.AreEqual(20, passwordElement.Size);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetMaxLengthReturns80_When_MaxLengthAttributeIsPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword2");
Assert.AreEqual(80, passwordElement.MaxLength);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetMinLengthReturns10_When_MinLengthAttributeIsPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword2");
Assert.AreEqual(10, passwordElement.MinLength);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetSizeReturns30_When_SizeAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword2");
Assert.AreEqual(30, passwordElement.Size);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetRequiredReturnsFalse_When_RequiredAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword4");
Assert.AreEqual(false, passwordElement.IsRequired);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetRequiredReturnsTrue_When_RequiredAttributeIsPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword7");
Assert.AreEqual(true, passwordElement.IsRequired);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetPlaceholder_When_PlaceholderAttributeIsSet_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword");
Assert.AreEqual("your password term goes here", passwordElement.Placeholder);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void GetPlaceholderReturnsNull_When_PlaceholderAttributeIsNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword1");
Assert.IsNull(passwordElement.Placeholder);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void ReturnRed_When_Hover_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword8");
passwordElement.Hover();
Assert.AreEqual("color: red;", passwordElement.GetStyle());
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void ReturnBlue_When_Focus_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword9");
passwordElement.Focus();
Assert.AreEqual("color: blue;", passwordElement.GetStyle());
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void ReturnFalse_When_DisabledAttributeNotPresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword9");
bool isDisabled = passwordElement.IsDisabled;
Assert.IsFalse(isDisabled);
}
[TestMethod]
[TestCategory(Categories.Chrome), TestCategory(Categories.Windows), TestCategory(Categories.OSX)]
public void ReturnTrue_When_DisabledAttributePresent_Chrome()
{
var passwordElement = App.ElementCreateService.CreateById<Password>("myPassword10");
bool isDisabled = passwordElement.IsDisabled;
Assert.IsTrue(isDisabled);
}
}
} | 42.995595 | 157 | 0.704201 | [
"Apache-2.0"
] | alexandrejulien/BELLATRIX | tests/Bellatrix.Web.Tests/Controls/Password/PasswordControlTestsChrome.cs | 9,762 | C# |
using Foundation;
using Prism;
using Prism.Ioc;
using UIKit;
namespace APIMVVM.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App(new iOSInitializer()));
return base.FinishedLaunching(app, options);
}
}
public class iOSInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry container)
{
}
}
}
| 31.641026 | 98 | 0.666937 | [
"MIT"
] | openorbt/treinamento-xamarinforms | MVVM/APIMVVM/APIMVVM.iOS/AppDelegate.cs | 1,236 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using DotnetSpider.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace DotnetSpider
{
/// <summary>
/// 启动任务工具
/// </summary>
public abstract class Startup
{
public static void Execute<TSpider>(params string[] args)
{
var logfile = Environment.GetEnvironmentVariable("DOTNET_SPIDER_ID");
logfile = string.IsNullOrWhiteSpace(logfile) ? "dotnet-spider.log" : $"/logs/{logfile}.log";
Environment.SetEnvironmentVariable("LOGFILE", logfile);
if (Log.Logger == null)
{
var configure = new LoggerConfiguration()
#if DEBUG
.MinimumLevel.Verbose()
#else
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console().WriteTo
.RollingFile(logfile);
Log.Logger = configure.CreateLogger();
}
Framework.SetMultiThread();
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
configurationBuilder.AddCommandLine(args, Framework.SwitchMappings);
configurationBuilder.AddEnvironmentVariables();
var configuration = configurationBuilder.Build();
var id = configuration["DOTNET_SPIDER_ID"] ?? Guid.NewGuid().ToString("N");
var name = configuration["DOTNET_SPIDER_NAME"] ?? id;
var arguments = Environment.GetCommandLineArgs();
var builder = new SpiderHostBuilder();
builder.ConfigureLogging(b =>
{
#if DEBUG
b.SetMinimumLevel(LogLevel.Debug);
#else
b.SetMinimumLevel(LogLevel.Information);
#endif
b.AddSerilog();
});
var config = configuration["DOTNET_SPIDER_CONFIG"];
builder.ConfigureAppConfiguration(x =>
{
if (!string.IsNullOrWhiteSpace(config) && File.Exists(config))
{
// 添加 JSON 配置文件
x.AddJsonFile(config);
}
else
{
if (File.Exists("appsettings.json"))
{
x.AddJsonFile("appsettings.json");
}
}
x.AddCommandLine(Environment.GetCommandLineArgs(), Framework.SwitchMappings);
x.AddEnvironmentVariables();
});
builder.ConfigureServices(services =>
{
services.AddLocalEventBus();
services.AddLocalDownloadCenter();
services.AddDownloaderAgent(x =>
{
x.UseFileLocker();
x.UseDefaultAdslRedialer();
x.UseDefaultInternetDetector();
});
services.AddStatisticsCenter(x =>
{
// 添加内存统计服务
x.UseMemory();
});
});
var spiderType = typeof(TSpider);
builder.Register(spiderType);
var provider = builder.Build();
var instance = provider.Create(spiderType);
if (instance != null)
{
instance.Name = name;
instance.Id = id;
instance.RunAsync(arguments).ConfigureAwait(true).GetAwaiter().GetResult();
}
else
{
Log.Logger.Error("Create spider object failed", 0, ConsoleColor.DarkYellow);
}
}
/// <summary>
/// DLL 名字中包含任意一个即是需要扫描的 DLL
/// </summary>
protected List<string> DetectAssembles { get; set; } = new List<string> {"spiders"};
protected abstract void ConfigureService(IConfiguration configuration, SpiderHostBuilder builder);
/// <summary>
/// 运行
/// </summary>
/// <param name="args">运行参数</param>
public void Execute(params string[] args)
{
try
{
var logfile = Environment.GetEnvironmentVariable("DOTNET_SPIDER_ID");
logfile = string.IsNullOrWhiteSpace(logfile) ? "dotnet-spider.log" : $"/logs/{logfile}.log";
Environment.SetEnvironmentVariable("LOGFILE", logfile);
ConfigureSerialLog(logfile);
Framework.SetMultiThread();
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
configurationBuilder.AddCommandLine(args, Framework.SwitchMappings);
configurationBuilder.AddEnvironmentVariables();
var configuration = configurationBuilder.Build();
string spiderTypeName = configuration["DOTNET_SPIDER_TYPE"];
if (string.IsNullOrWhiteSpace(spiderTypeName))
{
Log.Logger.Error("There is no specified spider type");
return;
}
var name = configuration["DOTNET_SPIDER_NAME"];
var id = configuration["DOTNET_SPIDER_ID"] ?? Guid.NewGuid().ToString("N");
var arguments = configuration["DOTNET_SPIDER_ARGS"]?.Split(' ');
var spiderTypes = DetectSpiders();
if (spiderTypes == null || spiderTypes.Count == 0)
{
return;
}
var spiderType = spiderTypes.FirstOrDefault(x =>
x.UnderlyingSystemType.ToString().ToLower() == spiderTypeName.ToLower());
if (spiderType == null)
{
Log.Logger.Error($"Spider {spiderTypeName} not found", 0, ConsoleColor.DarkYellow);
return;
}
var builder = new SpiderHostBuilder();
ConfigureService(configuration, builder);
builder.Register(spiderType);
var provider = builder.Build();
var instance = provider.Create(spiderType);
if (instance != null)
{
instance.Name = name;
instance.Id = id;
instance.RunAsync(arguments).ConfigureAwait(true).GetAwaiter().GetResult();
}
else
{
Log.Logger.Error("Create spider object failed", 0, ConsoleColor.DarkYellow);
}
}
catch (Exception e)
{
Log.Logger.Error($"Execute spider failed: {e}");
}
}
protected virtual void ConfigureSerialLog(string file)
{
var configure = new LoggerConfiguration()
#if DEBUG
.MinimumLevel.Verbose()
#else
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console().WriteTo
.RollingFile(file);
Log.Logger = configure.CreateLogger();
}
/// <summary>
/// 检测爬虫类型
/// </summary>
/// <returns></returns>
protected virtual HashSet<Type> DetectSpiders()
{
var spiderTypes = new HashSet<Type>();
var spiderType = typeof(Spider);
var asmNames = DetectAssemblies();
foreach (var file in asmNames)
{
var asm = Assembly.Load(file);
var types = asm.GetTypes();
foreach (var type in types)
{
if (spiderType.IsAssignableFrom(type))
{
spiderTypes.Add(type);
}
}
}
if (asmNames.Count == 0)
{
var entryAsm = Assembly.GetEntryAssembly();
if (entryAsm == null)
{
throw new SpiderException("EntryAssembly not found");
}
asmNames = new List<string>
{
entryAsm.GetName(false).Name
};
var types = entryAsm.GetTypes();
foreach (var type in types)
{
if (spiderType.IsAssignableFrom(type))
{
spiderTypes.Add(type);
}
}
}
var spiderInfo = $"Spiders : {spiderTypes.Count}";
if (Environment.GetEnvironmentVariable("DOTNET_SPIDER_PRINT_SPIDERS") == "true")
{
spiderInfo = $"{spiderInfo}, {string.Join(", ", spiderTypes.Select(x => x.Name))}";
}
Log.Logger.Information($"Assembly : {string.Join(", ", asmNames)}", 0, ConsoleColor.DarkYellow);
Log.Logger.Information(spiderInfo, 0, ConsoleColor.DarkYellow);
return spiderTypes;
}
/// <summary>
/// 扫描所有需要求的DLL
/// </summary>
/// <returns></returns>
protected virtual List<string> DetectAssemblies()
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
var files = Directory.GetFiles(path)
.Where(f => f.EndsWith(".dll") || f.EndsWith(".exe"))
.Select(f => Path.GetFileName(f).Replace(".dll", "").Replace(".exe", "")).ToList();
return
files.Where(f => !f.Contains("DotnetSpider")
&& DetectAssembles.Any(n => f.ToLower().Contains(n))).ToList();
}
}
} | 26.846154 | 103 | 0.672571 | [
"MIT"
] | Meng-Ye/DotnetSpider | src/DotnetSpider/Startup.cs | 7,790 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WinDynamicDesktop
{
class DesktopHelper
{
public static string GetCurrentDirectory()
{
return Path.GetDirectoryName(Application.ExecutablePath);
}
}
class DesktopStartupManager : StartupManager
{
private bool startOnBoot;
private string registryStartupLocation = @"Software\Microsoft\Windows\CurrentVersion\Run";
public DesktopStartupManager(MenuItem startupMenuItem) : base(startupMenuItem)
{
RegistryKey startupKey = Registry.CurrentUser.OpenSubKey(registryStartupLocation);
startOnBoot = startupKey.GetValue("WinDynamicDesktop") != null;
startupKey.Close();
_menuItem.Checked = startOnBoot;
}
public override void ToggleStartOnBoot()
{
RegistryKey startupKey = Registry.CurrentUser.OpenSubKey(registryStartupLocation, true);
if (!startOnBoot)
{
string exePath = Path.Combine(Directory.GetCurrentDirectory(),
Environment.GetCommandLineArgs()[0]);
startupKey.SetValue("WinDynamicDesktop", exePath);
startOnBoot = true;
}
else
{
startupKey.DeleteValue("WinDynamicDesktop");
startOnBoot = false;
}
_menuItem.Checked = startOnBoot;
}
}
}
| 30.236364 | 101 | 0.603728 | [
"MIT"
] | GitArpe/WinDynamicDesktop | src/DesktopHelper.cs | 1,665 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
/* This class was auto-generated by the message builder generator tools. */
using Ca.Infoway.Messagebuilder;
namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue {
public interface EntericCoatedTablet : Code {
}
}
| 36.37931 | 83 | 0.709953 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/EntericCoatedTablet.cs | 1,055 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Newtonsoft.Json;
using Xunit;
using Xunit.Sdk;
using System.Threading.Tasks;
using System.IO;
namespace System.Text.Json.Serialization.Tests
{
public static partial class NullTests
{
[Fact]
public static void ClassWithNullProperty()
{
TestClassWithNull obj = JsonSerializer.Deserialize<TestClassWithNull>(TestClassWithNull.s_json);
obj.Verify();
}
[Fact]
public static void RootObjectIsNull()
{
{
TestClassWithNull obj = JsonSerializer.Deserialize<TestClassWithNull>("null");
Assert.Null(obj);
}
{
object obj = JsonSerializer.Deserialize<object>("null");
Assert.Null(obj);
}
{
string obj = JsonSerializer.Deserialize<string>("null");
Assert.Null(obj);
}
{
IEnumerable<int> obj = JsonSerializer.Deserialize<IEnumerable<int>>("null");
Assert.Null(obj);
}
{
Dictionary<string, object> obj = JsonSerializer.Deserialize<Dictionary<string, object>>("null");
Assert.Null(obj);
}
}
[Fact]
public static void RootArrayIsNull()
{
{
int[] obj = JsonSerializer.Deserialize<int[]>("null");
Assert.Null(obj);
}
{
object[] obj = JsonSerializer.Deserialize<object[]>("null");
Assert.Null(obj);
}
{
TestClassWithNull[] obj = JsonSerializer.Deserialize<TestClassWithNull[]>("null");
Assert.Null(obj);
}
}
[Fact]
public static void DefaultIgnoreNullValuesOnRead()
{
TestClassWithInitializedProperties obj = JsonSerializer.Deserialize<TestClassWithInitializedProperties>(TestClassWithInitializedProperties.s_null_json);
Assert.Null(obj.MyString);
Assert.Null(obj.MyInt);
Assert.Null(obj.MyDateTime);
Assert.Null(obj.MyIntArray);
Assert.Null(obj.MyIntList);
Assert.Null(obj.MyNullableIntList);
Assert.Null(obj.MyObjectList[0]);
Assert.Null(obj.MyListList[0][0]);
Assert.Null(obj.MyDictionaryList[0]["key"]);
Assert.Null(obj.MyStringDictionary["key"]);
Assert.Null(obj.MyNullableDateTimeDictionary["key"]);
Assert.Null(obj.MyObjectDictionary["key"]);
Assert.Null(obj.MyStringDictionaryDictionary["key"]["key"]);
Assert.Null(obj.MyListDictionary["key"][0]);
Assert.Null(obj.MyObjectDictionaryDictionary["key"]["key"]);
}
[Fact]
public static void EnableIgnoreNullValuesOnRead()
{
var options = new JsonSerializerOptions();
options.IgnoreNullValues = true;
TestClassWithInitializedProperties obj = JsonSerializer.Deserialize<TestClassWithInitializedProperties>(TestClassWithInitializedProperties.s_null_json, options);
Assert.Equal("Hello", obj.MyString);
Assert.Equal(1, obj.MyInt);
Assert.Equal(new DateTime(1995, 4, 16), obj.MyDateTime);
Assert.Equal(1, obj.MyIntArray[0]);
Assert.Equal(1, obj.MyIntList[0]);
Assert.Equal(1, obj.MyNullableIntList[0]);
Assert.Null(obj.MyObjectList[0]);
Assert.Null(obj.MyObjectList[0]);
Assert.Null(obj.MyListList[0][0]);
Assert.Null(obj.MyDictionaryList[0]["key"]);
Assert.Null(obj.MyNullableDateTimeDictionary["key"]);
Assert.Null(obj.MyStringDictionary["key"]);
Assert.Null(obj.MyObjectDictionary["key"]);
Assert.Null(obj.MyStringDictionaryDictionary["key"]["key"]);
Assert.Null(obj.MyListDictionary["key"][0]);
Assert.Null(obj.MyObjectDictionaryDictionary["key"]["key"]);
}
[Fact]
public static void ParseNullArgumentFail()
{
Assert.Throws<ArgumentNullException>(() => JsonSerializer.Deserialize<string>((string)null));
Assert.Throws<ArgumentNullException>(() => JsonSerializer.Deserialize("1", (Type)null));
}
[Fact]
public static void NullLiteralObjectInput()
{
{
string obj = JsonSerializer.Deserialize<string>("null");
Assert.Null(obj);
}
{
string obj = JsonSerializer.Deserialize<string>(@"""null""");
Assert.Equal("null", obj);
}
}
[Fact]
public static void NullAcceptsLeadingAndTrailingTrivia()
{
{
TestClassWithNull obj = JsonSerializer.Deserialize<TestClassWithNull>(" null");
Assert.Null(obj);
}
{
object obj = JsonSerializer.Deserialize<object>("null ");
Assert.Null(obj);
}
{
object obj = JsonSerializer.Deserialize<object>(" null\t");
Assert.Null(obj);
}
}
[Fact]
public static void NullReadTestChar()
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("null"));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>(""));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("1234"));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("\"stringTooLong\""));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("\"\u0059\"B"));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<char>("\"\uD800\uDC00\""));
Assert.Equal('a', JsonSerializer.Deserialize<char>("\"a\""));
Assert.Equal('Y', JsonSerializer.Deserialize<char>("\"\u0059\""));
}
[ActiveIssue("https://github.com/dotnet/corefx/issues/1037")]
[Fact]
public static void ParseNullStringToStructShouldThrowJsonException()
{
string nullString = "null";
Utf8JsonReader reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(nullString));
JsonTestHelper.AssertThrows<JsonException>(reader, (reader) => JsonSerializer.Deserialize<SimpleStruct>(ref reader));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<SimpleStruct>(Encoding.UTF8.GetBytes(nullString)));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<SimpleStruct>(nullString));
}
[ActiveIssue("https://github.com/dotnet/corefx/issues/1037")]
[Fact]
public static async Task ParseNullStringShouldThrowJsonExceptionAsync()
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("null")))
{
await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializer.DeserializeAsync<SimpleStruct>(stream));
}
}
}
}
| 37.872449 | 173 | 0.581571 | [
"MIT"
] | AzureMentor/runtime | src/libraries/System.Text.Json/tests/Serialization/Null.ReadTests.cs | 7,423 | C# |
using Windows.UI.Xaml.Controls;
namespace XamarinMVVM.UWP.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
| 20.9375 | 81 | 0.591045 | [
"MIT"
] | qmatteoq/XamarinSamples | Shared/XamarinMVVM/XamarinMVVM.UWP/Views/MainPage.xaml.cs | 337 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.DotNet.ImageBuilder.Models.Image;
namespace Microsoft.DotNet.ImageBuilder.Tests.Helpers
{
public static class ImageInfoHelper
{
public static PlatformData CreatePlatform(
string dockerfile,
string digest = null,
string architecture = "amd64",
string osType = "Linux",
string osVersion = "focal",
List<string> simpleTags = null,
string baseImageDigest = null,
DateTime? created = null)
{
PlatformData platform = new PlatformData
{
Dockerfile = dockerfile,
Digest = digest,
Architecture = architecture,
OsType = osType,
OsVersion = osVersion,
SimpleTags = simpleTags,
BaseImageDigest = baseImageDigest,
};
if (created.HasValue)
{
platform.Created = created.Value;
}
return platform;
}
}
}
| 30.302326 | 71 | 0.572525 | [
"MIT"
] | MichaelSimons/docker-tools | src/Microsoft.DotNet.ImageBuilder/tests/Helpers/ImageInfoHelper.cs | 1,305 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WebApp.Shared
{
public class TestTypes
{
public TestTypes()
{
this.AllHeadings = new[] { "Lighthouse Performance", "404 page", "Lighthouse SEO", "Lighthouse Best Practices", "W3C HTML", "W3C CSS", "Lighthouse PWA", "Standard files", "Lighthouse A11y", "Sitespeed.io", "Yellow Lab Tools", "Webbkoll", "HTTP & Tech" };
this.ExcludedTypes = new[] { 7, 8 };
this.Count = this.AllHeadings.Length;
}
public string[] AllHeadings { get; private set; }
public int[] ExcludedTypes { get; private set; }
public int Count { get; private set; }
}
}
| 31.954545 | 266 | 0.611664 | [
"MIT"
] | krompaco/webperf-leaderboard | src/WebApp/Shared/TestTypes.cs | 703 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Coyote.IO;
namespace Microsoft.Coyote.Utilities
{
internal sealed class CommandLineOptions
{
/// <summary>
/// The command line parser to use.
/// </summary>
private readonly CommandLineArgumentParser Parser;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLineOptions"/> class.
/// </summary>
internal CommandLineOptions()
{
this.Parser = new CommandLineArgumentParser("Coyote",
"The Coyote tool enables you to systematically test a specified Coyote test, generate " +
"a reproducible bug-trace if a bug is found, and replay a bug-trace using the VS debugger.");
var basicGroup = this.Parser.GetOrCreateGroup("Basic", "Basic options", true);
var commandArg = basicGroup.AddPositionalArgument("command", "The operation perform (test, replay)");
commandArg.AllowedValues = new List<string>(new string[] { "test", "replay", "telemetry" });
basicGroup.AddPositionalArgument("path", "Path to the Coyote program to test");
basicGroup.AddArgument("method", "m", "Suffix of the test method to execute");
basicGroup.AddArgument("timeout", "t", "Timeout in seconds (disabled by default)", typeof(uint));
basicGroup.AddArgument("outdir", "o", "Dump output to directory x (absolute path or relative to current directory");
basicGroup.AddArgument("verbose", "v", "Enable verbose log output during testing", typeof(bool));
basicGroup.AddArgument("debug", "d", "Enable debugging", typeof(bool)).IsHidden = true;
basicGroup.AddArgument("break", "b", "Attaches the debugger and also adds a breakpoint when an assertion fails (disabled during parallel testing)", typeof(bool));
basicGroup.AddArgument("version", null, "Show tool version", typeof(bool));
var testingGroup = this.Parser.GetOrCreateGroup("testingGroup", "Systematic testing options");
testingGroup.DependsOn = new CommandLineArgumentDependency() { Name = "command", Value = "test" };
testingGroup.AddArgument("iterations", "i", "Number of schedules to explore for bugs", typeof(uint));
testingGroup.AddArgument("max-steps", "ms", @"Max scheduling steps to be explored during systematic testing (by default 10,000 unfair and 100,000 fair steps).
You can provide one or two unsigned integer values", typeof(uint)).IsMultiValue = true;
testingGroup.AddArgument("timeout-delay", null, "Controls the frequency of timeouts by built-in timers (not a unit of time)", typeof(uint));
testingGroup.AddArgument("fail-on-maxsteps", null, "Consider it a bug if the test hits the specified max-steps", typeof(bool));
testingGroup.AddArgument("liveness-temperature-threshold", null, "Specify the liveness temperature threshold is the liveness temperature value that triggers a liveness bug", typeof(uint));
testingGroup.AddArgument("parallel", "p", "Number of parallel testing processes (the default '0' runs the test in-process)", typeof(uint));
testingGroup.AddArgument("sch-random", null, "Choose the random scheduling strategy (this is the default)", typeof(bool));
testingGroup.AddArgument("sch-probabilistic", "sp", "Choose the probabilistic scheduling strategy with given probability for each scheduling decision where the probability is " +
"specified as the integer N in the equation 0.5 to the power of N. So for N=1, the probability is 0.5, for N=2 the probability is 0.25, N=3 you get 0.125, etc.", typeof(uint));
testingGroup.AddArgument("sch-pct", null, "Choose the PCT scheduling strategy with given maximum number of priority switch points", typeof(uint));
testingGroup.AddArgument("sch-fairpct", null, "Choose the fair PCT scheduling strategy with given maximum number of priority switch points", typeof(uint));
testingGroup.AddArgument("sch-portfolio", null, "Choose the portfolio scheduling strategy", typeof(bool));
var replayOptions = this.Parser.GetOrCreateGroup("replayOptions", "Replay options");
replayOptions.DependsOn = new CommandLineArgumentDependency() { Name = "command", Value = "replay" };
replayOptions.AddPositionalArgument("schedule", "Schedule file to replay");
var coverageGroup = this.Parser.GetOrCreateGroup("coverageGroup", "Code and activity coverage options");
var coverageArg = coverageGroup.AddArgument("coverage", "c", @"Generate code coverage statistics (via VS instrumentation) with zero or more values equal to:
code: Generate code coverage statistics (via VS instrumentation)
activity: Generate activity (state machine, event, etc.) coverage statistics
activity-debug: Print activity coverage statistics with debug info", typeof(string));
coverageArg.AllowedValues = new List<string>(new string[] { string.Empty, "code", "activity", "activity-debug" });
coverageArg.IsMultiValue = true;
coverageGroup.AddArgument("instrument", "instr", "Additional file spec(s) to instrument for code coverage (wildcards supported)", typeof(string));
coverageGroup.AddArgument("instrument-list", "instr-list", "File containing the paths to additional file(s) to instrument for code " +
"coverage, one per line, wildcards supported, lines starting with '//' are skipped", typeof(string));
var advancedGroup = this.Parser.GetOrCreateGroup("advancedGroup", "Advanced options");
advancedGroup.AddArgument("explore", null, "Keep testing until the bound (e.g. iteration or time) is reached", typeof(bool));
advancedGroup.AddArgument("seed", null, "Specify the random value generator seed", typeof(uint));
advancedGroup.AddArgument("wait-for-testing-processes", null, "Wait for testing processes to start (default is to launch them)", typeof(bool));
advancedGroup.AddArgument("testing-scheduler-ipaddress", null, "Specify server ip address and optional port (default: 127.0.0.1:0))", typeof(string));
advancedGroup.AddArgument("testing-scheduler-endpoint", null, "Specify a name for the server (default: CoyoteTestScheduler)", typeof(string));
advancedGroup.AddArgument("graph-bug", null, "Output a DGML graph of the iteration that found a bug", typeof(bool));
advancedGroup.AddArgument("graph", null, "Output a DGML graph of all test iterations whether a bug was found or not", typeof(bool));
advancedGroup.AddArgument("xml-trace", null, "Specify a filename for XML runtime log output to be written to", typeof(bool));
advancedGroup.AddArgument("actor-runtime-log", null, "Specify an additional custom logger using fully qualified name: 'fullclass,assembly'", typeof(string));
// Hidden options (for debugging or experimentation only).
var hiddenGroup = this.Parser.GetOrCreateGroup("hiddenGroup", "Hidden Options");
hiddenGroup.IsHidden = true;
hiddenGroup.AddArgument("sch-interactive", null, "Choose the interactive scheduling strategy", typeof(bool));
hiddenGroup.AddArgument("prefix", null, "Safety prefix bound", typeof(int)); // why is this needed, seems to just be an override for MaxUnfairSchedulingSteps?
hiddenGroup.AddArgument("run-as-parallel-testing-task", null, null, typeof(bool));
hiddenGroup.AddArgument("additional-paths", null, null, typeof(string));
hiddenGroup.AddArgument("testing-process-id", null, "The id of the controlling TestingProcessScheduler", typeof(uint));
// hiddenGroup.AddArgument("sch-dfs", null, "Choose the DFS scheduling strategy", typeof(bool)); // currently broken, re-enable when it's fixed
hiddenGroup.AddArgument("parallel-debug", "pd", "Used with --parallel to put up a debugger prompt on each child process", typeof(bool));
}
internal void PrintHelp(TextWriter w)
{
this.Parser.PrintHelp(w);
}
/// <summary>
/// Parses the command line options and returns a configuration.
/// </summary>
/// <param name="args">The command line arguments to parse.</param>
/// <param name="configuration">The Configuration object populated with the parsed command line options.</param>
internal bool Parse(string[] args, Configuration configuration)
{
try
{
var result = this.Parser.ParseArguments(args);
if (result != null)
{
foreach (var arg in result)
{
UpdateConfigurationWithParsedArgument(configuration, arg);
}
SanitizeConfiguration(configuration);
return true;
}
}
catch (CommandLineException ex)
{
if ((from arg in ex.Result where arg.LongName == "version" select arg).Any())
{
WriteVersion();
Environment.Exit(1);
}
else
{
this.Parser.PrintHelp(Console.Out);
Error.ReportAndExit(ex.Message);
}
}
catch (Exception ex)
{
this.Parser.PrintHelp(Console.Out);
Error.ReportAndExit(ex.Message);
}
return false;
}
/// <summary>
/// Updates the configuration with the specified parsed argument.
/// </summary>
private static void UpdateConfigurationWithParsedArgument(Configuration configuration, CommandLineArgument option)
{
switch (option.LongName)
{
case "command":
configuration.ToolCommand = (string)option.Value;
break;
case "outdir":
configuration.OutputFilePath = (string)option.Value;
break;
case "verbose":
configuration.IsVerbose = true;
break;
case "debug":
configuration.EnableDebugging = true;
Debug.IsEnabled = true;
break;
case "timeout":
configuration.Timeout = (int)(uint)option.Value;
break;
case "path":
configuration.AssemblyToBeAnalyzed = (string)option.Value;
break;
case "method":
configuration.TestMethodName = (string)option.Value;
break;
case "seed":
configuration.RandomGeneratorSeed = (uint)option.Value;
break;
case "sch-random":
case "sch-dfs":
case "sch-interactive":
case "sch-portfolio":
configuration.SchedulingStrategy = option.LongName.Substring(4);
break;
case "sch-probabilistic":
case "sch-pct":
case "sch-fairpct":
configuration.SchedulingStrategy = option.LongName.Substring(4);
configuration.StrategyBound = (int)(uint)option.Value;
break;
case "schedule":
{
string filename = (string)option.Value;
string extension = System.IO.Path.GetExtension(filename);
if (!extension.Equals(".schedule"))
{
Error.ReportAndExit("Please give a valid schedule file " +
"with extension '.schedule'.");
}
configuration.ScheduleFile = filename;
}
break;
case "version":
WriteVersion();
Environment.Exit(1);
break;
case "break":
configuration.AttachDebugger = true;
break;
case "iterations":
configuration.TestingIterations = (int)(uint)option.Value;
break;
case "parallel":
configuration.ParallelBugFindingTasks = (uint)option.Value;
break;
case "parallel-debug":
configuration.ParallelDebug = true;
break;
case "wait-for-testing-processes":
configuration.WaitForTestingProcesses = true;
break;
case "testing-scheduler-ipaddress":
{
var ipAddress = (string)option.Value;
int port = 0;
if (ipAddress.Contains(":"))
{
string[] parts = ipAddress.Split(':');
if (parts.Length != 2 || !int.TryParse(parts[1], out port))
{
Error.ReportAndExit("Please give a valid port number for --testing-scheduler-ipaddress option");
}
ipAddress = parts[0];
}
if (!IPAddress.TryParse(ipAddress, out _))
{
Error.ReportAndExit("Please give a valid ip address for --testing-scheduler-ipaddress option");
}
configuration.TestingSchedulerIpAddress = ipAddress + ":" + port;
}
break;
case "run-as-parallel-testing-task":
configuration.RunAsParallelBugFindingTask = true;
break;
case "additional-paths":
configuration.AdditionalPaths = (string)option.Value;
break;
case "testing-scheduler-endpoint":
configuration.TestingSchedulerEndPoint = (string)option.Value;
break;
case "testing-process-id":
configuration.TestingProcessId = (uint)option.Value;
break;
case "graph":
configuration.IsDgmlGraphEnabled = true;
configuration.IsDgmlBugGraph = false;
break;
case "graph-bug":
configuration.IsDgmlGraphEnabled = true;
configuration.IsDgmlBugGraph = true;
break;
case "xml-trace":
configuration.IsXmlLogEnabled = true;
break;
case "actor-runtime-log":
configuration.CustomActorRuntimeLogType = (string)option.Value;
break;
case "explore":
configuration.PerformFullExploration = true;
break;
case "coverage":
if (option.Value == null)
{
configuration.ReportCodeCoverage = true;
configuration.ReportActivityCoverage = true;
}
else
{
foreach (var item in (string[])option.Value)
{
switch (item)
{
case "code":
configuration.ReportCodeCoverage = true;
break;
case "activity":
configuration.ReportActivityCoverage = true;
break;
case "activity-debug":
configuration.ReportActivityCoverage = true;
configuration.DebugActivityCoverage = true;
break;
default:
break;
}
}
}
break;
case "instrument":
configuration.AdditionalCodeCoverageAssemblies[(string)option.Value] = false;
break;
case "instrument-list":
configuration.AdditionalCodeCoverageAssemblies[(string)option.Value] = true;
break;
case "timeout-delay":
configuration.TimeoutDelay = (uint)option.Value;
break;
case "max-steps":
{
uint[] values = (uint[])option.Value;
if (values.Length > 2)
{
Error.ReportAndExit("Invalid number of options supplied via '--max-steps'.");
}
try
{
uint i = values[0];
uint j;
if (values.Length == 2)
{
j = values[1];
configuration.WithMaxSchedulingSteps(i, j);
}
else
{
configuration.WithMaxSchedulingSteps(i);
}
}
catch (ArgumentException)
{
Error.ReportAndExit("For the option '--max-steps N[,M]', please make sure that M >= N.");
}
}
break;
case "fail-on-maxsteps":
configuration.ConsiderDepthBoundHitAsBug = true;
break;
case "prefix":
configuration.SafetyPrefixBound = (int)option.Value;
break;
case "liveness-temperature-threshold":
configuration.LivenessTemperatureThreshold = (int)(uint)option.Value;
configuration.UserExplicitlySetLivenessTemperatureThreshold = true;
break;
default:
throw new Exception(string.Format("Unhandled parsed argument: '{0}'", option.LongName));
}
}
private static void WriteVersion()
{
Console.WriteLine("Version: {0}", typeof(CommandLineOptions).Assembly.GetName().Version);
}
/// <summary>
/// Checks the configuration for errors.
/// </summary>
private static void SanitizeConfiguration(Configuration configuration)
{
if (string.IsNullOrEmpty(configuration.AssemblyToBeAnalyzed) &&
string.Compare(configuration.ToolCommand, "test", StringComparison.OrdinalIgnoreCase) == 0)
{
Error.ReportAndExit("Please give a valid path to a Coyote program's dll using 'test x'.");
}
if (configuration.SchedulingStrategy != "portfolio" &&
configuration.SchedulingStrategy != "interactive" &&
configuration.SchedulingStrategy != "random" &&
configuration.SchedulingStrategy != "pct" &&
configuration.SchedulingStrategy != "fairpct" &&
configuration.SchedulingStrategy != "probabilistic" &&
configuration.SchedulingStrategy != "dfs")
{
Error.ReportAndExit("Please provide a scheduling strategy (see --sch* options)");
}
if (configuration.SafetyPrefixBound > 0 &&
configuration.SafetyPrefixBound >= configuration.MaxUnfairSchedulingSteps)
{
Error.ReportAndExit("Please give a safety prefix bound that is less than the " +
"max scheduling steps bound.");
}
}
}
}
| 52.951407 | 200 | 0.542456 | [
"MIT"
] | Bhaskers-Blu-Org2/coyote | Tools/Coyote/Utilities/CommandLineOptions.cs | 20,706 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Automation.V20170515Preview.Inputs
{
/// <summary>
/// Linux specific update configuration.
/// </summary>
public sealed class LinuxPropertiesArgs : Pulumi.ResourceArgs
{
[Input("excludedPackageNameMasks")]
private InputList<string>? _excludedPackageNameMasks;
/// <summary>
/// packages excluded from the software update configuration.
/// </summary>
public InputList<string> ExcludedPackageNameMasks
{
get => _excludedPackageNameMasks ?? (_excludedPackageNameMasks = new InputList<string>());
set => _excludedPackageNameMasks = value;
}
/// <summary>
/// Update classifications included in the software update configuration.
/// </summary>
[Input("includedPackageClassifications")]
public Input<string>? IncludedPackageClassifications { get; set; }
[Input("includedPackageNameMasks")]
private InputList<string>? _includedPackageNameMasks;
/// <summary>
/// packages included from the software update configuration.
/// </summary>
public InputList<string> IncludedPackageNameMasks
{
get => _includedPackageNameMasks ?? (_includedPackageNameMasks = new InputList<string>());
set => _includedPackageNameMasks = value;
}
/// <summary>
/// Reboot setting for the software update configuration.
/// </summary>
[Input("rebootSetting")]
public Input<string>? RebootSetting { get; set; }
public LinuxPropertiesArgs()
{
}
}
}
| 33.186441 | 102 | 0.645557 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Automation/V20170515Preview/Inputs/LinuxPropertiesArgs.cs | 1,958 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.foas.Model.V20181111
{
public class CommitJobResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.209302 | 63 | 0.71606 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-foas/Foas/Model/V20181111/CommitJobResponse.cs | 1,127 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Entities.Tabs.TabVersions.Exceptions
{
using System;
/// <summary>
/// Exception to notify error about managing tab versions.
/// </summary>
public class DnnTabVersionException : ApplicationException
{
/// <summary>
/// Initializes a new instance of the <see cref="DnnTabVersionException"/> class.
/// Constructs an instance of <see cref = "ApplicationException" /> class with the specified message.
/// </summary>
/// <param name = "message">The message to associate with the exception.</param>
public DnnTabVersionException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DnnTabVersionException"/> class.
/// Constructs an instance of <see cref = "ApplicationException" /> class with the specified message and
/// inner exception.
/// </summary>
/// <param name = "message">The message to associate with the exception.</param>
/// <param name = "innerException">The exception which caused this error.</param>
public DnnTabVersionException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| 40.756757 | 114 | 0.644562 | [
"MIT"
] | Acidburn0zzz/Dnn.Platform | DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs | 1,510 | C# |
using MagicalLifeAPI.Components.Generic.Renderable;
using MagicalLifeAPI.Components.Resource;
using MagicalLifeAPI.Sound;
using MagicalLifeAPI.Visual.Rendering.AbstractVisuals;
using MagicalLifeAPI.World.Base;
using MagicalLifeAPI.World.Items;
using ProtoBuf;
using System.Collections.Generic;
namespace MagicalLifeAPI.World.Resources.Tree
{
/// <summary>
/// An oak tree.
/// </summary>
[ProtoContract]
public class OakTree : TreeBase
{
private static readonly string Name = "Oak Tree";
public static readonly int Durabilitie = 20;
public static readonly int XOffset = Tile.GetTileSize().X / -2;
public static readonly int YOffset = Tile.GetTileSize().Y * -3 / 2;
public static OffsetTexture OffsetStump { get; set; }
public static OffsetTexture OffsetTrunk { get; set; }
public static OffsetTexture OffsetLeaves { get; set; }
public OakTree(int durability) : base(Name, durability)
{
this.HarvestingBehavior = new DropWhenCompletelyHarvested(new List<Base.Item>
{
new Log(1, this.Durability)
}, SoundsTable.AxeHit, SoundsTable.TreeFall);
}
public OakTree()
{
}
public override AbstractHarvestable HarvestingBehavior { get; set; }
public override List<AbstractVisual> GetVisuals()
{
List<AbstractVisual> ret = new List<AbstractVisual>
{
OffsetTrunk,
OffsetLeaves,
OffsetStump
};
return ret;
}
}
} | 29.962963 | 89 | 0.62979 | [
"MIT"
] | ockenyberg/MagicalLife | MagicalLifeAPIStandard/World/Resources/OakTree.cs | 1,620 | C# |
// ReSharper disable All
namespace OpenTl.Schema.Updates
{
using System;
using System.Collections;
using OpenTl.Schema;
public interface IDifferenceCommon : IObject
{
}
}
| 12.933333 | 48 | 0.701031 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/Updates/Difference/IDifferenceCommon.cs | 196 | C# |
using System;
namespace ShinySwitch
{
public class Switch
{
public static TypeSwitchStatement<TSubject> On<TSubject>(TSubject subject) => new TypeSwitchStatement<TSubject>(subject, new SwitchResult<bool>());
public static SystemTypeSwitchStatement On(Type subject) => new SystemTypeSwitchStatement(subject, new SwitchResult<bool>());
}
public class Switch<TExpression>
{
public static TypeSwitchExpression<TSubject, TExpression> On<TSubject>(TSubject subject) => new TypeSwitchExpression<TSubject, TExpression>(subject, new SwitchResult<TExpression>());
public static TypeSwitchExpression2<TLeft, TRight, TExpression> On<TLeft, TRight>(TLeft left, TRight right) => new TypeSwitchExpression2<TLeft, TRight, TExpression>(left, right, new SwitchResult<TExpression>());
public static SystemTypeSwitchExpression<TExpression> On(Type subject) => new SystemTypeSwitchExpression<TExpression>(subject, new SwitchResult<TExpression>());
}
public static class SwitchStatementEx
{
public static TypeSwitchExpression<TSubject, TExpression> Return<TExpression, TSubject>(this SwitchStatement<TSubject> expression, TExpression prototype) =>
new TypeSwitchExpression<TSubject, TExpression>(expression.Subject, new SwitchResult<TExpression>());
}
} | 57.913043 | 219 | 0.756006 | [
"MIT"
] | asgerhallas/ShinySwitch | ShinySwitch/Switch.cs | 1,334 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace NbaStore.App.Infrastructure.Validations
{
public class SizeValidationAttirubte : ValidationAttribute
{
public override bool IsValid(object value)
{
var size = value as string;
if (size == null)
{
return true;
}
if(size!="Small" && size!="Medium" && size != "Large" && size != "XXL")
{
return false;
}
return true;
}
}
}
| 23.321429 | 83 | 0.539051 | [
"MIT"
] | YordanYordanov97/Softuni | Nba Store/NbaStore.App/Infrastructure/Validations/SizeValidation.cs | 655 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Mozlite.Extensions.Security.Permissions;
using System.Collections.Generic;
using System.Linq;
namespace Mozlite.Mvc.AdminMenus.TagHelpers
{
/// <summary>
/// 管理员菜单标签。
/// </summary>
[HtmlTargetElement("moz:menu", Attributes = AttributeName)]
public class AdminMenuTagHelper : Mvc.TagHelpers.ViewContextableTagHelperBase
{
private readonly IMenuProviderFactory _menuProviderFactory;
private readonly IUrlHelperFactory _factory;
private readonly IPermissionManager _permissionManager;
private IUrlHelper _urlHelper;
private const string AttributeName = "provider";
/// <summary>
/// 菜单提供者名称。
/// </summary>
[HtmlAttributeName(AttributeName)]
public string Provider { get; set; }
/// <summary>
/// 初始化类<see cref="AdminMenuTagHelper"/>。
/// </summary>
/// <param name="menuProviderFactory">菜单提供者工厂接口。</param>
/// <param name="factory">URL辅助类工厂接口。</param>
/// <param name="permissionManager">权限管理接口。</param>
public AdminMenuTagHelper(IMenuProviderFactory menuProviderFactory, IUrlHelperFactory factory, IPermissionManager permissionManager)
{
_menuProviderFactory = menuProviderFactory;
_factory = factory;
_permissionManager = permissionManager;
}
/// <summary>
/// 访问并呈现当前标签实例。
/// </summary>
/// <param name="context">当前HTML标签上下文,包含当前HTML相关信息。</param>
/// <param name="output">当前标签输出实例,用于呈现标签相关信息。</param>
public override void Process(TagHelperContext context, TagHelperOutput output)
{
_urlHelper = _factory.GetUrlHelper(ViewContext);
output.TagName = "ul";
var items = _menuProviderFactory.GetRoots(Provider)
.Where(IsAuthorized)//当前项
.ToList();
if (items.Count == 0)
return;
var current = ViewContext.GetCurrent(_menuProviderFactory, Provider, _urlHelper);
foreach (var item in items)
{
var children = item.Where(IsAuthorized).ToList();
var li = CreateMenuItem(item, current, children, item.Any());
if (li == null)
continue;
output.Content.AppendHtml(li);
}
}
private TagBuilder CreateMenuItem(MenuItem item, MenuItem current, List<MenuItem> items, bool hasSub)
{
var li = new TagBuilder("li");
if (items?.Count > 0)
{
if (current.IsCurrent(item))
li.AddCssClass("opened");
li.AddCssClass("has-sub");
}
else if (hasSub)
{//包含子菜单,子菜单中没有一个有权限,则主菜单也没有权限
return null;
}
li.AddCssClass("nav-item");
var isCurrent = current.IsCurrent(item);
if (isCurrent)
li.AddCssClass("active");
var anchor = new TagBuilder("a");
anchor.MergeAttribute("href", item.LinkUrl(_urlHelper));
anchor.MergeAttribute("title", item.Text);
anchor.AddCssClass($"nav-link level-{item.Level}");
//图标
if (!string.IsNullOrWhiteSpace(item.IconName))
{
if (item.IconName.StartsWith("fa-"))
anchor.InnerHtml.AppendHtml($"<i class=\"fa {item.IconName}\"></i>");
else
anchor.InnerHtml.AppendHtml($"<i class=\"{item.IconName}\"></i>");
}
//文本
var span = new TagBuilder("span");
span.AddCssClass("title");
span.InnerHtml.Append(item.Text);
anchor.InnerHtml.AppendHtml(span);
if (!string.IsNullOrWhiteSpace(item.BadgeText))
//badge
{
var badge = new TagBuilder("span");
badge.AddCssClass("badge");
badge.AddCssClass(item.BadgeClassName);
badge.InnerHtml.Append(item.BadgeText);
anchor.InnerHtml.AppendHtml(badge);
}
li.InnerHtml.AppendHtml(anchor);
//子菜单
if (items?.Count > 0)
CreateChildren(li, items, current);
return li;
}
private void CreateChildren(TagBuilder li, List<MenuItem> items, MenuItem current)
{
var ihasSub = false;
var iul = new TagBuilder("ul");
foreach (var it in items.OrderByDescending(x => x.Priority))
{
var children = it.Where(IsAuthorized).ToList();
var ili = CreateMenuItem(it, current, children, it.Any());
if (ili != null)
{
ihasSub = true;
iul.InnerHtml.AppendHtml(ili);
}
}
if (ihasSub)
li.InnerHtml.AppendHtml(iul);
}
/// <summary>
/// 判断是否具有权限。
/// </summary>
/// <param name="item">菜单项。</param>
/// <returns>返回验证结果。</returns>
public bool IsAuthorized(MenuItem item)
{
if (item.PermissionName == null)
return true;
return _permissionManager.IsAuthorized($"{item.PermissionName}");
}
}
} | 37.445946 | 140 | 0.550704 | [
"Apache-2.0"
] | Mozlite/Docs | src/Mozlite.Mvc/AdminMenus/TagHelpers/AdminMenuTagHelper.cs | 5,848 | C# |
using OnlineQuizClasses;
using OnlineQuizClasses.QuizManagement;
using Rotativa;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
namespace OnLineQuizApplication.Controllers
{
public class AdminController : Controller
{
// GET: Admin
public ActionResult Index()
{
return View();
}
public ActionResult AllQuizes()
{
List<Quiz> quizzes = new QuizHandler().GetAllQuizzes();
return View(quizzes);
}
public ActionResult PrintAll()
{
var print = new ActionAsPdf("AllQuizes");
return print;
}
public ActionResult DeleteQuiz(int id)
{
QuizContext db = new QuizContext();
List<Quiz> p = (from c in db.Quizzes
where c.Id == id
select c).ToList();
db.Entry(User).State = EntityState.Unchanged;
db.Entry(p).State = EntityState.Deleted;
db.SaveChanges();
return Json("Delete", JsonRequestBehavior.AllowGet);
}
}
}
| 26.409091 | 67 | 0.564544 | [
"Apache-2.0"
] | ArslanAmeer/eQuiizz | OnLineQuizApplication/Controllers/AdminController.cs | 1,164 | C# |
//
// Encog(tm) Core v3.1 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2012 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
namespace Encog.ML.Genetic.Genome
{
/// <summary>
/// Used to compare two genomes, a score object is used.
/// </summary>
///
public class GenomeComparator : IComparer<IGenome>
{
/// <summary>
/// The method to calculate the score.
/// </summary>
///
private readonly ICalculateGenomeScore _calculateScore;
/// <summary>
/// Construct the genome comparator.
/// </summary>
///
/// <param name="theCalculateScore">The score calculation object to use.</param>
public GenomeComparator(ICalculateGenomeScore theCalculateScore)
{
_calculateScore = theCalculateScore;
}
/// <value>The score calculation object.</value>
public ICalculateGenomeScore CalculateScore
{
get { return _calculateScore; }
}
#region IComparer<IGenome> Members
/// <summary>
/// Compare two genomes.
/// </summary>
///
/// <param name="genome1">The first genome.</param>
/// <param name="genome2">The second genome.</param>
/// <returns>Zero if equal, or less than or greater than zero to indicate
/// order.</returns>
public int Compare(IGenome genome1, IGenome genome2)
{
return genome1.Score.CompareTo(genome2.Score);
}
#endregion
/// <summary>
/// Apply a bonus, this is a simple percent that is applied in the direction
/// specified by the "should minimize" property of the score function.
/// </summary>
///
/// <param name="v">The current value.</param>
/// <param name="bonus">The bonus.</param>
/// <returns>The resulting value.</returns>
public double ApplyBonus(double v, double bonus)
{
double amount = v*bonus;
if (_calculateScore.ShouldMinimize)
{
return v - amount;
}
return v + amount;
}
/// <summary>
/// Apply a penalty, this is a simple percent that is applied in the
/// direction specified by the "should minimize" property of the score
/// function.
/// </summary>
///
/// <param name="v">The current value.</param>
/// <param name="bonus">The penalty.</param>
/// <returns>The resulting value.</returns>
public double ApplyPenalty(double v, double bonus)
{
double amount = v*bonus;
return _calculateScore.ShouldMinimize ? v - amount : v + amount;
}
/// <summary>
/// Determine the best score from two scores, uses the "should minimize"
/// property of the score function.
/// </summary>
///
/// <param name="d1">The first score.</param>
/// <param name="d2">The second score.</param>
/// <returns>The best score.</returns>
public double BestScore(double d1, double d2)
{
return _calculateScore.ShouldMinimize ? Math.Min(d1, d2) : Math.Max(d1, d2);
}
/// <summary>
/// Determine if one score is better than the other.
/// </summary>
///
/// <param name="d1">The first score to compare.</param>
/// <param name="d2">The second score to compare.</param>
/// <returns>True if d1 is better than d2.</returns>
public bool IsBetterThan(double d1, double d2)
{
return _calculateScore.ShouldMinimize ? d1 < d2 : d1 > d2;
}
}
}
| 33.639098 | 88 | 0.587394 | [
"BSD-3-Clause"
] | mpcoombes/MaterialPredictor | encog-core-cs/ML/Genetic/Genome/GenomeComparator.cs | 4,474 | C# |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Abstract.Parts;
using System.Reflection;
using System.Text;
namespace System.Abstract
{
/// <summary>
/// ServiceLocatorManager
/// </summary>
public class ServiceLocatorManager : ServiceManagerBase<IServiceLocator, Action<IServiceLocator>, ServiceLocatorManagerDebugger>
{
private static readonly Type _ignoreServiceLocatorType = typeof(IIgnoreServiceLocator);
static ServiceLocatorManager()
{
Registration = new ServiceRegistration
{
MakeAction = a => x => a(x),
OnSetup = (service, descriptor) =>
{
var behavior = (service.Registrar as IServiceRegistrarBehaviorAccessor);
if (behavior == null || behavior.RegisterInLocator)
RegisterSelfInLocator(service);
if (descriptor != null)
foreach (var action in descriptor.Actions)
action(service);
return service;
},
OnChange = (service, descriptor) =>
{
if (descriptor != null)
foreach (var action in descriptor.Actions)
action(service);
},
};
// default provider
if (Lazy == null && DefaultServiceProvider != null)
SetProvider(DefaultServiceProvider);
}
/// <summary>
/// Sets the provider.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="setupDescriptor">The setup descriptor.</param>
/// <returns></returns>
public static Lazy<IServiceLocator> SetProvider(Func<IServiceLocator> provider, ISetupDescriptor setupDescriptor = null) { return (Lazy = MakeByProviderProtected(provider, setupDescriptor)); }
/// <summary>
/// Makes the by provider.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="setupDescriptor">The setup descriptor.</param>
/// <returns></returns>
public static Lazy<IServiceLocator> MakeByProvider(Func<IServiceLocator> provider, ISetupDescriptor setupDescriptor = null) { return MakeByProviderProtected(provider, setupDescriptor); }
/// <summary>
/// Gets the current.
/// </summary>
public static IServiceLocator Current
{
get { return GetCurrent(); }
}
/// <summary>
/// Ensures the registration.
/// </summary>
public static void EnsureRegistration() { }
/// <summary>
/// Gets the setup descriptor.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
public static ISetupDescriptor GetSetupDescriptor(Lazy<IServiceLocator> service) { return GetSetupDescriptorProtected(service, null); }
private static void RegisterSelfInLocator(IServiceLocator locator)
{
locator.Registrar.RegisterInstance<IServiceLocator>(locator);
}
/// <summary>
/// Determines whether [has ignore service locator] [the specified instance].
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns>
/// <c>true</c> if [has ignore service locator] [the specified instance]; otherwise, <c>false</c>.
/// </returns>
public static bool HasIgnoreServiceLocator(object instance) { return (instance == null || HasIgnoreServiceLocator(instance.GetType())); }
/// <summary>
/// Determines whether [has ignore service locator].
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns>
/// <c>true</c> if [has ignore service locator]; otherwise, <c>false</c>.
/// </returns>
public static bool HasIgnoreServiceLocator<TService>() { return HasIgnoreServiceLocator(typeof(TService)); }
/// <summary>
/// Determines whether [has ignore service locator] [the specified type].
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if [has ignore service locator] [the specified type]; otherwise, <c>false</c>.
/// </returns>
public static bool HasIgnoreServiceLocator(Type type)
{
return (type == null || _ignoreServiceLocatorType.IsAssignableFrom(type) || IgnoreServiceLocatorAttribute.HasIgnoreServiceLocator(type));
}
}
}
| 44.210526 | 201 | 0.609864 | [
"MIT"
] | BclEx/BclEx-Abstract | src/System.Abstract/Abstract+ServiceLocator/ServiceLocatorManager.cs | 5,880 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyGUIPlugin;
using Engine.Editing;
using Engine;
namespace Anomalous.GuiFramework.Editor
{
class PropertiesFormUInt16 : ConstrainableFormComponent
{
private UInt16NumericEdit num;
private bool allowValueChanges = true;
public PropertiesFormUInt16(EditableProperty property, Widget parent)
: base(property, parent, "Anomalous.GuiFramework.Editor.GUI.PropertiesForm.PropertiesFormTextBox.layout")
{
widget.ForwardMouseWheelToParent = true;
TextBox textBox = (TextBox)widget.findWidget("TextBox");
textBox.Caption = property.getValue(0);
textBox.ForwardMouseWheelToParent = true;
num = new UInt16NumericEdit((EditBox)widget.findWidget("EditBox"));
num.Value = (UInt16)property.getRealValue(1);
num.ValueChanged += new MyGUIEvent(editBox_ValueChanged);
}
public override void refreshData()
{
num.Value = (UInt16)Property.getRealValue(1);
}
public override void setConstraints(ReflectedMinMaxEditableProperty minMaxProp)
{
num.MinValue = minMaxProp.MinValue.AsUInt16;
num.MaxValue = minMaxProp.MaxValue.AsUInt16;
num.Increment = minMaxProp.Increment.AsUInt16;
}
void editBox_ValueChanged(Widget source, EventArgs e)
{
setValue();
}
private void setValue()
{
if (allowValueChanges)
{
allowValueChanges = false;
Property.setValue(1, num.Value);
allowValueChanges = true;
}
}
}
} | 31.344828 | 118 | 0.607261 | [
"MIT"
] | AnomalousMedical/Engine | GuiFramework.Editor/GUI/PropertiesForm/PropertiesFormUInt16.cs | 1,820 | C# |
using System.ComponentModel;
using System.Runtime.Serialization;
namespace CloudinaryDotNet.Actions
{
public enum ArchiveCallMode
{
/// <summary>
/// Indicates to return the generated archive file
/// </summary>
[EnumMember(Value = "download")]
Download,
/// <summary>
/// Indicates to store the generated archive file as a raw resource in your Cloudinary account and return a JSON with the URLs for accessing it
/// </summary>
[EnumMember(Value = "create")]
Create
}
}
| 28.25 | 151 | 0.626549 | [
"MIT"
] | ShaharrHorn/CloudinaryChallenge | Shared/Actions/ArchiveCallMode.cs | 567 | C# |
using System.Collections.Generic;
namespace Landmarks.Models
{
public class Region
{
public Region()
{
this.Landmarks = new HashSet<Landmark>();
}
public int Id { get; set; }
public string Name { get; set; }
public double Area { get; set; }
public int Population { get; set; }
public ICollection<Landmark> Landmarks { get; set; }
}
}
| 18.652174 | 60 | 0.55711 | [
"MIT"
] | stefkavasileva/Project | Landmarks/Landmarks.Models/Region.cs | 431 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AzureServiceTags.WebApp.Services;
using AzureServiceTags.WebApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace AzureServiceTags.WebApp.Pages
{
public class ServiceTagModel : PageModel
{
private readonly ILogger<IndexModel> logger;
private readonly ServiceTagProvider serviceTagProvider;
[BindProperty(SupportsGet = true)]
public string ServiceTagId { get; set; }
public IList<string> TopLevelServiceTags { get; set; }
public IList<string> ServiceTagIds { get; set; }
public IList<CloudServiceTag> ServiceTags { get; set; }
public ServiceTagModel(ILogger<IndexModel> logger, ServiceTagProvider serviceTagProvider)
{
this.logger = logger;
this.serviceTagProvider = serviceTagProvider;
}
public async Task OnGet()
{
var serviceTagListFiles = await this.serviceTagProvider.GetAllServiceTagListFilesAsync();
if (string.IsNullOrWhiteSpace(this.ServiceTagId))
{
// No specific Service Tag (prefix) was requested, return top-level Service Tags (i.e. anything before the first '.').
this.TopLevelServiceTags = serviceTagListFiles.SelectMany(f => f.ServiceTagList.Values)
.Select(l => l.Id.Contains('.') ? l.Id.Substring(0, l.Id.IndexOf('.')) : l.Id)
.Distinct().OrderBy(n => n).ToArray();
}
else if (this.ServiceTagId.EndsWith('*'))
{
// Find Service Tag ID's starting with the requested ID.
this.ServiceTagIds = new List<string>();
var matchString = this.ServiceTagId.TrimEnd('*');
this.ServiceTagIds = serviceTagListFiles.SelectMany(f => f.ServiceTagList.Values)
.Where(s => string.Equals(matchString, s.Id, StringComparison.OrdinalIgnoreCase) || s.Id.StartsWith(matchString + '.', StringComparison.OrdinalIgnoreCase))
.Select(s => s.Id).Distinct().OrderBy(s => s).ToArray();
}
else
{
// Return the requested Service Tag.
this.ServiceTags = new List<CloudServiceTag>();
foreach (var serviceTagList in serviceTagListFiles.Select(f => f.ServiceTagList))
{
foreach (var serviceTag in serviceTagList.Values.Where(s => string.Equals(this.ServiceTagId, s.Id, StringComparison.OrdinalIgnoreCase)))
{
this.ServiceTags.Add(new CloudServiceTag(serviceTagList, serviceTag));
}
}
}
}
public void OnPost()
{
}
}
} | 42.764706 | 175 | 0.610385 | [
"MIT"
] | jelledruyts/AzureServiceTags | AzureServiceTags.WebApp/Pages/ServiceTag.cshtml.cs | 2,908 | C# |
using AnnoSavegameViewer.Serialization.Core;
using System;
using System.Windows;
using System.Windows.Controls;
namespace ClassCreator {
public class TreeNodeItemTemplateSelector : DataTemplateSelector {
#region Public Methods
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
if (item is TreeNode node) {
string styleName = String.Empty;
if (node.IsArrayItem) {
styleName = "TreeNodeArrayTemplate";
}
else if (node.NodeType == BinaryContentTypes.Attribute) {
styleName = "TreeNodeContentTemplate";
}
else {
styleName = "TreeNodeObjectTemplate";
}
return Application.Current.TryFindResource(styleName) as DataTemplate;
}
return base.SelectTemplate(item, container);
}
#endregion Public Methods
}
} | 28.129032 | 90 | 0.682339 | [
"MIT"
] | Veraatversus/AnnoSavegameViewer | src/ClassCreator/TreeNodeItemTemplateSelector.cs | 874 | C# |
using MediatR;
using Microsoft.EntityFrameworkCore;
using ModelWrapper.Extensions.FullSearch;
using BAYSOFT.Core.Domain.Interfaces.Infrastructures.Data.Contexts;
using System.Threading;
using System.Threading.Tasks;
namespace BAYSOFT.Core.Application.StockWallet.Grades.Queries.GetGradesByFilter
{
public class GetGradesByFilterQueryHandler : IRequestHandler<GetGradesByFilterQuery, GetGradesByFilterQueryResponse>
{
private IStockWalletDbContext Context { get; set; }
public GetGradesByFilterQueryHandler(IStockWalletDbContext context)
{
Context = context;
}
public async Task<GetGradesByFilterQueryResponse> Handle(GetGradesByFilterQuery request, CancellationToken cancellationToken)
{
long resultCount = 0;
var data = await Context.Grades
.FullSearch(request, out resultCount)
.AsNoTracking()
.ToListAsync(cancellationToken);
return new GetGradesByFilterQueryResponse(request, data, resultCount: resultCount);
}
}
}
| 37.033333 | 133 | 0.70297 | [
"MIT"
] | BAYSOFT-001/baysoft-stockwallet | src/BAYSOFT.Core.Application/StockWallet/Grades/Queries/GetGradesByFilter/GetGradesByFilterQueryHandler.cs | 1,111 | C# |
using System.Threading;
using System.Threading.Tasks;
using DLCS.Repository.Caching;
using IIIF.Presentation;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orchestrator.Features.Manifests.Requests;
using Orchestrator.Infrastructure;
using Orchestrator.Infrastructure.IIIF.Conneg;
using Orchestrator.Settings;
namespace Orchestrator.Features.Manifests
{
[Route("iiif-resource")]
[ApiController]
public class NamedQueryController : IIIFAssetControllerBase
{
private readonly OrchestratorSettings orchestratorSettings;
public NamedQueryController(
IMediator mediator,
IOptions<CacheSettings> cacheSettings,
IOptions<OrchestratorSettings> orchestratorSettings,
ILogger<NamedQueryController> logger
) : base(mediator, cacheSettings, logger)
{
this.orchestratorSettings = orchestratorSettings.Value;
}
/// <summary>
/// Get results of named query with specified name. The IIIF Presentation version returned will depend on server
/// configuration but can be specified via the Accepts header
/// </summary>
/// <returns>IIIF manifest containing results of specified named query</returns>
[Route("{customer}/{namedQueryName}/{**namedQueryArgs}")]
[HttpGet]
public Task<IActionResult> Index(string customer, string namedQueryName, string? namedQueryArgs = null,
CancellationToken cancellationToken = default)
{
var requestedVersion = Request.GetTypedHeaders().Accept.GetIIIFPresentationType();
var version = requestedVersion == Version.Unknown
? orchestratorSettings.GetDefaultIIIFPresentationVersion()
: requestedVersion;
return RenderNamedQuery(customer, namedQueryName, namedQueryArgs, version, cancellationToken);
}
/// <summary>
/// Get results of named query with specified name as a IIIF Manifest conforming to v2.1.
/// </summary>
/// <returns>IIIF manifest containing results of specified named query</returns>
[Route("v2/{customer}/{namedQueryName}/{**namedQueryArgs}")]
public Task<IActionResult> V2(string customer, string namedQueryName, string? namedQueryArgs = null,
CancellationToken cancellationToken = default)
=> RenderNamedQuery(customer, namedQueryName, namedQueryArgs, Version.V2, cancellationToken);
/// <summary>
/// Get results of named query with specified name as a IIIF Manifest conforming to v3.0.
/// </summary>
/// <returns>IIIF manifest containing results of specified named query</returns>
[Route("v3/{customer}/{namedQueryName}/{**namedQueryArgs}")]
public Task<IActionResult> V3(string customer, string namedQueryName, string? namedQueryArgs = null,
CancellationToken cancellationToken = default)
=> RenderNamedQuery(customer, namedQueryName, namedQueryArgs, Version.V3, cancellationToken);
public Task<IActionResult> RenderNamedQuery(string customer, string namedQueryName, string? namedQueryArgs,
Version presentationVersion, CancellationToken cancellationToken = default)
{
var contentType = presentationVersion == Version.V3 ? ContentTypes.V3 : ContentTypes.V2;
return GenerateIIIFDescriptionResource(
() => new GetNamedQueryResults(customer, namedQueryName, namedQueryArgs, presentationVersion),
contentType,
cancellationToken);
}
}
} | 48.641026 | 121 | 0.681603 | [
"MIT"
] | dlcs/protagonist | Orchestrator/Features/Manifests/NamedQueryController.cs | 3,796 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Fs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Fs")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("857cd782-3280-4e93-8ca3-542692447d5c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.216216 | 84 | 0.741467 | [
"MIT"
] | mind0n/hive | History/JsLib/1.0-branch/Fs/Properties/AssemblyInfo.cs | 1,380 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AcceptApi.Areas.Api.Models;
using AcceptApi.Areas.Api.Models.Core;
using AcceptApi.Areas.Api.Models.Filters;
using AcceptApi.Areas.Api.Models.Core;
namespace AcceptApi.Areas.Api.Controllers
{
[CrossSiteJsonCall]
public class GrammarController : Controller
{
private IAcceptApiManager acceptCoreManager;
public IAcceptApiManager AcceptCoreManager
{
get { return acceptCoreManager; }
}
public GrammarController()
{
this.acceptCoreManager = new AcceptApiManager();
}
public ActionResult Index()
{
return View();
}
[RestHttpVerbFilter]
public JsonResult GrammarRequest(CoreApiRequest requestObject, string httpVerb)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("username", requestObject.User);
parameters.Add("password", requestObject.Password);
parameters.Add("text", HttpUtility.UrlDecode(requestObject.Text));
parameters.Add("lang", requestObject.Language);
parameters.Add("rule", requestObject.Rule);
var model = AcceptCoreManager.GrammarRequest(parameters);
return Json(model);
}
[HttpGet]
public JsonResult GrammarLanguages()
{
var model = AcceptCoreManager.GrammarLanguages();
return Json(model, JsonRequestBehavior.AllowGet);
}
}
}
| 31.574074 | 87 | 0.61349 | [
"Apache-2.0"
] | accept-project/accept-api | AcceptApi/Areas/Api/Controllers/GrammarController.cs | 1,707 | C# |
#pragma checksum "C:\Users\46791749865\Desktop\web-mvc\EX3_HAMBURGUERIA\Views\Pedido\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "237076d6457084bbeb45772587f55e5173ac3d39"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Pedido_Index), @"mvc.1.0.view", @"/Views/Pedido/Index.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Pedido/Index.cshtml", typeof(AspNetCore.Views_Pedido_Index))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\46791749865\Desktop\web-mvc\EX3_HAMBURGUERIA\Views\_ViewImports.cshtml"
using EX3_HAMBURGUERIA;
#line default
#line hidden
#line 2 "C:\Users\46791749865\Desktop\web-mvc\EX3_HAMBURGUERIA\Views\_ViewImports.cshtml"
using EX3_HAMBURGUERIA.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"237076d6457084bbeb45772587f55e5173ac3d39", @"/Views/Pedido/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"739bd1a80938a84e91a8cd20512a15ee40634165", @"/Views/_ViewImports.cshtml")]
public class Views_Pedido_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "furioso", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "combo", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "chocolate", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "biscoito", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "POST", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("action", new global::Microsoft.AspNetCore.Html.HtmlString("Pedido/RegistrarPedido"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(0, 10, true);
WriteLiteral("<header>\r\n");
EndContext();
#line 2 "C:\Users\46791749865\Desktop\web-mvc\EX3_HAMBURGUERIA\Views\Pedido\Index.cshtml"
Html.RenderPartial("_HeaderNavBar");
#line default
#line hidden
BeginContext(71, 63, true);
WriteLiteral("</header>\r\n\r\n<main>\r\n <h2>Pede aí, jovem!</h2>\r\n ");
EndContext();
BeginContext(134, 1834, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "2b2edf62d7dd4279948d46ff6f7602e4", async() => {
BeginContext(186, 1043, true);
WriteLiteral(@"
<div>
<label for=""nome"">Nome Completo</label>
<br />
<input id=""nome"" type=""text"" maxlength=""20"" minlength=""3"" name=""nome"" />
</div>
<div>
<label for=""endereco"">Endereço</label>
<br />
<input id=""endereco"" type=""text"" maxlength=""20"" minlength=""3"" name=""endereco"" />
</div>
<div>
<label for=""telefone"">Telefone para contato</label>
<br />
<input id=""telefone"" type=""text"" name=""telefone"" />
</div>
<div>
<label for=""email"">E-mail</label>
<br />
<input id=""email"" type=""email"" name=""email""/>
</div>
<div class=""double-field"">
<div>
<label for=""hamburguer"">Hamburguer</label>
<select id=""hamburguer"" name=""hamburguer"" required>
");
WriteLiteral(" ");
EndContext();
BeginContext(1229, 53, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "a568920c439d448892e1caa1274c1ea8", async() => {
BeginContext(1264, 9, true);
WriteLiteral("Selecione");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute("disabled", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute("selected", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1282, 26, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1308, 40, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "bf9d39f1661d4aaf9947060bdd3ca3b4", async() => {
BeginContext(1332, 7, true);
WriteLiteral("Furioso");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1348, 26, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1374, 36, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "2b7239d4c9d84da39e7bb00856e19529", async() => {
BeginContext(1396, 5, true);
WriteLiteral("Combo");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1410, 212, true);
WriteLiteral("\r\n </select>\r\n </div>\r\n <div>\r\n <label for=\"shake\">Shake</label>\r\n <select id=\"shake\" name=\"shake\">\r\n ");
EndContext();
BeginContext(1622, 53, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "406bb691db364f799083d720352209c1", async() => {
BeginContext(1657, 9, true);
WriteLiteral("Selecione");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute("disabled", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
BeginWriteTagHelperAttribute();
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute("selected", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1675, 26, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1701, 44, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "57b5a1b419bd4eb893dd6731aa447759", async() => {
BeginContext(1727, 9, true);
WriteLiteral("Chocolate");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1745, 26, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1771, 42, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b7b9e5c214ce41caa2fa69339f507f87", async() => {
BeginContext(1796, 8, true);
WriteLiteral("Biscoito");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1813, 148, true);
WriteLiteral("\r\n </select>\r\n </div>\r\n </div>\r\n <input type=\"submit\" value=\"Finalizar pedido!\" />\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1968, 15, true);
WriteLiteral("\r\n\r\n </main>");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 69.267361 | 361 | 0.673618 | [
"MIT"
] | Scapin-Raul/web-mvc | EX3_HAMBURGUERIA/obj/Debug/netcoreapp2.1/Razor/Views/Pedido/Index.g.cshtml.cs | 19,951 | C# |
using System;
using UnityEngine;
using UnityEngine.XR.ARSubsystems;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
namespace UnityEngine.XR.ARFoundation
{
/// <summary>
/// Container that pairs a <see cref="Unity.XR.ARSubsystems.XRTextureDescriptor"/> that wraps a native texture
/// object and a <c>Texture</c> that is created for the native texture object.
/// </summary>
internal struct ARTextureInfo : IEquatable<ARTextureInfo>, IDisposable
{
/// <summary>
/// Constant for whether the texture is in a linear color space.
/// </summary>
/// <value>
/// Constant for whether the texture is in a linear color space.
/// </value>
const bool k_TextureHasLinearColorSpace = false;
/// <summary>
/// The texture descriptor describing the metadata for the native texture object.
/// </summary>
/// <value>
/// The texture descriptor describing the metadata for the native texture object.
/// </value>
public XRTextureDescriptor descriptor
{
get { return m_Descriptor; }
}
XRTextureDescriptor m_Descriptor;
/// <summary>
/// The Unity <c>Texture</c> object for the native texture.
/// </summary>
/// <value>
/// The Unity <c>Texture</c> object for the native texture.
/// </value>
public Texture texture
{
get { return m_Texture; }
}
Texture m_Texture;
/// <summary>
/// Constructs the texture info with the given descriptor and material.
/// </summary>
/// <param name="descriptor">The texture descriptor wrapping a native texture object.</param>
public ARTextureInfo(XRTextureDescriptor descriptor)
{
m_Descriptor = descriptor;
m_Texture = CreateTexture(m_Descriptor);
}
/// <summary>
/// Resets the texture info back to the default state destroying the texture game object, if one exists.
/// </summary>
public void Reset()
{
m_Descriptor.Reset();
DestroyTexture();
}
/// <summary>
/// Destroys the texture, and sets the property to <c>null</c>.
/// </summary>
void DestroyTexture()
{
if (m_Texture != null)
{
UnityEngine.Object.Destroy(m_Texture);
m_Texture = null;
}
}
/// <summary>
/// Sets the current descriptor, and creates/updates the associated texture as appropriate.
/// </summary>
/// <param name="textureInfo">The texture info to update.</param>
/// <param name="descriptor">The texture descriptor wrapping a native texture object.</param>
/// <returns>
/// The updated texture information.
/// </returns>
public static ARTextureInfo GetUpdatedTextureInfo(ARTextureInfo textureInfo, XRTextureDescriptor descriptor)
{
// If the current and given descriptors are equal, exit early from this method.
if (textureInfo.m_Descriptor.Equals(descriptor))
{
return textureInfo;
}
// If the given descriptor is invalid, destroy any existing texture, and return the default texture
// info.
if (!descriptor.valid)
{
textureInfo.DestroyTexture();
return default(ARTextureInfo);
}
Debug.Assert(textureInfo.m_Descriptor.dimension == descriptor.dimension, $"Texture descriptor dimension should not change from {textureInfo.m_Descriptor.dimension} to {descriptor.dimension}.");
// If there is a texture already and if the descriptors have identical texture metadata, we only need
// to update the existing texture with the given native texture object.
if ((textureInfo.m_Texture != null) && textureInfo.m_Descriptor.hasIdenticalTextureMetadata(descriptor))
{
// Update the current descriptor with the given descriptor.
textureInfo.m_Descriptor = descriptor;
// Update the current texture with the native texture object.
switch(descriptor.dimension)
{
#if UNITY_2020_2_OR_NEWER
case TextureDimension.Tex3D:
((Texture3D)textureInfo.m_Texture).UpdateExternalTexture(textureInfo.m_Descriptor.nativeTexture);
break;
#endif
case TextureDimension.Tex2D:
((Texture2D)textureInfo.m_Texture).UpdateExternalTexture(textureInfo.m_Descriptor.nativeTexture);
break;
case TextureDimension.Cube:
((Cubemap)textureInfo.m_Texture).UpdateExternalTexture(textureInfo.m_Descriptor.nativeTexture);
break;
default:
throw new NotSupportedException($"'{descriptor.dimension.ToString()}' is not a supported texture type.");
}
}
// Else, we need to destroy the existing texture object and create a new texture object.
else
{
// Update the current descriptor with the given descriptor.
textureInfo.m_Descriptor = descriptor;
// Replace the current texture with a newly created texture, and update the material.
textureInfo.DestroyTexture();
textureInfo.m_Texture = CreateTexture(textureInfo.m_Descriptor);
}
return textureInfo;
}
/// <summary>
/// Create the texture object for the native texture wrapped by the valid descriptor.
/// </summary>
/// <param name="descriptor">The texture descriptor wrapping a native texture object.</param>
/// <returns>
/// If the descriptor is valid, the <c>Texture</c> object created from the texture descriptor. Otherwise,
/// <c>null</c>.
/// </returns>
static Texture CreateTexture(XRTextureDescriptor descriptor)
{
if (!descriptor.valid)
{
return null;
}
switch(descriptor.dimension)
{
#if UNITY_2020_2_OR_NEWER
case TextureDimension.Tex3D:
return Texture3D.CreateExternalTexture(descriptor.width, descriptor.height,
descriptor.depth, descriptor.format,
(descriptor.mipmapCount != 0), descriptor.nativeTexture);
#endif
case TextureDimension.Tex2D:
var texture = Texture2D.CreateExternalTexture(descriptor.width, descriptor.height,
descriptor.format, (descriptor.mipmapCount != 0),
k_TextureHasLinearColorSpace,
descriptor.nativeTexture);
// NB: SetWrapMode needs to be the first call here, and the value passed
// needs to be kTexWrapClamp - this is due to limitations of what
// wrap modes are allowed for external textures in OpenGL (which are
// used for ARCore), as Texture::ApplySettings will eventually hit
// an assert about an invalid enum (see calls to glTexParameteri
// towards the top of ApiGLES::TextureSampler)
// reference: "3.7.14 External Textures" section of
// https://www.khronos.org/registry/OpenGL/extensions/OES/OES_EGL_image_external.txt
// (it shouldn't ever matter what the wrap mode is set to normally, since
// this is for a pass-through video texture, so we shouldn't ever need to
// worry about the wrap mode as textures should never "wrap")
texture.wrapMode = TextureWrapMode.Clamp;
texture.filterMode = FilterMode.Bilinear;
texture.hideFlags = HideFlags.HideAndDontSave;
return texture;
case TextureDimension.Cube:
return Cubemap.CreateExternalTexture(descriptor.width,
descriptor.format,
(descriptor.mipmapCount != 0),
descriptor.nativeTexture);
default:
return null;
}
}
public static bool IsSupported(XRTextureDescriptor descriptor)
{
if(descriptor.dimension == TextureDimension.Tex3D)
{
#if UNITY_2020_2_OR_NEWER
return true;
#else
return false;
#endif
}
else if(descriptor.dimension == TextureDimension.Tex2D)
{
return true;
}
else if(descriptor.dimension == TextureDimension.Cube)
{
return true;
}
else
{
return false;
}
}
public void Dispose()
{
DestroyTexture();
}
public override int GetHashCode()
{
int hash = 486187739;
unchecked
{
hash = hash * 486187739 + m_Descriptor.GetHashCode();
hash = hash * 486187739 + ((m_Texture == null) ? 0 : m_Texture.GetHashCode());
}
return hash;
}
public bool Equals(ARTextureInfo other)
{
return m_Descriptor.Equals(other) && (m_Texture == other.m_Texture);
}
public override bool Equals(System.Object obj)
{
return ((obj is ARTextureInfo) && Equals((ARTextureInfo)obj));
}
public static bool operator ==(ARTextureInfo lhs, ARTextureInfo rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(ARTextureInfo lhs, ARTextureInfo rhs)
{
return !lhs.Equals(rhs);
}
}
}
| 40.758755 | 205 | 0.54969 | [
"MIT"
] | JLuisRojas/HinduAR | unity/ArPruebas/Library/PackageCache/com.unity.xr.arfoundation@4.0.12/Runtime/AR/ARTextureInfo.cs | 10,475 | C# |
using System;
using LibGit2Sharp.Core;
using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// Options to define clone behaviour
/// </summary>
public sealed class CloneOptions : IConvertableToGitCheckoutOpts, ICredentialsProvider
{
/// <summary>
/// Creates default <see cref="CloneOptions"/> for a non-bare clone
/// </summary>
public CloneOptions()
{
Checkout = true;
}
/// <summary>
/// True will result in a bare clone, false a full clone.
/// </summary>
public bool IsBare { get; set; }
/// <summary>
/// If true, the origin's HEAD will be checked out. This only applies
/// to non-bare repositories.
/// </summary>
public bool Checkout { get; set; }
/// <summary>
/// Handler for network transfer and indexing progress information
/// </summary>
public TransferProgressHandler OnTransferProgress { get; set; }
/// <summary>
/// Handler for checkout progress information
/// </summary>
public CheckoutProgressHandler OnCheckoutProgress { get; set; }
/// <summary>
/// Handler to generate <see cref="LibGit2Sharp.Credentials"/> for authentication.
/// </summary>
public CredentialsHandler CredentialsProvider { get; set; }
#region IConvertableToGitCheckoutOpts
CheckoutCallbacks IConvertableToGitCheckoutOpts.GenerateCallbacks()
{
return CheckoutCallbacks.From(OnCheckoutProgress, null);
}
CheckoutStrategy IConvertableToGitCheckoutOpts.CheckoutStrategy
{
get
{
return this.Checkout ?
CheckoutStrategy.GIT_CHECKOUT_SAFE_CREATE :
CheckoutStrategy.GIT_CHECKOUT_NONE;
}
}
CheckoutNotifyFlags IConvertableToGitCheckoutOpts.CheckoutNotifyFlags
{
get { return CheckoutNotifyFlags.None; }
}
#endregion
}
}
| 29.408451 | 90 | 0.594828 | [
"MIT"
] | gitextensions/libgit2sharp | LibGit2Sharp/CloneOptions.cs | 2,090 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace AutoLot.Web.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.655172 | 88 | 0.665323 | [
"BSD-3-Clause",
"MIT"
] | RomitMehta/presentations | DOTNETCORE/ASP.NETCore/v5.0/AutoLot50/AutoLot.Web/Pages/Error.cshtml.cs | 744 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Smidge.Models;
namespace Smidge
{
public class RequestHelper : IRequestHelper
{
private readonly IWebsiteInfo _siteInfo;
public RequestHelper(IWebsiteInfo siteInfo)
{
_siteInfo = siteInfo ?? throw new ArgumentNullException(nameof(siteInfo));
}
public bool IsExternalRequestPath(string path)
{
if ((path.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
path.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ||
path.StartsWith("//", StringComparison.OrdinalIgnoreCase)))
{
return true;
}
return false;
}
public string Content(IWebFile file)
{
if (string.IsNullOrEmpty(file.FilePath))
return null;
//if this is a protocol-relative/protocol-less uri, then we need to add the protocol for the remaining
// logic to work properly
if (file.FilePath.StartsWith("//"))
{
var scheme = _siteInfo.GetBaseUrl().Scheme;
return Regex.Replace(file.FilePath, @"^\/\/", string.Format("{0}{1}", scheme, SmidgeConstants.SchemeDelimiter));
}
var filePath = Content(file.FilePath);
if (filePath == null)
return null;
var requestPath = file.RequestPath != null ? Content(file.RequestPath) : string.Empty;
if (requestPath.EndsWith('/'))
{
requestPath.TrimEnd('/');
}
return string.Concat(requestPath, filePath);
}
/// <summary>
/// Converts a virtual (relative) path to an application absolute path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string Content(string path)
{
if (string.IsNullOrEmpty(path))
return null;
//if this is a protocol-relative/protocol-less uri, then we need to add the protocol for the remaining
// logic to work properly
if (path.StartsWith("//"))
{
var scheme = _siteInfo.GetBaseUrl().Scheme;
return Regex.Replace(path, @"^\/\/", string.Format("{0}{1}", scheme, SmidgeConstants.SchemeDelimiter));
}
//This code is taken from the UrlHelper code ... which shouldn't need to be tucked away in there
// since it is not dependent on the ActionContext
if (path[0] == 126)
{
PathString pathBase = _siteInfo.GetBasePath();
return pathBase.Add(new PathString(path.Substring(1))).Value;
}
return path;
}
/// <summary>
/// Check what kind of compression to use. Need to select the first available compression
/// from the header value as this is how .Net performs caching by compression so we need to follow
/// this process.
/// If IE 6 is detected, we will ignore compression as it's known that some versions of IE 6
/// have issues with it.
/// </summary>
public CompressionType GetClientCompression(IDictionary<string, StringValues> headers)
{
var type = CompressionType.None;
if (headers is not IHeaderDictionary headerDictionary)
{
headerDictionary = new HeaderDictionary(headers.Count);
foreach ((var key, StringValues stringValues) in headers)
{
headerDictionary[key] = stringValues;
}
}
var acceptEncoding = headerDictionary.GetCommaSeparatedValues(HeaderNames.AcceptEncoding);
if (acceptEncoding.Length > 0)
{
// Prefer in order: Brotli, GZip, Deflate.
// https://www.iana.org/assignments/http-parameters/http-parameters.xml#http-content-coding-registry
for (var i = 0; i < acceptEncoding.Length; i++)
{
var encoding = acceptEncoding[i].Trim();
CompressionType parsed = CompressionType.Parse(encoding);
// Brotli is typically last in the accept encoding header.
if (parsed == CompressionType.Brotli)
{
return CompressionType.Brotli;
}
// Not pack200-gzip.
if (parsed == CompressionType.GZip)
{
type = CompressionType.GZip;
}
if (type != CompressionType.GZip && parsed == CompressionType.Deflate)
{
type = CompressionType.Deflate;
}
}
}
return type;
}
}
}
| 36.302817 | 128 | 0.54452 | [
"MIT"
] | craigs100/Smidge | src/Smidge/RequestHelper.cs | 5,155 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Accounting;
using Accounting.Core.Cards;
using Accounting.Core.Purchases;
using Accounting.Report.Purchases;
using Accounting.Core.Definitions;
using Accounting.Core.Inventory;
using Accounting.Core.Terms;
using Accounting.Core.ShippingMethods;
using Accounting.Core.TaxCodes;
using Accounting.Core.Currencies;
using Accounting.Bll;
using Accounting.Bll.Purchases;
using Accounting.Bll.Purchases.PurchaseLines;
using SyntechRpt.WinForms.Purchases.PurchaseLines;
using SyntechRpt.Util;
namespace SyntechRpt.WinForms.Purchases
{
public partial class FrmPurchaseQuote : Form
{
private BOPurchaseQuote mModel;
public BOPurchaseQuote Model
{
set
{
mModel = value;
mModel.Revised += new BOPurchase.RevisedHandler(Model_Revised);
}
}
public FrmPurchaseQuote()
{
InitializeComponent();
}
private void ViewModel()
{
cboComments.Text = mModel.Comment;
txtPurchaseNo.Text = mModel.PurchaseNumber;
if (mModel.PromisedDate != null)
{
dtpPromisedDate.Value = mModel.PromisedDate.Value;
}
if (mModel.PurchaseDate != null)
{
dtpPurchaseDate.Value = mModel.PurchaseDate.Value;
}
cboInvoiceDelivery.SelectedItem = mModel.InvoiceDelivery;
cboTerms.SelectedItem = mModel.Terms;
txtAddressLine1.Text = mModel.ShipToAddressLine1;
txtAddressLine2.Text = mModel.ShipToAddressLine2;
txtAddressLine3.Text = mModel.ShipToAddressLine3;
txtAddressLine4.Text = mModel.ShipToAddressLine4;
cboShippMethod.SelectedItem = mModel.ShippingMethod;
cboSupplier.SelectedItem = mModel.Supplier;
txtSupplierPO.Text = mModel.SupplierInvoiceNumber;
cboFreightTaxCode.SelectedItem = mModel.FreightTaxCode;
txtFreight.Text = string.Format("{0}", mModel.TaxExclusiveFreight);
chkTaxInclusive.Checked = mModel.IsTaxInclusive;
cboPurchaseLayout.SelectedItem = mModel.PurchaseType;
cboCurrency.SelectedItem = mModel.Currency;
txtJournalMemo.Text = mModel.Memo;
Supplier customer = mModel.Supplier;
if (customer != null)
{
Address addr = customer.Address1;
txtSupplierPhone1.Text = addr.Phone1;
txtSupplierPhone2.Text = addr.Phone2;
txtSupplierEmail.Text = addr.Email;
txtSupplierCountry.Text = addr.Country;
}
txtSubtotalValue.Text = string.Format("{0:C}", mModel.Subtotal);
txtTaxValue.Text = string.Format("{0:C}", mModel.TotalTax);
txtTotalValue.Text = string.Format("{0:C}", mModel.Total);
dgvPurchaseLines.DataSource = mModel.PurchaseLineDataGridView;
}
private void FrmPurchaseQuote_Load(object sender, EventArgs e)
{
cboSupplier.DataSource = mModel.List("Supplier");
cboComments.DataSource = mModel.List("Comment");
cboTerms.DataSource = mModel.List("Terms");
cboInvoiceDelivery.DataSource = mModel.List("InvoiceDelivery");
cboShippMethod.DataSource = mModel.List("ShippingMethod");
cboFreightTaxCode.DataSource = mModel.List("FreightTaxCode");
cboReferralSource.DataSource = mModel.List("ReferralSource");
cboPurchaseLayout.DataSource = mModel.List("PurchaseLayout");
cboCurrency.DataSource = mModel.List("Currency");
cboAddresses.Items.Add("Address 1");
cboAddresses.Items.Add("Address 2");
cboAddresses.Items.Add("Address 3");
cboAddresses.Items.Add("Address 4");
cboAddresses.Items.Add("Address 5");
cboAddresses.SelectedIndex = 0;
if (mModel.RecordContext == BusinessObject.BOContext.Record_Update)
{
ViewModel();
}
else if (mModel.RecordContext == BusinessObject.BOContext.Record_Create)
{
txtPurchaseNo.Text = mModel.GeneratePurchaseNumber();
UI_Clear();
}
if (Editable)
{
this.cboSupplier.SelectedIndexChanged += new System.EventHandler(this.cboSupplier_SelectedIndexChanged);
this.cboAddresses.SelectedIndexChanged += new System.EventHandler(this.cboAddresses_SelectedIndexChanged);
this.cboPurchaseLayout.SelectedIndexChanged += new EventHandler(cboPurchaseLayout_SelectedIndexChanged);
this.dgvPurchaseLines.DoubleClick += new EventHandler(dgvPurchaseLines_DoubleClick);
}
else
{
UI_Disable();
}
}
void dgvPurchaseLines_DoubleClick(object sender, EventArgs e)
{
int linenumber;
if (WinFormUtil.DataGridView_GetSelectedID(dgvPurchaseLines, out linenumber))
{
BOPurchaseLine lineModel = mModel.UpdatePurchaseLine(linenumber);
OpenPurchaseLineDialog(lineModel);
}
}
private bool Editable
{
get
{
if (mModel.RecordContext == BusinessObject.BOContext.Record_Update && SecurityUtil.CheckAccessSilent("Purchase_UpdatePurchaseQuote"))
{
return true;
}
else if (mModel.RecordContext == BusinessObject.BOContext.Record_Create && SecurityUtil.CheckAccessSilent("Purchase_CreatePurchaseQuote"))
{
return true;
}
return false;
}
}
private void UI_Disable()
{
cboSupplier.Enabled = false;
cboComments.Enabled = false;
cboTerms.Enabled = false;
cboInvoiceDelivery.Enabled = false;
cboShippMethod.Enabled = false;
cboFreightTaxCode.Enabled = false;
cboReferralSource.Enabled = false;
cboPurchaseLayout.Enabled = false;
cboCurrency.Enabled = false;
txtAddressLine1.Enabled = false;
txtAddressLine2.Enabled = false;
txtAddressLine3.Enabled = false;
txtAddressLine4.Enabled = false;
txtFreight.Enabled = false;
txtSupplierCity.Enabled = false;
txtSupplierEmail.Enabled = false;
txtPurchaseNo.Enabled = false;
chkTaxInclusive.Enabled = false;
txtJournalMemo.Enabled = false;
txtSupplierPO.Enabled = false;
txtSupplierCountry.Enabled = false;
dtpPromisedDate.Enabled = false;
dtpPurchaseDate.Enabled = false;
btnRecord.Enabled = false;
btnCopyAddress.Enabled = false;
btnDelLine.Enabled = false;
btnClearAddress.Enabled = false;
btnNewLine.Enabled = false;
cboAddresses.Enabled = false;
btnClearAddress.Enabled = false;
}
private void cboSupplier_SelectedIndexChanged(object sender, EventArgs e)
{
Supplier _obj = (Supplier)cboSupplier.SelectedItem;
if (_obj == null)
{
UI_Clear();
return;
}
cboAddresses.SelectedIndex = 0;
Address addr = _obj.Address1;
txtSupplierPhone1.Text = addr.Phone1;
txtSupplierPhone2.Text = addr.Phone2;
txtSupplierCountry.Text = addr.Country;
txtSupplierEmail.Text = addr.Email;
cboShippMethod.SelectedItem = _obj.ShippingMethod;
cboInvoiceDelivery.SelectedItem = _obj.InvoiceDelivery;
cboFreightTaxCode.SelectedItem = _obj.FreightTaxCode;
cboTerms.SelectedItem = _obj.Terms;
cboComments.SelectedItem = _obj.PurchaseComment;
cboPurchaseLayout.SelectedItem = _obj.PurchaseLayout;
cboCurrency.SelectedItem = _obj.Currency;
txtFreight.Text = "0";
txtJournalMemo.Text = mModel.GenerateJournalMemo(_obj);
RenderSelectedAddress();
if (!tc.Contains(tpPurchaseLines))
{
tc.Controls.Add(tpPurchaseLines);
}
}
void Model_Revised()
{
txtSubtotalValue.Text = string.Format("{0:C}", mModel.Subtotal);
txtTaxValue.Text = string.Format("{0:C}", mModel.TotalTax);
txtTotalValue.Text = string.Format("{0:C}", mModel.Total);
dgvPurchaseLines.DataSource = mModel.PurchaseLineDataGridView;
}
private void UI_Clear()
{
cboSupplier.SelectedIndex = -1;
cboComments.SelectedIndex = -1;
cboTerms.SelectedIndex = -1;
cboInvoiceDelivery.SelectedIndex = -1;
cboShippMethod.SelectedIndex = -1;
cboFreightTaxCode.SelectedIndex = -1;
cboReferralSource.SelectedIndex = -1;
cboPurchaseLayout.SelectedIndex = -1;
cboCurrency.SelectedIndex = -1;
txtAddressLine1.Text = "";
txtAddressLine2.Text = "";
txtAddressLine3.Text = "";
txtAddressLine4.Text = "";
txtFreight.Text = "0";
txtSubtotalValue.Text = string.Format("{0:C}", 0);
txtTaxValue.Text = string.Format("{0:C}", 0);
txtTotalValue.Text = string.Format("{0:C}", 0);
if (tc.Contains(tpPurchaseLines))
{
tc.Controls.Remove(tpPurchaseLines);
}
}
private void cboAddresses_SelectedIndexChanged(object sender, EventArgs e)
{
RenderSelectedAddress();
}
private void RenderSelectedAddress()
{
Supplier customer = (Supplier)cboSupplier.SelectedItem;
if (customer == null) return;
Address addr = customer.Address1;
txtSupplierPhone1.Text = addr.Phone1;
txtSupplierPhone2.Text = addr.Phone2;
txtSupplierCountry.Text = addr.Country;
txtSupplierEmail.Text = addr.Email;
switch (cboAddresses.SelectedIndex)
{
case 1:
addr = customer.Address2;
break;
case 2:
addr = customer.Address3;
break;
case 3:
addr = customer.Address4;
break;
case 4:
addr = customer.Address5;
break;
}
txtAddressLine1.Text = customer.Name;
txtAddressLine2.Text = addr.StreetLine1;
txtAddressLine3.Text = addr.StreetLine2;
txtAddressLine4.Text = addr.StreetLine3;
}
private void btnRecord_Click(object sender, EventArgs e)
{
if (!IsValidated())
{
return;
}
ReviseModel();
OpResult result = mModel.Record();
if (!result.IsValid)
{
DialogResult = DialogResult.None;
MessageBox.Show(result.Error);
}
}
private bool IsValidated()
{
string errorText = "";
if (txtPurchaseNo.Text.Length == 0)
{
errorText = "Purchase No cannot be empty!";
errorProvider.SetError(txtPurchaseNo, errorText);
return false;
}
if (cboTerms.SelectedIndex == -1)
{
errorText = "Terms is not selected!";
errorProvider.SetError(cboTerms, errorText);
return false;
}
if (cboSupplier.SelectedIndex == -1)
{
errorText = "Supplier is not selected!";
errorProvider.SetError(cboSupplier, errorText);
return false;
}
if (cboInvoiceDelivery.SelectedIndex == -1)
{
errorText = "Delivery status is not selected";
errorProvider.SetError(cboInvoiceDelivery, errorText);
return false;
}
return true;
}
private void ReviseModel()
{
mModel.Comment = cboComments.Text;
mModel.Memo = txtJournalMemo.Text;
mModel.PurchaseNumber = txtPurchaseNo.Text;
mModel.PromisedDate = dtpPromisedDate.Value;
mModel.PurchaseDate = dtpPurchaseDate.Value;
mModel.InvoiceDelivery = (InvoiceDelivery)cboInvoiceDelivery.SelectedItem;
mModel.Terms = (Terms)cboTerms.SelectedItem;
mModel.ShipToAddressLine1 = txtAddressLine1.Text;
mModel.ShipToAddressLine2 = txtAddressLine2.Text;
mModel.ShipToAddressLine3 = txtAddressLine3.Text;
mModel.ShipToAddressLine4 = txtAddressLine4.Text;
mModel.ShippingMethod = (ShippingMethod)cboShippMethod.SelectedItem;
mModel.Supplier = (Supplier)cboSupplier.SelectedItem;
mModel.SupplierInvoiceNumber = txtSupplierPO.Text;
mModel.FreightTaxCode = (TaxCode)cboFreightTaxCode.SelectedItem;
mModel.TaxExclusiveFreight = double.Parse(txtFreight.Text);
mModel.IsTaxInclusive = chkTaxInclusive.Checked;
mModel.PurchaseType = (InvoiceType)cboPurchaseLayout.SelectedItem;
mModel.Currency = (Currency)cboCurrency.SelectedItem;
mModel.Revise();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnPrint_Click(object sender, EventArgs e)
{
/*
string reportname = "rptPurchaseOrder";
Report.WinForms.FrmPurchaseOrder frm = new Dac.WinForms.Report.FrmPurchaseOrder(new PurchaseOrder(mModel.Purchase));
frm.MdiParent = this.MdiParent;
frm.LoadReport(string.Format("Dac.WinForms.Report.{0}.rdlc", reportname));
frm.Show();
*/
}
private void btnClearAddress_Click(object sender, EventArgs e)
{
txtAddressLine1.Text = "";
txtAddressLine2.Text = "";
txtAddressLine3.Text = "";
txtAddressLine4.Text = "";
}
private void btnCopyAddress_Click(object sender, EventArgs e)
{
RenderSelectedAddress();
}
private void btnNewLine_Click(object sender, EventArgs e)
{
ReviseModel();
BOPurchaseLine lineModel=mModel.CreatePurchaseLine();
OpenPurchaseLineDialog(lineModel);
}
private void chkTaxInclusive_CheckedChanged(object sender, EventArgs e)
{
mModel.IsTaxInclusive = chkTaxInclusive.Checked;
mModel.Revise();
}
private void btnDelLine_Click(object sender, EventArgs e)
{
int linenumber;
if (WinFormUtil.DataGridView_GetSelectedID(dgvPurchaseLines, out linenumber))
{
ReviseModel();
mModel.DeletePurchaseLine(linenumber);
}
}
private void OpenPurchaseLineDialog(BOPurchaseLine lineModel)
{
if (lineModel is BOItemPurchaseLine)
{
FrmItemPurchaseLine frm = new FrmItemPurchaseLine();
frm.Model = (BOItemPurchaseLine)lineModel;
frm.ShowDialog();
}
else if (lineModel is BOServicePurchaseLine)
{
FrmServicePurchaseLine frm = new FrmServicePurchaseLine();
frm.Model = (BOServicePurchaseLine)lineModel;
frm.ShowDialog();
}
else if (lineModel is BOProfessionalPurchaseLine)
{
FrmProfessionalPurchaseLine frm = new FrmProfessionalPurchaseLine();
frm.Model = (BOProfessionalPurchaseLine)lineModel;
frm.ShowDialog();
}
else if (lineModel is BOTimeBillingPurchaseLine)
{
FrmTimeBillingPurchaseLine frm = new FrmTimeBillingPurchaseLine();
frm.Model = (BOTimeBillingPurchaseLine)lineModel;
frm.ShowDialog() ;
}
else if (lineModel is BOMiscPurchaseLine)
{
FrmMiscPurchaseLine frm = new FrmMiscPurchaseLine();
frm.Model = (BOMiscPurchaseLine)lineModel;
frm.ShowDialog();
}
else
{
MessageBox.Show("Please select a valid purchase layout first!", "Current Sale Layout: No Default");
}
}
private void cboPurchaseLayout_SelectedIndexChanged(object sender, EventArgs e)
{
ReviseModel();
}
}
} | 36.445378 | 154 | 0.5773 | [
"MIT"
] | cschen1205/myob-accounting-plugin | Inventorist/SyntechRpt/WinForms/Purchases/FrmPurchaseQuote.cs | 17,348 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Stride.Core;
using Stride.Core.Mathematics;
using Stride.Core.Serialization;
namespace Stride.Graphics
{
/// <summary>
/// Describes a sampler state.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential)]
public struct SamplerStateDescription : IEquatable<SamplerStateDescription>
{
/// <summary>
/// Initializes a new instance of the <see cref="SamplerStateDescription"/> class.
/// </summary>
/// <param name="filter">The filter.</param>
/// <param name="addressMode">The address mode.</param>
public SamplerStateDescription(TextureFilter filter, TextureAddressMode addressMode) : this()
{
SetDefaults();
Filter = filter;
AddressU = AddressV = AddressW = addressMode;
}
/// <summary>
/// Gets or sets filtering method to use when sampling a texture (see <see cref="TextureFilter"/>).
/// </summary>
public TextureFilter Filter;
/// <summary>
/// Gets or sets method to use for resolving a u texture coordinate that is outside the 0 to 1 range (see <see cref="TextureAddressMode"/>).
/// </summary>
public TextureAddressMode AddressU;
/// <summary>
/// Gets or sets method to use for resolving a v texture coordinate that is outside the 0 to 1 range.
/// </summary>
public TextureAddressMode AddressV;
/// <summary>
/// Gets or sets method to use for resolving a w texture coordinate that is outside the 0 to 1 range.
/// </summary>
public TextureAddressMode AddressW;
/// <summary>
/// Gets or sets offset from the calculated mipmap level.
/// For example, if Direct3D calculates that a texture should be sampled at mipmap level 3 and MipLODBias is 2, then the texture will be sampled at mipmap level 5.
/// </summary>
public float MipMapLevelOfDetailBias;
/// <summary>
/// Gets or sets clamping value used if Anisotropy or ComparisonAnisotropy is specified in Filter. Valid values are between 1 and 16.
/// </summary>
public int MaxAnisotropy;
/// <summary>
/// Gets or sets a function that compares sampled data against existing sampled data. The function options are listed in <see cref="CompareFunction"/>.
/// </summary>
public CompareFunction CompareFunction;
/// <summary>
/// Gets or sets border color to use if <see cref="TextureAddressMode.Border"/> is specified for AddressU, AddressV, or AddressW. Range must be between 0.0 and 1.0 inclusive.
/// </summary>
public Color4 BorderColor;
/// <summary>
/// Gets or sets lower end of the mipmap range to clamp access to, where 0 is the largest and most detailed mipmap level and any level higher than that is less detailed.
/// </summary>
public float MinMipLevel;
/// <summary>
/// Gets or sets upper end of the mipmap range to clamp access to, where 0 is the largest and most detailed mipmap level and any level higher than that is less detailed. This value must be greater than or equal to MinLOD. To have no upper limit on LOD set this to a large value such as D3D11_FLOAT32_MAX.
/// </summary>
public float MaxMipLevel;
/// <summary>
/// Gets default values for this instance.
/// </summary>
public static SamplerStateDescription Default
{
get
{
var desc = new SamplerStateDescription();
desc.SetDefaults();
return desc;
}
}
public bool Equals(SamplerStateDescription other)
{
return Filter == other.Filter && AddressU == other.AddressU && AddressV == other.AddressV && AddressW == other.AddressW && MipMapLevelOfDetailBias.Equals(other.MipMapLevelOfDetailBias) && MaxAnisotropy == other.MaxAnisotropy && CompareFunction == other.CompareFunction && BorderColor.Equals(other.BorderColor) && MinMipLevel.Equals(other.MinMipLevel) && MaxMipLevel.Equals(other.MaxMipLevel);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is SamplerStateDescription && Equals((SamplerStateDescription)obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (int)Filter;
hashCode = (hashCode * 397) ^ (int)AddressU;
hashCode = (hashCode * 397) ^ (int)AddressV;
hashCode = (hashCode * 397) ^ (int)AddressW;
hashCode = (hashCode * 397) ^ MipMapLevelOfDetailBias.GetHashCode();
hashCode = (hashCode * 397) ^ MaxAnisotropy;
hashCode = (hashCode * 397) ^ (int)CompareFunction;
hashCode = (hashCode * 397) ^ BorderColor.GetHashCode();
hashCode = (hashCode * 397) ^ MinMipLevel.GetHashCode();
hashCode = (hashCode * 397) ^ MaxMipLevel.GetHashCode();
return hashCode;
}
}
private void SetDefaults()
{
Filter = TextureFilter.Linear;
AddressU = TextureAddressMode.Clamp;
AddressV = TextureAddressMode.Clamp;
AddressW = TextureAddressMode.Clamp;
BorderColor = new Color4();
MaxAnisotropy = 16;
MinMipLevel = -float.MaxValue;
MaxMipLevel = float.MaxValue;
MipMapLevelOfDetailBias = 0.0f;
CompareFunction = CompareFunction.Never;
}
}
}
| 42.93662 | 404 | 0.621125 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride/Graphics/SamplerStateDescription.cs | 6,097 | C# |
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Xyperico.Agres.DocumentStore;
namespace Xyperico.Agres.JsonNet
{
public class JsonNetDocumentSerializer : IDocumentSerializer
{
JsonSerializer Serializer = new JsonSerializer();
public void Serialize(Stream s, object item)
{
using (var tw = new StreamWriter(s, Encoding.UTF8))
using (var jw = new JsonTextWriter(tw))
{
Serializer.Serialize(jw, item);
// Make sure nothing from any previous serialization is left in the stream
s.SetLength(s.Position);
}
}
public object Deserialize(Type t, Stream s)
{
using (var tr = new StreamReader(s, Encoding.UTF8))
using (var jr = new JsonTextReader(tr))
{
return Serializer.Deserialize(jr, t);
}
}
}
}
| 23.702703 | 83 | 0.630559 | [
"MIT"
] | JornWildt/Xyperico | Xyperico.Agres/Xyperico.Agres.JsonNet/JsonNetDocumentSerializer.cs | 879 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
using System;
namespace DotNetty.Codecs.Http2
{
/// <summary>
/// Builder for the <see cref="Http2FrameCodec"/>.
/// </summary>
public class Http2FrameCodecBuilder : AbstractHttp2ConnectionHandlerBuilder<Http2FrameCodec, Http2FrameCodecBuilder>
{
private IHttp2FrameWriter _frameWriter;
public Http2FrameCodecBuilder(bool isServer)
{
IsServer = isServer;
// For backwards compatibility we should disable to timeout by default at this layer.
GracefulShutdownTimeout = TimeSpan.Zero;
}
/// <summary>
/// Creates a builder for an HTTP/2 client.
/// </summary>
public static Http2FrameCodecBuilder ForClient()
{
return new Http2FrameCodecBuilder(false);
}
/// <summary>
/// Creates a builder for an HTTP/2 server.
/// </summary>
public static Http2FrameCodecBuilder ForServer()
{
return new Http2FrameCodecBuilder(true);
}
// For testing only.
internal Http2FrameCodecBuilder FrameWriter(IHttp2FrameWriter frameWriter)
{
if (frameWriter is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.frameWriter); }
_frameWriter = frameWriter;
return this;
}
/// <summary>
/// Build a <see cref="Http2FrameCodec"/> object.
/// </summary>
public override Http2FrameCodec Build()
{
var frameWriter = _frameWriter;
if (frameWriter is object)
{
// This is to support our tests and will never be executed by the user as frameWriter(...)
// is package-private.
DefaultHttp2Connection connection = new DefaultHttp2Connection(IsServer, MaxReservedStreams);
var maxHeaderListSize = InitialSettings.MaxHeaderListSize();
IHttp2FrameReader frameReader = new DefaultHttp2FrameReader(!maxHeaderListSize.HasValue ?
new DefaultHttp2HeadersDecoder(IsValidateHeaders) :
new DefaultHttp2HeadersDecoder(IsValidateHeaders, maxHeaderListSize.Value));
if (FrameLogger is object)
{
frameWriter = new Http2OutboundFrameLogger(frameWriter, FrameLogger);
frameReader = new Http2InboundFrameLogger(frameReader, FrameLogger);
}
IHttp2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, frameWriter);
if (EncoderEnforceMaxConcurrentStreams)
{
encoder = new StreamBufferingEncoder(encoder);
}
IHttp2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, frameReader,
PromisedRequestVerifier, AutoAckSettingsFrame, AutoAckPingFrame);
int maxConsecutiveEmptyDataFrames = DecoderEnforceMaxConsecutiveEmptyDataFrames;
if ((uint)maxConsecutiveEmptyDataFrames > 0u)
{
decoder = new Http2EmptyDataFrameConnectionDecoder(decoder, maxConsecutiveEmptyDataFrames);
}
return Build(decoder, encoder, InitialSettings);
}
return base.Build();
}
protected override Http2FrameCodec Build(IHttp2ConnectionDecoder decoder, IHttp2ConnectionEncoder encoder, Http2Settings initialSettings)
{
return new Http2FrameCodec(encoder, decoder, initialSettings, DecoupleCloseAndGoAway)
{
GracefulShutdownTimeout = GracefulShutdownTimeout
};
}
}
}
| 40.373913 | 145 | 0.642688 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Codecs.Http2/Http2FrameCodecBuilder.cs | 4,645 | C# |
namespace NosSmooth.Extensions.Events
{
public class GMJoinedMap
{
}
} | 14 | 39 | 0.571429 | [
"MIT"
] | Rutherther/NosSmooth | Core/NosSmooth.Extensions/Events/GMJoinedMap.cs | 100 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using Newtonsoft.Json.Linq;
using umbraco.cms.businesslogic.Files;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
namespace Umbraco.Web.PropertyEditors
{
[PropertyEditor(Constants.PropertyEditors.UploadFieldAlias, "File upload", "fileupload")]
public class FileUploadPropertyEditor : PropertyEditor
{
/// <summary>
/// We're going to bind to the MediaService Saving event so that we can populate the umbracoFile size, type, etc... label fields
/// if we find any attached to the current media item.
/// </summary>
/// <remarks>
/// I think this kind of logic belongs on this property editor, I guess it could exist elsewhere but it all has to do with the upload field.
/// </remarks>
static FileUploadPropertyEditor()
{
MediaService.Saving += MediaServiceSaving;
MediaService.Created += MediaServiceCreating;
ContentService.Copied += ContentServiceCopied;
}
/// <summary>
/// Creates our custom value editor
/// </summary>
/// <returns></returns>
protected override PropertyValueEditor CreateValueEditor()
{
var baseEditor = base.CreateValueEditor();
baseEditor.Validators.Add(new UploadFileTypeValidator());
return new FileUploadPropertyValueEditor(baseEditor);
}
protected override PreValueEditor CreatePreValueEditor()
{
return new FileUploadPreValueEditor();
}
/// <summary>
/// After the content is copied we need to check if there are files that also need to be copied
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void ContentServiceCopied(IContentService sender, Core.Events.CopyEventArgs<IContent> e)
{
if (e.Original.Properties.Any(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias))
{
bool isUpdated = false;
var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
//Loop through properties to check if the content contains media that should be deleted
foreach (var property in e.Original.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias
&& x.Value != null
&& string.IsNullOrEmpty(x.Value.ToString()) == false))
{
if (fs.FileExists(IOHelper.MapPath(property.Value.ToString())))
{
var currentPath = fs.GetRelativePath(property.Value.ToString());
var propertyId = e.Copy.Properties.First(x => x.Alias == property.Alias).Id;
var newPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(currentPath));
fs.CopyFile(currentPath, newPath);
e.Copy.SetValue(property.Alias, fs.GetUrl(newPath));
//Copy thumbnails
foreach (var thumbPath in fs.GetThumbnails(currentPath))
{
var newThumbPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(thumbPath));
fs.CopyFile(thumbPath, newThumbPath);
}
isUpdated = true;
}
}
if (isUpdated)
{
//need to re-save the copy with the updated path value
sender.Save(e.Copy);
}
}
}
static void MediaServiceCreating(IMediaService sender, Core.Events.NewEventArgs<IMedia> e)
{
AutoFillProperties(e.Entity);
}
static void MediaServiceSaving(IMediaService sender, Core.Events.SaveEventArgs<IMedia> e)
{
foreach (var m in e.SavedEntities)
{
AutoFillProperties(m);
}
}
static void AutoFillProperties(IContentBase model)
{
foreach (var p in model.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias))
{
var uploadFieldConfigNode =
UmbracoConfig.For.UmbracoSettings().Content.ImageAutoFillProperties
.FirstOrDefault(x => x.Alias == p.Alias);
if (uploadFieldConfigNode != null)
{
model.PopulateFileMetaDataProperties(uploadFieldConfigNode, p.Value == null ? string.Empty : p.Value.ToString());
}
}
}
/// <summary>
/// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in
/// </summary>
internal class FileUploadPreValueEditor : ValueListPreValueEditor
{
public FileUploadPreValueEditor()
: base()
{
var field = Fields.First();
field.Description = "Enter a max width/height for each thumbnail";
field.Name = "Add thumbnail size";
//need to have some custom validation happening here
field.Validators.Add(new ThumbnailListValidator());
}
/// <summary>
/// Format the persisted value to work with our multi-val editor.
/// </summary>
/// <param name="defaultPreVals"></param>
/// <param name="persistedPreVals"></param>
/// <returns></returns>
public override IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals)
{
var result = new Dictionary<string, object>();
//the pre-values just take up one field with a semi-colon delimiter so we'll just parse
var dictionary = persistedPreVals.FormatAsDictionary();
if (dictionary.Any())
{
//there should only be one val
var delimited = dictionary.First().Value.Value.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);
for (var index = 0; index < delimited.Length; index++)
{
result.Add(index.ToInvariantString(), delimited[index]);
}
}
//the items list will be a dictionary of it's id -> value we need to use the id for persistence for backwards compatibility
return new Dictionary<string, object> { { "items", result } };
}
/// <summary>
/// Take the posted values and convert them to a semi-colon separated list so that its backwards compatible
/// </summary>
/// <param name="editorValue"></param>
/// <param name="currentValue"></param>
/// <returns></returns>
public override IDictionary<string, PreValue> ConvertEditorToDb(IDictionary<string, object> editorValue, PreValueCollection currentValue)
{
var result = base.ConvertEditorToDb(editorValue, currentValue);
//this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is
// semi-colon delimited
var values = result.Select(item => item.Value.Value).ToList();
result.Clear();
result.Add("thumbs", new PreValue(string.Join(";", values)));
return result;
}
internal class ThumbnailListValidator : IPropertyValidator
{
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
{
var json = value as JArray;
if (json == null) yield break;
//validate each item which is a json object
for (var index = 0; index < json.Count; index++)
{
var i = json[index];
var jItem = i as JObject;
if (jItem == null || jItem["value"] == null) continue;
//NOTE: we will be removing empty values when persisting so no need to validate
var asString = jItem["value"].ToString();
if (asString.IsNullOrWhiteSpace()) continue;
int parsed;
if (int.TryParse(asString, out parsed) == false)
{
yield return new ValidationResult("The value " + asString + " is not a valid number", new[]
{
//we'll make the server field the index number of the value so it can be wired up to the view
"item_" + index.ToInvariantString()
});
}
}
}
}
}
}
}
| 44.977578 | 155 | 0.541974 | [
"MIT"
] | ma1f/Umbraco-CMS | src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs | 10,030 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Domain.Apps.Core.Rules;
using Squidex.Domain.Apps.Core.Rules.Actions;
using Squidex.Domain.Apps.Core.Rules.Triggers;
using Squidex.Domain.Apps.Entities.Rules.Commands;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Infrastructure;
using Xunit;
#pragma warning disable SA1310 // Field names must not contain underscore
namespace Squidex.Domain.Apps.Entities.Rules.Guards
{
public class GuardRuleTests
{
private readonly Uri validUrl = new Uri("https://squidex.io");
private readonly Rule rule_0 = new Rule(new ContentChangedTrigger(), new WebhookAction());
private readonly NamedId<Guid> appId = new NamedId<Guid>(Guid.NewGuid(), "my-app");
private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
public GuardRuleTests()
{
A.CallTo(() => appProvider.GetSchemaAsync(appId.Id, A<Guid>.Ignored, false))
.Returns(A.Fake<ISchemaEntity>());
}
[Fact]
public async Task CanCreate_should_throw_exception_if_trigger_null()
{
var command = CreateCommand(new CreateRule
{
Trigger = null,
Action = new WebhookAction
{
Url = validUrl
}
});
await Assert.ThrowsAsync<ValidationException>(() => GuardRule.CanCreate(command, appProvider));
}
[Fact]
public async Task CanCreate_should_throw_exception_if_action_null()
{
var command = CreateCommand(new CreateRule
{
Trigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
},
Action = null
});
await Assert.ThrowsAsync<ValidationException>(() => GuardRule.CanCreate(command, appProvider));
}
[Fact]
public async Task CanCreate_should_not_throw_exception_if_trigger_and_action_valid()
{
var command = CreateCommand(new CreateRule
{
Trigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
},
Action = new WebhookAction
{
Url = validUrl
}
});
await GuardRule.CanCreate(command, appProvider);
}
[Fact]
public async Task CanUpdate_should_throw_exception_if_action_and_trigger_are_null()
{
var command = new UpdateRule();
await Assert.ThrowsAsync<ValidationException>(() => GuardRule.CanUpdate(command, appId.Id, appProvider));
}
[Fact]
public async Task CanUpdate_should_not_throw_exception_if_trigger_and_action_valid()
{
var command = new UpdateRule
{
Trigger = new ContentChangedTrigger
{
Schemas = ImmutableList<ContentChangedTriggerSchema>.Empty
},
Action = new WebhookAction
{
Url = validUrl
}
};
await GuardRule.CanUpdate(command, appId.Id, appProvider);
}
[Fact]
public void CanEnable_should_throw_exception_if_rule_enabled()
{
var command = new EnableRule();
var rule_1 = rule_0.Enable();
Assert.Throws<ValidationException>(() => GuardRule.CanEnable(command, rule_1));
}
[Fact]
public void CanEnable_should_not_throw_exception_if_rule_disabled()
{
var command = new EnableRule();
var rule_1 = rule_0.Disable();
GuardRule.CanEnable(command, rule_1);
}
[Fact]
public void CanDisable_should_throw_exception_if_rule_disabled()
{
var command = new DisableRule();
var rule_1 = rule_0.Disable();
Assert.Throws<ValidationException>(() => GuardRule.CanDisable(command, rule_1));
}
[Fact]
public void CanDisable_should_not_throw_exception_if_rule_enabled()
{
var command = new DisableRule();
var rule_1 = rule_0.Enable();
GuardRule.CanDisable(command, rule_1);
}
[Fact]
public void CanDelete_should_not_throw_exception()
{
var command = new DeleteRule();
GuardRule.CanDelete(command);
}
private CreateRule CreateCommand(CreateRule command)
{
command.AppId = appId;
return command;
}
}
}
| 31.203593 | 117 | 0.557091 | [
"MIT"
] | SarensDev/squidex | tests/Squidex.Domain.Apps.Entities.Tests/Rules/Guards/GuardRuleTests.cs | 5,214 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20181101.Outputs
{
/// <summary>
/// Gateway routing details
/// </summary>
[OutputType]
public sealed class GatewayRouteResponse
{
/// <summary>
/// The route's AS path sequence
/// </summary>
public readonly string AsPath;
/// <summary>
/// The gateway's local address
/// </summary>
public readonly string LocalAddress;
/// <summary>
/// The route's network prefix
/// </summary>
public readonly string Network;
/// <summary>
/// The route's next hop
/// </summary>
public readonly string NextHop;
/// <summary>
/// The source this route was learned from
/// </summary>
public readonly string Origin;
/// <summary>
/// The peer this route was learned from
/// </summary>
public readonly string SourcePeer;
/// <summary>
/// The route's weight
/// </summary>
public readonly int Weight;
[OutputConstructor]
private GatewayRouteResponse(
string asPath,
string localAddress,
string network,
string nextHop,
string origin,
string sourcePeer,
int weight)
{
AsPath = asPath;
LocalAddress = localAddress;
Network = network;
NextHop = nextHop;
Origin = origin;
SourcePeer = sourcePeer;
Weight = weight;
}
}
}
| 25.689189 | 81 | 0.552867 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20181101/Outputs/GatewayRouteResponse.cs | 1,901 | C# |
using System.ComponentModel.DataAnnotations;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using SystemDbContext = Microsoft.EntityFrameworkCore.DbContext;
namespace essentialMix.Core.Data.Entity;
public abstract class DbContext : SystemDbContext
{
/// <inheritdoc />
protected DbContext()
{
}
/// <inheritdoc />
protected DbContext([NotNull] DbContextOptions options)
: base(options)
{
}
/// <inheritdoc />
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
Validate();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
/// <inheritdoc />
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
Validate();
return base.SaveChangesAsync(cancellationToken);
}
protected virtual void Validate()
{
IEnumerable<EntityEntry> entries = ChangeTracker.Entries()
.Where(e => e.State is EntityState.Added or EntityState.Modified);
foreach (EntityEntry entry in entries)
{
object entity = entry.Entity;
Validator.ValidateObject(entity, new ValidationContext(entity), true);
}
}
} | 25.765957 | 141 | 0.763832 | [
"MIT"
] | asm2025/essentailMix.Core | essentialMix.Core.Data.Entity/DbContext.cs | 1,213 | C# |
using System;
using OpenTK;
namespace Sharp
{
public struct Ray
{
public Vector3 origin;
public Vector3 direction;
public Ray(Vector3 orig, Vector3 dir){
origin = orig;
direction = dir;
}
}
}
| 11.833333 | 40 | 0.676056 | [
"MIT"
] | BreyerW/Sharp.Engine | Sharp/Ray.cs | 215 | C# |
using System.Runtime.Serialization;
namespace StarwebSharp.Entities
{
public enum ShippingMethodModelValidForCountries
{
[EnumMember(Value = @"all")] All = 0,
[EnumMember(Value = @"EU")] EU = 1,
[EnumMember(Value = @"non-EU")] NonEU = 2,
[EnumMember(Value = @"selected")] Selected = 3,
[EnumMember(Value = @"none")] None = 4
}
} | 22.705882 | 55 | 0.595855 | [
"MIT"
] | PrimePenguin/PrimePenguin.StarwebSharp | StarwebSharp/Entities/ShippingMethodModelValidForCountries.cs | 388 | C# |
// Jeebs Rapid Application Development
// Copyright (c) bfren.uk - licensed under https://mit.bfren.uk/2013
using System;
namespace Jx.Config
{
/// <summary>
/// Configuration Schema Validation Failed
/// </summary>
public class ConfigurationSchemaValidationFailedException : Exception
{
/// <summary>
/// Create exception
/// </summary>
public ConfigurationSchemaValidationFailedException() { }
/// <summary>
/// Create exception
/// </summary>
/// <param name="message"></param>
public ConfigurationSchemaValidationFailedException(string message) : base(message) { }
/// <summary>
/// Create exception
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public ConfigurationSchemaValidationFailedException(string message, Exception inner) : base(message, inner) { }
}
}
| 26.375 | 113 | 0.695498 | [
"MIT"
] | bencgreen/jeebs | src/Jeebs.Config/Exceptions/ConfigurationSchemaValidationFailedException.cs | 846 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DefenderButton : MonoBehaviour
{
[SerializeField] Defenders defenderPrefab;
private void Start()
{
LabelButtonWithCost();
}
private void LabelButtonWithCost() //Show star cost to button
{
Text costText = GetComponentInChildren<Text>();
if (!costText)
{
Debug.LogError(name + "has no cost text, add some!");
}
else
{
costText.text = defenderPrefab.GetStarCost().ToString();
}
}
private void OnMouseDown()
{
var buttons = FindObjectsOfType<DefenderButton>();
//sound
foreach (DefenderButton button in buttons)
{
button.GetComponent<SpriteRenderer>().color = new Color32(51, 51, 51, 255);
}
GetComponent<SpriteRenderer>().color = Color.white;
FindObjectOfType<DefenderSpawner>().SetSelectedDefender(defenderPrefab);
}
}
| 24.697674 | 87 | 0.616761 | [
"MIT"
] | NanthawatKTY/Mosquitoes-Slayer | Assets/Scripts/Defenders/DefenderButton.cs | 1,064 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the guardduty-2017-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.GuardDuty.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GuardDuty.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListFindings operation
/// </summary>
public class ListFindingsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListFindingsResponse response = new ListFindingsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("findingIds", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
response.FindingIds = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException"))
{
return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonGuardDutyException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListFindingsResponseUnmarshaller _instance = new ListFindingsResponseUnmarshaller();
internal static ListFindingsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListFindingsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.208333 | 193 | 0.623167 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/GuardDuty/Generated/Model/Internal/MarshallTransformations/ListFindingsResponseUnmarshaller.cs | 4,705 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace AwesomeNamespace.Models
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime;
using System.Runtime.Serialization;
/// <summary>
/// Defines values for AccountType.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum AccountType
{
[EnumMember(Value = "Standard_LRS")]
StandardLRS,
[EnumMember(Value = "Standard_ZRS")]
StandardZRS,
[EnumMember(Value = "Standard_GRS")]
StandardGRS,
[EnumMember(Value = "Standard_RAGRS")]
StandardRAGRS,
[EnumMember(Value = "Premium_LRS")]
PremiumLRS
}
}
| 29 | 74 | 0.669371 | [
"MIT"
] | bloudraak/autorest | Samples/1d-common-settings/base/folder/AzureClient/Models/AccountType.cs | 986 | C# |
using System.Collections;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.VFX;
using UnityEngine.VFX;
using UnityEditor;
using UnityEditor.VFX.UI;
using UnityEditor.ProjectWindowCallback;
using UnityObject = UnityEngine.Object;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
namespace UnityEditor
{
class VFXBuildPreprocessor : IPreprocessBuildWithReport
{
int IOrderedCallback.callbackOrder => 0;
void IPreprocessBuildWithReport.OnPreprocessBuild(BuildReport report)
{
VFXManagerEditor.CheckVFXManager();
}
}
[InitializeOnLoad]
static class VisualEffectAssetEditorUtility
{
private static string m_TemplatePath = null;
public static string templatePath
{
get
{
if (m_TemplatePath == null)
{
m_TemplatePath = VisualEffectGraphPackageInfo.assetPackagePath + "/Editor/Templates/";
}
return m_TemplatePath;
}
}
static void CheckVFXManagerOnce()
{
VFXManagerEditor.CheckVFXManager();
EditorApplication.update -= CheckVFXManagerOnce;
}
static VisualEffectAssetEditorUtility()
{
EditorApplication.update += CheckVFXManagerOnce;
UnityEngine.VFX.VFXManager.activateVFX = true;
}
public const string templateAssetName = "Simple Particle System.vfx";
public const string templateBlockSubgraphAssetName = "Default Subgraph Block.vfxblock";
public const string templateOperatorSubgraphAssetName = "Default Subgraph Operator.vfxoperator";
[MenuItem("GameObject/Visual Effects/Visual Effect", false, 10)]
public static void CreateVisualEffectGameObject(MenuCommand menuCommand)
{
GameObject go = new GameObject("Visual Effect");
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
var vfxComp = go.AddComponent<VisualEffect>();
if (Selection.activeObject != null && Selection.activeObject is VisualEffectAsset)
{
vfxComp.visualEffectAsset = Selection.activeObject as VisualEffectAsset;
vfxComp.startSeed = (uint)Random.Range(int.MinValue, int.MaxValue);
}
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}
public static VisualEffectAsset CreateNewAsset(string path)
{
return CreateNew<VisualEffectAsset>(path);
}
public static T CreateNew<T>(string path) where T : UnityObject
{
string emptyAsset = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!2058629511 &1\nVisualEffectResource:\n";
File.WriteAllText(path, emptyAsset);
AssetDatabase.ImportAsset(path);
return AssetDatabase.LoadAssetAtPath<T>(path);
}
[MenuItem("Assets/Create/Visual Effects/Visual Effect Graph", false, 306)]
public static void CreateVisualEffectAsset()
{
string templateString = "";
try
{
templateString = System.IO.File.ReadAllText(templatePath + templateAssetName);
}
catch (System.Exception e)
{
Debug.LogError("Couldn't read template for new vfx asset : " + e.Message);
return;
}
Texture2D texture = EditorGUIUtility.FindTexture(typeof(VisualEffectAsset));
var action = ScriptableObject.CreateInstance<DoCreateNewVFX>();
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action, "New VFX.vfx", texture, null);
}
[MenuItem("Assets/Create/Visual Effects/Visual Effect Defaults", false, 307)]
public static void CreateVisualEffectDefaults()
{
var obj = VFXResources.CreateInstance<VFXResources>();
obj.SetDefaults();
AssetDatabase.CreateAsset(obj, "Assets/Visual Effects Defaults.asset");
Selection.activeObject = obj;
}
[MenuItem("Assets/Create/Visual Effects/Visual Effect Defaults", true)]
public static bool IsCreateVisualEffectDefaultsActive()
{
var resources = Resources.FindObjectsOfTypeAll<VFXResources>();
return resources == null || resources.Length == 0;
}
internal class DoCreateNewVFX : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
try
{
var templateString = System.IO.File.ReadAllText(templatePath + templateAssetName);
System.IO.File.WriteAllText(pathName, templateString);
}
catch (FileNotFoundException)
{
CreateNewAsset(pathName);
}
AssetDatabase.ImportAsset(pathName);
var resource = VisualEffectResource.GetResourceAtPath(pathName);
ProjectWindowUtil.FrameObjectInProjectWindow(resource.asset.GetInstanceID());
}
}
internal class DoCreateNewSubgraphOperator : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
var sg = CreateNew<VisualEffectSubgraphOperator>(pathName);
ProjectWindowUtil.FrameObjectInProjectWindow(sg.GetInstanceID());
}
}
internal class DoCreateNewSubgraphBlock : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
var sg = CreateNew<VisualEffectSubgraphBlock>(pathName);
ProjectWindowUtil.FrameObjectInProjectWindow(sg.GetInstanceID());
}
}
[MenuItem("Assets/Create/Visual Effects/Visual Effect Subgraph Operator", false, 308)]
public static void CreateVisualEffectSubgraphOperator()
{
string fileName = "New VFX Subgraph Operator.vfxoperator";
CreateVisualEffectSubgraph<VisualEffectSubgraphOperator, DoCreateNewSubgraphOperator>(fileName, templateOperatorSubgraphAssetName);
}
[MenuItem("Assets/Create/Visual Effects/Visual Effect Subgraph Block", false, 309)]
public static void CreateVisualEffectSubgraphBlock()
{
string fileName = "New VFX Subgraph Block.vfxblock";
CreateVisualEffectSubgraph<VisualEffectSubgraphBlock, DoCreateNewSubgraphBlock>(fileName, templateBlockSubgraphAssetName);
}
public static void CreateVisualEffectSubgraph<T, U>(string fileName, string templateName) where U : EndNameEditAction
{
string templateString = "";
Texture2D texture = EditorGUIUtility.FindTexture(typeof(T));
try // try with the template
{
templateString = System.IO.File.ReadAllText(templatePath + templateName);
ProjectWindowUtil.CreateAssetWithContent(fileName, templateString, texture);
}
catch (System.Exception e)
{
Debug.LogError("Couldn't read template for new visual effect subgraph : " + e.Message);
var action = ScriptableObject.CreateInstance<U>();
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action, fileName, texture, null);
return;
}
}
}
}
| 37.023923 | 143 | 0.630137 | [
"MIT"
] | KoroBli/LifeOn | LifeOn/Library/PackageCache/com.unity.visualeffectgraph@8.2.0/Editor/VFXAssetEditorUtility.cs | 7,738 | C# |
namespace Sla.Repository.Enities
{
/// <summary>
/// Class QueryFoo.
/// </summary>
public class QueryFoo
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the key.
/// </summary>
public string Key { get; set; }
}
} | 21 | 40 | 0.47619 | [
"MIT"
] | raychiutw/software-layered-architecture-pattern-smaple | src/Sla.Repository/Enities/QueryFoo.cs | 380 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnterpriseMessagingGateway.Services.Interfaces.Dto
{
public class DocumentTypeCreateDto
{
public string Name { get; set; }
public string Description { get; set; }
public string DocType { get; set; }
public string Channel { get; set; }
public virtual ICollection<DocumentTypeResolverCreateDto> ResolverList { get; set; }
}
}
| 26.631579 | 92 | 0.701581 | [
"MIT"
] | zdonev/enterprise-messaging-gateway | src/Services.Interfaces/Dto/DocumentTypeCreateDto.cs | 508 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using static Interop;
using static Interop.Ole32;
namespace System.Windows.Forms.ComponentModel.Com2Interop
{
/// <summary>
/// This class wraps a com native property in a property descriptor.
/// It maintains all information relative to the basic (e.g. ITypeInfo)
/// information about the member dispid function, and converts that info
/// to meaningful managed code information.
///
/// It also allows other objects to register listeners to add extended
/// information at runtime such as attributes of TypeConverters.
/// </summary>
internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable
{
private EventHandlerList events;
/// <summary>
/// Is this guy read only?
/// </summary>
private readonly bool baseReadOnly;
private bool readOnly;
/// <summary>
/// The resolved native type -> clr type
/// </summary>
private readonly Type propertyType;
/// <summary>
/// The dispid. This is also in a DispIDAttribute, but we
/// need it a lot.
/// </summary>
private readonly DispatchID dispid;
private TypeConverter converter;
private object editor;
/// <summary>
/// The current display name to show for this property
/// </summary>
private string displayName;
/// <summary>
/// This is any extra data needed. For IDispatch types, it's the GUID of
/// the interface, etc.
/// </summary>
private readonly object typeData;
/// <summary>
/// Keeps track of which data members need to be refreshed.
/// </summary>
private int refreshState;
/// <summary>
/// Our properties manager
/// </summary>
private Com2Properties com2props;
/// <summary>
/// Our original baseline properties
/// </summary>
private Attribute[] baseAttrs;
/// <summary>
/// Our cached last value -- this is only
/// for checking if we should ask for a display value
/// </summary>
private object lastValue;
/// <summary>
/// For Object and dispatch types, we hide them by default.
/// </summary>
private readonly bool typeHide;
/// <summary>
/// Set if the metadata causes this property to always be hidden
/// </summary>
private readonly bool canShow;
/// <summary>
/// This property is hidden because its get didn't return S_OK
/// </summary>
private bool hrHidden;
/// <summary>
/// Set if we are in the process of asking handlers for attributes
/// </summary>
private bool inAttrQuery;
/// <summary>
/// Our event signatures.
/// </summary>
private static readonly object EventGetBaseAttributes = new object();
private static readonly object EventGetDynamicAttributes = new object();
private static readonly object EventShouldRefresh = new object();
private static readonly object EventGetDisplayName = new object();
private static readonly object EventGetDisplayValue = new object();
private static readonly object EventGetIsReadOnly = new object();
private static readonly object EventGetTypeConverterAndTypeEditor = new object();
private static readonly object EventShouldSerializeValue = new object();
private static readonly object EventCanResetValue = new object();
private static readonly object EventResetValue = new object();
private static readonly Guid GUID_COLOR = new Guid("{66504301-BE0F-101A-8BBB-00AA00300CAB}");
/// <summary>
/// Our map of native types that we can map to managed types for editors
/// </summary>
private static readonly IDictionary oleConverters = new SortedList
{
[GUID_COLOR] = typeof(Com2ColorConverter),
[typeof(IFontDisp).GUID] = typeof(Com2FontConverter),
[typeof(IFont).GUID] = typeof(Com2FontConverter),
[typeof(IPictureDisp).GUID] = typeof(Com2PictureConverter),
[typeof(IPicture).GUID] = typeof(Com2PictureConverter)
};
/// <summary>
/// Should we convert our type?
/// </summary>
private readonly Com2DataTypeToManagedDataTypeConverter valueConverter;
/// <summary>
/// Ctor.
/// </summary>
public Com2PropertyDescriptor(DispatchID dispid, string name, Attribute[] attrs, bool readOnly, Type propType, object typeData, bool hrHidden)
: base(name, attrs)
{
baseReadOnly = readOnly;
this.readOnly = readOnly;
baseAttrs = attrs;
SetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes, true);
this.hrHidden = hrHidden;
// readonly to begin with are always read only
SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, readOnly);
propertyType = propType;
this.dispid = dispid;
if (typeData is not null)
{
this.typeData = typeData;
if (typeData is Com2Enum)
{
converter = new Com2EnumConverter((Com2Enum)typeData);
}
else if (typeData is Guid)
{
valueConverter = CreateOleTypeConverter((Type)oleConverters[(Guid)typeData]);
}
}
// check if this thing is hidden from metadata
canShow = true;
if (attrs is not null)
{
for (int i = 0; i < attrs.Length; i++)
{
if (attrs[i].Equals(BrowsableAttribute.No) && !hrHidden)
{
canShow = false;
break;
}
}
}
if (canShow && (propType == typeof(object) || (valueConverter is null && propType == typeof(Oleaut32.IDispatch))))
{
typeHide = true;
}
}
protected Attribute[] BaseAttributes
{
get
{
if (GetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes))
{
SetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes, false);
int baseCount = baseAttrs is null ? 0 : baseAttrs.Length;
ArrayList attrList = new ArrayList();
if (baseCount != 0)
{
attrList.AddRange(baseAttrs);
}
OnGetBaseAttributes(new GetAttributesEvent(attrList));
if (attrList.Count != baseCount)
{
baseAttrs = new Attribute[attrList.Count];
}
if (baseAttrs is not null)
{
attrList.CopyTo(baseAttrs, 0);
}
else
{
baseAttrs = Array.Empty<Attribute>();
}
}
return baseAttrs;
}
set
{
baseAttrs = value;
}
}
/// <summary>
/// Attributes
/// </summary>
public override AttributeCollection Attributes
{
get
{
if (AttributesValid || InAttrQuery)
{
return base.Attributes;
}
// restore our base attributes
AttributeArray = BaseAttributes;
ArrayList newAttributes = null;
// if we are forcing a hide
if (typeHide && canShow)
{
if (newAttributes is null)
{
newAttributes = new ArrayList(AttributeArray);
}
newAttributes.Add(new BrowsableAttribute(false));
}
else if (hrHidden)
{
// check to see if the get still fails
object target = TargetObject;
if (target is not null)
{
HRESULT hr = new ComNativeDescriptor().GetPropertyValue(target, dispid, new object[1]);
// if not, go ahead and make this a browsable item
if (hr.Succeeded())
{
// make it browsable
if (newAttributes is null)
{
newAttributes = new ArrayList(AttributeArray);
}
newAttributes.Add(new BrowsableAttribute(true));
hrHidden = false;
}
}
}
inAttrQuery = true;
try
{
// demand get any extended attributes
ArrayList attrList = new ArrayList();
OnGetDynamicAttributes(new GetAttributesEvent(attrList));
Attribute ma;
if (attrList.Count != 0 && newAttributes is null)
{
newAttributes = new ArrayList(AttributeArray);
}
// push any new attributes into the base type
for (int i = 0; i < attrList.Count; i++)
{
ma = (Attribute)attrList[i];
newAttributes.Add(ma);
}
}
finally
{
inAttrQuery = false;
}
// these are now valid.
SetNeedsRefresh(Com2PropertyDescriptorRefresh.Attributes, false);
// If we reconfigured attributes, then poke the new set back in.
//
if (newAttributes is not null)
{
Attribute[] temp = new Attribute[newAttributes.Count];
newAttributes.CopyTo(temp, 0);
AttributeArray = temp;
}
return base.Attributes;
}
}
/// <summary>
/// Checks if the attributes are valid. Asks any clients if they
/// would like attributes required.
/// </summary>
protected bool AttributesValid
{
get
{
bool currentRefresh = !GetNeedsRefresh(Com2PropertyDescriptorRefresh.Attributes);
return currentRefresh;
}
}
/// <summary>
/// Checks if this item can be shown.
/// </summary>
public bool CanShow
{
get
{
return canShow;
}
}
/// <summary>
/// Retrieves the type of the component this PropertyDescriptor is bound to.
/// </summary>
public override Type ComponentType => typeof(Oleaut32.IDispatch);
/// <summary>
/// Retrieves the type converter for this property.
/// </summary>
public override TypeConverter Converter
{
get
{
if (TypeConverterValid)
{
return converter;
}
object typeEd = null;
GetTypeConverterAndTypeEditor(ref converter, typeof(UITypeEditor), ref typeEd);
if (!TypeEditorValid)
{
editor = typeEd;
SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false);
}
SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false);
return converter;
}
}
/// <summary>
/// Retrieves whether this component is applying a type conversion...
/// </summary>
public bool ConvertingNativeType
{
get
{
return (valueConverter is not null);
}
}
/// <summary>
/// Retrieves the default value for this property.
/// </summary>
protected virtual object DefaultValue
{
get
{
return null;
}
}
/// <summary>
/// Retrieves the DISPID for this item
/// </summary>
public DispatchID DISPID
{
get
{
return dispid;
}
}
/// <summary>
/// Gets the friendly name that should be displayed to the user in a window like
/// the Property Browser.
/// </summary>
public override string DisplayName
{
get
{
if (!DisplayNameValid)
{
GetNameItemEvent gni = new GetNameItemEvent(base.DisplayName);
OnGetDisplayName(gni);
displayName = gni.NameString;
SetNeedsRefresh(Com2PropertyDescriptorRefresh.DisplayName, false);
}
return displayName;
}
}
/// <summary>
/// Checks if the property display name is valid
/// asks clients if they would like display name required.
/// </summary>
protected bool DisplayNameValid
{
get
{
bool currentRefresh = !(displayName is null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.DisplayName));
return currentRefresh;
}
}
protected EventHandlerList Events
{
get
{
if (events is null)
{
events = new EventHandlerList();
}
return events;
}
}
protected bool InAttrQuery
{
get
{
return inAttrQuery;
}
}
/// <summary>
/// Indicates whether this property is read only.
/// </summary>
public override bool IsReadOnly
{
get
{
if (!ReadOnlyValid)
{
readOnly |= (Attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes));
GetBoolValueEvent gbv = new GetBoolValueEvent(readOnly);
OnGetIsReadOnly(gbv);
readOnly = gbv.Value;
SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, false);
}
return readOnly;
}
}
internal Com2Properties PropertyManager
{
set
{
com2props = value;
}
get
{
return com2props;
}
}
/// <summary>
/// Retrieves the type of the property.
/// </summary>
public override Type PropertyType
{
get
{
// replace the type with the mapped converter type
if (valueConverter is not null)
{
return valueConverter.ManagedType;
}
else
{
return propertyType;
}
}
}
/// <summary>
/// Checks if the read only state is valid.
/// Asks clients if they would like read-only required.
/// </summary>
protected bool ReadOnlyValid
{
get
{
if (baseReadOnly)
{
return true;
}
bool currentRefresh = !GetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly);
return currentRefresh;
}
}
/// <summary>
/// Gets the Object that this descriptor was created for.
/// May be null if the Object's ref has died.
/// </summary>
public virtual object TargetObject
{
get
{
if (com2props is not null)
{
return com2props.TargetObject;
}
return null;
}
}
protected bool TypeConverterValid
{
get
{
bool currentRefresh = !(converter is null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter));
return currentRefresh;
}
}
protected bool TypeEditorValid
{
get
{
bool currentRefresh = !(editor is null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor));
return currentRefresh;
}
}
public event GetBoolValueEventHandler QueryCanResetValue
{
add => Events.AddHandler(EventCanResetValue, value);
remove => Events.RemoveHandler(EventCanResetValue, value);
}
public event GetAttributesEventHandler QueryGetBaseAttributes
{
add => Events.AddHandler(EventGetBaseAttributes, value);
remove => Events.RemoveHandler(EventGetBaseAttributes, value);
}
public event GetAttributesEventHandler QueryGetDynamicAttributes
{
add => Events.AddHandler(EventGetDynamicAttributes, value);
remove => Events.RemoveHandler(EventGetDynamicAttributes, value);
}
public event GetNameItemEventHandler QueryGetDisplayName
{
add => Events.AddHandler(EventGetDisplayName, value);
remove => Events.RemoveHandler(EventGetDisplayName, value);
}
public event GetNameItemEventHandler QueryGetDisplayValue
{
add => Events.AddHandler(EventGetDisplayValue, value);
remove => Events.RemoveHandler(EventGetDisplayValue, value);
}
public event GetBoolValueEventHandler QueryGetIsReadOnly
{
add => Events.AddHandler(EventGetIsReadOnly, value);
remove => Events.RemoveHandler(EventGetIsReadOnly, value);
}
public event GetTypeConverterAndTypeEditorEventHandler QueryGetTypeConverterAndTypeEditor
{
add => Events.AddHandler(EventGetTypeConverterAndTypeEditor, value);
remove => Events.RemoveHandler(EventGetTypeConverterAndTypeEditor, value);
}
public event Com2EventHandler QueryResetValue
{
add => Events.AddHandler(EventResetValue, value);
remove => Events.RemoveHandler(EventResetValue, value);
}
public event GetBoolValueEventHandler QueryShouldSerializeValue
{
add => Events.AddHandler(EventShouldSerializeValue, value);
remove => Events.RemoveHandler(EventShouldSerializeValue, value);
}
/// <summary>
/// Indicates whether reset will change the value of the component. If there
/// is a DefaultValueAttribute, then this will return true if getValue returns
/// something different than the default value. If there is a reset method and
/// a shouldPersist method, this will return what shouldPersist returns.
/// If there is just a reset method, this always returns true. If none of these
/// cases apply, this returns false.
/// </summary>
public override bool CanResetValue(object component)
{
if (component is ICustomTypeDescriptor)
{
component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this);
}
if (component == TargetObject)
{
GetBoolValueEvent gbv = new GetBoolValueEvent(false);
OnCanResetValue(gbv);
return gbv.Value;
}
return false;
}
public object Clone()
{
return new Com2PropertyDescriptor(dispid, Name, (Attribute[])baseAttrs.Clone(), readOnly, propertyType, typeData, hrHidden);
}
/// <summary>
/// Creates a converter Object, first by looking for a ctor with a Com2PropertyDescriptor
/// parameter, then using the default ctor if it is not found.
/// </summary>
private Com2DataTypeToManagedDataTypeConverter CreateOleTypeConverter(Type t)
{
if (t is null)
{
return null;
}
ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(Com2PropertyDescriptor) });
Com2DataTypeToManagedDataTypeConverter converter;
if (ctor is not null)
{
converter = (Com2DataTypeToManagedDataTypeConverter)ctor.Invoke(new object[] { this });
}
else
{
converter = (Com2DataTypeToManagedDataTypeConverter)Activator.CreateInstance(t);
}
return converter;
}
/// <summary>
/// Creates an instance of the member attribute collection. This can
/// be overriden by subclasses to return a subclass of AttributeCollection.
/// </summary>
protected override AttributeCollection CreateAttributeCollection()
{
return new AttributeCollection(AttributeArray);
}
private TypeConverter GetBaseTypeConverter()
{
if (PropertyType is null)
{
return new TypeConverter();
}
TypeConverter localConverter = null;
TypeConverterAttribute attr = (TypeConverterAttribute)Attributes[typeof(TypeConverterAttribute)];
if (attr is not null)
{
string converterTypeName = attr.ConverterTypeName;
if (converterTypeName is not null && converterTypeName.Length > 0)
{
Type converterType = Type.GetType(converterTypeName);
if (converterType is not null && typeof(TypeConverter).IsAssignableFrom(converterType))
{
try
{
localConverter = (TypeConverter)Activator.CreateInstance(converterType);
if (localConverter is not null)
{
refreshState |= Com2PropertyDescriptorRefresh.TypeConverterAttr;
}
}
catch (Exception ex)
{
Debug.Fail("Failed to create TypeConverter of type '" + attr.ConverterTypeName + "' from Attribute", ex.ToString());
}
}
}
}
// if we didn't get one from the attribute, ask the type descriptor
if (localConverter is null)
{
// we don't want to create the value editor for the IDispatch props because
// that will create the reference editor. We don't want that guy!
//
if (!typeof(Oleaut32.IDispatch).IsAssignableFrom(PropertyType))
{
localConverter = base.Converter;
}
else
{
localConverter = new Com2IDispatchConverter(this, false);
}
}
if (localConverter is null)
{
localConverter = new TypeConverter();
}
return localConverter;
}
private object GetBaseTypeEditor(Type editorBaseType)
{
if (PropertyType is null)
{
return null;
}
object localEditor = null;
EditorAttribute attr = (EditorAttribute)Attributes[typeof(EditorAttribute)];
if (attr is not null)
{
string editorTypeName = attr.EditorBaseTypeName;
if (editorTypeName is not null && editorTypeName.Length > 0)
{
Type attrEditorBaseType = Type.GetType(editorTypeName);
if (attrEditorBaseType is not null && attrEditorBaseType == editorBaseType)
{
Type type = Type.GetType(attr.EditorTypeName);
if (type is not null)
{
try
{
localEditor = Activator.CreateInstance(type);
if (localEditor is not null)
{
refreshState |= Com2PropertyDescriptorRefresh.TypeEditorAttr;
}
}
catch (Exception ex)
{
Debug.Fail("Failed to create editor of type '" + attr.EditorTypeName + "' from Attribute", ex.ToString());
}
}
}
}
}
if (localEditor is null)
{
localEditor = base.GetEditor(editorBaseType);
}
return localEditor;
}
/// <summary>
/// Gets the value that should be displayed to the user, such as in
/// the Property Browser.
/// </summary>
public virtual string GetDisplayValue(string defaultValue)
{
GetNameItemEvent nie = new GetNameItemEvent(defaultValue);
OnGetDisplayValue(nie);
string str = (nie.Name?.ToString());
return str;
}
/// <summary>
/// Retrieves an editor of the requested type.
/// </summary>
public override object GetEditor(Type editorBaseType)
{
if (TypeEditorValid)
{
return editor;
}
if (PropertyType is null)
{
return null;
}
if (editorBaseType == typeof(UITypeEditor))
{
TypeConverter c = null;
GetTypeConverterAndTypeEditor(ref c, editorBaseType, ref editor);
if (!TypeConverterValid)
{
converter = c;
SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false);
}
SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false);
}
else
{
editor = base.GetEditor(editorBaseType);
}
return editor;
}
/// <summary>
/// Retrieves the current native value of the property on component,
/// invoking the getXXX method. An exception in the getXXX
/// method will pass through.
/// </summary>
public unsafe object GetNativeValue(object component)
{
if (component is null)
{
return null;
}
if (component is ICustomTypeDescriptor)
{
component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this);
}
if (component is null || !Marshal.IsComObject(component) || !(component is Oleaut32.IDispatch))
{
return null;
}
Oleaut32.IDispatch pDisp = (Oleaut32.IDispatch)component;
object[] pVarResult = new object[1];
var pExcepInfo = new Oleaut32.EXCEPINFO();
var dispParams = new Oleaut32.DISPPARAMS();
Guid g = Guid.Empty;
HRESULT hr = pDisp.Invoke(
dispid,
&g,
Kernel32.GetThreadLocale(),
Oleaut32.DISPATCH.PROPERTYGET,
&dispParams,
pVarResult,
&pExcepInfo,
null);
switch (hr)
{
case HRESULT.S_OK:
case HRESULT.S_FALSE:
if (pVarResult[0] is null || Convert.IsDBNull(pVarResult[0]))
{
lastValue = null;
}
else
{
lastValue = pVarResult[0];
}
return lastValue;
case HRESULT.DISP_E_EXCEPTION:
return null;
default:
throw new ExternalException(string.Format(SR.DispInvokeFailed, "GetValue", hr), (int)hr);
}
}
/// <summary>
/// Checks whether the particular item(s) need refreshing.
/// </summary>
private bool GetNeedsRefresh(int mask)
{
return (refreshState & mask) != 0;
}
/// <summary>
/// Retrieves the current value of the property on component,
/// invoking the getXXX method. An exception in the getXXX
/// method will pass through.
/// </summary>
public override object GetValue(object component)
{
lastValue = GetNativeValue(component);
// do we need to convert the type?
if (ConvertingNativeType && lastValue is not null)
{
lastValue = valueConverter.ConvertNativeToManaged(lastValue, this);
}
else if (lastValue is not null && propertyType is not null && propertyType.IsEnum && lastValue.GetType().IsPrimitive)
{
// we've got to convert the value here -- we built the enum but the native object returns
// us values as integers
//
try
{
lastValue = Enum.ToObject(propertyType, lastValue);
}
catch
{
}
}
return lastValue;
}
/// <summary>
/// Retrieves the value editor for the property. If a value editor is passed
/// in as a TypeConverterAttribute, that value editor will be instantiated.
/// If no such attribute was found, a system value editor will be looked for.
/// See TypeConverter for a description of how system value editors are found.
/// If there is no system value editor, null is returned. If the value editor found
/// takes an IEditorSite in its constructor, the parameter will be passed in.
/// </summary>
public void GetTypeConverterAndTypeEditor(ref TypeConverter typeConverter, Type editorBaseType, ref object typeEditor)
{
// get the base editor and converter, attributes first
TypeConverter localConverter = typeConverter;
object localEditor = typeEditor;
if (localConverter is null)
{
localConverter = GetBaseTypeConverter();
}
if (localEditor is null)
{
localEditor = GetBaseTypeEditor(editorBaseType);
}
// if this is a object, get the value and attempt to create the correct value editor based on that value.
// we don't do this if the state came from an attribute
//
if (0 == (refreshState & Com2PropertyDescriptorRefresh.TypeConverterAttr) && PropertyType == typeof(Com2Variant))
{
Type editorType = PropertyType;
object value = GetValue(TargetObject);
if (value is not null)
{
editorType = value.GetType();
}
ComNativeDescriptor.ResolveVariantTypeConverterAndTypeEditor(value, ref localConverter, editorBaseType, ref localEditor);
}
// now see if someone else would like to serve up a value editor
//
// unwrap the editor if it's one of ours.
if (localConverter is Com2PropDescMainConverter)
{
localConverter = ((Com2PropDescMainConverter)localConverter).InnerConverter;
}
GetTypeConverterAndTypeEditorEvent e = new GetTypeConverterAndTypeEditorEvent(localConverter, localEditor);
OnGetTypeConverterAndTypeEditor(e);
localConverter = e.TypeConverter;
localEditor = e.TypeEditor;
// just in case one of the handlers removed our editor...
//
if (localConverter is null)
{
localConverter = GetBaseTypeConverter();
}
if (localEditor is null)
{
localEditor = GetBaseTypeEditor(editorBaseType);
}
// wrap the value editor in our main value editor, but only if it isn't "TypeConverter" or already a Com2PropDescMainTypeConverter
//
Type localConverterType = localConverter.GetType();
if (localConverterType != typeof(TypeConverter) && localConverterType != (typeof(Com2PropDescMainConverter)))
{
localConverter = new Com2PropDescMainConverter(this, localConverter);
}
// save the values back to the variables.
//
typeConverter = localConverter;
typeEditor = localEditor;
}
/// <summary>
/// Is the given value equal to the last known value for this object?
/// </summary>
public bool IsCurrentValue(object value)
{
return (value == lastValue || (lastValue is not null && lastValue.Equals(value)));
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnCanResetValue(GetBoolValueEvent gvbe)
{
RaiseGetBoolValueEvent(EventCanResetValue, gvbe);
}
protected void OnGetBaseAttributes(GetAttributesEvent e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((GetAttributesEventHandler)Events[EventGetBaseAttributes])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnGetDisplayName(GetNameItemEvent gnie)
{
RaiseGetNameItemEvent(EventGetDisplayName, gnie);
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnGetDisplayValue(GetNameItemEvent gnie)
{
RaiseGetNameItemEvent(EventGetDisplayValue, gnie);
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnGetDynamicAttributes(GetAttributesEvent e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((GetAttributesEventHandler)Events[EventGetDynamicAttributes])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnGetIsReadOnly(GetBoolValueEvent gvbe)
{
RaiseGetBoolValueEvent(EventGetIsReadOnly, gvbe);
}
protected void OnGetTypeConverterAndTypeEditor(GetTypeConverterAndTypeEditorEvent e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((GetTypeConverterAndTypeEditorEventHandler)Events[EventGetTypeConverterAndTypeEditor])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnResetValue(EventArgs e)
{
RaiseCom2Event(EventResetValue, e);
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnShouldSerializeValue(GetBoolValueEvent gvbe)
{
RaiseGetBoolValueEvent(EventShouldSerializeValue, gvbe);
}
/// <summary>
/// Raises the appropriate event
/// </summary>
protected void OnShouldRefresh(GetRefreshStateEvent gvbe)
{
RaiseGetBoolValueEvent(EventShouldRefresh, gvbe);
}
/// <summary>
/// Raises the appropriate event
/// </summary>
private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((GetBoolValueEventHandler)Events[key])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Raises the appropriate event
/// </summary>
private void RaiseCom2Event(object key, EventArgs e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((Com2EventHandler)Events[key])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Raises the appropriate event
/// </summary>
private void RaiseGetNameItemEvent(object key, GetNameItemEvent e)
{
try
{
com2props.AlwaysValid = com2props.CheckValid();
((GetNameItemEventHandler)Events[key])?.Invoke(this, e);
}
finally
{
com2props.AlwaysValid = false;
}
}
/// <summary>
/// Will reset the default value for this property on the component. If
/// there was a default value passed in as a DefaultValueAttribute, that
/// value will be set as the value of the property on the component. If
/// there was no default value passed in, a ResetXXX method will be looked
/// for. If one is found, it will be invoked. If one is not found, this
/// is a nop.
/// </summary>
public override void ResetValue(object component)
{
if (component is ICustomTypeDescriptor)
{
component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this);
}
if (component == TargetObject)
{
OnResetValue(EventArgs.Empty);
}
}
/// <summary>
/// Sets whether the particular item(s) need refreshing.
/// </summary>
internal void SetNeedsRefresh(int mask, bool value)
{
if (value)
{
refreshState |= mask;
}
else
{
refreshState &= ~mask;
}
}
/// <summary>
/// This will set value to be the new value of this property on the
/// component by invoking the setXXX method on the component. If the
/// value specified is invalid, the component should throw an exception
/// which will be passed up. The component designer should design the
/// property so that getXXX following a setXXX should return the value
/// passed in if no exception was thrown in the setXXX call.
/// </summary>
public unsafe override void SetValue(object component, object value)
{
if (readOnly)
{
throw new NotSupportedException(string.Format(SR.COM2ReadonlyProperty, Name));
}
object owner = component;
if (owner is ICustomTypeDescriptor)
{
owner = ((ICustomTypeDescriptor)owner).GetPropertyOwner(this);
}
if (owner is null || !Marshal.IsComObject(owner) || !(owner is Oleaut32.IDispatch))
{
return;
}
// do we need to convert the type?
if (valueConverter is not null)
{
bool cancel = false;
value = valueConverter.ConvertManagedToNative(value, this, ref cancel);
if (cancel)
{
return;
}
}
Oleaut32.IDispatch pDisp = (Oleaut32.IDispatch)owner;
var excepInfo = new Oleaut32.EXCEPINFO();
Ole32.DispatchID namedArg = Ole32.DispatchID.PROPERTYPUT;
var dispParams = new Oleaut32.DISPPARAMS
{
cArgs = 1,
cNamedArgs = 1,
rgdispidNamedArgs = &namedArg
};
using var variant = new Oleaut32.VARIANT();
Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant));
dispParams.rgvarg = &variant;
Guid g = Guid.Empty;
HRESULT hr = pDisp.Invoke(
dispid,
&g,
Kernel32.GetThreadLocale(),
Oleaut32.DISPATCH.PROPERTYPUT,
&dispParams,
null,
&excepInfo,
null);
string errorInfo = null;
if (hr == HRESULT.DISP_E_EXCEPTION && excepInfo.scode != 0)
{
hr = excepInfo.scode;
if (excepInfo.bstrDescription != IntPtr.Zero)
{
errorInfo = Marshal.PtrToStringBSTR(excepInfo.bstrDescription);
}
}
switch (hr)
{
case HRESULT.E_ABORT:
case HRESULT.OLE_E_PROMPTSAVECANCELLED:
// cancelled checkout, etc.
return;
case HRESULT.S_OK:
case HRESULT.S_FALSE:
OnValueChanged(component, EventArgs.Empty);
lastValue = value;
return;
default:
if (pDisp is Oleaut32.ISupportErrorInfo iSupportErrorInfo)
{
g = typeof(Oleaut32.IDispatch).GUID;
if (iSupportErrorInfo.InterfaceSupportsErrorInfo(&g) == HRESULT.S_OK)
{
Oleaut32.IErrorInfo pErrorInfo;
Oleaut32.GetErrorInfo(0, out pErrorInfo);
string info;
if (pErrorInfo is not null && pErrorInfo.GetDescription(out info).Succeeded())
{
errorInfo = info;
}
}
}
else if (errorInfo is null)
{
StringBuilder strMessage = new StringBuilder(256);
uint result = Kernel32.FormatMessageW(
Kernel32.FormatMessageOptions.FROM_SYSTEM | Kernel32.FormatMessageOptions.IGNORE_INSERTS,
IntPtr.Zero,
(uint)hr,
Kernel32.GetThreadLocale().RawValue,
strMessage,
255,
IntPtr.Zero);
if (result == 0)
{
errorInfo = string.Format(CultureInfo.CurrentCulture, string.Format(SR.DispInvokeFailed, "SetValue", hr));
}
else
{
errorInfo = TrimNewline(strMessage);
}
}
throw new ExternalException(errorInfo, (int)hr);
}
}
private static string TrimNewline(StringBuilder errorInfo)
{
int index = errorInfo.Length - 1;
while (index >= 0 && (errorInfo[index] == '\n' || errorInfo[index] == '\r'))
{
index--;
}
return errorInfo.ToString(0, index + 1);
}
/// <summary>
/// Indicates whether the value of this property needs to be persisted. In
/// other words, it indicates whether the state of the property is distinct
/// from when the component is first instantiated. If there is a default
/// value specified in this PropertyDescriptor, it will be compared against the
/// property's current value to determine this. If there isn't, the
/// shouldPersistXXX method is looked for and invoked if found. If both
/// these routes fail, true will be returned.
///
/// If this returns false, a tool should not persist this property's value.
/// </summary>
public override bool ShouldSerializeValue(object component)
{
GetBoolValueEvent gbv = new GetBoolValueEvent(false);
OnShouldSerializeValue(gbv);
return gbv.Value;
}
/// <summary>
/// we wrap all value editors in this one so we can intercept
/// the GetTextFromValue calls for objects that would like
/// to modify the display name
/// </summary>
private class Com2PropDescMainConverter : Com2ExtendedTypeConverter
{
readonly Com2PropertyDescriptor pd;
private const int CheckSubprops = 0;
private const int AllowSubprops = 1;
private const int SuppressSubprops = 2;
private int subprops = CheckSubprops;
public Com2PropDescMainConverter(Com2PropertyDescriptor pd, TypeConverter baseConverter) : base(baseConverter)
{
this.pd = pd;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
object baseConversion = base.ConvertTo(context, culture, value, destinationType);
if (destinationType == typeof(string))
{
// if this is our current value, ask if it should be changed for display,
// otherwise we'll ask for our enum drop downs, which we don't wanna do!
//
if (pd.IsCurrentValue(value))
{
// don't ever do this for enum types
if (!pd.PropertyType.IsEnum)
{
Com2EnumConverter baseConverter = (Com2EnumConverter)GetWrappedConverter(typeof(Com2EnumConverter));
if (baseConverter is null)
{
return pd.GetDisplayValue((string)baseConversion);
}
else
{
return baseConverter.ConvertTo(value, destinationType);
}
}
}
}
return baseConversion;
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value, attributes);
if (props is not null && props.Count > 0)
{
// Return sorted read-only collection (can't sort original because its read-only)
props = props.Sort();
PropertyDescriptor[] descs = new PropertyDescriptor[props.Count];
props.CopyTo(descs, 0);
props = new PropertyDescriptorCollection(descs, true);
}
return props;
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
if (subprops == CheckSubprops)
{
if (!base.GetPropertiesSupported(context))
{
subprops = SuppressSubprops;
}
else
{
// special case the font converter here.
//
if ((pd.valueConverter is not null && pd.valueConverter.AllowExpand) || Com2IVsPerPropertyBrowsingHandler.AllowChildProperties(pd))
{
subprops = AllowSubprops;
}
}
}
return (subprops == AllowSubprops);
}
}
}
internal class GetAttributesEvent : EventArgs
{
private readonly ArrayList attrList;
public GetAttributesEvent(ArrayList attrList)
{
this.attrList = attrList;
}
public void Add(Attribute attribute)
{
attrList.Add(attribute);
}
}
internal delegate void Com2EventHandler(Com2PropertyDescriptor sender, EventArgs e);
internal delegate void GetAttributesEventHandler(Com2PropertyDescriptor sender, GetAttributesEvent gaevent);
internal class GetNameItemEvent : EventArgs
{
private object nameItem;
public GetNameItemEvent(object defName)
{
nameItem = defName;
}
public object Name
{
get
{
return nameItem;
}
set
{
nameItem = value;
}
}
public string NameString
{
get
{
if (nameItem is not null)
{
return nameItem.ToString();
}
return "";
}
}
}
internal delegate void GetNameItemEventHandler(Com2PropertyDescriptor sender, GetNameItemEvent gnievent);
internal class GetBoolValueEvent : EventArgs
{
private bool value;
public GetBoolValueEvent(bool defValue)
{
value = defValue;
}
public bool Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
}
internal delegate void GetBoolValueEventHandler(Com2PropertyDescriptor sender, GetBoolValueEvent gbeevent);
internal class GetRefreshStateEvent : GetBoolValueEvent
{
readonly Com2ShouldRefreshTypes item;
public GetRefreshStateEvent(Com2ShouldRefreshTypes item, bool defValue) : base(defValue)
{
this.item = item;
}
}
internal delegate void GetTypeConverterAndTypeEditorEventHandler(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent e);
internal class GetTypeConverterAndTypeEditorEvent : EventArgs
{
private TypeConverter typeConverter;
private object typeEditor;
public GetTypeConverterAndTypeEditorEvent(TypeConverter typeConverter, object typeEditor)
{
this.typeEditor = typeEditor;
this.typeConverter = typeConverter;
}
public TypeConverter TypeConverter
{
get
{
return typeConverter;
}
set
{
typeConverter = value;
}
}
public object TypeEditor
{
get
{
return typeEditor;
}
set
{
typeEditor = value;
}
}
}
}
| 33.396357 | 155 | 0.509376 | [
"MIT"
] | AndreRRR/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs | 53,169 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossPhaseBigFireballs : BossPhase
{
public GameObject BigFireBallPrefab;
[SerializeField] float TimeBetweenFireballs = 1f;
[SerializeField] Transform shootingPivot;
bool canShoot = false;
public override void ActivatePhase()
{
Debug.Log("Big Fireball Phase Started");
base.ActivatePhase();
head.tag = "Enemy";
torso.tag = "Enemy";
restbody.tag = "Enemy";
canShoot = true;
StartCoroutine(HandleShooting());
//animator.Play("InitPhase");
}
private void OnEnable()
{
ActivatePhase();
}
public override void DeactivatePhase()
{
base.DeactivatePhase();
canShoot = false;
}
void OnDisable()
{
DeactivatePhase();
canShoot = false;
}
public override void Update()
{
base.Update();
}
IEnumerator HandleShooting()
{
while (canShoot)
{
yield return new WaitForSeconds(TimeBetweenFireballs);
Shoot();
}
}
void Shoot()
{
Vector2 direction = (playerObject.transform.position - shootingPivot.position).normalized;
GameObject fireball = (GameObject)Instantiate(BigFireBallPrefab, shootingPivot.position, Quaternion.identity);
fireball.GetComponent<BigFireball>().Initialize(5f, direction);
}
}
| 22.227273 | 118 | 0.620995 | [
"MIT"
] | ProjectMansionManiac/MansionMadness | Assets/Scripts/BossPhaseBigFireballs.cs | 1,469 | C# |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JamLib.Algorithms.Sorting.ExchangeSorts.Tests
{
[TestClass()]
public class StoogeSortTests
{
[TestMethod()]
public void StoogeSortTest()
{
int[] actual = new int[] { 12, 10, 4, 5, 0, 6, 2, 1, -4, -24, 7, 5 };
int[] expected = new int[] { -24, -4, 0, 1, 2, 4, 5, 5, 6, 7, 10, 12 };
StoogeSort.Sort(actual);
CollectionAssert.AreEqual(expected, actual, "StoogeSort did not sort correctly");
}
[TestMethod()]
public void StoogeSort_Generic_Test()
{
float[] actual = new float[] { 12, 10, 4, 5, 0, 6, 2, 1, -4, -24, 7, 5 };
float[] expected = new float[] { -24, -4, 0, 1, 2, 4, 5, 5, 6, 7, 10, 12 };
StoogeSort.Sort(actual);
CollectionAssert.AreEqual(expected, actual, "StoogeSort<T> did not sort correctly");
}
[TestMethod()]
public void StoogeSort_List_Test()
{
var actual = new List<double> { 12, 10, 4, 5, 0, 6, 2, 1, -4, -24, 7, 5 };
var expected = new List<double> { -24, -4, 0, 1, 2, 4, 5, 5, 6, 7, 10, 12 };
StoogeSort.Sort(actual);
CollectionAssert.AreEqual(expected, actual, "StoogeSort<T> did not sort correctly");
}
[TestMethod()]
public void StoogeSort_CustomComparer_Test()
{
int[] actual = new int[] { 12, 10, 4, 5, 0, 6, 2, 1, -4, -24, 7, 5 };
int[] expected = new int[] { 12, 10, 7, 6, 5, 5, 4, 2, 1, 0, -4, -24 };
Comparison<int> descending = ((x, y) => y > x ? 1 : y < x ? -1 : 0);
StoogeSort.Sort(actual, Comparer<int>.Create(descending));
CollectionAssert.AreEqual(expected, actual, "StoogeSort<T> did not sort descending");
}
}
}
| 36.807692 | 97 | 0.532393 | [
"MIT"
] | joshimoo/JamLib | JamLibTests/Algorithms/Sorting/ExchangeSorts/StoogeSortTests.cs | 1,916 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.AppPlatform.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Custom domain resource payload.
/// </summary>
public partial class CustomDomainResource : ProxyResource
{
/// <summary>
/// Initializes a new instance of the CustomDomainResource class.
/// </summary>
public CustomDomainResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the CustomDomainResource class.
/// </summary>
/// <param name="id">Fully qualified resource Id for the
/// resource.</param>
/// <param name="name">The name of the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="properties">Properties of the custom domain
/// resource.</param>
public CustomDomainResource(string id = default(string), string name = default(string), string type = default(string), CustomDomainProperties properties = default(CustomDomainProperties))
: base(id, name, type)
{
Properties = properties;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets properties of the custom domain resource.
/// </summary>
[JsonProperty(PropertyName = "properties")]
public CustomDomainProperties Properties { get; set; }
}
}
| 34.086207 | 195 | 0.62519 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/appplatform/Microsoft.Azure.Management.AppPlatform/src/Generated/Models/CustomDomainResource.cs | 1,977 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Oranikle.Studio.Controls
{
public interface IDropdownDisplayer
{
object GetDisplay(object value);
object GetDisplayOrNull(object value);
}
}
| 15.882353 | 46 | 0.718519 | [
"Apache-2.0"
] | parvbhullar/Windows-UI-Component-Framework | Oranikle.DesignBase/Interface/IDropdownDisplayer.cs | 272 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebClient
{
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 17.411765 | 60 | 0.679054 | [
"MIT"
] | ayanshaikh18/Smart-Contact-Manager-WebAPI | SmartContactManager/WebClient/About.aspx.cs | 298 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Demo.Site
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 26.555556 | 71 | 0.619247 | [
"MIT"
] | cwiederspan/appsvc-github-actions | src/Demo.Site/Program.cs | 717 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class UiaCore
{
[ComImport]
[Guid("9c860395-97b3-490a-b52a-858cc22af166")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ITableProvider
{
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
object[]? /*IRawElementProviderSimple[]*/ GetRowHeaders();
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
object[]? /*IRawElementProviderSimple[]*/ GetColumnHeaders();
RowOrColumnMajor RowOrColumnMajor { get; }
}
}
}
| 35 | 95 | 0.692063 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms.Primitives/src/Interop/UiaCore/Interop.ITableProvider.cs | 947 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace AvePoint.Migration.Api.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class GoogleDrivePlanSettingsModel
{
/// <summary>
/// Initializes a new instance of the GoogleDrivePlanSettingsModel
/// class.
/// </summary>
public GoogleDrivePlanSettingsModel()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the GoogleDrivePlanSettingsModel
/// class.
/// </summary>
/// <param name="nameLabel">Large migration projects are often phased
/// over several waves, each containing multiple plans.
/// To easily generate migration reports for each project or wave, we
/// recommend the Example name format Business Unit_Wave_Plan</param>
/// <param name="migrateVersions">whether to migrate versions of source
/// files in Google Drive</param>
/// <param name="policyId">the id of migration policy</param>
/// <param name="databaseId">the id of migration database</param>
/// <param name="schedule">the schedule for the migration</param>
public GoogleDrivePlanSettingsModel(PlanNameLabel nameLabel, bool? migrateVersions = default(bool?), string policyId = default(string), string databaseId = default(string), SimpleSchedule schedule = default(SimpleSchedule), IList<string> planGroups = default(IList<string>))
{
MigrateVersions = migrateVersions;
NameLabel = nameLabel;
PolicyId = policyId;
DatabaseId = databaseId;
Schedule = schedule;
PlanGroups = planGroups;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets whether to migrate versions of source files in Google
/// Drive
/// </summary>
[JsonProperty(PropertyName = "migrateVersions")]
public bool? MigrateVersions { get; set; }
/// <summary>
/// Gets or sets large migration projects are often phased over several
/// waves, each containing multiple plans.
/// To easily generate migration reports for each project or wave, we
/// recommend the Example name format Business Unit_Wave_Plan
/// </summary>
[JsonProperty(PropertyName = "nameLabel")]
public PlanNameLabel NameLabel { get; set; }
/// <summary>
/// Gets or sets the id of migration policy
/// </summary>
[JsonProperty(PropertyName = "policyId")]
public string PolicyId { get; set; }
/// <summary>
/// Gets or sets the id of migration database
/// </summary>
[JsonProperty(PropertyName = "databaseId")]
public string DatabaseId { get; set; }
/// <summary>
/// Gets or sets the schedule for the migration
/// </summary>
[JsonProperty(PropertyName = "schedule")]
public SimpleSchedule Schedule { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "planGroups")]
public IList<string> PlanGroups { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (NameLabel == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "NameLabel");
}
if (NameLabel != null)
{
NameLabel.Validate();
}
if (Schedule != null)
{
Schedule.Validate();
}
}
}
}
| 36 | 282 | 0.591406 | [
"MIT"
] | AvePoint/FLY-Migration | WebAPI/CSharp/FLY 4.5/FLY/Models/GoogleDrivePlanSettingsModel.cs | 4,212 | C# |
// ***********************************************************************
// Copyright (c) Charlie Poole and TestCentric GUI contributors.
// Licensed under the MIT License. See LICENSE.txt in root directory.
// ***********************************************************************
using System;
using System.Collections.Generic;
using TestCentric.Engine;
using TestCentric.Engine.Extensibility;
namespace TestCentric.TestUtilities.Fakes
{
public class ExtensionService : IExtensionService
{
private List<IExtensionPoint> _extensionPoints;
private List<IExtensionNode> _extensions;
public ExtensionService()
{
_extensionPoints = new List<IExtensionPoint>();
_extensions = new List<IExtensionNode>();
// ExtensionPoints are all known, so we add in constructor. Extensions
// may vary, so we use a method to add them.
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/NUnitV2Driver", "TestCentric.Engine.Extensibility.IDriverFactory", "Driver for NUnit tests using the V2 framework."));
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/TypeExtensions/IService", "TestCentric.Engine.Extensibility.IService", "Provides a service within the engine and possibly externally as well."));
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/TypeExtensions/ITestEventListener", "TestCentric.Engine.Extensibility.ITestEventListener", "Allows an extension to process progress reports and other events from the test."));
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/TypeExtensions/IDriverFactory", "TestCentric.Engine.Extensibility.IDriverFactory", "Supplies a driver to run tests that use a specific test framework."));
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/TypeExtensions/IProjectLoader", "TestCentric.Engine.Extensibility.IProjectLoader", "Recognizes and loads assemblies from various types of project formats."));
_extensionPoints.Add(new ExtensionPoint(
"/NUnit/Engine/TypeExtensions/IResultWriter", "TestCentric.Engine.Extensibility.IResultWriter", "Supplies a writer to write the result of a test to a file using a specific format."));
}
public void AddExtensions(params IExtensionNode[] extensions)
{
_extensions.AddRange(extensions);
}
public IEnumerable<IExtensionPoint> ExtensionPoints { get { return _extensionPoints; } }
public IEnumerable<IExtensionNode> Extensions { get; } = new List<IExtensionNode>();
public void EnableExtension(string typeName, bool enabled)
{
}
public IEnumerable<IExtensionNode> GetExtensionNodes(string path)
{
return new IExtensionNode[0];
}
public IExtensionPoint GetExtensionPoint(string path)
{
return null;
}
// ExtensionPoint class is nested since the list of extension points is fixed
public class ExtensionPoint : IExtensionPoint
{
public ExtensionPoint(string path, string typeName, string description)
{
Path = path;
TypeName = typeName;
Description = description;
}
public string Description { get; }
public IEnumerable<IExtensionNode> Extensions { get; } = new List<IExtensionNode>();
public string Path { get; }
public string TypeName { get; }
}
}
public class ExtensionNode : IExtensionNode
{
public ExtensionNode(string path, string typeName, string description)
{
Path = path;
TypeName = typeName;
Description = description;
}
public string Description { get; }
public bool Enabled { get; }
public string Path { get; }
public IEnumerable<string> PropertyNames { get; }
public string TypeName { get; }
public IRuntimeFramework TargetFramework { get; }
public IEnumerable<string> GetValues(string name)
{
return new string[0];
}
public string AssemblyPath { get; }
public Version AssemblyVersion { get; }
}
}
| 38.716814 | 206 | 0.629486 | [
"MIT"
] | jurczakk/testcentric-gui | src/tests/test-utilities/Fakes/ExtensionService.cs | 4,375 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "GBL_008e",
"name": [
"法力值消耗-4",
"Cost - 4"
],
"text": [
"法力值消耗减少(4)点。",
"Costs (4) less."
],
"CardClass": "NEUTRAL",
"type": "ENCHANTMENT",
"cost": null,
"rarity": null,
"set": "CORE",
"collectible": null,
"dbfId": 53197
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_GBL_008e : SimTemplate
{
}
} | 13.857143 | 36 | 0.536082 | [
"MIT"
] | chi-rei-den/Silverfish | cards/CORE/GBL/Sim_GBL_008e.cs | 420 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
internal static partial class Interop
{
internal static partial class Ole32
{
[DllImport(Libraries.Ole32, ExactSpelling = true)]
public static extern HRESULT OleSetClipboard(IDataObject pDataObj);
}
}
| 32.5 | 75 | 0.755769 | [
"MIT"
] | ArtemTatarinov/winforms | src/System.Windows.Forms.Primitives/src/Interop/Ole32/Interop.OleSetClipboard.cs | 522 | C# |
using System.Collections.Generic;
using Toe.SPIRV.Spv;
namespace Toe.SPIRV.Instructions
{
public partial class OpReadClockKHR: InstructionWithId
{
public OpReadClockKHR()
{
}
public override Op OpCode { get { return Op.OpReadClockKHR; } }
/// <summary>
/// Returns true if instruction has IdResult field.
/// </summary>
public override bool HasResultId => true;
/// <summary>
/// Returns true if instruction has IdResultType field.
/// </summary>
public override bool HasResultType => true;
public Spv.IdRef IdResultType { get; set; }
public uint Execution { get; set; }
/// <summary>
/// Read complete instruction from the bytecode source.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
public override void Parse(WordReader reader, uint end)
{
IdResultType = Spv.IdResultType.Parse(reader, end-reader.Position);
IdResult = Spv.IdResult.Parse(reader, end-reader.Position);
reader.Instructions.Add(this);
ParseOperands(reader, end);
PostParse(reader, end);
}
/// <summary>
/// Read instruction operands from the bytecode source.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
public override void ParseOperands(WordReader reader, uint end)
{
Execution = Spv.IdScope.Parse(reader, end-reader.Position);
}
/// <summary>
/// Process parsed instruction if required.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
partial void PostParse(WordReader reader, uint end);
/// <summary>
/// Calculate number of words to fit complete instruction bytecode.
/// </summary>
/// <returns>Number of words in instruction bytecode.</returns>
public override uint GetWordCount()
{
uint wordCount = 0;
wordCount += IdResultType.GetWordCount();
wordCount += IdResult.GetWordCount();
wordCount += Execution.GetWordCount();
return wordCount;
}
/// <summary>
/// Write instruction into bytecode stream.
/// </summary>
/// <param name="writer">Bytecode writer.</param>
public override void Write(WordWriter writer)
{
IdResultType.Write(writer);
IdResult.Write(writer);
WriteOperands(writer);
WriteExtras(writer);
}
/// <summary>
/// Write instruction operands into bytecode stream.
/// </summary>
/// <param name="writer">Bytecode writer.</param>
public override void WriteOperands(WordWriter writer)
{
Execution.Write(writer);
}
partial void WriteExtras(WordWriter writer);
public override string ToString()
{
return $"{IdResultType} {IdResult} = {OpCode} {Execution}";
}
}
}
| 33.088235 | 88 | 0.578963 | [
"MIT"
] | gleblebedev/Toe.SPIRV | src/Toe.SPIRV/Instructions/OpReadClockKHR.cs | 3,375 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.480)
// Version 5.480.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Layout area containing a quick access toolbar border and extra button.
/// </summary>
internal class ViewLayoutRibbonQATMini : ViewLayoutDocker
{
#region Static Fields
private const int SEP_GAP = 2;
#endregion
#region Instance Fields
private readonly KryptonRibbon _ribbon;
private readonly ViewDrawRibbonQATBorder _border;
private readonly ViewLayoutRibbonQATFromRibbon _borderContents;
private readonly ViewDrawRibbonQATExtraButtonMini _extraButton;
private readonly ViewLayoutSeparator _extraSeparator;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewLayoutRibbonQATMini class.
/// </summary>
/// <param name="ribbon">Owning control instance.</param>
/// <param name="needPaintDelegate">Delegate for notifying paint/layout changes.</param>
public ViewLayoutRibbonQATMini(KryptonRibbon ribbon,
NeedPaintHandler needPaintDelegate)
{
Debug.Assert(ribbon != null);
_ribbon = ribbon;
// Create the minibar border suitable for a caption area
_border = new ViewDrawRibbonQATBorder(ribbon, needPaintDelegate, true);
// Create minibar content that synchs with ribbon collection
_borderContents = new ViewLayoutRibbonQATFromRibbon(ribbon, needPaintDelegate, false);
_border.Add(_borderContents);
// Separator gap before the extra button
_extraSeparator = new ViewLayoutSeparator(SEP_GAP);
// Need the extra button to show after the border area
_extraButton = new ViewDrawRibbonQATExtraButtonMini(ribbon, needPaintDelegate);
_extraButton.ClickAndFinish += OnExtraButtonClick;
// Add layout contents
Add(_border, ViewDockStyle.Fill);
Add(_extraSeparator, ViewDockStyle.Right);
Add(_extraButton, ViewDockStyle.Right);
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewLayoutRibbonQATMini:" + Id;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_extraButton.ClickAndFinish -= OnExtraButtonClick;
}
base.Dispose(disposing);
}
#endregion
#region OwnerForm
/// <summary>
/// Gets and sets the associated form instance.
/// </summary>
public KryptonForm OwnerForm
{
get => _border.OwnerForm;
set => _border.OwnerForm = value;
}
#endregion
#region Visible
/// <summary>
/// Gets and sets the visible state of the element.
/// </summary>
public override bool Visible
{
get => (_ribbon.Visible && base.Visible);
set => base.Visible = value;
}
#endregion
#region OverlapAppButton
/// <summary>
/// Should the element overlap the app button to the left.
/// </summary>
public bool OverlapAppButton
{
get => _border.OverlapAppButton;
set => _border.OverlapAppButton = value;
}
#endregion
#region GetTabKeyTips
/// <summary>
/// Generate a key tip info for each visible tab.
/// </summary>
/// <returns>Array of KeyTipInfo instances.</returns>
public KeyTipInfo[] GetQATKeyTips()
{
KeyTipInfoList keyTipList = new KeyTipInfoList();
// Add all the entries for the contents
keyTipList.AddRange(_borderContents.GetQATKeyTips(OwnerForm));
// If we have the extra button and it is in overflow appearance
if (_extraButton.Overflow)
{
// If integrated into the caption area then get the caption area height
Padding borders = Padding.Empty;
if ((OwnerForm != null) && !OwnerForm.ApplyComposition)
{
borders = OwnerForm.RealWindowBorders;
}
// Get the screen location of the extra button
Rectangle viewRect = _borderContents.ParentControl.RectangleToScreen(_extraButton.ClientRectangle);
// The keytip should be centered on the bottom center of the view
Point screenPt = new Point((viewRect.Left + (viewRect.Width / 2)) - borders.Left,
viewRect.Bottom - 2 - borders.Top);
// Create fixed key tip of '00' that invokes the extra button contoller
keyTipList.Add(new KeyTipInfo(true, "00", screenPt,
_extraButton.ClientRectangle,
_extraButton.KeyTipTarget));
}
return keyTipList.ToArray();
}
#endregion
#region GetFirstQATView
/// <summary>
/// Gets the view element for the first visible and enabled quick access toolbar button.
/// </summary>
/// <returns></returns>
public ViewBase GetFirstQATView()
{
// Find the first qat button
ViewBase view = _borderContents.GetFirstQATView() ?? _extraButton;
// If defined then use the extra button
return view;
}
#endregion
#region GetLastQATView
/// <summary>
/// Gets the view element for the first visible and enabled quick access toolbar button.
/// </summary>
/// <returns></returns>
public ViewBase GetLastQATView()
{
// Last view is the extra button if defined
return _extraButton ?? _borderContents.GetLastQATView();
// Find the last qat button
}
#endregion
#region GetNextQATView
/// <summary>
/// Gets the view element the button after the one provided.
/// </summary>
/// <param name="qatButton">Search for entry after this view.</param>
/// <returns>ViewBase if found; otherwise false.</returns>
public ViewBase GetNextQATView(ViewBase qatButton)
{
ViewBase view = _borderContents.GetNextQATView(qatButton);
// If no qat button is found and not already at the extra button
if ((view == null) && (_extraButton != qatButton))
{
view = _extraButton;
}
return view;
}
#endregion
#region GetPreviousQATView
/// <summary>
/// Gets the view element for the button before the one provided.
/// </summary>
/// <param name="qatButton">Search for entry after this view.</param>
/// <returns>ViewBase if found; otherwise false.</returns>
public ViewBase GetPreviousQATView(ViewBase qatButton)
{
// If on the extra button then find the right most qat button instead
return qatButton == _extraButton ? _borderContents.GetLastQATView() : _borderContents.GetPreviousQATView(qatButton);
}
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
Debug.Assert(context != null);
bool visibleQATButtons = false;
// Scan to see if there are any visible quick access toolbar buttons
foreach(IQuickAccessToolbarButton qatButton in _ribbon.QATButtons)
{
if (qatButton.GetVisible())
{
visibleQATButtons = true;
break;
}
}
// Only show the border if there are some visible contents
_border.Visible = visibleQATButtons;
// If there are no visible buttons, then extra button must be for customization
if (!visibleQATButtons)
{
_extraButton.Overflow = false;
}
return base.GetPreferredSize(context);
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
// Cache the provided size of our area
Rectangle clientRect = context.DisplayRectangle;
// If we are in the ribbon caption area line
if (OwnerForm == null)
{
// Limit the width, so we do not flow over right edge of caption area
int maxWidth = _ribbon.Width - clientRect.X;
clientRect.Width = Math.Min(clientRect.Width, maxWidth);
}
// Update with modified value
context.DisplayRectangle = clientRect;
// Let base class layout all contents
base.Layout(context);
// Only if border is visible do we need to find the latest overflow value
// otherwise it must be a customization image because there are no buttons
_extraButton.Overflow = _border.Visible && _borderContents.Overflow;
}
private void OnExtraButtonClick(object sender, EventHandler finishDelegate)
{
ViewDrawRibbonQATExtraButton button = (ViewDrawRibbonQATExtraButton)sender;
// Convert the button rectangle to screen coordinates
Rectangle screenRect = _ribbon.RectangleToScreen(button.ClientRectangle);
// If integrated into the caption area
if ((OwnerForm != null) && !OwnerForm.ApplyComposition)
{
// Adjust for the height/width of borders
Padding borders = OwnerForm.RealWindowBorders;
screenRect.X -= borders.Left;
screenRect.Y -= borders.Top;
}
if (_extraButton.Overflow)
{
_ribbon.DisplayQATOverflowMenu(screenRect, _borderContents, finishDelegate);
}
else
{
_ribbon.DisplayQATCustomizeMenu(screenRect, _borderContents, finishDelegate);
}
}
#endregion
}
}
| 36.953125 | 157 | 0.585116 | [
"BSD-3-Clause"
] | MarketingInternetOnlines/Krypton-NET-5.480 | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Layout/ViewLayoutRibbonQATMini.cs | 11,828 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Compute
{
internal partial class RestorePointCollectionsRestOperations
{
private readonly string _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> Initializes a new instance of RestorePointCollectionsRestOperations. </summary>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
public RestorePointCollectionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2021-07-01";
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointGroupData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections/", false);
uri.AppendPath(restorePointCollectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> The operation to create or update the restore point collection. Please refer to https://aka.ms/RestorePoints for more details. When updating a restore point collection, only tags may be modified. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="parameters"> Parameters supplied to the Create or Update restore point collection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="restorePointCollectionName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointGroupData>> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointGroupData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, restorePointCollectionName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
{
RestorePointGroupData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> The operation to create or update the restore point collection. Please refer to https://aka.ms/RestorePoints for more details. When updating a restore point collection, only tags may be modified. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="parameters"> Parameters supplied to the Create or Update restore point collection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="restorePointCollectionName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointGroupData> CreateOrUpdate(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointGroupData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, restorePointCollectionName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
{
RestorePointGroupData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string restorePointCollectionName, PatchableRestorePointGroupData data)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections/", false);
uri.AppendPath(restorePointCollectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(data);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> The operation to update the restore point collection. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="data"> Parameters supplied to the Update restore point collection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="restorePointCollectionName"/> or <paramref name="data"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointGroupData>> UpdateAsync(string subscriptionId, string resourceGroupName, string restorePointCollectionName, PatchableRestorePointGroupData data, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
Argument.AssertNotNull(data, nameof(data));
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, restorePointCollectionName, data);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointGroupData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> The operation to update the restore point collection. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="data"> Parameters supplied to the Update restore point collection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="restorePointCollectionName"/> or <paramref name="data"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointGroupData> Update(string subscriptionId, string resourceGroupName, string restorePointCollectionName, PatchableRestorePointGroupData data, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
Argument.AssertNotNull(data, nameof(data));
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, restorePointCollectionName, data);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointGroupData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string restorePointCollectionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections/", false);
uri.AppendPath(restorePointCollectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> The operation to delete the restore point collection. This operation will also delete all the contained restore points. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the Restore Point Collection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string restorePointCollectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, restorePointCollectionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> The operation to delete the restore point collection. This operation will also delete all the contained restore points. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the Restore Point Collection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public Response Delete(string subscriptionId, string resourceGroupName, string restorePointCollectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, restorePointCollectionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointCollectionExpandOptions? expand)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections/", false);
uri.AppendPath(restorePointCollectionName, true);
if (expand != null)
{
uri.AppendQuery("$expand", expand.Value.ToString(), true);
}
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> The operation to get the restore point collection. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="expand"> The expand expression to apply on the operation. If expand=restorePoints, server will return all contained restore points in the restorePointCollection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointGroupData>> GetAsync(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointCollectionExpandOptions? expand = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, restorePointCollectionName, expand);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointGroupData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((RestorePointGroupData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> The operation to get the restore point collection. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="restorePointCollectionName"> The name of the restore point collection. </param>
/// <param name="expand"> The expand expression to apply on the operation. If expand=restorePoints, server will return all contained restore points in the restorePointCollection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="restorePointCollectionName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointGroupData> Get(string subscriptionId, string resourceGroupName, string restorePointCollectionName, RestorePointCollectionExpandOptions? expand = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(restorePointCollectionName, nameof(restorePointCollectionName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, restorePointCollectionName, expand);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointGroupData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointGroupData.DeserializeRestorePointGroupData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((RestorePointGroupData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the list of restore point collections in a resource group. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointCollectionListResult>> ListAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListRequest(subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets the list of restore point collections in a resource group. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointCollectionListResult> List(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListRequest(subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAllRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Compute/restorePointCollections", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the list of restore point collections in the subscription. Use nextLink property in the response to get the next page of restore point collections. Do this till nextLink is not null to fetch all the restore point collections. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointCollectionListResult>> ListAllAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListAllRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets the list of restore point collections in the subscription. Use nextLink property in the response to get the next page of restore point collections. Do this till nextLink is not null to fetch all the restore point collections. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointCollectionListResult> ListAll(string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListAllRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the list of restore point collections in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointCollectionListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets the list of restore point collections in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointCollectionListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAllNextPageRequest(string nextLink, string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the list of restore point collections in the subscription. Use nextLink property in the response to get the next page of restore point collections. Do this till nextLink is not null to fetch all the restore point collections. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<RestorePointCollectionListResult>> ListAllNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListAllNextPageRequest(nextLink, subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets the list of restore point collections in the subscription. Use nextLink property in the response to get the next page of restore point collections. Do this till nextLink is not null to fetch all the restore point collections. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<RestorePointCollectionListResult> ListAllNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
using var message = CreateListAllNextPageRequest(nextLink, subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
RestorePointCollectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = RestorePointCollectionListResult.DeserializeRestorePointCollectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
}
}
| 69.015244 | 263 | 0.671445 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/RestOperations/RestorePointCollectionsRestOperations.cs | 45,274 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.