content
stringlengths
23
1.05M
namespace Merchello.Bazaar.Models { using System.ComponentModel.DataAnnotations; /// <summary> /// The model for the RedeemCouponOffer partial view. /// </summary> public partial class RedeemCouponOfferForm { /// <summary> /// Gets or sets the Bazaar theme name. /// </summary> public string ThemeName { get; set; } /// <summary> /// Gets or sets the offer code. /// </summary> [Required(ErrorMessage = "Required")] public string OfferCode { get; set; } /// <summary> /// Gets or sets the currency symbol. /// </summary> public string CurrencySymbol { get; set; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Merchant.Todont.Domain.Habits { public interface IHabitsService { Task<Habit> GetHabitById(Guid id); Task<IReadOnlyList<Habit>> GetHabitsByUserId(Guid userId); Task<Habit> SaveHabit(Habit habit); Task<HabitEntry> SaveHabitEntry(HabitEntry entry); } }
using System; using System.Collections.Generic; namespace Checkout.Reconciliation { public class StatementData { public string Id { get; set; } public DateTime? Date { get; set; } public IList<PayoutStatement> Payouts { get; set; } public DateTime? PeriodEnd { get; set; } public DateTime? PeriodStart { get; set; } } }
using System.Collections.Generic; using Bitmex.Client.Websocket.Messages; namespace Bitmex.Client.Websocket.Responses { /// <summary> /// Base message for every response /// </summary> public class ResponseBase : MessageBase { /// <summary> /// The type of the message. Types: /// 'partial'; This is a table image, replace your data entirely. /// 'update': Update a single row. /// 'insert': Insert a new row. /// 'delete': Delete a row. /// </summary> public BitmexAction Action { get; set; } /// <summary> /// Table name / Subscription topic. /// Could be "trade", "order", "instrument", etc. /// </summary> public string Table { get; set; } /// <summary> /// Attribute names that are guaranteed to be unique per object. /// If more than one is provided, the key is composite. /// Use these key names to uniquely identify rows. Key columns are guaranteed /// to be present on all data received. /// </summary> public string[] Keys { get; set; } /// <summary> /// This lists the shape of the table. The possible types: /// "symbol" - In most languages this is equal to "string" /// "guid" /// "timestamp" /// "timespan" /// "float" /// "long" /// "integer" /// "boolean" /// </summary> public Dictionary<string, string> Types { get; set; } /// <summary> /// This lists key relationships with other tables. /// For example, `quote`'s foreign key is {"symbol": "instrument"} /// </summary> public Dictionary<string, string> ForeignKeys { get; set; } /// <summary> /// These are internal fields that indicate how responses are sorted and grouped. /// </summary> public Dictionary<string, string> Attributes { get; set; } /// <summary> /// When multiple subscriptions are active to the same table, use the `filter` to correlate which datagram /// belongs to which subscription, as the `table` property will not contain the subscription's symbol. /// </summary> public FilterInfo Filter { get; set; } } }
namespace WinterIsComing.Core.Commands { using Contracts; public class WinterCameCommand : AbstractCommand { public WinterCameCommand(IEngine engine) : base(engine) { } public override void Execute(string[] commandArgs) { this.Engine.Stop(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CollisionSound { public class SoundCollider : MonoBehaviour { [Header("General")] [Tooltip("Name of the material. There must be a folder with this exact name in the FMOD Studio project, " + "and it must contain a default sound with the same name ['wood/wood']")] [SerializeField] private string _soundMaterial = "wood"; private Collider _collider; private float _worldSize; [Tooltip("If set to true, sounds will only be played if the " + "other gameobject also has a SoundMaterial component.")] public bool requireAnotherSoundMaterial = false; [Tooltip("If set to true, this SoundCollider will always play its default event, " + "ignoring the events defined for specific material interactions.")] public bool alwaysPlayDefaultEvent = false; [Tooltip("When this GameObject collides with another SoundCollider, it will force it " + "NOT to play its default event. Specific interaction events will still be played.")] public bool muteOtherDefaultEvents = false; [Tooltip("ONLY FOR 2D COLLIDERS. If set to true, Y axis will " + "be treated as forward/backward when positioning the sounds in 3D" + ", instead of up/down.")] public bool yAxisIsForward2D = false; [Header("Sound parameters")] [Range(0, 1)] [Tooltip("Volume the events of this SoundCollider will be played this. When playing specific interaction" + "events, the volume will be the average of both volumes.")] public float volume = 1.0f; [Tooltip("Mute the SoundCollider.When two SoundColliders collide, if one of them is muted(or both)" + "the event will not be played.")] public bool mute = false; [Header("FMOD Studio parameters")] public bool sizeActive = true; public bool massActive = true; public bool velocityActive = true; private Dictionary<string, float> _customParams; private Rigidbody _rigidbody3D = null; private Rigidbody2D _rigidbody2D = null; private void Start() { _collider = GetComponent<Collider>(); if (_collider == null) Debug.LogError("No collider found. You must have a collider in order to use SoundCollider."); _rigidbody3D = GetComponent<Rigidbody>(); _rigidbody2D = GetComponent<Rigidbody2D>(); _customParams = new Dictionary<string, float>(); } /// <summary> /// Notifies the manager about a collision with another SoundCollider, /// given the collision position & relative velocity /// </summary> /// <param name="collidedWith"></param> /// <param name="pos">Position of the collision (the position where the sound will be played)</param> /// <param name="velocity">Relative velocity between the two colliding bodies</param> private void collisionSound(SoundCollider collidedWith, Vector3 pos, float velocity) { updateSize(); Manager.collisionDetected(this, collidedWith, pos, velocity); } /// <summary> /// Notifies the manager about a collision with another GameObject without SoundColllider, /// given the collision position & relative velocity /// </summary> /// <param name="pos">Position of the collision (the position where the sound will be played)</param> /// <param name="velocity">Relative velocity between the two colliding bodies</param> private void genericCollisionSound(Vector3 pos, float velocity) { updateSize(); Manager.genericCollisionDetected(this, transform.position, velocity); } /// <summary> /// Updates the size variables with the current size of the object's collider /// </summary> private void updateSize() { _worldSize = _collider.bounds.size.magnitude; } // *** COLLISION DETECTION for every possible scenario *** private void OnCollisionEnter(Collision collision) { SoundCollider collidedWith = collision.gameObject.GetComponent<SoundCollider>(); Vector3 pos = collision.GetContact(0).point; float vel = collision.relativeVelocity.magnitude; if (collidedWith != null) collisionSound(collidedWith, pos, vel); else if (!requireAnotherSoundMaterial) genericCollisionSound(pos, vel); } private void OnTriggerEnter(Collider other) { SoundCollider collidedWith = other.gameObject.GetComponent<SoundCollider>(); Vector3 pos = other.ClosestPointOnBounds(transform.position); Vector3 vel = getVelocity(); if (other.attachedRigidbody != null) vel += other.attachedRigidbody.velocity; if (collidedWith != null) collisionSound(collidedWith, pos, vel.magnitude); else if (!requireAnotherSoundMaterial) genericCollisionSound(pos, vel.magnitude); } private void OnCollisionEnter2D(Collision2D collision) { SoundCollider collidedWith = collision.gameObject.GetComponent<SoundCollider>(); Vector2 pos = collision.GetContact(0).point; float vel = collision.relativeVelocity.magnitude; if (collidedWith != null) collisionSound(collidedWith, pos, vel); else if (!requireAnotherSoundMaterial) genericCollisionSound(pos, vel); } private void OnTriggerEnter2D(Collider2D other) { SoundCollider collidedWith = other.gameObject.GetComponent<SoundCollider>(); Vector2 pos = other.ClosestPoint(transform.position); Vector3 vel = getVelocity(); if (other.attachedRigidbody != null) vel += (Vector3) other.attachedRigidbody.velocity; if (collidedWith != null) collisionSound(collidedWith, pos, vel.magnitude); else if (!requireAnotherSoundMaterial) genericCollisionSound(pos, vel.magnitude); } /// <summary> /// Sets the material of this SoundCollider /// </summary> /// <param name="material">Material name</param> public void setSoundMaterial(string material) { _soundMaterial = material; } /// <summary> /// Sets the material of this SoundCollider /// </summary> /// <returns>Material name</returns> public string getSoundMaterial() { return _soundMaterial; } /// <summary> /// Gets the magnitude of the object's size in world units /// </summary> /// <returns>magnitude of the object's size in world units</returns> public float getWorldSize() { return _worldSize; } /// <summary> /// Gets the mass of this GameObject's Rigidbody/Rigidbody2D (kg) /// </summary> /// <returns>The mass of this GameObject's Rigidbody/Rigidbody2D (kg)</returns> public float getMass() { if (_rigidbody3D != null) return _rigidbody3D.mass; else if (_rigidbody2D != null) return _rigidbody2D.mass; return 0; } /// <summary> /// Gets the current velocity of this GameObject's Rigidbody/Rigidbody2D (m/s) /// </summary> /// <returns>The velocity of this GameObject's Rigidbody/Rigidbody2D (m/s)</returns> public Vector3 getVelocity() { if (_rigidbody3D != null) return _rigidbody3D.velocity; else if (_rigidbody2D != null) return _rigidbody2D.velocity; return Vector3.zero; } /// <summary> /// Get a dictionary with all the custom parameters that have been already set /// </summary> /// <returns>A dictionary with all the custom parameters that have been already set</returns> public Dictionary<string, float> getCustomParams() { return _customParams; } /// <summary> /// Set the custom parameters of this object to the given ones /// </summary> /// <param name="customParams">Dictionary with the custom parameters as pairs [name, value]</param> public void setCustomParams(Dictionary<string, float> customParams) { _customParams = customParams; } /// <summary> /// Set a custom parameter to the given value /// </summary> /// <param name="parameter">Parameter name</param> /// <param name="value">Parameter value</param> public void setCustomParam(string parameter, float value) { _customParams[parameter] = value; } /// <summary> /// Gets a custom parameter that has been already set /// </summary> /// <param name="parameter">Name of the custom parameter that has been already set</param> /// <returns>The current value of the parameter</returns> public float getCustomParam(string parameter) { if (_customParams.ContainsKey(parameter)) return _customParams[parameter]; Debug.Log("Parameter " + parameter + " not set."); return 0; } } }
using UnityEngine; using UnityEngine.SceneManagement; public class ExitFromNest : MonoBehaviour { public string mondoEsterno; void OnTriggerEnter() { SceneManager.LoadScene(mondoEsterno); } }
using System; using System.Windows; using System.Windows.Threading; namespace GitHubFolderDownloader.Toolkit { public static class DispatcherHelper { public static void DispatchAction(Action action, DispatcherPriority dispatcherPriority = DispatcherPriority.Background) { var dispatcher = Application.Current != null ? Application.Current.Dispatcher : Dispatcher.CurrentDispatcher; if (action == null || dispatcher == null) return; dispatcher.Invoke(dispatcherPriority, action); } } }
namespace Cuku.Terrain { using Cuku.ScriptableObject; using Sirenix.OdinInspector; using System.IO; public class TerrainCommonConfig : SerializedScriptableObject { [PropertySpace(20), Title("Id"), InfoBox("Used to separate tile names.", InfoMessageType.None)] public string IdSeparator = "_"; [PropertySpace(20), Title("City"), Required, InlineEditor] public StringSO CityName; [PropertySpace, InlineEditor, Required] [InfoBox("City Center in Universal Transverse Mercator coordinates.", InfoMessageType.None)] public Vector2IntSO CenterUtm; [PropertySpace, InlineEditor, Required] [InfoBox("Minimum and maximum terrain heights.", InfoMessageType.None)] public Vector2SO TerrainHeightRange; [PropertySpace(20), Title("Heightmap"), FolderPath(RequireExistingPath = true)] [InfoBox("Folder path where terrain data is stored, must be inside Resources folder.", InfoMessageType.None)] public string TerrainDataPath; [PropertySpace, ValueDropdown("heighmapResolutions")] public int HeightmapResolution = 4097; private int[] heighmapResolutions = { 33, 65, 129, 257, 513, 1025, 2049, 4097 }; public string TerrainDataFolder() { return new DirectoryInfo(TerrainDataPath).Name; } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Caber.Util; namespace Caber.UnitTests.TestHelpers { public class ConcurrentOperations { /// <summary> /// Run the specified action at a requested degree of concurrency. /// </summary> /// <remarks> /// Waits for all threads to spin up before running the action. Completes when /// all instances of the action have completed. /// Uses Threads rather than the threadpool in an attempt to force concurrent /// execution, although in practice this will be limited by available CPUs and /// system workload. /// </remarks> public static async Task Run(int count, Action action) { var start = new Barrier(count); var end = new CountdownEvent(count); var threads = Enumerable.Range(0, count).Select(_ => RunThread(start, end, action)).ToArray(); await end.WaitHandle.WaitOneAsync(CancellationToken.None).ConfigureAwait(false); GC.KeepAlive(threads); } private static Thread RunThread(Barrier start, CountdownEvent end, Action action) { var thread = new Thread(_ => { start.SignalAndWait(); try { action(); } finally { end.Signal(); } }); thread.Start(); return thread; } } }
namespace Akka.Interfaced.SlimSocket.Client { public class SlimTaskFactory : ISlimTaskFactory { public ISlimTaskCompletionSource<TResult> Create<TResult>() => new SlimTaskCompletionSource<TResult>(); } }
namespace Bet.Extensions.Walmart.Models; public enum OrderShipMethodEnum { Standard, Express, OneDay, Freight, WhiteGlove, Value }
using System; namespace Umbraco.Cms.Core.Events { public class EventDefinition : EventDefinitionBase { private readonly EventHandler _trackedEvent; private readonly object _sender; private readonly EventArgs _args; public EventDefinition(EventHandler trackedEvent, object sender, EventArgs args, string eventName = null) : base(sender, args, eventName) { _trackedEvent = trackedEvent; _sender = sender; _args = args; } public override void RaiseEvent() { if (_trackedEvent != null) { _trackedEvent(_sender, _args); } } } public class EventDefinition<TEventArgs> : EventDefinitionBase { private readonly EventHandler<TEventArgs> _trackedEvent; private readonly object _sender; private readonly TEventArgs _args; public EventDefinition(EventHandler<TEventArgs> trackedEvent, object sender, TEventArgs args, string eventName = null) : base(sender, args, eventName) { _trackedEvent = trackedEvent; _sender = sender; _args = args; } public override void RaiseEvent() { if (_trackedEvent != null) { _trackedEvent(_sender, _args); } } } public class EventDefinition<TSender, TEventArgs> : EventDefinitionBase { private readonly TypedEventHandler<TSender, TEventArgs> _trackedEvent; private readonly TSender _sender; private readonly TEventArgs _args; public EventDefinition(TypedEventHandler<TSender, TEventArgs> trackedEvent, TSender sender, TEventArgs args, string eventName = null) : base(sender, args, eventName) { _trackedEvent = trackedEvent; _sender = sender; _args = args; } public override void RaiseEvent() { if (_trackedEvent != null) { _trackedEvent(_sender, _args); } } } }
using LoanProcessManagement.Application.Responses; using MediatR; using System; namespace LoanProcessManagement.Application.Features.Events.Queries.GetEventDetail { public class GetEventDetailQuery : IRequest<Response<EventDetailVm>> { public string Id { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class InstanceManager : MonoBehaviour { public static InstanceManager Instance; private Dictionary<Type, object> instancesDictionary; private void Awake() { Instance = this; instancesDictionary = new Dictionary<Type, object>(); } public T AddInstance<T>(T instance) { gameObject.AddComponent(instance.GetType()); // instancesDictionary[typeof(T)] = instance; return instance; } public T Get<T>() where T : MonoBehaviour { T foundComponent = GetComponentInChildren<T>(); if (foundComponent == null) { foundComponent = gameObject.AddComponent<T>(); } return foundComponent; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class SpecialAbility : GUIComponent { [SerializeField] private List<SpecialAbilitySlot> _slots = new List<SpecialAbilitySlot>(); [SerializeField] private List<SpecialAbilityListUnit> _specialAbilitylist = new List<SpecialAbilityListUnit>(); void Awake() { UpdateSlotInfo(); SetupList(); } private void UpdateSlotInfo() { var slots = PlayerDataRepository.Instance.GetAbilitySlot(); for (short index = 0; index < _slots.Count; ++index) { short slotNo = (short)(index + 1); int abilityID = slots[slotNo]; _slots[index].SlotNO = slotNo; _slots[index].UpdateInfo(abilityID); } } private void SetupList() { var list = PlayerDataRepository.Instance.GetAbilityList(); for (int index = 0; index < list.Count; ++index) { _specialAbilitylist[index].UpdateInfo(list[index]); } } public override void OnHandleEvent(GameEventType gameEventType, params System.Object[] args) { switch(gameEventType) { case GameEventType.AbilitySlotOpenAnsOK: case GameEventType.AbilityEquipAnsOK: UpdateSlotInfo(); break; case GameEventType.AbilityAcquireAnsOK: var abilityId = (int)args[0]; SpecialAbilityListUnit target = _specialAbilitylist.Find( delegate (SpecialAbilityListUnit unit) { return unit.ID == abilityId; }); var abilityInfo = PlayerDataRepository.Instance.GetAbilityInfo(abilityId); target.UpdateInfo(abilityInfo); break; case GameEventType.EquipSpecialAbility: for(int index = 0; index < _slots.Count; ++index) { if (!_slots[index].Unlock) { continue; } _slots[index].EnableEquip((int)args[0]); } break; } } public void SelectEquipSlot() { for (int index = 0; index < _slots.Count; ++index) { _slots[index].EnableEquip(0); } } public void Unlock(int aIndex) { // TO DO : request buy special ability slot. } }
using System.Collections.Generic; using NUnit.Framework; using Hsm; namespace UnitTesting { [TestFixture] class StateMachineTests : AssertionHelper { [Test] public void InstantiateEmpty() { var statemachine = new StateMachine(); Expect(statemachine, Is.InstanceOf<StateMachine>()); Expect(statemachine.states.Count, Is.EqualTo(0)); } [Test] public void InstantiateWithStates() { // with List<State> var statemachine_from_list = new StateMachine(new List<State> {new State("foo"), new State("bar")}); Expect(statemachine_from_list, Is.InstanceOf<StateMachine>()); Expect(statemachine_from_list.states.Count, Is.EqualTo(2)); statemachine_from_list.addState(new State("krokodil")); Expect(statemachine_from_list.states.Count, Is.EqualTo(3)); Expect(statemachine_from_list.states[2].id, Is.EqualTo("krokodil")); // with State[] var statemachine_from_array = new StateMachine(new[] {new State("foo"), new State("bar")}); // or new State[] Expect(statemachine_from_array, Is.InstanceOf<StateMachine>()); Expect(statemachine_from_array.states.Count, Is.EqualTo(2)); statemachine_from_array.addState(new State("krokodil")); Expect(statemachine_from_array.states.Count, Is.EqualTo(3)); Expect(statemachine_from_array.states[2].id, Is.EqualTo("krokodil")); // with multiple State arguments var statemachine_from_arguments = new StateMachine(new State("foo"), new State("bar")); Expect(statemachine_from_arguments, Is.InstanceOf<StateMachine>()); Expect(statemachine_from_arguments.states.Count, Is.EqualTo(2)); statemachine_from_arguments.addState(new State("krokodil")); Expect(statemachine_from_arguments.states.Count, Is.EqualTo(3)); Expect(statemachine_from_arguments.states[2].id, Is.EqualTo("krokodil")); // Empty at construction time var initially_empty = new StateMachine(); Expect(initially_empty, Is.InstanceOf<StateMachine>()); Expect(initially_empty.states.Count, Is.EqualTo(0)); initially_empty.addState(new State("foo")); initially_empty.addState(new State("bar")); Expect(initially_empty.states.Count, Is.EqualTo(2)); } [Test] public void InitialState() { var sm = new StateMachine(new State("first"), new State("second")); sm.setup(); Expect(sm.initialState.id, Is.EqualTo("first")); } [Test] public void TeardownResetsCurrentState() { var sm = new StateMachine(new State("first"), new State("second")); sm.setup(); sm.tearDown(null); Expect(sm.currentState, Is.EqualTo(null)); } } }
using System; using System.Threading.Tasks; using Uintra.Features.Groups.Models; namespace Uintra.Features.Groups.Helpers { public interface IGroupHelper { GroupHeaderViewModel GetHeader(Guid groupId); Task<GroupHeaderViewModel> GetHeaderAsync(Guid groupId); GroupViewModel GetGroupViewModel(Guid groupId); Task<GroupViewModel> GetGroupViewModelAsync(Guid groupId); GroupInfoViewModel GetInfoViewModel(Guid groupId); Task<GroupInfoViewModel> GetInfoViewModelAsync(Guid groupId); GroupLeftNavigationMenuViewModel GroupNavigation(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using Newtonsoft.Json; public class APImannager : MonoBehaviour { private Info info; private string api = "http://127.0.0.1:8012/Spy_Game/"; // Use this for initialization void Start () { info = GameObject.FindObjectOfType<Info>(); StartCoroutine(getPlayerData(1)); //var w = UnityWebRequest.Put(); //string json = JsonConvert.SerializeObject(); } public IEnumerator getPlayerData(int id) { api += id.ToString(); WWW www = new WWW(api); yield return www; string data = www.text; var playerdataList = JsonConvert.DeserializeObject<List<PlayerData>>(data); var playerdata = playerdataList[0]; info.playerData = playerdata; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Schedule.ModelInterfaces { public interface ISchedule { public Models.Schedule GetSchedule(int id); public IEnumerable<Models.Schedule> GetSchedules { get; } public void AddSchedule(Models.Schedule schedule); public void UpdateSchedule(Models.Schedule schedule); public void DeleteSchedules(); } }
using System; using Backend.DDD.Sample.Contracts.Issues; using GoldenEye.Backend.Core.Entity; using GoldenEye.Shared.Core.Objects.General; namespace Backend.DDD.Sample.Issues { internal class Issue: IEntity { public Issue() { } public Issue(Guid id, IssueType type, string title) { Id = id; Type = type; Title = title; } public Guid Id { get; set; } public IssueType Type { get; set; } public string Title { get; set; } public string Description { get; set; } object IHaveId.Id => Id; } }
using RabbitMQ.Client; using System; namespace Msh.EasyRabbitMQ.ServiceBus.ServiceBusConnection { public interface IConnectionManager : IDisposable { IModel Channel { get; } void Connect(); void TryConnect(); } }
namespace EnvironmentAssessment.Common.VimApi { public class HostSnmpConfigSpec : DynamicData { protected bool? _enabled; protected int? _port; protected string[] _readOnlyCommunities; protected HostSnmpDestination[] _trapTargets; protected KeyValue[] _option; public bool? Enabled { get { return this._enabled; } set { this._enabled = value; } } public int? Port { get { return this._port; } set { this._port = value; } } public string[] ReadOnlyCommunities { get { return this._readOnlyCommunities; } set { this._readOnlyCommunities = value; } } public HostSnmpDestination[] TrapTargets { get { return this._trapTargets; } set { this._trapTargets = value; } } public KeyValue[] Option { get { return this._option; } set { this._option = value; } } } }
using System.Collections.Generic; using System.Linq; using System.Text; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.Web.Models; namespace Our.Umbraco.NonProfitFramework.Core.Custom { public class TypedPictureElement : PictureElement { public IPublishedContent Content { get; set; } private string PropertyAlias { get; set; } private ImageCropMode ImageCropMode { get; set; } #region Constructors public TypedPictureElement(IPublishedContent content, string propertyAlias = "umbracoFile", ImageCropMode imageCropMode = ImageCropMode.Crop) : base() { if (content == null) throw new System.ArgumentNullException("Content", "Missing Content from Picture. Use Umbraco.Picture(IPublishedContent)"); ImageCropMode = imageCropMode; Content = content; PropertyAlias = propertyAlias; } #endregion public string GetCropUrl(int width, int? height, double? devicePixelRatio = null) { string url = this.Content.GetCropUrl(width: width, height: height, imageCropMode: this.ImageCropMode); if(devicePixelRatio.HasValue) url += " " + string.Format("{0:0.##}x", devicePixelRatio).Replace(',', '.'); return url; } } }
using HTTPlease; using System; namespace KubeClient { using Models; /// <summary> /// Exception raised when an error result is returned by the Kubernetes API. /// </summary> #if NETSTANDARD20 [Serializable] #endif // NETSTANDARD20 public class KubeApiException : KubeClientException { /// <summary> /// Create a new <see cref="KubeApiException"/> using the information contained in a Kubernetes status model. /// </summary> /// <param name="status"> /// The Kubernetes <see ref="StatusV1"/> model. /// </param> public KubeApiException(StatusV1 status) : base(GetExceptionMessage(status)) { Status = status; } /// <summary> /// Create a new <see cref="KubeApiException"/> using the information contained in a Kubernetes status model. /// </summary> /// <param name="message"> /// The exception message. /// </param> /// <param name="status"> /// The Kubernetes <see ref="StatusV1"/> model. /// </param> public KubeApiException(string message, StatusV1 status) : base(message + Environment.NewLine + GetExceptionMessage(status)) { Status = status; } /// <summary> /// Create a new <see cref="KubeApiException"/> using the information contained in a Kubernetes status model. /// </summary> /// <param name="status"> /// The Kubernetes <see ref="StatusV1"/> model. /// </param> /// <param name="innerException"> /// The exception that caused the current exception to be raised. /// </param> public KubeApiException(StatusV1 status, Exception innerException) : base(GetExceptionMessage(status), innerException) { if (innerException == null) throw new ArgumentNullException(nameof(innerException)); Status = status; } /// <summary> /// Create a new <see cref="KubeApiException"/> with the specified message. /// </summary> /// <param name="message"> /// The exception message. /// </param> /// <param name="innerException"> /// The exception that caused the current exception to be raised. /// </param> public KubeApiException(string message, HttpRequestException<StatusV1> innerException) : base(message + Environment.NewLine + GetExceptionMessage(innerException?.Response), innerException) { if (String.IsNullOrWhiteSpace(message)) throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'message'.", nameof(message)); if (innerException == null) throw new ArgumentNullException(nameof(innerException)); Status = innerException.Response; } /// <summary> /// Create a new <see cref="KubeApiException"/> from an <see cref="HttpRequestException{TResponse}"/>. /// </summary> /// <param name="requestException"> /// The exception that caused the current exception to be raised. /// </param> public KubeApiException(HttpRequestException<StatusV1> requestException) : base(GetExceptionMessage(requestException?.Response), requestException) { if (requestException == null) throw new ArgumentNullException(nameof(requestException)); Status = requestException.Response; } #if NETSTANDARD2_0 /// <summary> /// Deserialisation constructor. /// </summary> /// <param name="info"> /// The serialisation data store. /// </param> /// <param name="context"> /// A <see cref="StreamingContext"/> containing information about the origin of the serialised data. /// </param> protected KubeClientException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif // NETSTANDARD2_0 /// <summary> /// A Kubernetes <see cref="StatusV1"/> model that (if present) contains more information about the error. /// </summary> public StatusV1 Status { get; protected set; } /// <summary> /// Does the exception have a <see cref="Status"/> model available? /// </summary> public bool HasStatus => Status != null; /// <summary> /// The Kubernetes reason code (if available from <see cref="Status"/>). /// </summary> public string StatusReason => Status?.Reason; /// <summary> /// The Kubernetes error message (if available from <see cref="Status"/>). /// </summary> public string StatusMessage => Status?.Message; /// <summary> /// Generate an exception message from a Kubernetes status model. /// </summary> /// <param name="status"> /// The Kubernetes <see cref="StatusV1"/> model. /// </param> /// <returns> /// The exception message. /// </returns> protected static string GetExceptionMessage(StatusV1 status) { if (status == null) return DefaultMessage; if (!String.IsNullOrWhiteSpace(status.Reason)) return $"{status.Reason}: {status.Message}"; if (!String.IsNullOrWhiteSpace(status.Message)) return status.Message; return DefaultMessage; } } }
using System; namespace BlazorX.NavigationState { public interface INavigationParameter<T> { public T Value { get; set; } public IObservable<T> ValueStream { get; } } public interface IQueryParameter<T> : INavigationParameter<T> { } }
using System; //struct holding x and y coordinates public struct Point { public int X, Y; public Point(int x, int y) { X = x; Y = y; } // override object.Equals public override bool Equals(object obj) { // // See the full list of guidelines at // http://go.microsoft.com/fwlink/?LinkID=85237 // and also the guidance for operator== at // http://go.microsoft.com/fwlink/?LinkId=85238 // if (obj == null || GetType() != obj.GetType()) { return false; } Point p = (Point)obj; return X == p.X && Y == p.Y; } // override object.GetHashCode public override int GetHashCode() { return Y ^ X; } }
using Volo.Abp.Localization; namespace EasyAbp.EShop.Plugins.Baskets.Localization { [LocalizationResourceName("EShopPluginsBaskets")] public class BasketsResource { } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Xunit; namespace Test.Utility { public static class ExceptionUtility { public static void AssertMicrosoftAssumesException(Exception exception) { Assert.NotNull(exception); Assert.Equal("Microsoft.Assumes+InternalErrorException", exception.GetType().FullName); Assert.Equal(0x80131500, (uint)exception.HResult); Assert.Equal("Microsoft.VisualStudio.Validation", exception.Source); Assert.Equal("An internal error occurred. Please contact Microsoft Support.", exception.Message); } } }
using UnityEngine; namespace Production.Scripts.Items { public class OnItem : MonoBehaviour { public UntilDeathBoolItem untilDeathBool; public DurationBoolItem durationBoolItem; public SpecialEffectItem specialEffectItem; public InstantFloatItem instantFloatItem; } }
using System; using Arbor.App.Extensions; using Xunit; namespace Milou.Deployer.Web.Tests.Unit { public class DisposeTest { private class TestDisposable : IDisposable { public void Dispose() { } } [Fact] public void DisposeDisposable() { var o = new TestDisposable(); o.SafeDispose(); } [Fact] public void DisposeNonDisposable() { var o = new object(); o.SafeDispose(); } [Fact] public void DisposeNull() { object? o = null; // ReSharper disable once ExpressionIsAlwaysNull o.SafeDispose(); } } }
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>Create a Custom Postcard!</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>Fill in your name and your friend's name to create your custom postcard!</h1> <form action="/madlib" method="post"> <label for="adjective1">Enter an Adjective</label> <input id="adjective1" name="adjective1" type="text"> <label for="adjective2">Enter an Adjective</label> <input id="adjective2" name="adjective2" type="text"> <label for="adjective3">Enter an Adjective</label> <input id="adjective3" name="adjective3" type="text"> <label for="adjective4">Enter an Adjective</label> <input id="adjective4" name="adjective4" type="text"> <label for="adjective5">Enter an Adjective</label> <input id="adjective5" name="adjective5" type="text"> <label for="verb1">Enter an Verb</label> <input id="verb1" name="verb1" type="text"> <label for="verb2">Enter an Verb</label> <input id="verb2" name="verb2" type="text"> <label for="noun1">Enter an Noun</label> <input id="noun1" name="noun1" type="text"> <label for="noun2">Enter an Noun</label> <input id="noun2" name="noun2" type="text"> <label for="noun3">Enter an Noun</label> <input id="noun3" name="noun3" type="text"> <label for="noun4">Enter an Noun</label> <input id="noun4" name="noun4" type="text"> <button type="submit" value="submit-1">Go!</button> </form> </div> </body> </html>
using System; using System.Collections.Generic; using System.Linq; namespace Count_Same_Values_In_Array { class Program { static void Main(string[] args) { var numbers = Console.ReadLine().Split().Select(double.Parse); var doubles = new Dictionary<double, int>(); foreach (var number in numbers) { if(!doubles.ContainsKey(number)) { doubles.Add(number, 0); } doubles[number]++; } foreach (var KVP in doubles) { Console.WriteLine($"{KVP.Key} - {KVP.Value} times"); } } } }
using BusinessEngine.Operating; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; namespace BusinessEngine.Sales { public abstract class IProduct: INotifyPropertyChanged { private string name; private AccountingCompany mft; private float price; public string Name { get { return name; } set { name = value; NotifyPropertyChanged("Name"); } } public AccountingCompany Manufacturer { get { return mft; } set { mft = value; NotifyPropertyChanged("Manufacturer"); } } public float Price { get { return price; } set { price = value; NotifyPropertyChanged("Price"); } } public ObservableCollection<IProduct> Costs { get; set; } = new ObservableCollection<IProduct>(); //매출 원가 public bool Equals(IProduct product) { return (product.Name == this.Name && product.Manufacturer.Equals(this.Manufacturer) && product.Price == this.Price); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void NotifyPropertyChanged(string property) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } } }
using Cordonez.BubbleInvasion.DataModels; namespace Cordonez.BubbleInvasion.Models { public interface IBullet { SO_BulletData BulletData { get; set; } void Shoot(); } }
// InBuffer.cs using System.IO; namespace SevenZip.Buffer { public class InBuffer { private readonly byte[] _mBuffer; private readonly uint _mBufferSize; private uint _mLimit; private uint _mPos; private ulong _mProcessedSize; private Stream _mStream; private bool _mStreamWasExhausted; public InBuffer(uint bufferSize) { _mBuffer = new byte[bufferSize]; _mBufferSize = bufferSize; } public void Init(Stream stream) { _mStream = stream; _mProcessedSize = 0; _mLimit = 0; _mPos = 0; _mStreamWasExhausted = false; } public bool ReadBlock() { if (_mStreamWasExhausted) return false; _mProcessedSize += _mPos; var aNumProcessedBytes = _mStream.Read(_mBuffer, 0, (int) _mBufferSize); _mPos = 0; _mLimit = (uint) aNumProcessedBytes; _mStreamWasExhausted = (aNumProcessedBytes == 0); return (!_mStreamWasExhausted); } public void ReleaseStream() { // m_Stream.Close(); _mStream = null; } public bool ReadByte(byte b) // check it { if (_mPos >= _mLimit) if (!ReadBlock()) return false; b = _mBuffer[_mPos++]; return true; } public byte ReadByte() { // return (byte)m_Stream.ReadByte(); if (_mPos >= _mLimit) if (!ReadBlock()) return 0xFF; return _mBuffer[_mPos++]; } public ulong GetProcessedSize() { return _mProcessedSize + _mPos; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Policy; using System.Web; namespace Marcusca10.Samples.BuildingAccessNet.Web.Models { public class ManageUserViewModel { public string Id { get; set; } [EmailAddress] public string Email { get; set; } public string Name { get; set; } public string Tenant { get; set; } } public class TenantViewModel { public string Id { get; set; } public string Name { get; set; } public string Caption { get; set; } public string Realm { get; set; } } public class TenantEditViewModel { public string Id { get; set; } public string Name { get; set; } public string CallbackPath { get; set; } public string Caption { get; set; } [Url] public string Realm { get; set; } [Url] public string MetadataAddress { get; set; } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.VisualStudio.Shell.Interop; using System; using System.Diagnostics; namespace GoogleCloudExtension.Utils { /// <summary> /// This utility class implements helpers to log to the activity log, which will help /// debug issues with the extension that only our customers can reproduce. The log is only /// written to if the /log parameter is passed to Visual Studio on startup, other than that /// writing to the log is a noop. /// </summary> internal static class ActivityLogUtils { private static IServiceProvider s_serviceProvider; /// <summary> /// Initialize the helper, most importantly provides the service provider to use /// to get to the log service. /// </summary> /// <param name="serviceProvider">The service provider to use to get the log service.</param> public static void Initialize(IServiceProvider serviceProvider) { s_serviceProvider = serviceProvider; } /// <summary> /// Logs a information entry into the log. /// </summary> /// <param name="entry">The log entry.</param> public static void LogInfo(string entry) { Debug.WriteLine($"Info: {entry}"); var log = GetActivityLog(); log?.LogEntry( (int)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, nameof(GoogleCloudExtensionPackage), entry); } /// <summary> /// Logs an error entry into the log. /// </summary> /// <param name="entry">The log entry.</param> public static void LogError(string entry) { Debug.WriteLine($"Error: {entry}"); var log = GetActivityLog(); log.LogEntry( (int)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, nameof(GoogleCloudExtensionPackage), entry); } /// <summary> /// This method retrieves the activity log service, as per the documentation a new interface must /// be fetched everytime it is needed, which is why not caching is performed. /// See https://msdn.microsoft.com/en-us/library/bb166359.aspx for more details. /// </summary> /// <returns>The current instance of IVsACtivityLog to use.</returns> private static IVsActivityLog GetActivityLog() { var log = s_serviceProvider.GetService(typeof(SVsActivityLog)) as IVsActivityLog; Debug.WriteLineIf(log == null, "Failed to obtain IVsActivityLog interface."); return log; } } }
#region /* * Author: Jackalsoft Games * Date: February 2018 * Project: Presto! (#MonoGameJam2018 entry) * * This code is provided as-is under the MIT license, * with no warranty express or implied. */ using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Presto; using Presto.Extensions; using Presto.Input; #endregion namespace Presto { public sealed class GameState : ITickable { #region Constructors public GameState() { Player = new PlayerStateManager(this); Entity = new EntityStateManager(this); Particles = new ParticleStateManager(this); } #endregion // Types #region Component public abstract class Component : ITickable { #region Constructors public Component(GameState state) { if (state == null) throw new ArgumentNullException("state"); State = state; } #endregion // Properties public GameState State { get; private set; } // Methods #region Tick public virtual void Tick(float time) { } #endregion } #endregion // Fields public PlayerStateManager Player; public EntityStateManager Entity; public ParticleStateManager Particles; public TickTimer GlobalAnim_30 = new TickTimer(30, true); public TickTimer GlobalAnim_60 = new TickTimer(60, true); public TickTimer GlobalAnim_120 = new TickTimer(120, true); // Methods #region Tick public void Tick(float time) { Player.Tick(time); Entity.Tick(time); Particles.Tick(time); GlobalAnim_30.Tick(time); GlobalAnim_60.Tick(time); GlobalAnim_120.Tick(time); } #endregion } }
namespace UCP.Patching { public abstract class BinElement { public virtual int Length => 0; int rawAddr, virtAddr; public int RawAddress => rawAddr; public int VirtAddress => virtAddr; public virtual void Initialize(int rawAddr, int virtAddr, byte[] original) { this.rawAddr = rawAddr; this.virtAddr = virtAddr; } public virtual void Write(BinArgs data) { } public static implicit operator BinElement(byte value) { return new BinBytes(value); } public static implicit operator BinElement(byte[] buffer) { return new BinBytes(buffer); } } }
@model List<InventoryManager.Models.InventoryItem> <h1>Inventory</h1> <table class="table"> <tr> <th>Name</th> <th>Upc</th> <th>Unit</th> <th>Cost</th> <th>Category</th> <th>Vendor</th> <th>Quantity</th> </tr> @foreach (var item in Model) { <tr> <td>@item.Name</td> <td>@item.Upc</td> <td>@item.Unit</td> <td>@item.Cost</td> <td>@item.Category.Name</td> <td>@item.Vendor.Name</td> <td>@item.Quantity</td> <td><a asp-controller="Inventory" asp-action="Edit" asp-route-id="@item.ID">Edit</a></td> </tr> } </table> @if (Model.Count == 0) { <p>No Inventory</p> } <p> <a asp-controller="Inventory" asp-action="Add">Add Item</a> &nbsp; | &nbsp; <a asp-contrlloer="Inventory" asp-action="Remove">Remove Item(s)</a> </p>
using System.Linq; using System.Xml.Linq; namespace FeedlyOpmlExport.Functions { public static class OpmlLabeler { public static string LabelOpmlFile(string opmlXml) { var opmlDoc = XElement.Parse(opmlXml); var firstLevelChildren = opmlDoc.DescendantNodes().Where(x => x.Parent.Name == "body"); foreach (var child in firstLevelChildren) { var containerized = (XElement)child; var titleAttribute = containerized.Attribute(XName.Get("title")); titleAttribute.SetValue(titleAttribute.Value + " - via Sean Killeen"); var textAttribute = containerized.Attribute(XName.Get("text")); textAttribute.SetValue(textAttribute.Value + " - via Sean Killeen"); } return opmlDoc.ToString(); } } }
// Licensed under the MIT license. // See LICENSE file in the project root directory for full information. // Copyright (c) 2018 Jacob Schlesinger // File authors (in chronological order): // - Jacob Schlesinger <schlesinger.jacob@gmail.com> using System; using System.Linq; using jsc.commons.behaving.interfaces; using jsc.commons.cli.config; using jsc.commons.cli.interfaces; using jsc.commons.rc; using jsc.commons.rc.interfaces; namespace jsc.commons.cli.policies { public class UniqueNames : RuleBase<ICliSpecification> { private static readonly Func<UniqueNames, ICliSpecification, ICliConfig, IViolation<ICliSpecification>>[] __checks; static UniqueNames( ) { __checks = new Func<UniqueNames, ICliSpecification, ICliConfig, IViolation<ICliSpecification>>[] { CheckOptionNames, CheckOptionAliases, CheckFlagNames, CheckFlagNamesAndOptionAliases }; } public override IViolation<ICliSpecification> Check( ICliSpecification subject, IBehaviors context = null ) { ConfigBehavior cb = null; context?.TryGet( out cb ); ICliConfig conf = cb?.Config; foreach( Func<UniqueNames, ICliSpecification, ICliConfig, IViolation<ICliSpecification>> check in __checks ) { IViolation<ICliSpecification> violation = check( this, subject, conf ); if( violation != NonViolation<ICliSpecification>.Instance ) return violation; } return NonViolation<ICliSpecification>.Instance; } private static IViolation<ICliSpecification> CheckOptionNames( UniqueNames _this, ICliSpecification subject, ICliConfig conf ) { bool CmpOptNames( IOption o1, IOption o2 ) { return o1 != o2&&o1.Name.Equals( o2.Name, conf?.CaseSensitiveOptions??true ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase ); } IOption opt1 = subject.Options.FirstOrDefault( o1 => subject.Options.Any( o2 => CmpOptNames( o1, o2 ) ) ); if( opt1 != null ) { IOption opt2 = subject.Options.First( o2 => CmpOptNames( opt1, o2 ) ); return new Violation<ICliSpecification>( _this, Enumerable.Empty<ISolution<ICliSpecification>>( ), $"name collision between options {opt1.Name} and {opt2.Name}" ); } return NonViolation<ICliSpecification>.Instance; } private static IViolation<ICliSpecification> CheckFlagNames( UniqueNames _this, ICliSpecification subject, ICliConfig conf ) { bool CmpFlagNames( IFlag f1, IFlag f2 ) { return f1 != f2&&CmpChars( f1.Name, f2.Name, conf?.CaseSensitiveFlags??true ); } IFlag flag1 = subject.Flags.FirstOrDefault( f1 => subject.Flags.Any( f2 => CmpFlagNames( f1, f2 ) ) ); if( flag1 != null ) { IFlag flag2 = subject.Flags.First( f2 => CmpFlagNames( flag1, f2 ) ); return new Violation<ICliSpecification>( _this, Enumerable.Empty<ISolution<ICliSpecification>>( ), $"name collision between flags {flag1.Name} and {flag2.Name}" ); } return NonViolation<ICliSpecification>.Instance; } private static IViolation<ICliSpecification> CheckFlagNamesAndOptionAliases( UniqueNames _this, ICliSpecification subject, ICliConfig conf ) { bool CmpOptAliasFlag( IOption opt, IFlag flag ) { return CmpChars( // ReSharper disable once PossibleInvalidOperationException opt.FlagAlias.Value, flag.Name, conf?.CaseSensitiveFlags??true ); } IOption opt1 = subject.Options.FirstOrDefault( o1 => o1.FlagAlias.HasValue&&subject.Flags.Any( f1 => CmpOptAliasFlag( o1, f1 ) ) ); if( opt1 != null ) { IFlag flag1 = subject.Flags.First( f1 => CmpOptAliasFlag( opt1, f1 ) ); return new Violation<ICliSpecification>( _this, Enumerable.Empty<ISolution<ICliSpecification>>( ), $"name collision between option {opt1.Name} flag alias and flag {flag1.Name}" ); } return NonViolation<ICliSpecification>.Instance; } private static IViolation<ICliSpecification> CheckOptionAliases( UniqueNames _this, ICliSpecification subject, ICliConfig conf ) { bool CmpOptAliases( IOption o1, IOption o2 ) { return o1 != o2&& o1.FlagAlias.HasValue&& o2.FlagAlias.HasValue&& CmpChars( o1.FlagAlias.Value, o2.FlagAlias.Value, conf?.CaseSensitiveFlags??true ); } IOption opt1 = subject.Options.FirstOrDefault( o1 => subject.Options.Any( o2 => CmpOptAliases( o1, o2 ) ) ); if( opt1 != null ) { IOption opt2 = subject.Options.First( o2 => CmpOptAliases( opt1, o2 ) ); return new Violation<ICliSpecification>( _this, Enumerable.Empty<ISolution<ICliSpecification>>( ), $"flag alias name collision between options {opt1.Name} and {opt2.Name}" ); } return NonViolation<ICliSpecification>.Instance; } private static bool CmpChars( char c1, char c2, bool cs ) { return cs? c1 == c2 : char.ToUpperInvariant( c1 ) == char.ToUpperInvariant( c2 ); } } }
using Stratis.Bitcoin.Consensus.Rules; using Stratis.Bitcoin.Features.Consensus.CoinViews; using Stratis.Bitcoin.Utilities; namespace Stratis.Bitcoin.Features.Consensus.Rules { /// <summary> /// Rules that provide easy access to the <see cref="CoinView"/> which is the store for a PoW system. /// </summary> public abstract class UtxoStoreConsensusRule : ConsensusRule { /// <summary>Allow access to the POS parent.</summary> protected PowConsensusRules PowParent; /// <inheritdoc /> public override void Initialize() { this.PowParent = this.Parent as PowConsensusRules; Guard.NotNull(this.PowParent, nameof(this.PowParent)); } } /// <summary> /// Rules that provide easy access to the <see cref="IStakeChain"/> which is the store for a PoS system. /// </summary> public abstract class StakeStoreConsensusRule : ConsensusRule { /// <summary>Allow access to the POS parent.</summary> protected PosConsensusRules PosParent; /// <inheritdoc /> public override void Initialize() { this.PosParent = this.Parent as PosConsensusRules; Guard.NotNull(this.PosParent, nameof(this.PosParent)); } } }
using Panosen.CodeDom.Tag.Vue; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panosen.CodeDom.Vue { /// <summary> /// /// </summary> public class VueRoute { /// <summary> /// Path /// </summary> public string Path { get; set; } = string.Empty; /// <summary> /// Name /// </summary> public string Name { get; set; } = string.Empty; /// <summary> /// Component /// </summary> public VueComponent Component { get; set; } /// <summary> /// LazyLoad /// </summary> public bool LazyLoad { get; set; } /// <summary> /// Redirect /// </summary> public string Redirect { get; set; } = string.Empty; /// <summary> /// Children /// </summary> public List<VueRoute> Children { get; set; } } }
namespace ForumSystem.Web.Controllers { using System; using System.Linq; using System.Web.Mvc; using ForumSystem.Data.Common.Repository; using ForumSystem.Data.Models; using ForumSystem.Web.ViewModels.Feedbacks; using Microsoft.AspNet.Identity; public class FeedbackController : Controller { private const string SuccessfulMessageOnCreateNewFeedback = "You successfully created a new feedback!"; private IDeletableEntityRepository<Feedback> feedbacks; public FeedbackController(IDeletableEntityRepository<Feedback> feedbacks) { this.feedbacks = feedbacks; } [HttpGet] public ActionResult Create() { return this.View(); } [HttpPost] public ActionResult Create(FeedbackViewModel model) { if (model != null && this.ModelState.IsValid) { var feedback = AutoMapper.Mapper.Map<Feedback>(model); var userId = this.GetCurrentUserId(); if (userId != null) { feedback.AuthorId = userId; } this.feedbacks.Add(feedback); this.feedbacks.SaveChanges(); this.SetSuccessfullMessage(SuccessfulMessageOnCreateNewFeedback); return this.RedirectToAction("Index", "Home"); } return this.View(model); } private void SetSuccessfullMessage(string message) { this.TempData["successfulMessage"] = message; } private string GetCurrentUserId() { var userId = this.User.Identity.GetUserId(); return userId; } } }
using System.Windows.Input; using Syncfusion.ListView.XForms; using Xamarin.Forms; using ItemTappedEventArgs = Syncfusion.ListView.XForms.ItemTappedEventArgs; namespace ShoppingCart.Behaviors { /// <summary> /// This class extends the behavior of the SfListView to invoke a command when an event occurs. /// </summary> public class SfListViewTapBehavior : Behavior<SfListView> { #region Properties /// <summary> /// Gets or sets the CommandProperty, and it is a bindable property. /// </summary> public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(SfListViewTapBehavior)); /// <summary> /// Gets or sets the Command. /// </summary> public ICommand Command { get => (ICommand) GetValue(CommandProperty); set => SetValue(CommandProperty, value); } #endregion #region Method /// <summary> /// Invoked when added sflistview to the page. /// </summary> /// <param name="bindableListView">The SfListView</param> protected override void OnAttachedTo(SfListView bindableListView) { base.OnAttachedTo(bindableListView); bindableListView.ItemTapped += BindableListView_ItemTapped; } /// <summary> /// Invoked when exit from the page. /// </summary> /// <param name="bindableListView">The SfListView</param> protected override void OnDetachingFrom(SfListView bindableListView) { base.OnDetachingFrom(bindableListView); bindableListView.ItemTapped -= BindableListView_ItemTapped; } /// <summary> /// Invoked when tapping the listview item. /// </summary> /// <param name="sender">The Sender</param> /// <param name="e">ItemTapped EventArgs</param> private void BindableListView_ItemTapped(object sender, ItemTappedEventArgs e) { if (Command == null) return; if (Command.CanExecute(e.ItemData)) Command.Execute(e.ItemData); } #endregion } }
namespace Abp.TestBase.SampleApplication { public static class SampleApplicationConsts { public const string LocalizationSourceName = "SampleApplication"; } }
namespace Epi.DataPersistence.Constants { public struct RecordStatus { public const int PhysicalDelete = int.MinValue; public const int RecoverLastRecordVersion = -2; public const int New = -1; public const int Deleted = 0; public const int InProcess = 1; public const int Saved = 2; public const int Completed = 3; public const int Downloaded = 4; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KeyforgeDownloader { /// <summary> /// Utilities for formatting console input/output /// </summary> static class ConsoleHelper { /// <summary> /// Print an exception, along with any inner exceptions /// </summary> /// <param name="ex">Exception</param> public static void ShowException(Exception ex) { Console.Error.WriteLine(); Console.Error.Write("Error: "); Console.Error.WriteLine(ex.Message); ex = ex.InnerException; while(ex != null) { Console.Error.Write("--> "); Console.Error.WriteLine(ex.Message); ex = ex.InnerException; } } /// <summary> /// Print an aggregate exception by printing each of the inner exceptions /// </summary> /// <param name="ex"></param> public static void ShowAggregateException(AggregateException ex) { if(ex.InnerExceptions == null) { ShowException(ex); } else { foreach(Exception innerEx in ex.InnerExceptions) ShowException(innerEx); } } /// <summary> /// Prompt for input /// </summary> /// <param name="message">Message to display</param> /// <returns>A line of input</returns> public static string Prompt(string message) { Console.Write($"{message}: "); return Console.ReadLine(); } /// <summary> /// Prompt the user for a yes/no response. /// Also accepts partial inputs. /// Invalid inputs map to the default selection. /// </summary> /// <param name="message">Message to display</param> /// <param name="defaultValue">Default selection value</param> /// <returns>The user's choice</returns> public static bool PromptYesNo(string message, bool defaultValue) { Console.Write(message); string otherTarget; if(defaultValue) { Console.Write(" (Y/n)? "); otherTarget = "no"; } else { Console.Write(" (y/N)? "); otherTarget = "yes"; } string input = Console.ReadLine(); if(String.IsNullOrEmpty(input)) return defaultValue; input = input.ToLower(); string targetSubset = otherTarget.Substring(0, Math.Min(otherTarget.Length, input.Length)); if(input == targetSubset) return !defaultValue; else return defaultValue; } /// <summary> /// Prompt the user for a file path. /// Will also prompt to overwrite, and repeats the prompt otherwise. /// </summary> /// <param name="message">Message to display</param> /// <returns></returns> public static string PromptFile(string message) { string path; while(true) { path = Prompt("Save to image file"); if(String.IsNullOrWhiteSpace(path)) return null; if(File.Exists(path)) { if(PromptYesNo("Overwrite this file", false)) break; } else if(IsValidFilePath(path)) break; else Console.WriteLine("Invalid file path"); } return path; } /// <summary> /// Check if a file can be created at this path /// </summary> /// <param name="path">File path</param> /// <returns>Whether a file could be created</returns> private static bool IsValidFilePath(string path) { try { using(FileStream file = File.Create(path, 1, FileOptions.DeleteOnClose)) return true; } catch { return false; } } } }
namespace KsWare.Presentation.Testing { public class TestBase { public virtual void TestInitialize() { } public virtual void TestCleanup() { } } public class TestBase<TSubject>:TestBase { } }
using System; using System.Diagnostics; namespace Testing.TestClasses { public class ShimMe { public ShimMe() { var text = "Constructor"; //Debug.WriteLine(text); } public ShimMe(string parameter) { var text = $"Constructor: {parameter}"; //Debug.WriteLine(text); } public string PublicInstance() { var text = "PublicInstance"; //Debug.WriteLine(text); PublicStatic(); var test = PublicStaticParameters("what"); //Debug.WriteLine($"Let us see: {test}"); return $"xxx {test} yyy"; } public string PublicInstanceParameters(string parameter) { var text = $"PublicInstanceParameters: {parameter}"; //Debug.WriteLine(text); return text; } public ShimMeDependency PublicInstanceReturnsDependency() { return new ShimMeDependency(); } public static void PublicStatic() { var text = "PublicStatic"; //Debug.WriteLine(text); } public static string PublicStaticParameters(string parameter) { var text = $"PublicStaticParameters: {parameter}"; //Debug.WriteLine(text); return text; } private int _privateField = int.MaxValue; public int PublicProperty { get { //Debug.WriteLine($"Value from getter: {_privateField}"); return _privateField; } set { //Debug.WriteLine($"Input to setter: {value}"); _privateField = value; } } private string _privateField2; public string PublicProperty2 { get { //Debug.WriteLine($"Value from getter: {_privateField2}"); return _privateField2; } set { //Debug.WriteLine($"Input to setter: {value}"); _privateField2 = value; } } public string PublicProperty3 => "let's see here"; internal string PublicProperty4 => "a test of internals"; } }
namespace PiaSharp.Core.Objects { public class PaletteCluster { public int First { get; } public int Second { get; } public int Length { get; } public PaletteCluster(int first) { First = first; Second = int.MaxValue; Length = 1; } public PaletteCluster(int first, int second) { First = first; Second = second; Length = 2; } } }
using System.Drawing; namespace RicardoGaefke.QrCode { public interface ICode { Bitmap GetImage(string link); } }
using Newtonsoft.Json; namespace PddOpenSdk.Models.Response.Voucher { public partial class AddVoucherVirtualCardBatchResponseModel : PddResponseModel { /// <summary> /// 响应体 /// </summary> [JsonProperty("response")] public ResponseResponseModel Response { get; set; } public partial class ResponseResponseModel : PddResponseModel { /// <summary> /// 状态码 /// </summary> [JsonProperty("code")] public int? Code { get; set; } /// <summary> /// 错误信息 /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// 响应信息 /// </summary> [JsonProperty("result")] public ResultResponseModel Result { get; set; } public partial class ResultResponseModel : PddResponseModel { /// <summary> /// 卡密批次Id /// </summary> [JsonProperty("batchId")] public long? BatchId { get; set; } /// <summary> /// 充值地址 /// </summary> [JsonProperty("chargeAddress")] public string ChargeAddress { get; set; } /// <summary> /// 店铺Id /// </summary> [JsonProperty("mallId")] public long? MallId { get; set; } /// <summary> /// 批次添加的卡密数量 /// </summary> [JsonProperty("totalNum")] public int? TotalNum { get; set; } } } } }
using System; namespace MyLab3 { public class Reader { public virtual int reader_id { get; set; } public virtual string ReaderName { get; set; } public virtual string ReaderAddress { get; set; } public virtual DateTime ReaderDob { get; set; } } public class ReaderManipulations { public static void Insert(string readerName, string address, string readerDob) { using (var session = DbHelper.OpenSession()) { var readerEntity = new Reader() { ReaderName = readerName, ReaderAddress = address, ReaderDob = DateTime.Parse(readerDob), }; session.Save(readerEntity); session.Flush(); session.Close(); } } public static void Update(int id, string newReaderName , string newAddress, string newDob) { using (var session = DbHelper.OpenSession()) { var readerEntity = session.Get<Reader>(id); readerEntity.ReaderName = newReaderName; readerEntity.ReaderAddress = newAddress; readerEntity.ReaderDob = DateTime.Parse(newDob); session.Update(readerEntity); session.Flush(); session.Close(); } } public static void Delete(int id) { using (var session = DbHelper.OpenSession()) { session.Delete(session.Get<Reader>(id)); session.Flush(); session.Close(); } } } }
using System; using System.Collections.Generic; namespace CnGalWebSite.DataModel.ExamineModel { public class EntryImages { public List<EntryImage> Images { get; set; } } public class EntryImage { public string Url { get; set; } public string Note { get; set; } public string Modifier { get; set; } public bool IsDelete { get; set; } } }
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Supreme.Forms { public partial class FormKeyDetect : Form { public IContract contrato { get; set; } public FormKeyDetect() { InitializeComponent(); TopMost = true; } //DLL IMPORTS & VARIABLES [DllImport("user32.DLL", EntryPoint = "ReleaseCapture")] private extern static void ReleaseCapture(); [DllImport("user32.DLL", EntryPoint = "SendMessage")] private extern static void SendMessage(System.IntPtr hwnd, int wmsg, int wparam, int lparam); string keyPressed; //This command send the key pressed to formBinds throw IContract //contrato.Ejecutar(keyPressed); private void panel1_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); SendMessage(this.Handle, 0x112, 0xf012, 0); } private void ESC_Click(object sender, EventArgs e) { keyPressed = "Esc"; contrato.Ejecutar(keyPressed); Close(); } private void F1_Click(object sender, EventArgs e) { keyPressed = "F1"; contrato.Ejecutar(keyPressed); Close(); } private void F2_Click(object sender, EventArgs e) { keyPressed = "F2"; contrato.Ejecutar(keyPressed); Close(); } private void F3_Click(object sender, EventArgs e) { keyPressed = "F3"; contrato.Ejecutar(keyPressed); Close(); } private void F4_Click(object sender, EventArgs e) { keyPressed = "F4"; contrato.Ejecutar(keyPressed); Close(); } private void F5_Click(object sender, EventArgs e) { keyPressed = "F5"; contrato.Ejecutar(keyPressed); Close(); } private void F6_Click(object sender, EventArgs e) { keyPressed = "F6"; contrato.Ejecutar(keyPressed); Close(); } private void F7_Click(object sender, EventArgs e) { keyPressed = "F7"; contrato.Ejecutar(keyPressed); Close(); } private void F8_Click(object sender, EventArgs e) { keyPressed = "F8"; contrato.Ejecutar(keyPressed); Close(); } private void F9_Click(object sender, EventArgs e) { keyPressed = "F9"; contrato.Ejecutar(keyPressed); Close(); } private void F10_Click(object sender, EventArgs e) { keyPressed = "F10"; contrato.Ejecutar(keyPressed); Close(); } private void F11_Click(object sender, EventArgs e) { keyPressed = "F11"; contrato.Ejecutar(keyPressed); Close(); } private void F12_Click(object sender, EventArgs e) { keyPressed = "F12"; contrato.Ejecutar(keyPressed); Close(); } private void special1_Click(object sender, EventArgs e) { keyPressed = "`"; contrato.Ejecutar(keyPressed); Close(); } private void UNO_Click(object sender, EventArgs e) { keyPressed = "1"; contrato.Ejecutar(keyPressed); Close(); } private void DOS_Click(object sender, EventArgs e) { keyPressed = "2"; contrato.Ejecutar(keyPressed); Close(); } private void TRES_Click(object sender, EventArgs e) { keyPressed = "3"; contrato.Ejecutar(keyPressed); Close(); } private void CUATRO_Click(object sender, EventArgs e) { keyPressed = "4"; contrato.Ejecutar(keyPressed); Close(); } private void CINCO_Click(object sender, EventArgs e) { keyPressed = "5"; contrato.Ejecutar(keyPressed); Close(); } private void SEIS_Click(object sender, EventArgs e) { keyPressed = "6"; contrato.Ejecutar(keyPressed); Close(); } private void SIETE_Click(object sender, EventArgs e) { keyPressed = "7"; contrato.Ejecutar(keyPressed); Close(); } private void OCHO_Click(object sender, EventArgs e) { keyPressed = "8"; contrato.Ejecutar(keyPressed); Close(); } private void NUEVE_Click(object sender, EventArgs e) { keyPressed = "9"; contrato.Ejecutar(keyPressed); Close(); } private void DIEZ_Click(object sender, EventArgs e) { keyPressed = "0"; contrato.Ejecutar(keyPressed); Close(); } private void MINUS_Click(object sender, EventArgs e) { keyPressed = "-"; contrato.Ejecutar(keyPressed); Close(); } private void EQUALS_Click(object sender, EventArgs e) { keyPressed = "="; contrato.Ejecutar(keyPressed); Close(); } private void BACKSPACE_Click(object sender, EventArgs e) { keyPressed = "Backspace"; contrato.Ejecutar(keyPressed); Close(); } private void tab_Click(object sender, EventArgs e) { keyPressed = "Tab"; contrato.Ejecutar(keyPressed); Close(); } private void Q_Click(object sender, EventArgs e) { keyPressed = "Q"; contrato.Ejecutar(keyPressed); Close(); } private void W_Click(object sender, EventArgs e) { keyPressed = "W"; contrato.Ejecutar(keyPressed); Close(); } private void E_Click(object sender, EventArgs e) { keyPressed = "E"; contrato.Ejecutar(keyPressed); Close(); } private void R_Click(object sender, EventArgs e) { keyPressed = "R"; contrato.Ejecutar(keyPressed); Close(); } private void T_Click(object sender, EventArgs e) { keyPressed = "T"; contrato.Ejecutar(keyPressed); Close(); } private void Y_Click(object sender, EventArgs e) { keyPressed = "Y"; contrato.Ejecutar(keyPressed); Close(); } private void U_Click(object sender, EventArgs e) { keyPressed = "U"; contrato.Ejecutar(keyPressed); Close(); } private void I_Click(object sender, EventArgs e) { keyPressed = "I"; contrato.Ejecutar(keyPressed); Close(); } private void O_Click(object sender, EventArgs e) { keyPressed = "O"; contrato.Ejecutar(keyPressed); Close(); } private void P_Click(object sender, EventArgs e) { keyPressed = "P"; contrato.Ejecutar(keyPressed); Close(); } private void LBRACKET_Click(object sender, EventArgs e) { keyPressed = "["; contrato.Ejecutar(keyPressed); Close(); } private void RBRACKET_Click(object sender, EventArgs e) { keyPressed = "]"; contrato.Ejecutar(keyPressed); Close(); } private void SPECIAL2_Click(object sender, EventArgs e) { keyPressed = @"\"; contrato.Ejecutar(keyPressed); Close(); } private void ENTER_Click(object sender, EventArgs e) { keyPressed = "Enter"; contrato.Ejecutar(keyPressed); Close(); } private void COMILLA_Click(object sender, EventArgs e) { keyPressed = "'"; contrato.Ejecutar(keyPressed); Close(); } private void DOUBLEDOT_Click(object sender, EventArgs e) { keyPressed = ";"; contrato.Ejecutar(keyPressed); Close(); } private void L_Click(object sender, EventArgs e) { keyPressed = "L"; contrato.Ejecutar(keyPressed); Close(); } private void K_Click(object sender, EventArgs e) { keyPressed = "K"; contrato.Ejecutar(keyPressed); Close(); } private void J_Click(object sender, EventArgs e) { keyPressed = "J"; contrato.Ejecutar(keyPressed); Close(); } private void H_Click(object sender, EventArgs e) { keyPressed = "H"; contrato.Ejecutar(keyPressed); Close(); } private void G_Click(object sender, EventArgs e) { keyPressed = "G"; contrato.Ejecutar(keyPressed); Close(); } private void F_Click(object sender, EventArgs e) { keyPressed = "F"; contrato.Ejecutar(keyPressed); Close(); } private void D_Click(object sender, EventArgs e) { keyPressed = "D"; contrato.Ejecutar(keyPressed); Close(); } private void S_Click(object sender, EventArgs e) { keyPressed = "S"; contrato.Ejecutar(keyPressed); Close(); } private void A_Click(object sender, EventArgs e) { keyPressed = "A"; contrato.Ejecutar(keyPressed); Close(); } private void capsLock_Click(object sender, EventArgs e) { keyPressed = "CapsLock"; contrato.Ejecutar(keyPressed); Close(); } private void LSHIFT_Click(object sender, EventArgs e) { keyPressed = "Shift"; contrato.Ejecutar(keyPressed); Close(); } private void Z_Click(object sender, EventArgs e) { keyPressed = "Z"; contrato.Ejecutar(keyPressed); Close(); } private void X_Click(object sender, EventArgs e) { keyPressed = "X"; contrato.Ejecutar(keyPressed); Close(); } private void C_Click(object sender, EventArgs e) { keyPressed = "C"; contrato.Ejecutar(keyPressed); Close(); } private void V_Click(object sender, EventArgs e) { keyPressed = "V"; contrato.Ejecutar(keyPressed); Close(); } private void B_Click(object sender, EventArgs e) { keyPressed = "B"; contrato.Ejecutar(keyPressed); Close(); } private void N_Click(object sender, EventArgs e) { keyPressed = "N"; contrato.Ejecutar(keyPressed); Close(); } private void M_Click(object sender, EventArgs e) { keyPressed = "M"; contrato.Ejecutar(keyPressed); Close(); } private void COMMA_Click(object sender, EventArgs e) { keyPressed = ","; contrato.Ejecutar(keyPressed); Close(); } private void DOT_Click(object sender, EventArgs e) { keyPressed = "."; contrato.Ejecutar(keyPressed); Close(); } private void SLASH_Click(object sender, EventArgs e) { keyPressed = "/"; contrato.Ejecutar(keyPressed); Close(); } private void RSHIFT_Click(object sender, EventArgs e) { keyPressed = "RShift"; contrato.Ejecutar(keyPressed); Close(); } private void LCTRL_Click(object sender, EventArgs e) { keyPressed = "Ctrl"; contrato.Ejecutar(keyPressed); Close(); } private void LWIN_Click(object sender, EventArgs e) { MessageBox.Show("This key is not available"); } private void LALT_Click(object sender, EventArgs e) { keyPressed = "Alt"; contrato.Ejecutar(keyPressed); Close(); } private void RALT_Click(object sender, EventArgs e) { keyPressed = "RAlt"; contrato.Ejecutar(keyPressed); Close(); } private void RCTRL_Click(object sender, EventArgs e) { keyPressed = "RCtrl"; contrato.Ejecutar(keyPressed); Close(); } private void RWIN_Click(object sender, EventArgs e) { MessageBox.Show("This key is not available"); } private void MENU_Click(object sender, EventArgs e) { MessageBox.Show("This key is not available"); } private void PRTSC_Click(object sender, EventArgs e) { MessageBox.Show("This key is not available"); } private void SCRLLLCK_Click(object sender, EventArgs e) { keyPressed = "ScrollLock"; contrato.Ejecutar(keyPressed); Close(); } private void PAUSE_Click(object sender, EventArgs e) { MessageBox.Show("This key is not available"); } private void INSERT_Click(object sender, EventArgs e) { keyPressed = "ins"; contrato.Ejecutar(keyPressed); Close(); } private void HOME_Click(object sender, EventArgs e) { keyPressed = "Home"; contrato.Ejecutar(keyPressed); Close(); } private void PAGEUP_Click(object sender, EventArgs e) { keyPressed = "pgup"; contrato.Ejecutar(keyPressed); Close(); } private void PAGEDOWN_Click(object sender, EventArgs e) { keyPressed = "pgdn"; contrato.Ejecutar(keyPressed); Close(); } private void END_Click(object sender, EventArgs e) { keyPressed = "End"; contrato.Ejecutar(keyPressed); Close(); } private void DELETE_Click(object sender, EventArgs e) { keyPressed = "del"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox4_Click(object sender, EventArgs e) { keyPressed = "space"; contrato.Ejecutar(keyPressed); Close(); } private void ARROWUP_Click(object sender, EventArgs e) { keyPressed = "uparrow"; contrato.Ejecutar(keyPressed); Close(); } private void ARROWDOWN_Click(object sender, EventArgs e) { keyPressed = "downarrow"; contrato.Ejecutar(keyPressed); Close(); } private void ARROWLEFT_Click(object sender, EventArgs e) { keyPressed = "leftarrow"; contrato.Ejecutar(keyPressed); Close(); } private void ARROWRIGHT_Click(object sender, EventArgs e) { keyPressed = "rightarrow"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox3_Click(object sender, EventArgs e) { keyPressed = "NumLock"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox1_Click(object sender, EventArgs e) { keyPressed = "kp_slash"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox5_Click(object sender, EventArgs e) { keyPressed = "kp_multiply"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox7_Click(object sender, EventArgs e) { keyPressed = "kp_minus"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox8_Click(object sender, EventArgs e) { keyPressed = "kp_home"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox9_Click(object sender, EventArgs e) { keyPressed = "kp_uparrow"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox10_Click(object sender, EventArgs e) { keyPressed = "kp_pgup"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox13_Click(object sender, EventArgs e) { keyPressed = "kp_leftarrow"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox12_Click(object sender, EventArgs e) { keyPressed = "kp_5"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox11_Click(object sender, EventArgs e) { keyPressed = "kp_rightarrow"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox16_Click(object sender, EventArgs e) { keyPressed = "kp_end"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox15_Click(object sender, EventArgs e) { keyPressed = "kp_downarrow"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox14_Click(object sender, EventArgs e) { keyPressed = "kp_pgdn"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox18_Click(object sender, EventArgs e) { keyPressed = "kp_ins"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox17_Click(object sender, EventArgs e) { keyPressed = "kp_del"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox20_Click(object sender, EventArgs e) { keyPressed = "kp_enter"; contrato.Ejecutar(keyPressed); Close(); } private void pictureBox19_Click(object sender, EventArgs e) { keyPressed = "kp_plus"; contrato.Ejecutar(keyPressed); Close(); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters { public class ECGost3410Parameters : ECNamedDomainParameters { private readonly DerObjectIdentifier _publicKeyParamSet; private readonly DerObjectIdentifier _digestParamSet; private readonly DerObjectIdentifier _encryptionParamSet; public DerObjectIdentifier PublicKeyParamSet { get { return _publicKeyParamSet; } } public DerObjectIdentifier DigestParamSet { get { return _digestParamSet; } } public DerObjectIdentifier EncryptionParamSet { get { return _encryptionParamSet; } } public ECGost3410Parameters( ECNamedDomainParameters dp, DerObjectIdentifier publicKeyParamSet, DerObjectIdentifier digestParamSet, DerObjectIdentifier encryptionParamSet) : base(dp.Name, dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()) { this._publicKeyParamSet = publicKeyParamSet; this._digestParamSet = digestParamSet; this._encryptionParamSet = encryptionParamSet; } public ECGost3410Parameters(ECDomainParameters dp, DerObjectIdentifier publicKeyParamSet, DerObjectIdentifier digestParamSet, DerObjectIdentifier encryptionParamSet) : base(publicKeyParamSet, dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()) { this._publicKeyParamSet = publicKeyParamSet; this._digestParamSet = digestParamSet; this._encryptionParamSet = encryptionParamSet; } } } #pragma warning restore #endif
namespace BallsGame.Models.Balls { [System.Serializable] public class BallSetup { public SpeedRange speed; public DamageRange damage; public SizeRange size; public PriceRange price; } [System.Serializable] public class SpeedRange { public float min = 1; public float max = 2; public float accleration = 0.5f; } [System.Serializable] public class DamageRange { public int min = 1; public int max = 2; } [System.Serializable] public class SizeRange { public float min = 1; public float max = 2; } [System.Serializable] public class PriceRange { public int min = 1; public int max = 2; } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; namespace Gameye.Sdk { public class StatisticsStore { private StatisticsState statisticsState; /// <summary> /// Triggered when a statistics subsciption receieves new events /// </summary> public Action<StatisticsState> OnChange { get; set; } internal StatisticsStore() { statisticsState = StatisticsState.WithStatistics(new PatchDocument()); } internal void Dispatch(string json) { if (!string.IsNullOrWhiteSpace(json)) { var actions = JArray.Parse(json); statisticsState = StatisticsReducer.Reduce(statisticsState, actions); OnChange?.Invoke(statisticsState); } } } }
using GalaSoft.MvvmLight.Messaging; using SIL.Cog.Domain; namespace SIL.Cog.Application.ViewModels { public class PerformingComparisonMessage : MessageBase { private readonly VarietyPair _varietyPair; public PerformingComparisonMessage(VarietyPair varietyPair = null) { _varietyPair = varietyPair; } public VarietyPair VarietyPair { get { return _varietyPair; } } } }
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore; using System; using VRT.Resume.Domain.Entities; using VRT.Resume.Persistence.Data; #nullable disable namespace VRT.Resume.Persistence.Data.Configurations { public class PersonExperienceDutyConfiguration : IEntityTypeConfiguration<PersonExperienceDuty> { public void Configure(EntityTypeBuilder<PersonExperienceDuty> entity) { entity.HasKey(e => e.DutyId); entity.ToTable("PersonExperienceDuty", "Persons"); entity.HasComment("Contains information about person duties for the experience entitty"); entity.HasIndex(e => e.ExperienceId, "IX_PersonExperienceDuty_ExperienceId"); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(255); entity.HasOne(d => d.Experience) .WithMany(p => p.PersonExperienceDuty) .HasForeignKey(d => d.ExperienceId) .HasConstraintName("FK_PersonExperienceDuty_PersonExperience"); } } }
using System.Threading.Tasks; using Apocryph.Dao.Bot.Message; using Apocryph.Dao.Bot.Tests.Fixtures; using Apocryph.Dao.Bot.Validators; using FluentAssertions; using FluentValidation.TestHelper; using Nethereum.Web3; using NUnit.Framework; namespace Apocryph.Dao.Bot.Tests.Validators { [TestFixture] public class IntroInquiryValidatorTests { private InMemoryState _state; private IntroInquiryValidator _validator; private string _address = "0x699608158E4B13f98ad99EAb5Ccd65d2bfc2a333"; private string _userName = "TestUser"; private ulong _userId = 1000L; [SetUp] public void Setup() { _state = new InMemoryState(); _validator = new IntroInquiryValidator( _state, new Web3()); } [Test] public void Returns_Error_When_Address_NotValid() { // arrange & act var result = _validator.TestValidate(new IntroInquiryMessage(_userName, _userId, _address)); // assert result.ShouldHaveValidationErrorFor(person => person.Address); result.Errors.Count.Should().Be(1); } [Test] public async Task Returns_Error_When_Address_NotAvailable() { // arrange & act await _state.RegisterAddress(10L, _address); var result = _validator.TestValidate(new IntroInquiryMessage(_userName, _userId, _address)); // assert result.ShouldHaveValidationErrorFor(person => person.Address); result.Errors.Count.Should().Be(2); } [Test] public async Task Returns_Error_When_Address_ConfirmedAlready() { // arrange & act await _state.RegisterAddress(_userId, _address); await _state.SignAddress(_userId, _address); var result = _validator.TestValidate(new IntroInquiryMessage(_userName, _userId, _address)); // assert result.ShouldHaveValidationErrorFor(person => person.Address); result.Errors.Count.Should().Be(2); } } }
using System; using Wisej.Web; using MvvmFx.Bindings.Data; using MvvmFx.Bindings.Input; //using BoundCommand = MvvmFx.Bindings.Input.BoundCommand; //using Binding = MvvmFx.Bindings.Data.Binding; namespace EventBinding.WisejWeb { public partial class MainForm : Form { private BoundCommand _saveCommandButton; private BoundCommand _saveCommandToolStrip; private BoundCommand _closeComamand; private string _text = string.Empty; public string FullNameText { get { return _text; } set { if (_text != value) { _text = value; _saveCommandButton.RaiseCanExecuteChanged(); _saveCommandToolStrip.RaiseCanExecuteChanged(); } } } public bool FullNameTextLength { get { return FullNameText.Length > 0; } } private bool _saved; public bool Saved { get { return _saved; } set { if (_saved != value) { _saved = value; _closeComamand.RaiseCanExecuteChanged(); } } } public MainForm() { InitializeComponent(); Load += OnLoad; } private void OnLoad(object sender, EventArgs eventArgs) { try { var commandBindingManager = new CommandBindingManager(); var commandBinding = new CommandBinding(); _saveCommandButton = new BoundCommand(SaveMessage, CanSave, "Button"); commandBinding.SourceObject = Save; commandBinding.SourceEvent = ControlEvent.Click.ToString(); commandBinding.Command = _saveCommandButton; commandBindingManager.CommandBindings.Add(commandBinding); _saveCommandToolStrip = new BoundCommand(SaveMessage, CanSave, "ToolStrip"); commandBindingManager.CommandBindings.Add(new CommandBinding(_saveCommandToolStrip, Tool, ToolStripItemEvent.Click.ToString())); _closeComamand = new BoundCommand(Close, CanClose, null); commandBindingManager.CommandBindings.Add(new CommandBinding(_closeComamand, CloseForm, ControlEvent.Click.ToString())); var bindingManager = new BindingManager(); bindingManager.Bindings.Add(new TypedBinding<MainForm, TextBox>(this, t => t.FullNameText, FullName, s => s.Text)); } catch (Exception e) { MessageBox.Show(e.Message); } } private bool CanSave(object parameter) { return _text != string.Empty; } private void SaveMessage(object parameter) { FullName.Text += " " + parameter; MessageBox.Show(parameter + " control triggered", "Command", MessageBoxButtons.OK, MessageBoxIcon.Information); Saved = true; } private bool CanClose(object parameter) { return _saved; } private void Close(object parameter) { Close(); } } }
using CRM.Common.Models; using System; using System.Collections.Generic; using System.Text; namespace CRM.Common.Interfaces { public interface ICRMRepository { IEnumerable<ClientType> GetClientTypes(); void AddClient(Client client); Client GetClientById(string Id); IEnumerable<Line> GetLinesByClientId(string Id); void SendCall(Call call); void SendCall(SMS sMS); IEnumerable<Client> GetClients(); } }
using System; using System.Collections.Generic; using System.Windows.Forms; using log4net; namespace DSIS.Utils { public class Disposables : IDisposable { private readonly List<IDisposable> myDisposables = new List<IDisposable>(); private static readonly ILog LOG = LogManager.GetLogger(typeof(Disposables)); public void Add(IDisposable disp) { if (disp != null) { lock (myDisposables) { myDisposables.Add(disp); } } } public void Dispose() { IDisposable[] disposables; lock(myDisposables) { disposables = myDisposables.ToArray(); myDisposables.Clear(); } foreach (var disposable in disposables) { try { disposable.Dispose(); } catch (Exception e) { LOG.Warn("Failed to dispose " + disposable.GetType(), e); } } } } public static class DisposablesHelpers { public static void Add(this Disposables disp, Action init, Action dispose) { init(); disp.Add(new DisposableWrapper(() => dispose())); } public static void AddEvent<E>(this Disposables disp, E handler, Action<E> subscrbe, Action<E> unsubscribe) { subscrbe(handler); disp.Add(new DisposableWrapper(() => unsubscribe(handler))); } public static void Subscribe(this Disposables disp, Control control) { control.Disposed += delegate { disp.Dispose(); }; } } }
using InfixExpressionCalculator.Library; Console.WriteLine("When done, enter 'exit' to quit the calculator."); while (true) { string output; try { Console.Write("Enter an infix expression: "); string input = Console.ReadLine(); if (input.ToLower().Equals("exit")) break; output = Calculator.EvaluateInfix(input).ToString(); } catch (Exception e) { output = $"Invalid expression: {e.Message}"; } Console.WriteLine($"=> {output}\n"); }
using Wyam.Common.Execution; using Wyam.Common.Modules; using Wyam.Core.Modules.IO; namespace Wyam.Web.Pipelines { /// <summary> /// Processes any Sass stylesheets and outputs the resulting CSS files. /// </summary> public class Sass : Pipeline { /// <summary> /// Create the pipeline. /// </summary> /// <param name="name">The name of this pipeline.</param> public Sass(string name) : this(name, new[] { "**/{!.git,}/**/{!_,}*.scss" }) { } /// <summary> /// Create the pipeline. /// </summary> /// <param name="name">The name of this pipeline.</param> /// <param name="patterns">The patterns of Sass files to read.</param> public Sass(string name, string[] patterns) : base(name, GetModules(patterns)) { } private static IModuleList GetModules(string[] patterns) => new ModuleList { new ReadFiles(patterns), new Wyam.Sass.Sass(), new WriteFiles() }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Komaci.Core.Util { internal static class ErrorMessages { internal static readonly string LoopsNotAllowed = "loops are not allowed"; internal static readonly string VertexNotInGraph = "no such vertex in graph"; } }
#if LEGACY using Excel; #endif namespace ExcelDataReader.Portable.Core.BinaryFormat { /// <summary> /// Represents Dimensions of worksheet /// </summary> internal class XlsBiffDimensions : XlsBiffRecord { private bool isV8 = true; internal XlsBiffDimensions(byte[] bytes, uint offset, ExcelBinaryReader reader) : base(bytes, offset, reader) { } /// <summary> /// Gets or sets if BIFF8 addressing is used /// </summary> public bool IsV8 { get { return isV8; } set { isV8 = value; } } /// <summary> /// Index of first row /// </summary> public uint FirstRow { get { return (isV8) ? base.ReadUInt32(0x0) : base.ReadUInt16(0x0); } } /// <summary> /// Index of last row + 1 /// </summary> public uint LastRow { get { return (isV8) ? base.ReadUInt32(0x4) : base.ReadUInt16(0x2); } } /// <summary> /// Index of first column /// </summary> public ushort FirstColumn { get { return (isV8) ? base.ReadUInt16(0x8) : base.ReadUInt16(0x4); } } /// <summary> /// Index of last column + 1 /// </summary> public ushort LastColumn { get { return (isV8) ? (ushort)((base.ReadUInt16(0x9) >> 8) + 1) : base.ReadUInt16(0x6); } set { throw new System.NotImplementedException(); } } } }
using System; namespace Aggregates.Exceptions { /// <summary> /// Used by conflict resolvers to indicate that the resolution has failed and the command needs to be retried /// </summary> public class AbandonConflictException :Exception { public AbandonConflictException() { } public AbandonConflictException(string message) : base(message) { } } }
using System.Runtime.CompilerServices; using Xunit; namespace Snapper.Tests { public class SnapperInlineSnapshotTests { [Fact] [MethodImpl(MethodImplOptions.NoInlining)] public void SnapshotsMatch_PassInObject() { var snapshot = new { TestValue = "value" }; snapshot.ShouldMatchInlineSnapshot(new { TestValue = "value" }); } [Fact] [MethodImpl(MethodImplOptions.NoInlining)] public void SnapshotsMatch_PassInStringObject() { var snapshot = new { TestValue = "value" }; snapshot.ShouldMatchInlineSnapshot(@" { 'TestValue' : 'value' }"); } [Fact] [MethodImpl(MethodImplOptions.NoInlining)] public void SnapshotsMatch_PassInString() { const string snapshot = "Snapshot"; snapshot.ShouldMatchInlineSnapshot("Snapshot"); } } }
using System.ComponentModel; namespace LinqAn.Google.Metrics { /// <summary> /// The number of AdSense ads viewed. Multiple ads can be displayed within an Ad Unit. /// </summary> [Description("The number of AdSense ads viewed. Multiple ads can be displayed within an Ad Unit.")] public class AdsenseAdsViewed: Metric<int> { /// <summary> /// Instantiates a <seealso cref="AdsenseAdsViewed" />. /// </summary> public AdsenseAdsViewed(): base("AdSense Impressions",true,"ga:adsenseAdsViewed") { } } }
 namespace AwgTestFramework { public partial class CPi70KCmds { // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:SETADDress set the address of the GPIB adapter device<para> /// Note: Set command differs from Query, uses SETADDress instead of ADDress@n</para> /// </summary> /// <param name="address">Address of the GPIB adapter device</param> public void SetAwgGPIBUsbAddress(int address) { string commandLine = "GPIBUsb:SETADDress " + address; _mAWGVisaSession.Write(commandLine); } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:ADDress? get the address of the GPIB adapter device /// </summary> /// <returns>Address of the GPIB adapter device</returns> public string GetAwgGPIBUsbAddress() { string response; const string commandLine = "GPIBUsb:ADDress?"; _mAWGVisaSession.Query(commandLine, out response); return response; } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:HWVersion set the hardware version of the GPIB adapter device /// </summary> /// <param name="hwVersion">Hardware version of the GPIB adapter device</param> public void SetAwgGPIBUsbHwVersion(string hwVersion) { string commandLine = "GPIBUsb:HWVersion " + _mPiUtility.Quotify(hwVersion); _mAWGVisaSession.Write(commandLine); } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:HWVersion? get the hardware version of the GPIB adapter device /// </summary> /// <returns>Hardware version of the GPIB adapter device</returns> public string GetAwgGPIBUsbHwVersion() { string response; const string commandLine = "GPIBUsb:HWVersion?"; _mAWGVisaSession.Query(commandLine, out response); return response; } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:SETID set the ID of the GPIB adapter device<para> /// Note: Set command differs from Query, uses SETID instead of ID@n</para> /// </summary> /// <param name="id">ID of the GPIB adapter device</param> public void SetAwgGPIBUsbId(string id) { string commandLine = "GPIBUsb:SETID " + _mPiUtility.Quotify(id); _mAWGVisaSession.Write(commandLine); } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:ID? get the ID of the GPIB adapter device /// /// </summary> /// <returns>ID of the GPIB adapter device</returns> public string GetAwgGPIBUsbId() { string response; const string commandLine = "GPIBUsb:ID?"; _mAWGVisaSession.Query(commandLine, out response); return response; } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:STATus set the status of the GPIB adapter device /// </summary> /// <param name="status">Status of the GPIB adapter device</param> public void SetAwgGpibUsbStatus(string status) { string commandLine = "GPIBUsb:STATus " + _mPiUtility.Quotify(status); _mAWGVisaSession.Write(commandLine); } // glennj 7/23/2013 /// <summary> /// Using GPIBUsb:STATus? get the status of the GPIB adapter device /// </summary> /// <returns>Status of the GPIB adapter device</returns> public string GetAwgGpibUsbStatus() { string response; const string commandLine = "GPIBUsb:STATus?"; _mAWGVisaSession.Query(commandLine, out response); return response; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Panoukos41.Helpers.Services { public partial class PermissionsService : IPermissionsService { private Task<bool> PlatformHasPermission(string permission) => throw new PlatformNotSupportedException(".Net Standard is not supported."); private Task<IDictionary<string, bool>> PlatformHasPermission(params string[] permissions) => throw new PlatformNotSupportedException(".Net Standard is not supported."); private Task<bool> PlatformRequestPermission(string permission) => throw new PlatformNotSupportedException(".Net Standard is not supported."); private Task<IDictionary<string, bool>> PlatformRequestPermission(params string[] permissions) => throw new PlatformNotSupportedException(".Net Standard is not supported."); } }
using MelonLoader; namespace Bitzophrenia { namespace Actions { public class KillSpaceMonkey : Bitzophrenia.Actions.AbstractAction { private Bitzophrenia.Twitch.TwitchIRCClient ircClient; public KillSpaceMonkey(Bitzophrenia.Phasma.Global phasmophobia, Bitzophrenia.Twitch.TwitchIRCClient withIRCClient) : base("Instant kill Space Monkey.", phasmophobia) { this.ircClient = withIRCClient; } public override void Execute() { MelonLogger.Msg("Execuing KillSpaceMonkey"); if (!this.Phasmophobia().HasMissionStarted()) { this.ircClient.SendPrivateMessage("The investigation has not started yet."); return; } try { var players = this.Phasmophobia() ?.GetGameController() ?.ListPlayers(); if (players != null) { foreach(var player in players) { if (player.getNickName() .ToLower() .Contains("space")) { player.Kill(); this.ircClient.SendPrivateMessage("Chat has decreed that Space Moneky's time has come."); return; } } } } catch { } } } } }
using System; namespace Game.Online { [Serializable] public class Player { public string Username { get; } public uint Id { get; } //TODO: List of players in ConnProvider; public bool IsLocal { get; } public Player(string username, uint id, bool isLocal) { Username = username; Id = id; IsLocal = isLocal; } } }
using System; using System.Collections.Generic; using System.Text; namespace Ceras.ImmutableCollections { using System.Collections.Immutable; using Formatters; using Resolvers; public sealed class ImmutableCollectionFormatterResolver : IFormatterResolver { readonly Dictionary<Type, Type> _typeToFormatterType = new Dictionary<Type, Type> { [typeof(ImmutableArray<>)] = typeof(ImmutableArrayFormatter<>), [typeof(ImmutableDictionary<,>)] = typeof(ImmutableDictionaryFormatter<,>), [typeof(ImmutableHashSet<>)] = typeof(ImmutableHashSetFormatter<>), [typeof(ImmutableList<>)] = typeof(ImmutableListFormatter<>), [typeof(ImmutableQueue<>)] = typeof(ImmutableQueueFormatter<>), [typeof(ImmutableSortedDictionary<,>)] = typeof(ImmutableSortedDictionaryFormatter<,>), [typeof(ImmutableSortedSet<>)] = typeof(ImmutableSortedSetFormatter<>), [typeof(ImmutableStack<>)] = typeof(ImmutableStackFormatter<>), }; public IFormatter GetFormatter(Type type) { if(type.Assembly != typeof(System.Collections.Immutable.ImmutableArray).Assembly) return null; if(type.IsGenericType) if (_typeToFormatterType.TryGetValue(type.GetGenericTypeDefinition(), out var formatterType)) { var genericArgs = type.GetGenericArguments(); formatterType = formatterType.MakeGenericType(genericArgs); return (IFormatter)Activator.CreateInstance(formatterType); } return null; } public static void ApplyToConfig(SerializerConfig config) { var immutableResolver = new ImmutableCollectionFormatterResolver(); config.OnResolveFormatter.Add((c, t) => immutableResolver.GetFormatter(t)); } } public static class CerasImmutableExtension { public static void UseImmutableFormatters(this SerializerConfig config) { ImmutableCollectionFormatterResolver.ApplyToConfig(config); } } }
namespace Nest { public partial interface INodesInfoRequest { } public partial class NodesInfoRequest { } [DescriptorFor("NodesInfo")] public partial class NodesInfoDescriptor { } }
using Logshark.Config; using System; namespace Logshark.RequestModel.Config { /// <summary> /// Contains configuration information for various Logshark Local MongoDB options. /// </summary> public class LogsharkLocalMongoOptions { public bool AlwaysUseLocalMongo { get; protected set; } public bool PurgeLocalMongoOnStartup { get; protected set; } public LogsharkLocalMongoOptions(LocalMongoOptions configLocalMongoOptions) { AlwaysUseLocalMongo = configLocalMongoOptions.UseAlways; PurgeLocalMongoOnStartup = configLocalMongoOptions.PurgeOnStartup; } public override string ToString() { return String.Format("AlwaysUseLocalMongo:{0}, PurgeLocalMongoOnStartup:{1}", AlwaysUseLocalMongo, PurgeLocalMongoOnStartup); } } }
using System.Threading.Tasks; using FakeItEasy; using MailCheck.Common.Contracts.Messaging; using MailCheck.Common.Messaging.Abstractions; using MailCheck.Spf.Contracts.Entity; using MailCheck.Spf.Contracts.Scheduler; using MailCheck.Spf.Scheduler.Config; using MailCheck.Spf.Scheduler.Dao; using MailCheck.Spf.Scheduler.Dao.Model; using MailCheck.Spf.Scheduler.Handler; using Microsoft.Extensions.Logging; using NUnit.Framework; namespace MailCheck.Spf.Scheduler.Test.Handler { [TestFixture] public class SpfSchedulerHandlerTests { private SpfSchedulerHandler _sut; private ISpfSchedulerDao _dao; private IMessageDispatcher _dispatcher; private ISpfSchedulerConfig _config; private ILogger<SpfSchedulerHandler> _log; [SetUp] public void SetUp() { _dao = A.Fake<ISpfSchedulerDao>(); _dispatcher = A.Fake<IMessageDispatcher>(); _config = A.Fake<ISpfSchedulerConfig>(); _log = A.Fake<ILogger<SpfSchedulerHandler>>(); _sut = new SpfSchedulerHandler(_dao, _dispatcher, _config, _log); } [Test] public async Task ItShouldSaveAndDispatchTheSpfStateIfItDoesntExist() { A.CallTo(() => _dao.Get(A<string>._)).Returns<SpfSchedulerState>(null); await _sut.Handle(new SpfEntityCreated("ncsc.gov.uk", 1)); A.CallTo(() => _dao.Save(A<SpfSchedulerState>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _dispatcher.Dispatch(A<SpfRecordExpired>._, A<string>._)) .MustHaveHappenedOnceExactly(); } [Test] public async Task ItShouldNotSaveOrDispatchTheSpfStateIfItExists() { A.CallTo(() => _dao.Get(A<string>._)).Returns(new SpfSchedulerState("ncsc.gov.uk")); await _sut.Handle(new SpfEntityCreated("ncsc.gov.uk", 1)); A.CallTo(() => _dao.Save(A<SpfSchedulerState>._)).MustNotHaveHappened(); A.CallTo(() => _dispatcher.Dispatch(A<SpfRecordExpired>._, A<string>._)) .MustNotHaveHappened(); } [Test] public async Task ItShouldDeleteTheSpfState() { await _sut.Handle(new DomainDeleted("ncsc.gov.uk")); A.CallTo(() => _dao.Delete(A<string>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _dispatcher.Dispatch(A<Message>._, A<string>._)) .MustNotHaveHappened(); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; namespace JabbR_Core.Data.Models { public partial class JabbrContext : IdentityDbContext<ChatUser> { public JabbrContext(DbContextOptions<JabbrContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Attachment>(entity => { entity.HasKey(e => e.Key) .HasName("PK_dbo.Attachments"); entity.HasIndex(e => e.OwnerId) .HasName("IX_OwnerKey"); entity.HasIndex(e => e.RoomKey) .HasName("IX_RoomKey"); entity.Property(e => e.Size).HasDefaultValueSql("0"); entity.HasOne(d => d.OwnerKeyNavigation) .WithMany(p => p.Attachments) .HasForeignKey(d => d.OwnerId) .HasConstraintName("FK_dbo.Attachments_dbo.ChatUsers_OwnerKey"); entity.HasOne(d => d.RoomKeyNavigation) .WithMany(p => p.Attachments) .HasForeignKey(d => d.RoomKey) .HasConstraintName("FK_dbo.Attachments_dbo.ChatRooms_RoomKey"); }); modelBuilder.Entity<ChatClient>(entity => { entity.HasKey(e => e.Key) .HasName("PK_ChatClients"); entity.Property(e => e.LastActivity).HasDefaultValueSql("'0001-01-01T00:00:00.000+00:00'"); entity.Property(e => e.LastClientActivity).HasDefaultValueSql("'0001-01-01T00:00:00.000+00:00'"); entity.Property(e => e.UserId).HasColumnName("User_Key"); entity.HasOne(d => d.UserKeyNavigation) .WithMany(p => p.ConnectedClients) .HasForeignKey(d => d.UserId) .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<ChatMessage>(entity => { entity.HasKey(e => e.Key) .HasName("PK_ChatMessages"); entity.Property(e => e.HtmlEncoded).HasDefaultValueSql("1"); entity.Property(e => e.MessageType).HasDefaultValueSql("0"); entity.Property(e => e.RoomKey).HasColumnName("Room_Key"); entity.Property(e => e.UserId).HasColumnName("User_Key"); entity.HasOne(d => d.RoomKeyNavigation) .WithMany(p => p.ChatMessages) .HasForeignKey(d => d.RoomKey); entity.HasOne(d => d.UserKeyNavigation) .WithMany(p => p.ChatMessages) .HasForeignKey(d => d.UserId); }); modelBuilder.Entity<ChatPrivateRoomUsers>(entity => { entity.HasKey(e => new { e.ChatRoomKey, e.ChatUserId }) .HasName("PK_ChatPrivateRoomUsers"); entity.Property(e => e.ChatRoomKey).HasColumnName("ChatRoom_Key"); entity.Property(e => e.ChatUserId).HasColumnName("ChatUser_Key"); entity.HasOne(d => d.ChatRoomKeyNavigation) .WithMany(p => p.AllowedUsers) .HasForeignKey(d => d.ChatRoomKey) .OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.ChatUserKeyNavigation) .WithMany(p => p.AllowedRooms) .HasForeignKey(d => d.ChatUserId) .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<ChatRoomOwners>(entity => { entity.HasKey(e => new { e.ChatRoomKey, e.ChatUserId }) .HasName("PK_ChatRoomOwners"); entity.Property(e => e.ChatRoomKey).HasColumnName("ChatRoom_Key"); entity.Property(e => e.ChatUserId).HasColumnName("ChatUser_Key"); entity.HasOne(d => d.ChatRoomKeyNavigation) .WithMany(p => p.Owners) .HasForeignKey(d => d.ChatRoomKey) .OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.ChatUserKeyNavigation) .WithMany(p => p.OwnedRooms) .HasForeignKey(d => d.ChatUserId) .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<ChatRoom>(entity => { entity.HasKey(e => e.Key) .HasName("PK_ChatRooms"); entity.HasIndex(e => e.Name) .HasName("IX_Name") .IsUnique(); entity.Property(e => e.Closed).HasDefaultValueSql("0"); entity.Property(e => e.CreatorId); entity.Property(e => e.InviteCode).HasColumnType("nchar(6)"); entity.Property(e => e.LastNudged).HasColumnType("datetime"); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(200); entity.Property(e => e.Private).HasDefaultValueSql("0"); entity.Property(e => e.Topic).HasMaxLength(80); entity.Property(e => e.Welcome).HasMaxLength(200); entity.HasOne(d => d.CreatorKeyNavigation) .WithMany(p => p.ChatRooms) .HasForeignKey(d => d.CreatorId); }); modelBuilder.Entity<ChatRoomUsers>(entity => { entity.HasKey(e => new { e.ChatUserId, e.ChatRoomKey }) .HasName("PK_ChatRoomUsers"); entity.Property(e => e.ChatUserId).HasColumnName("ChatUser_Key"); entity.Property(e => e.ChatRoomKey).HasColumnName("ChatRoom_Key"); entity.HasOne(d => d.ChatRoomKeyNavigation) .WithMany(p => p.Users) .HasForeignKey(d => d.ChatRoomKey) .OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.ChatUserKeyNavigation) .WithMany(p => p.Rooms) .HasForeignKey(d => d.ChatUserId) .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<ChatUserIdentity>(entity => { entity.HasKey(e => e.Key) .HasName("PK_dbo.ChatUserIdentities"); entity.HasIndex(e => e.UserId) .HasName("IX_UserKey"); entity.HasOne(d => d.UserKeyNavigation) .WithMany(p => p.ChatUserIdentities) .HasForeignKey(d => d.UserId) .HasConstraintName("FK_dbo.ChatUserIdentities_dbo.ChatUsers_UserKey"); }); modelBuilder.Entity<ChatUser>(entity => { //entity.HasKey(e => e.Key) // .HasName("PK_ChatUsers"); //entity.HasIndex(e => e.Id) // .HasName("IX_Id") // .IsUnique(); entity.HasKey(e => e.Id) .HasName("PK_Id"); entity.Property(e => e.AfkNote).HasMaxLength(200); entity.Property(e => e.Flag).HasMaxLength(255); //entity.Property(e => e.Id) // .IsRequired() // .HasMaxLength(200); entity.Property(e => e.IsAdmin).HasDefaultValueSql("0"); entity.Property(e => e.IsAfk).HasDefaultValueSql("0"); entity.Property(e => e.IsBanned).HasDefaultValueSql("0"); entity.Property(e => e.LastActivity).HasColumnType("datetime"); entity.Property(e => e.LastNudged).HasColumnType("datetime"); entity.Property(e => e.Note).HasMaxLength(200); entity.Property(e => e.Status).HasDefaultValueSql("0"); }); modelBuilder.Entity<MigrationHistory>(entity => { entity.HasKey(e => new { e.MigrationId, e.ContextKey }) .HasName("PK_dbo.__MigrationHistory"); entity.ToTable("__MigrationHistory"); entity.Property(e => e.MigrationId).HasMaxLength(150); entity.Property(e => e.ContextKey).HasMaxLength(300); entity.Property(e => e.Model).IsRequired(); entity.Property(e => e.ProductVersion) .IsRequired() .HasMaxLength(32); }); modelBuilder.Entity<Notification>(entity => { entity.HasKey(e => e.Key) .HasName("PK_dbo.Notifications"); entity.HasIndex(e => e.MessageKey) .HasName("IX_MessageKey"); entity.HasIndex(e => e.RoomKey) .HasName("IX_RoomKey"); entity.HasIndex(e => e.UserId) .HasName("IX_UserKey"); entity.HasOne(d => d.MessageKeyNavigation) .WithMany(p => p.Notifications) .HasForeignKey(d => d.MessageKey) .HasConstraintName("FK_dbo.Notifications_dbo.ChatMessages_MessageKey"); entity.HasOne(d => d.RoomKeyNavigation) .WithMany(p => p.Notifications) .HasForeignKey(d => d.RoomKey) .HasConstraintName("FK_dbo.Notifications_dbo.ChatRooms_RoomKey"); entity.HasOne(d => d.UserKeyNavigation) .WithMany(p => p.Notifications) .HasForeignKey(d => d.UserId) .HasConstraintName("FK_dbo.Notifications_dbo.ChatUsers_UserKey"); }); modelBuilder.Entity<Settings>(entity => { entity.HasKey(e => e.Key) .HasName("PK_dbo.Settings"); }); } public DbSet<Attachment> Attachments { get; set; } public DbSet<ChatClient> ChatClients { get; set; } public DbSet<ChatMessage> ChatMessages { get; set; } public DbSet<ChatPrivateRoomUsers> ChatPrivateRoomUsers { get; set; } public DbSet<ChatRoomOwners> ChatRoomOwners { get; set; } public DbSet<ChatRoom> ChatRooms { get; set; } public DbSet<ChatRoomUsers> ChatRoomUsers { get; set; } public DbSet<ChatUserIdentity> ChatUserIdentities { get; set; } public DbSet<ChatUser> AspNetUsers { get; set; } public DbSet<MigrationHistory> MigrationHistory { get; set; } public DbSet<Notification> Notifications { get; set; } public DbSet<Settings> Settings { get; set; } } }
namespace WebApi.Models { public class PetItem { public int Id { get; set; } public string Nome { get; set; } public string Raca { get; set; } public string Tipo { get; set; } public string Porte { get; set; } public string Alergias { get; set; } public string Descricoes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Mono.Cecil; using NUnit.Framework; namespace NRoles.Engine.Test { public abstract class AssemblyReadonlyFixture { static AssemblyAccessor _assembly = new AssemblyAccessor(); static AssemblyReadonlyFixture() { new MutationContext(((AssemblyDefinition)_assembly).MainModule); } protected TypeDefinition GetType<T>() { return _assembly.GetType<T>(); } protected TypeDefinition GetType(Type type) { return _assembly.GetType(type); } protected ClassMember GetMethodByName(Type t, string methodName) { var type = GetType(t); var currentType = type; TypeReference typeContext = type; MethodDefinition method = null; while (currentType != null && (method = currentType.Methods.SingleOrDefault(m => m.Name == methodName)) == null) { typeContext = currentType.BaseType; currentType = typeContext == null ? null : typeContext.Resolve(); } Assert.IsNotNull(method); return new ClassMember(typeContext, method, typeContext != type); } } }
namespace InputDevicesSimulator.Native { internal enum KeyboardMessages { WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105 } }
using AdminWebsite.AcceptanceTests.Helpers; using FluentAssertions; using TechTalk.SpecFlow; namespace AdminWebsite.AcceptanceTests.Steps { [Binding] public class TestHelperSteps { private readonly TestContext _c; private readonly QuestionnaireSteps _questionnaireSteps; public TestHelperSteps(TestContext testContext, QuestionnaireSteps questionnaireSteps) { _c = testContext; _questionnaireSteps = questionnaireSteps; } [Given(@"I have (.*) hearings with questionnaire results")] public void GivenIHaveHearingsWithQuestionnaireResults(int hearingsCount) { hearingsCount.Should().BeInRange(1, 300); for (var i = 0; i < hearingsCount; i++) { _questionnaireSteps.GivenThereIsAHearingWithQuestionnaireAnswers("Individual"); } } } }
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System; using Common; using TestClasses; #if !NET35 using Xunit; #else using Fact = NUnit.Framework.TestAttribute; [NUnit.Framework.TestFixture] #endif public class WhenConvertingToDateTimes { [Fact] public void ShouldMapANullableDateTimeToADateTime() { var source = new PublicProperty<DateTime?> { Value = DateTime.Today }; var result = Mapper.Map(source).ToANew<PublicProperty<DateTime>>(); result.Value.ShouldBe(DateTime.Today); } [Fact] public void ShouldMapAYearMonthDayStringToADateTime() { var source = new PublicProperty<string> { Value = "2016/06/08" }; var result = Mapper.Map(source).ToANew<PublicProperty<DateTime>>(); result.Value.ShouldBe(new DateTime(2016, 06, 08)); } [Fact] public void ShouldMapAnUnparseableStringToANullableDateTime() { var source = new PublicProperty<string> { Value = "OOH OOH OOH" }; var result = Mapper.Map(source).ToANew<PublicProperty<DateTime?>>(); result.Value.ShouldBeNull(); } [Fact] public void ShouldMapANullObjectStringToADateTime() { var source = new PublicProperty<object> { Value = default(string) }; var result = Mapper.Map(source).ToANew<PublicProperty<DateTime>>(); result.Value.ShouldBeDefault(); } } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; using Stripe.Client.Sdk.Clients; using Stripe.Client.Sdk.Clients.Subscriptions; using Stripe.Client.Sdk.Models; using Stripe.Client.Sdk.Models.Arguments; using Stripe.Client.Sdk.Models.Filters; using System.Threading; using System.Threading.Tasks; namespace Stripe.Client.Sdk.Tests.Clients.Subscriptions { [TestClass] public class CouponClientTests { private readonly CancellationToken _cancellationToken = CancellationToken.None; private ICouponClient _client; private IStripeClient _stripe; [TestInitialize] public void Init() { _stripe = Substitute.For<IStripeClient>(); _client = new CouponClient(_stripe); } [TestMethod] public async Task GetCouponTest() { // Arrange var id = "coupon-id"; _stripe.Get(Arg.Is<StripeRequest<Coupon>>(a => a.UrlPath == "coupons/" + id), _cancellationToken) .Returns(Task.FromResult(new StripeResponse<Coupon>())); // Act var response = await _client.GetCoupon(id, _cancellationToken); // Assert response.Should().NotBeNull(); } [TestMethod] public async Task GetCouponsTest() { // Arrange var filter = new CouponListFilter(); _stripe.Get( Arg.Is<StripeRequest<CouponListFilter, Pagination<Coupon>>>( a => a.UrlPath == "coupons" && a.Model == filter), _cancellationToken) .Returns(Task.FromResult(new StripeResponse<Pagination<Coupon>>())); // Act var response = await _client.GetCoupons(filter, _cancellationToken); // Assert response.Should().NotBeNull(); } [TestMethod] public async Task CreateCouponTest() { // Arrange var args = new CouponCreateArguments(); _stripe.Post( Arg.Is<StripeRequest<CouponCreateArguments, Coupon>>(a => a.UrlPath == "coupons" && a.Model == args), _cancellationToken).Returns(Task.FromResult(new StripeResponse<Coupon>())); // Act var response = await _client.CreateCoupon(args, _cancellationToken); // Assert response.Should().NotBeNull(); } [TestMethod] public async Task UpdateCouponTest() { // Arrange var args = new CouponUpdateArguments { CouponId = "coupon-id" }; _stripe.Post( Arg.Is<StripeRequest<CouponUpdateArguments, Coupon>>( a => a.UrlPath == "coupons/" + args.CouponId && a.Model == args), _cancellationToken) .Returns(Task.FromResult(new StripeResponse<Coupon>())); // Act var response = await _client.UpdateCoupon(args, _cancellationToken); // Assert response.Should().NotBeNull(); } [TestMethod] public async Task DeleteCouponTest() { // Arrange var id = "coupon-id"; _stripe.Delete(Arg.Is<StripeRequest<DeletedObject>>(a => a.UrlPath == "coupons/" + id), _cancellationToken) .Returns(Task.FromResult(new StripeResponse<DeletedObject>())); // Act var response = await _client.DeleteCoupon(id, _cancellationToken); // Assert response.Should().NotBeNull(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rca.EzoDeviceLib.Specific.Ph { public enum CalPoint { /// <summary> /// Midrage calibration point. /// Default value is 7.00 pH /// </summary> Mid = 0, /// <summary> /// Lower calibration point. /// Default value is 4.00 pH /// </summary> Low, /// <summary> /// Upper calibration point. /// Default value is 10.00 pH /// </summary> High } }
using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Domain { /// <summary> /// InvoiceElementStatusSyncOpenModel Data Structure. /// </summary> public class InvoiceElementStatusSyncOpenModel : AlipayObject { /// <summary> /// 同步申请id,每次发起同步时生成,isv每次请求需要保证唯一 /// </summary> [JsonPropertyName("apply_id")] public string ApplyId { get; set; } /// <summary> /// 报销详情地址,提供用户通过发票管家查看报销进度的地址 如果报销企业入驻发票管家时需要isv传入报销详情地址,则必须提供 /// </summary> [JsonPropertyName("expense_detail_url")] public string ExpenseDetailUrl { get; set; } /// <summary> /// 发票代码 /// </summary> [JsonPropertyName("invoice_code")] public string InvoiceCode { get; set; } /// <summary> /// 发票号码 /// </summary> [JsonPropertyName("invoice_no")] public string InvoiceNo { get; set; } } }
namespace Weikio.ApiFramework.SDK.DatabasePlugin.CodeGeneration { public class DtoBase { public object this[string propertyName] { get { return GetType().GetProperty(propertyName).GetValue(this, null); } set { GetType().GetProperty(propertyName).SetValue(this, value, null); } } } }
using AllOverIt.Assertion; using AllOverIt.Evaluator.Variables.Extensions; using System; namespace AllOverIt.Evaluator.Variables { /// <summary>A delegate based variable that is re-evaluated each time the <see cref="Value"/> is read.</summary> /// <remarks>For a delegate based variable that is only evaluated the first time the <see cref="Value"/> is read, /// see <see cref="LazyVariable"/>.</remarks> public sealed record DelegateVariable : VariableBase { private readonly Func<double> _valueResolver; /// <summary>The current value of the variable. The value may change on each evaluation depending on how the /// delegate is implemented.</summary> public override double Value => _valueResolver.Invoke(); /// <summary>Constructor.</summary> /// <param name="name">The variable's name.</param> /// <param name="valueResolver">The delegate to invoke each time the <see cref="Value"/> is read.</param> public DelegateVariable(string name, Func<double> valueResolver) : base(name) { _valueResolver = valueResolver.WhenNotNull(nameof(valueResolver)); } /// <summary>Constructor.</summary> /// <param name="name">The variable's name.</param> /// <param name="compilerResult">The compiled result of a formula. The associated resolver will be re-evaluated /// each time the <see cref="Value"/> is read.</param> public DelegateVariable(string name, FormulaCompilerResult compilerResult) : this(name, compilerResult.Resolver) { ReferencedVariables = compilerResult.GetReferencedVariables(); } } }
// // ShipController.cs // Midnight Blue // // -------------------------------------------------------------- // // Created by Jacob Milligan on 4/10/2016. // Copyright (c) Jacob Milligan All rights reserved // using System; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Input; using MB2D.EntityComponent; using MB2D.IO; namespace MidnightBlue { /// <summary> /// Represents the current travelling state of the ship /// </summary> public enum ShipState { Normal, Landing, Launching, LeavingScreen, Warping } /// <summary> /// Controls a ships movement and actions /// </summary> public class ShipController : IComponent { /// <summary> /// The input map for the ship controller. /// Allows different input for different entities. /// </summary> private InputMap _inputMap; /// <summary> /// Initializes a new instance of the <see cref="T:MidnightBlue.ShipController"/> class /// and assigns all default input and key mappings. /// </summary> public ShipController() { _inputMap = new InputMap(); State = ShipState.Normal; IsLandable = false; _inputMap.Assign<MoveForward>(Keys.W, CommandType.Hold); _inputMap.Assign<MoveBackward>(Keys.S, CommandType.Hold); _inputMap.Assign<RotateRight>(Keys.D, CommandType.Hold); _inputMap.Assign<RotateLeft>(Keys.A, CommandType.Hold); _inputMap.Assign<MoveShip>(Keys.W, CommandType.Hold); _inputMap.Assign<MoveShip>(Keys.S, CommandType.Hold); _inputMap.Assign<EnterStarSystem>(Keys.E, CommandType.Trigger); _inputMap.Assign<LandCommand>(Keys.Space, CommandType.Trigger); _inputMap.Assign<LeaveStarSystem>(Keys.Q, CommandType.Trigger); } /// <summary> /// Gets the input map. /// </summary> /// <value>The input map.</value> public InputMap InputMap { get { return _inputMap; } } /// <summary> /// Gets or sets the current travel state of the ship. /// </summary> /// <value>The ships travelling state.</value> public ShipState State { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:MidnightBlue.ShipController"/> is able to /// be landed when the entity calls their LandCommand. /// </summary> /// <value><c>true</c> if is landable; otherwise, <c>false</c>.</value> public bool IsLandable { get; set; } } }
// Decompiled with JetBrains decompiler // Type: BlueStacks.BlueStacksUI.AppRecommendationSection // Assembly: Bluestacks, Version=4.250.0.1070, Culture=neutral, PublicKeyToken=null // MVID: 99F027F6-79F1-4BCA-896C-81F7B404BE8F // Assembly location: C:\Program Files\BlueStacks\Bluestacks.exe using Newtonsoft.Json; using System.Collections.Generic; using System.ComponentModel; namespace BlueStacks.BlueStacksUI { public class AppRecommendationSection { [JsonProperty(PropertyName = "section_header")] public string AppSuggestionHeader { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, PropertyName = "client_show_count")] [DefaultValue(3)] public int ClientShowCount { get; set; } = 3; [JsonProperty(PropertyName = "suggested_apps")] public List<AppRecommendation> AppSuggestions { get; } = new List<AppRecommendation>(); } }
using System.Collections.Generic; namespace Autodash.Core.UI.Models { public class ProjectsVm { public List<ProjectSuiteRunVm> Projects { get; set; } } public class ProjectSuiteRunVm { public Project Project { get; set; } public List<ProjectSuiteRunDetail> SuiteRuns { get; set; } } public class ProjectSuiteRunDetail { public double DurationMinutes { get; set; } public TestOutcome Outcome { get; set; } public string BgColor() { return TestOutcomeColorHelper.BgColor(Outcome); } public override string ToString() { return Outcome + ". Duration " + DurationMinutes.ToString("0.00") + " mins"; } } public static class TestOutcomeColorHelper { public static string BgColor(TestOutcome outcome) { switch (outcome) { case TestOutcome.Passed: return "bg-success"; case TestOutcome.Inconclusive: return "bg-warning"; } return "bg-danger"; } } }
using System; using TopAct.Domain.Contracts; namespace TopAct.Domain.Commanding { public record DeleteContactCommand(Guid ContactId) : CommandBase; }
using System.Collections.Generic; namespace ColladaSharp.Models { public partial class PrimitiveData { public bool HasSkinning => _utilizedBones == null ? false : _utilizedBones.Length > 0; public List<IDataBuffer> Buffers { get => _buffers; set => _buffers = value; } public InfluenceDef[] Influences { get => _influences; set => _influences = value; } public string[] UtilizedBones { get => _utilizedBones; set => _utilizedBones = value; } public List<FacePoint> FacePoints { get => _facePoints; set => _facePoints = value; } public List<IndexTriangle> Triangles { get => _triangles; set => _triangles = value; } public List<IndexLine> Lines { get => _lines; set => _lines = value; } public List<IndexPoint> Points { get => _points; set => _points = value; } public EPrimitiveType Type { get => _type; set => _type = value; } public VertexShaderDesc BufferInfo => _bufferInfo; internal string[] _utilizedBones; internal InfluenceDef[] _influences; internal VertexShaderDesc _bufferInfo; internal List<IDataBuffer> _buffers = null; internal List<FacePoint> _facePoints = null; internal List<IndexPoint> _points = null; internal List<IndexLine> _lines = null; internal List<IndexTriangle> _triangles = null; internal EPrimitiveType _type = EPrimitiveType.Triangles; } }
using System; namespace VsCodeProOne.Patterns.CompositeEntityPattern { public static class CompositeEntityPatternDemo { public static void Run() { Console.WriteLine("组合实体模式测试..."); var client = new Client(); client.SetData("Test", "John"); client.PrintData(); client.SetData("Second Test", "Data1"); client.PrintData(); Console.WriteLine("组合实体模式测试结束..."); } } }
// 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 System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; using System.Xml; using Microsoft.Templates.Core.Helpers; using WindowsTestHelpers; namespace Microsoft.Templates.Test.Build { public class BaseVisualComparisonTests : BaseGenAndBuildTests { public BaseVisualComparisonTests(GenerationFixture fixture) : base(fixture) { } protected (bool Success, List<string> TextOutput) RunWinAppDriverTests((string projectFolder, string imagesFolder) testProjectDetails) { var result = false; WinAppDriverHelper.StartIfNotRunning(); var buildOutput = Path.Combine(testProjectDetails.projectFolder, "bin", "Debug", "AutomatedUITests.dll"); var runTestsScript = $"& \"{GetVstestsConsoleExePath()}\" \"{buildOutput}\" "; // Test failures will be treated as an error but they are handled below var output = ExecutePowerShellScript(runTestsScript, outputOnError: true); var outputText = new List<string>(); var testCount = -1; var passCount = -1; foreach (var outputLine in output) { var outputLineString = outputLine.ToString(); outputText.Add(outputLineString); if (outputLineString.StartsWith("Total tests: ", StringComparison.OrdinalIgnoreCase)) { testCount = int.Parse(outputLineString.Substring(12).Trim()); } else if (outputLineString.Trim().StartsWith("Passed: ", StringComparison.OrdinalIgnoreCase)) { passCount = int.Parse(outputLineString.Trim().Substring(7).Trim()); if (testCount > 0) { result = testCount == passCount; } } } WinAppDriverHelper.StopIfRunning(); return (result, outputText); } protected (string projectFolder, string imagesFolder) SetUpTestProjectForInitialScreenshotComparison(VisualComparisonTestDetails app1Details, VisualComparisonTestDetails app2Details, string areasOfImageToExclude = null, int noClickCount = 0, bool longPause = false) { var rootFolder = $"{Path.GetPathRoot(Environment.CurrentDirectory)}UIT\\VIS\\{DateTime.Now:dd_HHmmss}\\"; var projectFolder = Path.Combine(rootFolder, "TestProject"); var imagesFolder = Path.Combine(rootFolder, "Images"); Fs.EnsureFolderExists(rootFolder); Fs.EnsureFolderExists(projectFolder); Fs.EnsureFolderExists(imagesFolder); // Copy base project Fs.CopyRecursive(@".\VisualTests\TestProjectSource", projectFolder, overwrite: true); // enable appropriate test var projFileName = Path.Combine(projectFolder, "AutomatedUITests.csproj"); var projFileContents = File.ReadAllText(projFileName); var newProjFileContents = projFileContents.Replace( @"<!--<Compile Include=""Tests\LaunchBothAppsAndCompareInitialScreenshots.cs"" />-->", @"<Compile Include=""Tests\LaunchBothAppsAndCompareInitialScreenshots.cs"" />"); File.WriteAllText(projFileName, newProjFileContents, Encoding.UTF8); // set AppInfo values var appInfoFileName = Path.Combine(projectFolder, "TestAppInfo.cs"); var appInfoFileContents = File.ReadAllText(appInfoFileName); var newAppInfoFileContents = appInfoFileContents .Replace("***APP-PFN-1-GOES-HERE***", $"{app1Details.PackageFamilyName}!App") .Replace("***APP-PFN-2-GOES-HERE***", $"{app2Details.PackageFamilyName}!App") .Replace("***APP-NAME-1-GOES-HERE***", app1Details.ProjectName) .Replace("***APP-NAME-2-GOES-HERE***", app2Details.ProjectName) .Replace("***FOLDER-GOES-HERE***", imagesFolder) .Replace("public const int NoClickCount = 0;", $"public const int NoClickCount = {noClickCount};"); if (longPause) { newAppInfoFileContents = newAppInfoFileContents.Replace("public const bool LongPauseAfterLaunch = false;", "public const bool LongPauseAfterLaunch = true;"); } if (!string.IsNullOrWhiteSpace(areasOfImageToExclude)) { newAppInfoFileContents = newAppInfoFileContents.Replace("new ImageComparer.ExclusionArea[0]", areasOfImageToExclude); } File.WriteAllText(appInfoFileName, newAppInfoFileContents, Encoding.UTF8); // build test project var restoreNugetScript = $"& \"{projectFolder}\\nuget.exe\" restore \"{projectFolder}\\AutomatedUITests.csproj\" -PackagesDirectory \"{projectFolder}\\Packages\""; ExecutePowerShellScript(restoreNugetScript); var buildSolutionScript = $"& \"{GetMsBuildExePath()}\" \"{projectFolder}\\AutomatedUITests.sln\" /t:Rebuild /p:RestorePackagesPath=\"{projectFolder}\\Packages\" /p:Configuration=Debug /p:Platform=\"Any CPU\""; ExecutePowerShellScript(buildSolutionScript); return (projectFolder, imagesFolder); } protected (string projectFolder, string imagesFolder) SetUpTestProjectForAllNavViewPagesComparison(VisualComparisonTestDetails app1Details, VisualComparisonTestDetails app2Details, Dictionary<string, string> pageAreasToExclude = null) { var rootFolder = $"{Path.GetPathRoot(Environment.CurrentDirectory)}UIT\\VIS\\{DateTime.Now:dd_HHmmss}\\"; var projectFolder = Path.Combine(rootFolder, "TestProject"); var imagesFolder = Path.Combine(rootFolder, "Images"); Fs.EnsureFolderExists(rootFolder); Fs.EnsureFolderExists(projectFolder); Fs.EnsureFolderExists(imagesFolder); // Copy base project Fs.CopyRecursive(@".\VisualTests\TestProjectSource", projectFolder, overwrite: true); // enable appropriate test var projFileName = Path.Combine(projectFolder, "AutomatedUITests.csproj"); var projFileContents = File.ReadAllText(projFileName); var newProjFileContents = projFileContents.Replace( @"<!--<Compile Include=""Tests\LaunchBothAppsAndCompareAllNavViewPages.cs"" />-->", @"<Compile Include=""Tests\LaunchBothAppsAndCompareAllNavViewPages.cs"" />"); File.WriteAllText(projFileName, newProjFileContents, Encoding.UTF8); // set AppInfo values var appInfoFileName = Path.Combine(projectFolder, "TestAppInfo.cs"); var appInfoFileContents = File.ReadAllText(appInfoFileName); var newAppInfoFileContents = appInfoFileContents .Replace("***APP-PFN-1-GOES-HERE***", $"{app1Details.PackageFamilyName}!App") .Replace("***APP-PFN-2-GOES-HERE***", $"{app2Details.PackageFamilyName}!App") .Replace("***APP-NAME-1-GOES-HERE***", app1Details.ProjectName) .Replace("***APP-NAME-2-GOES-HERE***", app2Details.ProjectName) .Replace("***FOLDER-GOES-HERE***", imagesFolder); if (pageAreasToExclude != null) { var replacement = string.Empty; foreach (var exclusion in pageAreasToExclude) { replacement += $" {{ \"{exclusion.Key}\", {exclusion.Value} }},{Environment.NewLine}"; } newAppInfoFileContents = newAppInfoFileContents.Replace( "PageSpecificExclusions = new Dictionary<string, ImageComparer.ExclusionArea>();", $"PageSpecificExclusions = new Dictionary<string, ImageComparer.ExclusionArea>{{{replacement}}};"); } File.WriteAllText(appInfoFileName, newAppInfoFileContents, Encoding.UTF8); // build test project var restoreNugetScript = $"& \"{projectFolder}\\nuget.exe\" restore \"{projectFolder}\\AutomatedUITests.csproj\" -PackagesDirectory \"{projectFolder}\\Packages\""; ExecutePowerShellScript(restoreNugetScript); var buildSolutionScript = $"& \"{GetMsBuildExePath()}\" \"{projectFolder}\\AutomatedUITests.sln\" /t:Rebuild /p:RestorePackagesPath=\"{projectFolder}\\Packages\" /p:Configuration=Debug /p:Platform=\"Any CPU\""; ExecutePowerShellScript(buildSolutionScript); return (projectFolder, imagesFolder); } protected (string projectFolder, string imagesFolder) SetUpTestProjectForAllMenuBarPagesComparison(VisualComparisonTestDetails app1Details, VisualComparisonTestDetails app2Details, Dictionary<string, string> pageAreasToExclude = null) { var rootFolder = $"{Path.GetPathRoot(Environment.CurrentDirectory)}UIT\\VIS\\{DateTime.Now:dd_HHmmss}\\"; var projectFolder = Path.Combine(rootFolder, "TestProject"); var imagesFolder = Path.Combine(rootFolder, "Images"); Fs.EnsureFolderExists(rootFolder); Fs.EnsureFolderExists(projectFolder); Fs.EnsureFolderExists(imagesFolder); // Copy base project Fs.CopyRecursive(@".\VisualTests\TestProjectSource", projectFolder, overwrite: true); // enable appropriate test var projFileName = Path.Combine(projectFolder, "AutomatedUITests.csproj"); var projFileContents = File.ReadAllText(projFileName); var newProjFileContents = projFileContents.Replace( @"<!--<Compile Include=""Tests\LaunchBothAppsAndCompareAllMenuBarPages.cs"" />-->", @"<Compile Include=""Tests\LaunchBothAppsAndCompareAllMenuBarPages.cs"" />"); File.WriteAllText(projFileName, newProjFileContents, Encoding.UTF8); // set AppInfo values var appInfoFileName = Path.Combine(projectFolder, "TestAppInfo.cs"); var appInfoFileContents = File.ReadAllText(appInfoFileName); var newAppInfoFileContents = appInfoFileContents .Replace("***APP-PFN-1-GOES-HERE***", $"{app1Details.PackageFamilyName}!App") .Replace("***APP-PFN-2-GOES-HERE***", $"{app2Details.PackageFamilyName}!App") .Replace("***APP-NAME-1-GOES-HERE***", app1Details.ProjectName) .Replace("***APP-NAME-2-GOES-HERE***", app2Details.ProjectName) .Replace("***FOLDER-GOES-HERE***", imagesFolder); if (pageAreasToExclude != null) { var replacement = string.Empty; foreach (var exclusion in pageAreasToExclude) { replacement += $" {{ \"{exclusion.Key}\", {exclusion.Value} }},{Environment.NewLine}"; } newAppInfoFileContents = newAppInfoFileContents.Replace( "PageSpecificExclusions = new Dictionary<string, ImageComparer.ExclusionArea>();", $"PageSpecificExclusions = new Dictionary<string, ImageComparer.ExclusionArea>{{{replacement}}};"); } File.WriteAllText(appInfoFileName, newAppInfoFileContents, Encoding.UTF8); // build test project var restoreNugetScript = $"& \"{projectFolder}\\nuget.exe\" restore \"{projectFolder}\\AutomatedUITests.csproj\" -PackagesDirectory \"{projectFolder}\\Packages\""; ExecutePowerShellScript(restoreNugetScript); var buildSolutionScript = $"& \"{GetMsBuildExePath()}\" \"{projectFolder}\\AutomatedUITests.sln\" /t:Rebuild /p:RestorePackagesPath=\"{projectFolder}\\Packages\" /p:Configuration=Debug /p:Platform=\"Any CPU\""; ExecutePowerShellScript(buildSolutionScript); return (projectFolder, imagesFolder); } protected void RemoveCertificate(string certificatePath) { var uninstallCertificateScript = $"$dump = certutil.exe -dump {certificatePath}" + @" ForEach ($i in $dump) { if ($i.StartsWith(""Serial Number: "")) { $serialNumber = ($i -split ""Serial Number: "")[1] certutil -delstore TrustedPeople $serialNumber break } }"; ExecutePowerShellScript(uninstallCertificateScript); } protected void UninstallAppx(string packageFullName) { ExecutePowerShellScript($"Remove-AppxPackage -Package {packageFullName}"); } protected async Task<VisualComparisonTestDetails> SetUpProjectForUiTestComparisonAsync(string language, string projectType, string framework, IEnumerable<string> genIdentities, bool lastPageIsHome = false, bool createForScreenshots = false) { var result = new VisualComparisonTestDetails(); var baseSetup = await SetUpComparisonProjectAsync(language, projectType, framework, genIdentities, lastPageIsHome: lastPageIsHome, includeMultipleInstances: false); result.ProjectName = baseSetup.ProjectName; if (createForScreenshots) { var pages = genIdentities.ToArray(); if (pages.Length == 1) { var page = pages.First(); if (page == "ts.Page.MediaPlayer") { // Change auto-play to false so not trying to compare images of screen-shot with video playing ReplaceInFiles("AutoPlay=\"True\"", "AutoPlay=\"False\"", baseSetup.ProjectPath, "*.xaml"); } } } // So building release version is fast ChangeProjectToNotUseDotNetNativeToolchain(baseSetup, language); ////Build solution in release mode // Building in release mode creates the APPX and certificate files we need var solutionFile = $"{baseSetup.ProjectPath}\\{baseSetup.ProjectName}.sln"; var buildSolutionScript = $"& \"{GetMsBuildExePath()}\" \"{solutionFile}\" /t:Restore,Rebuild /p:RestorePackagesPath=\"C:\\Packs\" /p:Configuration=Release /p:Platform=x86"; ExecutePowerShellScript(buildSolutionScript); result.CertificatePath = InstallCertificate(baseSetup); // install appx var appxFile = $"{baseSetup.ProjectPath}\\{baseSetup.ProjectName}\\AppPackages\\{baseSetup.ProjectName}_1.0.0.0_x86_Test\\{baseSetup.ProjectName}_1.0.0.0_x86.msix"; ExecutePowerShellScript($"Add-AppxPackage -Path {appxFile}"); // get app package name var manifest = new XmlDocument(); manifest.Load($"{baseSetup.ProjectPath}\\{baseSetup.ProjectName}\\Package.appxmanifest"); var packageName = manifest.GetElementsByTagName("Package")[0].FirstChild.Attributes["Name"].Value; // get details from appx install var getPackageNamesScript = $"$PackageName = \"{packageName}\"" + @" $packageDetails = Get-AppxPackage -Name $PackageName $packageFamilyName = $packageDetails.PackageFamilyName $packageFullName = $packageDetails.PackageFullName Write-Output $packageFamilyName Write-Output $packageFullName"; var response = ExecutePowerShellScript(getPackageNamesScript); result.PackageFamilyName = response[0].ToString(); result.PackageFullName = response[1].ToString(); return result; } protected async Task<(string ProjectPath, string ProjectName)> SetUpWpfProjectForUiTestComparisonAsync(string language, string projectType, string framework, IEnumerable<string> genIdentities, bool lastPageIsHome = false) { var baseSetup = await SetUpWpfComparisonProjectAsync(language, projectType, framework, genIdentities); // So building release version is fast ChangeProjectToNotUseDotNetNativeToolchain(baseSetup, language); ////Build solution in release mode // Building in release mode creates the APPX and certificate files we need var solutionFile = $"{baseSetup.ProjectPath}\\{baseSetup.ProjectName}.sln"; var buildSolutionScript = $"& \"{GetMsBuildExePath()}\" \"{solutionFile}\" /t:Restore,Rebuild /p:RestorePackagesPath=\"C:\\Packs\" /p:Configuration=Release /p:Platform=x86"; ExecutePowerShellScript(buildSolutionScript); return baseSetup; } private string GetVstestsConsoleExePath() { var possPath = $"{BaseGenAndBuildFixture.GetVsInstallRoot()}\\Common7\\IDE\\Extensions\\TestPlatform\\vstest.console.exe"; if (File.Exists(possPath)) { return possPath; } throw new FileNotFoundException("vstest.console.exe could not be found. If you installed Visual Studio somewhere other than the default location you will need to modify the test code."); } private string GetMsBuildExePath() { var possPath = $"{BaseGenAndBuildFixture.GetVsInstallRoot()}\\MSBuild\\Current\\Bin\\MSBuild.exe"; if (File.Exists(possPath)) { return possPath; } throw new FileNotFoundException("MSBuild.exe could not be found. If you installed Visual Studio somewhere other than the default location you will need to modify the test code."); } private void ReplaceInFiles(string find, string replace, string rootDirectory, string fileFilter) { foreach (var file in Directory.GetFiles(rootDirectory, fileFilter, SearchOption.AllDirectories)) { // open, replace, overwrite var contents = File.ReadAllText(file); var newContent = contents.Replace(find, replace); File.WriteAllText(file, newContent); } } protected string InstallCertificate((string SolutionPath, string ProjectName) baseSetup) { var cerFile = $"{baseSetup.SolutionPath}\\{baseSetup.ProjectName}\\AppPackages\\{baseSetup.ProjectName}_1.0.0.0_x86_Test\\{baseSetup.ProjectName}_1.0.0.0_x86.cer"; ExecutePowerShellScript($"& certutil.exe -addstore TrustedPeople \"{cerFile}\""); return cerFile; } protected void ChangeProjectToNotUseDotNetNativeToolchain((string SolutionPath, string ProjectName) baseSetup, string language) { var projFileName = $"{baseSetup.SolutionPath}\\{baseSetup.ProjectName}\\{baseSetup.ProjectName}.{GetProjectExtension(language)}"; var projFileContents = File.ReadAllText(projFileName); var newProjFileContents = projFileContents.Replace( "<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>", "<UseDotNetNativeToolchain>false</UseDotNetNativeToolchain>"); File.WriteAllText(projFileName, newProjFileContents, Encoding.UTF8); } private Collection<PSObject> ExecutePowerShellScript(string script, bool outputOnError = false) { using (var ps = System.Management.Automation.PowerShell.Create()) { ps.AddScript(script); Collection<PSObject> psOutput = ps.Invoke(); if (ps.Streams.Error.Count > 0) { foreach (var errorRecord in ps.Streams.Error) { Debug.WriteLine(errorRecord.ToString()); } // Some things (such as failing test execution) report an error but we still want the full output if (!outputOnError) { throw new PSInvalidOperationException(ps.Streams.Error.First().ToString()); } } return psOutput; } } protected class VisualComparisonTestDetails { public string CertificatePath { get; set; } public string PackageFamilyName { get; set; } public string PackageFullName { get; set; } public string ProjectName { get; set; } } } }