code
stringlengths
23
981k
language
stringclasses
2 values
AST_depth
int64
-1
40
alphanumeric_fraction
float64
0
1
max_line_length
int64
0
632k
avg_line_length
float64
0
15.4k
num_lines
int64
0
3.86k
original_docstring
stringlengths
7
42.9k
source
stringclasses
1 value
public class ConfigureYubicoOtp : OperationBase<ConfigureYubicoOtp> { internal ConfigureYubicoOtp(IYubiKeyConnection connection, IOtpSession session, Slot slot) : base(connection, session, slot) { } #region Private Fields private ReadOnlyMemory<byte> _publicIdentifier = Array.Empty<byte>(); private ReadOnlyMemory<byte> _privateIdentifier = Array.Empty<byte>(); private ReadOnlyMemory<byte> _key = Array.Empty<byte>(); private bool? _useSerialAsPublicId; private bool? _generatePrivateId; private bool? _generateKey; #endregion #region Size Constants public const int PublicIdentifierMaxLength = 16; public const int PrivateIdentifierSize = 6; public const int KeySize = 16; #endregion protected override void ExecuteOperation() { YubiKeyFlags ykFlags = Settings.YubiKeyFlags; var cmd = new ConfigureSlotCommand { YubiKeyFlags = ykFlags, OtpSlot = OtpSlot!.Value }; try { cmd.SetFixedData(_publicIdentifier.Span); cmd.SetUid(_privateIdentifier.Span); cmd.SetAesKey(_key.Span); cmd.ApplyCurrentAccessCode(CurrentAccessCode); cmd.SetAccessCode(NewAccessCode); ReadStatusResponse response = Connection.SendCommand(cmd); if (response.Status != ResponseStatus.Success) { throw new InvalidOperationException(string.Format( CultureInfo.CurrentCulture, ExceptionMessages.YubiKeyOperationFailed, response.StatusMessage)); } } finally { cmd.Clear(); } } protected override void PreLaunchOperation() { var exceptions = new List<Exception>(); if (!_generatePrivateId.HasValue) { exceptions.Add(new InvalidOperationException(ExceptionMessages.MustChooseOrGeneratePrivateId)); } if (!_useSerialAsPublicId.HasValue) { exceptions.Add(new InvalidOperationException(ExceptionMessages.MustChooseOrUseSerialAsPublicId)); } if (!_generateKey.HasValue) { exceptions.Add(new InvalidOperationException(ExceptionMessages.MustChooseOrGenerateKey)); } if (exceptions.Count > 0) { throw exceptions.Count == 1 ? exceptions[0] : new AggregateException(ExceptionMessages.MultipleExceptions, exceptions); } } #region Properties for Builder Pattern Setting an explicit public ID is not compatible with using the YubiKey serial public ConfigureYubicoOtp UsePublicId(ReadOnlyMemory<byte> publicId) { var exceptions = new List<Exception>(); if (_useSerialAsPublicId ?? false) { exceptions.Add( new InvalidOperationException(ExceptionMessages.CantSpecifyPublicIdAndUseSerial)); } _useSerialAsPublicId = false; if (publicId.Length == 0 || publicId.Length > PublicIdentifierMaxLength) { exceptions.Add( new ArgumentException(ExceptionMessages.PublicIdWrongSize)); } if (exceptions.Count > 0) { throw exceptions.Count == 1 ? exceptions[0] : new AggregateException(ExceptionMessages.MultipleExceptions, exceptions); } _publicIdentifier = publicId; return this; } public ConfigureYubicoOtp UseSerialNumberAsPublicId(Memory<byte>? publicId = null) { Memory<byte> serialAsId = publicId ?? new byte[6]; var exceptions = new List<Exception>(); if (!(_useSerialAsPublicId ?? true)) { exceptions.Add( new InvalidOperationException(ExceptionMessages.CantSpecifyPublicIdAndUseSerial)); } _useSerialAsPublicId = true; int? serialNumber = Session.YubiKey.SerialNumber; if (!serialNumber.HasValue) { exceptions.Add( new InvalidOperationException(ExceptionMessages.KeyHasNoVisibleSerial)); } if (serialAsId.Length != 6) { exceptions.Add( new InvalidOperationException(ExceptionMessages.MustBeSixBytesForSerial)); } if (exceptions.Count > 0) { throw exceptions.Count == 1 ? exceptions[0] : new AggregateException(ExceptionMessages.MultipleExceptions, exceptions); } _publicIdentifier = serialAsId; Span<byte> pidSpan = serialAsId.Span; pidSpan[0] = 0xff; pidSpan[1] = 0x00; BinaryPrimitives.WriteInt32BigEndian(pidSpan[2..], serialNumber!.Value); return this; } public ConfigureYubicoOtp UsePrivateId(ReadOnlyMemory<byte> privateId) { var exceptions = new List<Exception>(); if (_generatePrivateId ?? false) { exceptions.Add( new InvalidOperationException(ExceptionMessages.CantSpecifyPrivateIdAndGenerate)); } _generatePrivateId = false; if (privateId.Length != PrivateIdentifierSize) { exceptions.Add( new ArgumentException(ExceptionMessages.PrivateIdWrongSize, nameof(privateId))); } if (exceptions.Count > 0) { throw exceptions.Count == 1 ? exceptions[0] : new AggregateException(ExceptionMessages.MultipleExceptions, exceptions); } _privateIdentifier = privateId; return this; } public ConfigureYubicoOtp GeneratePrivateId(Memory<byte> privateId) { if (!(_generatePrivateId ?? true)) { throw new InvalidOperationException(ExceptionMessages.CantSpecifyPrivateIdAndGenerate); } _generatePrivateId = true; if (privateId.Length != PrivateIdentifierSize) { throw new ArgumentException(ExceptionMessages.PrivateIdWrongSize, nameof(privateId)); } _privateIdentifier = privateId; using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); rng.Fill(privateId.Span); return this; } public ConfigureYubicoOtp UseKey(Memory<byte> key) { if (_generateKey ?? false) { throw new InvalidOperationException(ExceptionMessages.CantSpecifyKeyAndGenerate); } _generateKey = false; if (key.Length != KeySize) { throw new ArgumentException(ExceptionMessages.YubicoKeyWrongSize, nameof(key)); } _key = key; return this; } public ConfigureYubicoOtp GenerateKey(Memory<byte> key) { if (!(_generateKey ?? true)) { throw new InvalidOperationException(ExceptionMessages.CantSpecifyKeyAndGenerate); } _generateKey = true; if (key.Length != KeySize) { throw new ArgumentException(ExceptionMessages.YubicoKeyWrongSize, nameof(key)); } _key = key; using RandomNumberGenerator rng = CryptographyProviders.RngCreator(); rng.Fill(key.Span); return this; } #region Flags to Relay public ConfigureYubicoOtp AppendCarriageReturn(bool setConfig = true) => Settings.AppendCarriageReturn(setConfig); public ConfigureYubicoOtp SendTabFirst(bool setConfig = true) => Settings.SendTabFirst(setConfig); public ConfigureYubicoOtp AppendTabToFixed(bool setConfig) => Settings.AppendTabToFixed(setConfig); public ConfigureYubicoOtp AppendDelayToFixed(bool setConfig = true) => Settings.AppendDelayToFixed(setConfig); public ConfigureYubicoOtp AppendDelayToOtp(bool setConfig = true) => Settings.AppendDelayToOtp(setConfig); public ConfigureYubicoOtp Use10msPacing(bool setConfig = true) => Settings.Use10msPacing(setConfig); public ConfigureYubicoOtp Use20msPacing(bool setConfig = true) => Settings.Use20msPacing(setConfig); public ConfigureYubicoOtp UseNumericKeypad(bool setConfig = true) => Settings.UseNumericKeypad(setConfig); public ConfigureYubicoOtp UseFastTrigger(bool setConfig = true) => Settings.UseFastTrigger(setConfig); public ConfigureYubicoOtp SetAllowUpdate(bool setConfig = true) => Settings.AllowUpdate(setConfig); public ConfigureYubicoOtp SendReferenceString(bool setConfig = true) => Settings.SendReferenceString(setConfig); #endregion #endregion }
c#
17
0.578604
113
41.783784
222
/// <summary> /// Configures a YubiKey's OTP slot to perform OTP using the Yubico OTP protocol. /// </summary> /// <remarks> /// <para> /// Once configured, pressing the button on the YubiKey will cause it to emit the standard /// Yubico OTP challenge string. /// </para> /// <para> /// This class is not to be instantiated by non-SDK code. Instead, you will get a reference to an /// instance of this class by calling <see cref="OtpSession.ConfigureYubicoOtp(Slot)"/>. /// </para> /// <para> /// Once you have a reference to an instance, the member methods of this class can be used to chain /// together configurations using a builder pattern. /// </para> /// </remarks>
class
public sealed class Progress { #region Events public static event Action<Indicator> Added { add => Instance.AddedInstance += value; remove => Instance.AddedInstance -= value; } public static event Action<Indicator> Removed { add => Instance.RemovedInstance += value; remove => Instance.RemovedInstance -= value; } public static event Action<Indicator> Updated { add => Instance.UpdatedInstance += value; remove => Instance.UpdatedInstance -= value; } #endregion #region Properties public float GlobalProgress => CalculateGlobalProgress(); public static bool Running => Instance.HasRunningIndicators(); #endregion #region Fields private static Progress Instance => lazy.Value; private static readonly Lazy<Progress> lazy = new Lazy<Progress>(() => new Progress()); private event Action<Indicator> AddedInstance; private event Action<Indicator> RemovedInstance; private event Action<Indicator> UpdatedInstance; private readonly Dictionary<int, Indicator> indicators = new Dictionary<int, Indicator>(); private static string IndicatorClass => typeof(Indicator).ToString(); #endregion #region Constructors and Finaliser private Progress() { } ~Progress() { } #endregion #region Static Methods public static IEnumerable<Indicator> EnumerateItems() { return Instance.indicators.Values; } public static bool Exists(int id) { if (Instance.indicators.ContainsKey(id)) return true; return false; } public static void Finish(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); Instance.indicators[id].Finish(); } public static int GetCount() { return Instance.indicators.Count; } public static int GetCurrentStep(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].CurrentStep; } public static string GetName(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Name; } public static int GetParentId(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].ParentID; } public static Indicator GetParent(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Parent; } public static float GetProgress(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Progress; } public static Indicator GetIndicatorById(int id) { if (!Exists(id)) return null; return Instance.indicators[id]; } public static Indicator GetRoot(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Root; } public static int GetRunningProgressCount() { var count = 0; foreach (Indicator indicator in Instance.indicators.Values) if (indicator.Running) count++; return count; } public static DateTime GetStartTime(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].StartTime; } public static IndicatorStatus GetStatus(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Status; } public static string GetStepLabel(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].StepLabel; } public static int GetTotalSteps(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].TotalSteps; } public static DateTime GetUpdateTime(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].UpdateTime; } public static int GetWeight(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); return Instance.indicators[id].Weight; } public static void RegisterFinishCallback(int id, Action<Indicator> callback) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); if (callback == null) throw new ArgumentNullException("callback"); Instance.indicators[id].RegisterFinishCallback(callback); } public static void Remove(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); Remove(Instance.indicators[id]); } public static void Report(int id, float progress) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); if (progress < 0f || progress > 1f) throw new ArgumentOutOfRangeException("progress"); Instance.indicators[id].Report(progress); } public static void Report(int id, int currentStep, int totalSteps) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); if (totalSteps < 1) throw new ArgumentOutOfRangeException("totalSteps"); if (currentStep > totalSteps) throw new ArgumentOutOfRangeException("currentStep"); Instance.indicators[id].Report(currentStep, totalSteps); } public static void SetStepLabel(int id, string stepLabel) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); Instance.indicators[id].SetStepLabel(stepLabel); } public static int Start(string name = "", int parentID = -1, int weight = 1) { if (parentID >= 0 && !Exists(parentID)) throw new ArgumentException(NoIndicatorWithIDExists(parentID)); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); var id = 0; while (Instance.indicators.ContainsKey(id)) id++; var indicator = FormatterServices.GetUninitializedObject(typeof(Indicator)) as Indicator; IIndicator starter = indicator; starter.Start(id, name, weight); Instance.indicators.Add(id, indicator); Instance.AddedInstance?.Invoke(indicator); if (parentID >= 0) starter.SetParent(parentID); return id; } public static int Start (int totalSteps, string name = "", string stepLabel = "", int parentID = -1, int weight = 1) { if (totalSteps < 1) throw new ArgumentOutOfRangeException("totalSteps"); if (parentID >= 0 && !Exists(parentID)) throw new ArgumentException(NoIndicatorWithIDExists(parentID)); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); int id = 0; while (Instance.indicators.ContainsKey(id)) id++; var indicator = FormatterServices.GetUninitializedObject(typeof(Indicator)) as Indicator; IIndicator starter = indicator; starter.Start(id, totalSteps, name, stepLabel, weight); Instance.indicators.Add(id, indicator); Instance.AddedInstance?.Invoke(indicator); if (parentID >= 0) starter.SetParent(parentID); return id; } public static void UnregisterFinishCallback(int id) { if (!Exists(id)) throw new ArgumentException(NoIndicatorWithIDExists(id)); Instance.indicators[id].UnregisterFinishCallback(); } private static void InvokeUpdated(Indicator indicator) { if (Exists(indicator.ID)) Instance.UpdatedInstance?.Invoke(indicator); } private static void Remove(Indicator indicator) { if (Exists(indicator.ID)) { if (indicator.HasChildren) foreach (Indicator childIndicator in indicator.Children) Remove(childIndicator); Instance.indicators.Remove(indicator.ID); Instance.RemovedInstance?.Invoke(indicator); if (indicator.HasParent && !indicator.Parent.Finished) { IIndicator parent = indicator.Parent; parent.RecalculateProgress(); } } } #endregion #region Methods private float CalculateGlobalProgress() { var totalProgress = 0f; foreach (Indicator indicator in Instance.indicators.Values) totalProgress += indicator.Progress; return totalProgress / Instance.indicators.Count; } private bool HasRunningIndicators() { foreach (Indicator indicator in Instance.indicators.Values) if (indicator.Running) return true; return false; } #endregion #region Exception Messages private static string NoIndicatorWithIDExists(int id) => string.Format("No {0} with ID value {1} exists.", IndicatorClass, id); #endregion #region Interfaces private interface IIndicator { void RecalculateProgress(); void SetParent(int parentID); void Start(int id, string name, int weight); void Start(int id, int totalSteps, string name, string stepLabel, int weight); } #endregion #region Progress.Indicator Subclass public sealed class Indicator : IIndicator { #region Properties public int ChildCount => HasChildren ? childIndicators.Count : 0; public IEnumerable<Indicator> Children => Exists && HasChildren ? childIndicators : null; public int CurrentStep { get; private set; } public bool Exists => Exists(ID); public bool Finished => Started && Exists && Progress >= 1f; public int ID { get; private set; } = -1; public bool HasChildren => childIndicators != null && childIndicators.Count > 0; public bool HasParent => ParentID >= 0 && Parent != null; public string Name { get; private set; } public Indicator Parent => GetIndicatorById(ParentID); public int ParentID { get; private set; } public float Progress => (!Exists || !Started) ? -1f : StepBased ? (float)CurrentStep / TotalSteps : reportedProgress; public Indicator Root => FindRoot(); public bool Running => Started && Progress < 1f; public DateTime StartTime { get; private set; } public IndicatorStatus Status { get { if (!Started) throw new InvalidOperationException(NotStarted); var progress = Progress; return progress <= 0f ? IndicatorStatus.Started : progress >= 1f ? IndicatorStatus.Finished : IndicatorStatus.InProgress; } } public bool StepBased => TotalSteps >= 1; public string StepLabel { get; private set; } public int TotalSteps { get; private set; } public DateTime UpdateTime { get; private set; } public int Weight { get; private set; } private bool ParentShouldRecalculate => (HasParent && !Parent.Finished); private bool Started => ID >= 0; #endregion #region Fields private event Action<Indicator> FinishCallback; private float reportedProgress; private List<Indicator> childIndicators; #endregion #region Constructors and Finaliser private Indicator() { } ~Indicator() { } #endregion #region Methods public void Finish() { if (!Started) throw new InvalidOperationException(NotStarted); if (!Exists) throw new InvalidOperationException(NoLongerExists); if (Progress < 1f) { if (StepBased) CurrentStep = TotalSteps; else reportedProgress = 1f; if (HasChildren) foreach (Indicator child in childIndicators) child.Finish(); UpdateTime = DateTime.Now; FinishCallback?.Invoke(this); FinishCallback = null; InvokeUpdated(this); if (!HasParent) Remove(this); else if (!Parent.Finished) IParent.RecalculateProgress(); } } public void RegisterFinishCallback(Action<Indicator> callback) { if (!Exists) throw new InvalidOperationException(NoLongerExists); FinishCallback = callback ?? throw new ArgumentNullException("callback"); } public void Report(float progress) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (!Running) throw new InvalidOperationException(NotRunning); if (HasChildren) throw new InvalidOperationException(CannotReportOnParent); if (progress < 0f || progress > 1f) throw new ArgumentOutOfRangeException("newProgress"); if (reportedProgress != progress || StepBased) { reportedProgress = progress; CurrentStep = 0; TotalSteps = -1; if (Progress == 1f) Finish(); else { UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } } public void Report(int currentStep, int totalSteps) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (!Running) throw new InvalidOperationException(NotRunning); if (HasChildren) throw new InvalidOperationException(CannotReportOnParent); if (totalSteps < 1) throw new ArgumentOutOfRangeException("newtotalSteps"); if (currentStep > totalSteps) throw new ArgumentOutOfRangeException("newCurrentTurnStep"); if (currentStep != CurrentStep || totalSteps != TotalSteps) { reportedProgress = 0f; CurrentStep = currentStep; TotalSteps = totalSteps; if (Progress == 1f) Finish(); else { UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } } public void SetStepLabel(string stepLabel) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (string.IsNullOrEmpty(stepLabel)) StepLabel = ""; else StepLabel = stepLabel; } public override string ToString() { if (!Exists) throw new InvalidOperationException(NoLongerExists); return StepBased ? string.Format("[ {0} | {1} | {2} | Progress: {3}% ({4}/{5} {6}) | Weight: {7} ]", ID, Name, Status, Math.Round(Progress * 100, 2), CurrentStep, TotalSteps, StepLabel, Weight) : string.Format("[ {0} | {1} | {2} | Progress: {3}% | Weight: {4} ]", ID, Name, Status, Math.Round(Progress * 100, 2), Weight); } public void UnregisterFinishCallback() { if (!Exists) throw new InvalidOperationException(NoLongerExists); FinishCallback = null; } private void AddChild(Indicator indicator) { if (childIndicators == null) childIndicators = new List<Indicator>(); childIndicators.Add(indicator); if (Progress > 0f) IThis.RecalculateProgress(); } private Indicator FindRoot() { Indicator currentIndicator = this; while (currentIndicator.HasParent) currentIndicator = currentIndicator.Parent; return currentIndicator; } #endregion #region IIndicator Implementation private IIndicator IParent => Parent; private IIndicator IThis => this; void IIndicator.RecalculateProgress() { var totalWeight = 0; var totalProgress = 0f; foreach (Indicator child in childIndicators) totalWeight += child.Weight; foreach (Indicator child in childIndicators) totalProgress += child.Progress * ((float)child.Weight / totalWeight); if (totalProgress == 1f) Finish(); else { reportedProgress = totalProgress; CurrentStep = 0; TotalSteps = -1; UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } void IIndicator.SetParent(int parentID) { if (parentID >= 0 && !Exists(parentID)) throw new ArgumentException (string.Format("No {0} with ID {1} exists.", IndicatorClass, parentID), "parentID"); if (parentID == ID) throw new ArgumentException("parentID"); ParentID = parentID; var parent = GetIndicatorById(parentID); parent.AddChild(this); } void IIndicator.Start(int id, string name, int weight) { if (Started) throw new InvalidOperationException(AlreadyStarted); if (id < 0) throw new ArgumentOutOfRangeException("id"); if (Exists(id)) throw new ArgumentException(AlreadyExists(id)); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); ID = id; Name = string.IsNullOrEmpty(name) ? "" : name; ParentID = -1; Weight = weight; StartTime = DateTime.Now; UpdateTime = StartTime; FinishCallback = null; reportedProgress = 0f; CurrentStep = 0; TotalSteps = -1; StepLabel = ""; } void IIndicator.Start(int id, int totalSteps, string name, string stepLabel, int weight) { if (Started) throw new InvalidOperationException(AlreadyStarted); if (id < 0) throw new ArgumentOutOfRangeException("id"); if (Exists(id)) throw new ArgumentException(AlreadyExists(id)); if (totalSteps < 1) throw new ArgumentOutOfRangeException("totalSteps"); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); ID = id; Name = string.IsNullOrEmpty(name) ? "" : name; ParentID = -1; Weight = weight; StartTime = DateTime.Now; UpdateTime = StartTime; FinishCallback = null; reportedProgress = 0f; CurrentStep = 0; TotalSteps = totalSteps; StepLabel = stepLabel; } #endregion #region Exception Messages private string AlreadyStarted => string.Format("{0} has already been started.", IndicatorClass); private string AlreadyExists(int id) => string.Format("A {0} with ID {1} already exists.", IndicatorClass, id); private string CannotReportOnParent => string.Format("Cannot report progress on a {0} that has one or more child {0}s.", IndicatorClass); private string NoLongerExists => string.Format("{0} no longer exists.", IndicatorClass); private string NotRunning => string.Format("Cannot report progress on a {0} that isn't running.", IndicatorClass); private string NotStarted => string.Format("{0} was not started.", IndicatorClass); #endregion } #endregion }
c#
16
0.487202
114
38.070203
641
/// <summary> /// Utility class to create and track <see cref="Indicator"/>s. /// </summary>
class
public sealed class Indicator : IIndicator { #region Properties public int ChildCount => HasChildren ? childIndicators.Count : 0; public IEnumerable<Indicator> Children => Exists && HasChildren ? childIndicators : null; public int CurrentStep { get; private set; } public bool Exists => Exists(ID); public bool Finished => Started && Exists && Progress >= 1f; public int ID { get; private set; } = -1; public bool HasChildren => childIndicators != null && childIndicators.Count > 0; public bool HasParent => ParentID >= 0 && Parent != null; public string Name { get; private set; } public Indicator Parent => GetIndicatorById(ParentID); public int ParentID { get; private set; } public float Progress => (!Exists || !Started) ? -1f : StepBased ? (float)CurrentStep / TotalSteps : reportedProgress; public Indicator Root => FindRoot(); public bool Running => Started && Progress < 1f; public DateTime StartTime { get; private set; } public IndicatorStatus Status { get { if (!Started) throw new InvalidOperationException(NotStarted); var progress = Progress; return progress <= 0f ? IndicatorStatus.Started : progress >= 1f ? IndicatorStatus.Finished : IndicatorStatus.InProgress; } } public bool StepBased => TotalSteps >= 1; public string StepLabel { get; private set; } public int TotalSteps { get; private set; } public DateTime UpdateTime { get; private set; } public int Weight { get; private set; } private bool ParentShouldRecalculate => (HasParent && !Parent.Finished); private bool Started => ID >= 0; #endregion #region Fields private event Action<Indicator> FinishCallback; private float reportedProgress; private List<Indicator> childIndicators; #endregion #region Constructors and Finaliser private Indicator() { } ~Indicator() { } #endregion #region Methods public void Finish() { if (!Started) throw new InvalidOperationException(NotStarted); if (!Exists) throw new InvalidOperationException(NoLongerExists); if (Progress < 1f) { if (StepBased) CurrentStep = TotalSteps; else reportedProgress = 1f; if (HasChildren) foreach (Indicator child in childIndicators) child.Finish(); UpdateTime = DateTime.Now; FinishCallback?.Invoke(this); FinishCallback = null; InvokeUpdated(this); if (!HasParent) Remove(this); else if (!Parent.Finished) IParent.RecalculateProgress(); } } public void RegisterFinishCallback(Action<Indicator> callback) { if (!Exists) throw new InvalidOperationException(NoLongerExists); FinishCallback = callback ?? throw new ArgumentNullException("callback"); } public void Report(float progress) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (!Running) throw new InvalidOperationException(NotRunning); if (HasChildren) throw new InvalidOperationException(CannotReportOnParent); if (progress < 0f || progress > 1f) throw new ArgumentOutOfRangeException("newProgress"); if (reportedProgress != progress || StepBased) { reportedProgress = progress; CurrentStep = 0; TotalSteps = -1; if (Progress == 1f) Finish(); else { UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } } public void Report(int currentStep, int totalSteps) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (!Running) throw new InvalidOperationException(NotRunning); if (HasChildren) throw new InvalidOperationException(CannotReportOnParent); if (totalSteps < 1) throw new ArgumentOutOfRangeException("newtotalSteps"); if (currentStep > totalSteps) throw new ArgumentOutOfRangeException("newCurrentTurnStep"); if (currentStep != CurrentStep || totalSteps != TotalSteps) { reportedProgress = 0f; CurrentStep = currentStep; TotalSteps = totalSteps; if (Progress == 1f) Finish(); else { UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } } public void SetStepLabel(string stepLabel) { if (!Exists) throw new InvalidOperationException(NoLongerExists); if (string.IsNullOrEmpty(stepLabel)) StepLabel = ""; else StepLabel = stepLabel; } public override string ToString() { if (!Exists) throw new InvalidOperationException(NoLongerExists); return StepBased ? string.Format("[ {0} | {1} | {2} | Progress: {3}% ({4}/{5} {6}) | Weight: {7} ]", ID, Name, Status, Math.Round(Progress * 100, 2), CurrentStep, TotalSteps, StepLabel, Weight) : string.Format("[ {0} | {1} | {2} | Progress: {3}% | Weight: {4} ]", ID, Name, Status, Math.Round(Progress * 100, 2), Weight); } public void UnregisterFinishCallback() { if (!Exists) throw new InvalidOperationException(NoLongerExists); FinishCallback = null; } private void AddChild(Indicator indicator) { if (childIndicators == null) childIndicators = new List<Indicator>(); childIndicators.Add(indicator); if (Progress > 0f) IThis.RecalculateProgress(); } private Indicator FindRoot() { Indicator currentIndicator = this; while (currentIndicator.HasParent) currentIndicator = currentIndicator.Parent; return currentIndicator; } #endregion #region IIndicator Implementation private IIndicator IParent => Parent; private IIndicator IThis => this; void IIndicator.RecalculateProgress() { var totalWeight = 0; var totalProgress = 0f; foreach (Indicator child in childIndicators) totalWeight += child.Weight; foreach (Indicator child in childIndicators) totalProgress += child.Progress * ((float)child.Weight / totalWeight); if (totalProgress == 1f) Finish(); else { reportedProgress = totalProgress; CurrentStep = 0; TotalSteps = -1; UpdateTime = DateTime.Now; InvokeUpdated(this); if (ParentShouldRecalculate) IParent.RecalculateProgress(); } } void IIndicator.SetParent(int parentID) { if (parentID >= 0 && !Exists(parentID)) throw new ArgumentException (string.Format("No {0} with ID {1} exists.", IndicatorClass, parentID), "parentID"); if (parentID == ID) throw new ArgumentException("parentID"); ParentID = parentID; var parent = GetIndicatorById(parentID); parent.AddChild(this); } void IIndicator.Start(int id, string name, int weight) { if (Started) throw new InvalidOperationException(AlreadyStarted); if (id < 0) throw new ArgumentOutOfRangeException("id"); if (Exists(id)) throw new ArgumentException(AlreadyExists(id)); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); ID = id; Name = string.IsNullOrEmpty(name) ? "" : name; ParentID = -1; Weight = weight; StartTime = DateTime.Now; UpdateTime = StartTime; FinishCallback = null; reportedProgress = 0f; CurrentStep = 0; TotalSteps = -1; StepLabel = ""; } void IIndicator.Start(int id, int totalSteps, string name, string stepLabel, int weight) { if (Started) throw new InvalidOperationException(AlreadyStarted); if (id < 0) throw new ArgumentOutOfRangeException("id"); if (Exists(id)) throw new ArgumentException(AlreadyExists(id)); if (totalSteps < 1) throw new ArgumentOutOfRangeException("totalSteps"); if (weight < 1) throw new ArgumentOutOfRangeException("weight"); ID = id; Name = string.IsNullOrEmpty(name) ? "" : name; ParentID = -1; Weight = weight; StartTime = DateTime.Now; UpdateTime = StartTime; FinishCallback = null; reportedProgress = 0f; CurrentStep = 0; TotalSteps = totalSteps; StepLabel = stepLabel; } #endregion #region Exception Messages private string AlreadyStarted => string.Format("{0} has already been started.", IndicatorClass); private string AlreadyExists(int id) => string.Format("A {0} with ID {1} already exists.", IndicatorClass, id); private string CannotReportOnParent => string.Format("Cannot report progress on a {0} that has one or more child {0}s.", IndicatorClass); private string NoLongerExists => string.Format("{0} no longer exists.", IndicatorClass); private string NotRunning => string.Format("Cannot report progress on a {0} that isn't running.", IndicatorClass); private string NotStarted => string.Format("{0} was not started.", IndicatorClass); #endregion }
c#
14
0.454127
114
41.604575
306
/// <summary> /// An indicator that can be used to tracks progress on some kind of arbitrary task. /// </summary>
class
public class FTXWithdrawalFee { [JsonProperty("method")] public string Network { get; set; } = string.Empty; public decimal Fee { get; set; } public bool Congested { get; set; } }
c#
9
0.584475
59
30.428571
7
/// <summary> /// Withdrawal fee info /// </summary>
class
public class TestRailClientFactory { private readonly string testRailServer; private readonly string user; private readonly string password; #region *** constructors *** public TestRailClientFactory(string testRailServer, string user, string password) { this.testRailServer = testRailServer; this.user = user; this.password = password; } #endregion public T CreateClient<T>() where T : TestRailClient { var type = typeof(T); var args = new object[] { testRailServer, user, password }; var client = (T)Activator.CreateInstance(type, args); Trace.TraceInformation($"client [{typeof(T).FullName}] successfully created"); return client; } }
c#
13
0.593261
90
36.818182
22
/// <summary> /// Generic factory for creating Test-Rail clients /// </summary>
class
[DataContract] [EntityLogicalName("competitorproduct")] [GeneratedCode("CrmSvcUtil", "6.0.0000.0809")] public class CompetitorProduct : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "competitorproduct"; public const int EntityTypeCode = 1006; public CompetitorProduct() : base(EntityLogicalName) { } [AttributeLogicalName("competitorid")] public Guid? CompetitorId { get { return GetAttributeValue<Guid?>("competitorid"); } } [AttributeLogicalName("competitorproductid")] public Guid? CompetitorProductId { get { return GetAttributeValue<Guid?>("competitorproductid"); } set { OnPropertyChanging("CompetitorProductId"); SetAttributeValue("competitorproductid", value); if (value.HasValue) { base.Id = value.Value; } else { base.Id = Guid.Empty; } OnPropertyChanged("CompetitorProductId"); } } [AttributeLogicalName("competitorproductid")] public override Guid Id { get { return base.Id; } set { CompetitorProductId = value; } } [AttributeLogicalName("productid")] public Guid? ProductId { get { return GetAttributeValue<Guid?>("productid"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return GetAttributeValue<long?>("versionnumber"); } } [RelationshipSchemaName("userentityinstancedata_competitorproduct")] public IEnumerable<UserEntityInstanceData> userentityinstancedata_competitorproduct { get { return GetRelatedEntities<UserEntityInstanceData>("userentityinstancedata_competitorproduct", null); } set { OnPropertyChanging("userentityinstancedata_competitorproduct"); SetRelatedEntities("userentityinstancedata_competitorproduct", null, value); OnPropertyChanged("userentityinstancedata_competitorproduct"); } } [RelationshipSchemaName("competitorproduct_association")] public IEnumerable<Competitor> competitorproduct_association { get { return GetRelatedEntities<Competitor>("competitorproduct_association", null); } set { OnPropertyChanging("competitorproduct_association"); SetRelatedEntities("competitorproduct_association", null, value); OnPropertyChanged("competitorproduct_association"); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; private void OnPropertyChanged(string propertyName) { if ((PropertyChanged != null)) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void OnPropertyChanging(string propertyName) { if ((PropertyChanging != null)) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } }
c#
14
0.58925
120
37.666667
90
/// <summary> /// Association between a competitor and a product offered by the competitor. /// </summary>
class
public class ManualMixerState : MixerState { #region Properties public static readonly AnimancerState[] NoStates = new AnimancerState[0]; private AnimancerState[] _States = NoStates; public override IList<AnimancerState> ChildStates => _States; public override int ChildCount => _States.Length; public override AnimancerState GetChild(int index) => _States[index]; #endregion #region Initialisation public virtual void Initialise(int childCount) { #if UNITY_ASSERTIONS if (childCount <= 1 && WarningType.MixerMinChildren.IsEnabled()) WarningType.MixerMinChildren.Log($"{GetType()} is being initialised with {nameof(childCount)} <= 1." + $" The purpose of a mixer is to mix multiple child states.", Root?.Component); #endif for (int i = _States.Length - 1; i >= 0; i--) { var state = _States[i]; if (state == null) continue; state.Destroy(); } _States = new AnimancerState[childCount]; if (_Playable.IsValid()) { _Playable.SetInputCount(childCount); } else if (Root != null) { CreatePlayable(); } } public void Initialise(params AnimationClip[] clips) { #if UNITY_ASSERTIONS if (clips == null) throw new ArgumentNullException(nameof(clips)); #endif var count = clips.Length; Initialise(count); for (int i = 0; i < count; i++) { var clip = clips[i]; if (clip != null) CreateChild(i, clip); } } #endregion #region Transition [Serializable] public abstract new class Transition<TMixer> : AnimancerState.Transition<TMixer>, IAnimationClipCollection where TMixer : ManualMixerState { [SerializeField, Tooltip(Strings.ProOnlyTag + "How fast the mixer plays (1x = normal speed, 2x = double speed)")] private float _Speed = 1; [<see cref="SerializeField"/>] public override float Speed { get => _Speed; set => _Speed = value; } [SerializeField, HideInInspector] private AnimationClip[] _Clips; [<see cref="SerializeField"/>] public ref AnimationClip[] Clips => ref _Clips; [SerializeField, HideInInspector] private float[] _Speeds; [<see cref="SerializeField"/>] public ref float[] Speeds => ref _Speeds; [SerializeField, HideInInspector] private bool[] _SynchroniseChildren; [<see cref="SerializeField"/>] public ref bool[] SynchroniseChildren => ref _SynchroniseChildren; [<see cref="ITransitionDetailed"/>] public override bool IsLooping { get { for (int i = _Clips.Length - 1; i >= 0; i--) { var clip = _Clips[i]; if (clip == null) continue; if (clip.isLooping) return true; } return false; } } [<see cref="ITransitionDetailed"/>] public override float MaximumDuration { get { if (_Clips == null) return 0; var duration = 0f; var hasSpeeds = _Speeds != null && _Speeds.Length == _Clips.Length; for (int i = _Clips.Length - 1; i >= 0; i--) { var clip = _Clips[i]; if (clip == null) continue; var length = clip.length; if (hasSpeeds) length *= _Speeds[i]; if (duration < length) duration = length; } return duration; } } public virtual void InitialiseState() { State.Initialise(_Clips); if (_Speeds != null) { #if UNITY_ASSERTIONS if (_Speeds.Length != 0 && _Speeds.Length != _Clips.Length) Debug.LogError( $"The number of serialized speeds ({_Speeds.Length})" + $" does not match the number of clips ({_Clips.Length}).", State.Root?.Component as Object); #endif for (int i = _Speeds.Length - 1; i >= 0; i--) { State._States[i].Speed = _Speeds[i]; } } State.SynchroniseChildren = _SynchroniseChildren; } public override void Apply(AnimancerState state) { base.Apply(state); if (!float.IsNaN(_Speed)) state.Speed = _Speed; } Adds the <see cref="Clips"/> to the collection.</summary> void IAnimationClipCollection.GatherAnimationClips(ICollection<AnimationClip> clips) => clips.Gather(_Clips); } [Serializable] public class Transition : Transition<ManualMixerState> { public override ManualMixerState CreateState() { State = new ManualMixerState(); InitialiseState(); return State; } #region Drawer #if UNITY_EDITOR [Editor-Only] Draws the Inspector GUI for a <see cref="Transition"/>.</summary> [CustomPropertyDrawer(typeof(Transition), true)] public class Drawer : Editor.TransitionDrawer { public static SerializedProperty CurrentProperty { get; private set; } The <see cref="Transition{TState}.Clips"/> field.</summary> public static SerializedProperty CurrentClips { get; private set; } The <see cref="Transition{TState}.Speeds"/> field.</summary> public static SerializedProperty CurrentSpeeds { get; private set; } The <see cref="Transition{TState}.SynchroniseChildren"/> field.</summary> public static SerializedProperty CurrentSynchroniseChildren { get; private set; } private readonly Dictionary<string, ReorderableList> PropertyPathToStates = new Dictionary<string, ReorderableList>(); protected virtual ReorderableList GatherDetails(SerializedProperty property) { InitialiseMode(property); GatherSubProperties(property); var propertyPath = property.propertyPath; if (!PropertyPathToStates.TryGetValue(propertyPath, out var states)) { states = new ReorderableList(CurrentClips.serializedObject, CurrentClips) { drawHeaderCallback = DoStateListHeaderGUI, elementHeightCallback = GetElementHeight, drawElementCallback = DoElementGUI, onAddCallback = OnAddElement, onRemoveCallback = OnRemoveElement, onReorderCallbackWithDetails = OnReorderList, }; PropertyPathToStates.Add(propertyPath, states); } states.serializedProperty = CurrentClips; return states; } protected virtual void GatherSubProperties(SerializedProperty property) => GatherSubPropertiesStatic(property); public static void GatherSubPropertiesStatic(SerializedProperty property) { CurrentProperty = property; CurrentClips = property.FindPropertyRelative("_Clips"); CurrentSpeeds = property.FindPropertyRelative("_Speeds"); CurrentSynchroniseChildren = property.FindPropertyRelative("_SynchroniseChildren"); if (CurrentSpeeds.arraySize != 0) CurrentSpeeds.arraySize = CurrentClips.arraySize; } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Editor.MenuFunctionState state, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, state, (property) => { GatherSubPropertiesStatic(property); function(property); }); } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, (property) => { GatherSubPropertiesStatic(property); function(property); }); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { var height = EditorGUI.GetPropertyHeight(property, label); if (property.isExpanded) { var states = GatherDetails(property); height += Editor.AnimancerGUI.StandardSpacing + states.GetHeight(); } return height; } public override void OnGUI(Rect area, SerializedProperty property, GUIContent label) { var originalProperty = property.Copy(); base.OnGUI(area, property, label); if (!originalProperty.isExpanded) return; using (TransitionContext.Get(this, property)) { if (Context.Transition == null) return; var states = GatherDetails(originalProperty); var indentLevel = EditorGUI.indentLevel; area.yMin = area.yMax - states.GetHeight(); EditorGUI.indentLevel++; area = EditorGUI.IndentedRect(area); EditorGUI.indentLevel = 0; states.DoList(area); EditorGUI.indentLevel = indentLevel; TryCollapseArrays(); } } private static float _SpeedLabelWidth; private static float _SyncLabelWidth; Splits the specified `area` into separate sections.</summary> protected static void SplitListRect(Rect area, bool isHeader, out Rect animation, out Rect speed, out Rect sync) { if (_SpeedLabelWidth == 0) _SpeedLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Speed"); if (_SyncLabelWidth == 0) _SyncLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Sync"); var spacing = Editor.AnimancerGUI.StandardSpacing; var syncWidth = isHeader ? _SyncLabelWidth : Editor.AnimancerGUI.ToggleWidth - spacing; var speedWidth = _SpeedLabelWidth + _SyncLabelWidth - syncWidth; area.width += spacing; sync = Editor.AnimancerGUI.StealFromRight(ref area, syncWidth, spacing); speed = Editor.AnimancerGUI.StealFromRight(ref area, speedWidth, spacing); animation = area; } #region Headers Draws the headdings of the state list.</summary> protected virtual void DoStateListHeaderGUI(Rect area) { SplitListRect(area, true, out var animationArea, out var speedArea, out var syncArea); DoAnimationHeaderGUI(animationArea); DoSpeedHeaderGUI(speedArea); DoSyncHeaderGUI(syncArea); } Draws an "Animation" header.</summary> protected static void DoAnimationHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Animation", "The animations that will be used for each child state"); DoHeaderDropdownGUI(area, CurrentClips, content, null); } #region Speeds Draws a "Speed" header.</summary> protected static void DoSpeedHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Speed", "Determines how fast each child state plays (Default = 1)"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { AddPropertyModifierFunction(menu, "Reset All to 1", CurrentSpeeds.arraySize == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal, (_) => CurrentSpeeds.arraySize = 0); AddPropertyModifierFunction(menu, "Normalize Durations", Editor.MenuFunctionState.Normal, NormalizeDurations); }); } private static void NormalizeDurations(SerializedProperty property) { var speedCount = CurrentSpeeds.arraySize; var lengths = new float[CurrentClips.arraySize]; if (lengths.Length <= 1) return; int nonZeroLengths = 0; float totalLength = 0; float totalSpeed = 0; for (int i = 0; i < lengths.Length; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip != null && clip.length > 0) { nonZeroLengths++; totalLength += clip.length; lengths[i] = clip.length; if (speedCount > 0) totalSpeed += CurrentSpeeds.GetArrayElementAtIndex(i).floatValue; } } if (nonZeroLengths == 0) return; var averageLength = totalLength / nonZeroLengths; var averageSpeed = speedCount > 0 ? totalSpeed / nonZeroLengths : 1; CurrentSpeeds.arraySize = lengths.Length; InitialiseSpeeds(speedCount); for (int i = 0; i < lengths.Length; i++) { if (lengths[i] == 0) continue; CurrentSpeeds.GetArrayElementAtIndex(i).floatValue = averageSpeed * lengths[i] / averageLength; } TryCollapseArrays(); } public static void InitialiseSpeeds(int start) { var count = CurrentSpeeds.arraySize; while (start < count) CurrentSpeeds.GetArrayElementAtIndex(start++).floatValue = 1; } #endregion #region Sync Draws a "Sync" header.</summary> protected static void DoSyncHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Sync", "Determines which child states have their normalized times constantly synchronised"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { var syncCount = CurrentSynchroniseChildren.arraySize; var allState = syncCount == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "All", allState, (_) => CurrentSynchroniseChildren.arraySize = 0); var syncNone = syncCount == CurrentClips.arraySize; if (syncNone) { for (int i = 0; i < syncCount; i++) { if (CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue) { syncNone = false; break; } } } var noneState = syncNone ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "None", noneState, (_) => { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Invert", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentSynchroniseChildren.arraySize; for (int i = 0; i < count; i++) { var property = CurrentSynchroniseChildren.GetArrayElementAtIndex(i); property.boolValue = !property.boolValue; } var newCount = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = count; i < newCount; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Non-Stationary", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentClips.arraySize; for (int i = 0; i < count; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip == null) continue; if (i >= syncCount) { CurrentSynchroniseChildren.arraySize = i + 1; for (int j = syncCount; j < i; j++) CurrentSynchroniseChildren.GetArrayElementAtIndex(j).boolValue = true; syncCount = i + 1; } CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = clip.averageSpeed != Vector3.zero; } TryCollapseSync(); }); }); } private static void SyncNone() { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; } #endregion Draws the GUI for a header dropdown button.</summary> public static void DoHeaderDropdownGUI(Rect area, SerializedProperty property, GUIContent content, Action<GenericMenu> populateMenu) { if (property != null) EditorGUI.BeginProperty(area, GUIContent.none, property); if (populateMenu != null) { if (EditorGUI.DropdownButton(area, content, FocusType.Passive)) { var menu = new GenericMenu(); populateMenu(menu); menu.ShowAsContext(); } } else { GUI.Label(area, content); } if (property != null) EditorGUI.EndProperty(); } #endregion Calculates the height of the state at the specified `index`.</summary> protected virtual float GetElementHeight(int index) => Editor.AnimancerGUI.LineHeight; Draws the GUI of the state at the specified `index`.</summary> private void DoElementGUI(Rect area, int index, bool isActive, bool isFocused) { if (index < 0 || index > CurrentClips.arraySize) return; var clip = CurrentClips.GetArrayElementAtIndex(index); var speed = CurrentSpeeds.arraySize > 0 ? CurrentSpeeds.GetArrayElementAtIndex(index) : null; DoElementGUI(area, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected virtual void DoElementGUI(Rect area, int index, SerializedProperty clip, SerializedProperty speed) { SplitListRect(area, false, out var animationArea, out var speedArea, out var syncArea); DoElementGUI(animationArea, speedArea, syncArea, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected void DoElementGUI(Rect animationArea, Rect speedArea, Rect syncArea, int index, SerializedProperty clip, SerializedProperty speed) { EditorGUI.PropertyField(animationArea, clip, GUIContent.none); if (speed != null) { EditorGUI.PropertyField(speedArea, speed, GUIContent.none); } else { EditorGUI.BeginProperty(speedArea, GUIContent.none, CurrentSpeeds); var value = EditorGUI.FloatField(speedArea, 1); if (value != 1) { CurrentSpeeds.InsertArrayElementAtIndex(0); CurrentSpeeds.GetArrayElementAtIndex(0).floatValue = 1; CurrentSpeeds.arraySize = CurrentClips.arraySize; CurrentSpeeds.GetArrayElementAtIndex(index).floatValue = value; } EditorGUI.EndProperty(); } DoSyncToggleGUI(syncArea, index); } protected void DoSyncToggleGUI(Rect area, int index) { var syncProperty = CurrentSynchroniseChildren; var syncFlagCount = syncProperty.arraySize; var enabled = true; if (index < syncFlagCount) { syncProperty = syncProperty.GetArrayElementAtIndex(index); enabled = syncProperty.boolValue; } EditorGUI.BeginChangeCheck(); EditorGUI.BeginProperty(area, GUIContent.none, syncProperty); enabled = GUI.Toggle(area, enabled, GUIContent.none); EditorGUI.EndProperty(); if (EditorGUI.EndChangeCheck()) { if (index < syncFlagCount) { syncProperty.boolValue = enabled; } else { syncProperty.arraySize = index + 1; for (int i = syncFlagCount; i < index; i++) { syncProperty.GetArrayElementAtIndex(i).boolValue = true; } syncProperty.GetArrayElementAtIndex(index).boolValue = enabled; } } } protected virtual void OnAddElement(ReorderableList list) { var index = CurrentClips.arraySize; CurrentClips.InsertArrayElementAtIndex(index); if (CurrentSpeeds.arraySize > 0) CurrentSpeeds.InsertArrayElementAtIndex(index); } protected virtual void OnRemoveElement(ReorderableList list) { var index = list.index; Editor.Serialization.RemoveArrayElement(CurrentClips, index); if (CurrentSpeeds.arraySize > 0) Editor.Serialization.RemoveArrayElement(CurrentSpeeds, index); } protected virtual void OnReorderList(ReorderableList list, int oldIndex, int newIndex) { CurrentSpeeds.MoveArrayElement(oldIndex, newIndex); var syncCount = CurrentSynchroniseChildren.arraySize; if (Math.Max(oldIndex, newIndex) >= syncCount) { CurrentSynchroniseChildren.arraySize++; CurrentSynchroniseChildren.GetArrayElementAtIndex(syncCount).boolValue = true; CurrentSynchroniseChildren.arraySize = newIndex + 1; } CurrentSynchroniseChildren.MoveArrayElement(oldIndex, newIndex); } public static void TryCollapseArrays() { TryCollapseSpeeds(); TryCollapseSync(); } public static void TryCollapseSpeeds() { var property = CurrentSpeeds; var speedCount = property.arraySize; if (speedCount <= 0) return; for (int i = 0; i < speedCount; i++) { if (property.GetArrayElementAtIndex(i).floatValue != 1) return; } property.arraySize = 0; } public static void TryCollapseSync() { var property = CurrentSynchroniseChildren; var count = property.arraySize; var changed = false; for (int i = count - 1; i >= 0; i--) { if (property.GetArrayElementAtIndex(i).boolValue) { count = i; changed = true; } else { break; } } if (changed) property.arraySize = count; } } #endif #endregion } #endregion }
c#
30
0.471349
134
48.967071
577
/// <summary>[Pro-Only] /// An <see cref="AnimancerState"/> which blends multiple child states. Unlike other mixers, this class does not /// perform any automatic weight calculations, it simple allows you to control the weight of all states manually. /// <para></para> /// This mixer type is similar to the Direct Blend Type in Mecanim Blend Trees. /// The official <a href="https://learn.unity.com/tutorial/5c5152bcedbc2a001fd5c696">Direct Blend Trees</a> /// tutorial explains their general concepts and purpose which apply to <see cref="ManualMixerState"/>s as well. /// </summary>
class
[Serializable] public abstract new class Transition<TMixer> : AnimancerState.Transition<TMixer>, IAnimationClipCollection where TMixer : ManualMixerState { [SerializeField, Tooltip(Strings.ProOnlyTag + "How fast the mixer plays (1x = normal speed, 2x = double speed)")] private float _Speed = 1; public override float Speed { get => _Speed; set => _Speed = value; } [SerializeField, HideInInspector] private AnimationClip[] _Clips; public ref AnimationClip[] Clips => ref _Clips; [SerializeField, HideInInspector] private float[] _Speeds; public ref float[] Speeds => ref _Speeds; [SerializeField, HideInInspector] private bool[] _SynchroniseChildren; public ref bool[] SynchroniseChildren => ref _SynchroniseChildren; public override bool IsLooping { get { for (int i = _Clips.Length - 1; i >= 0; i--) { var clip = _Clips[i]; if (clip == null) continue; if (clip.isLooping) return true; } return false; } } public override float MaximumDuration { get { if (_Clips == null) return 0; var duration = 0f; var hasSpeeds = _Speeds != null && _Speeds.Length == _Clips.Length; for (int i = _Clips.Length - 1; i >= 0; i--) { var clip = _Clips[i]; if (clip == null) continue; var length = clip.length; if (hasSpeeds) length *= _Speeds[i]; if (duration < length) duration = length; } return duration; } } public virtual void InitialiseState() { State.Initialise(_Clips); if (_Speeds != null) { #if UNITY_ASSERTIONS if (_Speeds.Length != 0 && _Speeds.Length != _Clips.Length) Debug.LogError( $"The number of serialized speeds ({_Speeds.Length})" + $" does not match the number of clips ({_Clips.Length}).", State.Root?.Component as Object); #endif for (int i = _Speeds.Length - 1; i >= 0; i--) { State._States[i].Speed = _Speeds[i]; } } State.SynchroniseChildren = _SynchroniseChildren; } public override void Apply(AnimancerState state) { base.Apply(state); if (!float.IsNaN(_Speed)) state.Speed = _Speed; } Adds the <see cref="Clips"/> to the collection.</summary> void IAnimationClipCollection.GatherAnimationClips(ICollection<AnimationClip> clips) => clips.Gather(_Clips); }
c#
16
0.426064
121
39.905882
85
/// <summary> /// Base class for serializable <see cref="ITransition"/>s which can create a particular type of /// <see cref="ManualMixerState"/> when passed into <see cref="AnimancerPlayable.Play(ITransition)"/>. /// </summary> /// <remarks> /// Unfortunately the tool used to generate this documentation does not currently support nested types with /// identical names, so only one <c>Transition</c> class will actually have a documentation page. /// <para></para> /// Even though it has the <see cref="SerializableAttribute"/>, this class won't actually get serialized /// by Unity because it's generic and abstract. Each child class still needs to include the attribute. /// </remarks>
class
[Serializable] public class Transition : Transition<ManualMixerState> { public override ManualMixerState CreateState() { State = new ManualMixerState(); InitialiseState(); return State; } #region Drawer #if UNITY_EDITOR [Editor-Only] Draws the Inspector GUI for a <see cref="Transition"/>.</summary> [CustomPropertyDrawer(typeof(Transition), true)] public class Drawer : Editor.TransitionDrawer { public static SerializedProperty CurrentProperty { get; private set; } The <see cref="Transition{TState}.Clips"/> field.</summary> public static SerializedProperty CurrentClips { get; private set; } The <see cref="Transition{TState}.Speeds"/> field.</summary> public static SerializedProperty CurrentSpeeds { get; private set; } The <see cref="Transition{TState}.SynchroniseChildren"/> field.</summary> public static SerializedProperty CurrentSynchroniseChildren { get; private set; } private readonly Dictionary<string, ReorderableList> PropertyPathToStates = new Dictionary<string, ReorderableList>(); protected virtual ReorderableList GatherDetails(SerializedProperty property) { InitialiseMode(property); GatherSubProperties(property); var propertyPath = property.propertyPath; if (!PropertyPathToStates.TryGetValue(propertyPath, out var states)) { states = new ReorderableList(CurrentClips.serializedObject, CurrentClips) { drawHeaderCallback = DoStateListHeaderGUI, elementHeightCallback = GetElementHeight, drawElementCallback = DoElementGUI, onAddCallback = OnAddElement, onRemoveCallback = OnRemoveElement, onReorderCallbackWithDetails = OnReorderList, }; PropertyPathToStates.Add(propertyPath, states); } states.serializedProperty = CurrentClips; return states; } protected virtual void GatherSubProperties(SerializedProperty property) => GatherSubPropertiesStatic(property); public static void GatherSubPropertiesStatic(SerializedProperty property) { CurrentProperty = property; CurrentClips = property.FindPropertyRelative("_Clips"); CurrentSpeeds = property.FindPropertyRelative("_Speeds"); CurrentSynchroniseChildren = property.FindPropertyRelative("_SynchroniseChildren"); if (CurrentSpeeds.arraySize != 0) CurrentSpeeds.arraySize = CurrentClips.arraySize; } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Editor.MenuFunctionState state, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, state, (property) => { GatherSubPropertiesStatic(property); function(property); }); } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, (property) => { GatherSubPropertiesStatic(property); function(property); }); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { var height = EditorGUI.GetPropertyHeight(property, label); if (property.isExpanded) { var states = GatherDetails(property); height += Editor.AnimancerGUI.StandardSpacing + states.GetHeight(); } return height; } public override void OnGUI(Rect area, SerializedProperty property, GUIContent label) { var originalProperty = property.Copy(); base.OnGUI(area, property, label); if (!originalProperty.isExpanded) return; using (TransitionContext.Get(this, property)) { if (Context.Transition == null) return; var states = GatherDetails(originalProperty); var indentLevel = EditorGUI.indentLevel; area.yMin = area.yMax - states.GetHeight(); EditorGUI.indentLevel++; area = EditorGUI.IndentedRect(area); EditorGUI.indentLevel = 0; states.DoList(area); EditorGUI.indentLevel = indentLevel; TryCollapseArrays(); } } private static float _SpeedLabelWidth; private static float _SyncLabelWidth; Splits the specified `area` into separate sections.</summary> protected static void SplitListRect(Rect area, bool isHeader, out Rect animation, out Rect speed, out Rect sync) { if (_SpeedLabelWidth == 0) _SpeedLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Speed"); if (_SyncLabelWidth == 0) _SyncLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Sync"); var spacing = Editor.AnimancerGUI.StandardSpacing; var syncWidth = isHeader ? _SyncLabelWidth : Editor.AnimancerGUI.ToggleWidth - spacing; var speedWidth = _SpeedLabelWidth + _SyncLabelWidth - syncWidth; area.width += spacing; sync = Editor.AnimancerGUI.StealFromRight(ref area, syncWidth, spacing); speed = Editor.AnimancerGUI.StealFromRight(ref area, speedWidth, spacing); animation = area; } #region Headers Draws the headdings of the state list.</summary> protected virtual void DoStateListHeaderGUI(Rect area) { SplitListRect(area, true, out var animationArea, out var speedArea, out var syncArea); DoAnimationHeaderGUI(animationArea); DoSpeedHeaderGUI(speedArea); DoSyncHeaderGUI(syncArea); } Draws an "Animation" header.</summary> protected static void DoAnimationHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Animation", "The animations that will be used for each child state"); DoHeaderDropdownGUI(area, CurrentClips, content, null); } #region Speeds Draws a "Speed" header.</summary> protected static void DoSpeedHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Speed", "Determines how fast each child state plays (Default = 1)"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { AddPropertyModifierFunction(menu, "Reset All to 1", CurrentSpeeds.arraySize == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal, (_) => CurrentSpeeds.arraySize = 0); AddPropertyModifierFunction(menu, "Normalize Durations", Editor.MenuFunctionState.Normal, NormalizeDurations); }); } private static void NormalizeDurations(SerializedProperty property) { var speedCount = CurrentSpeeds.arraySize; var lengths = new float[CurrentClips.arraySize]; if (lengths.Length <= 1) return; int nonZeroLengths = 0; float totalLength = 0; float totalSpeed = 0; for (int i = 0; i < lengths.Length; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip != null && clip.length > 0) { nonZeroLengths++; totalLength += clip.length; lengths[i] = clip.length; if (speedCount > 0) totalSpeed += CurrentSpeeds.GetArrayElementAtIndex(i).floatValue; } } if (nonZeroLengths == 0) return; var averageLength = totalLength / nonZeroLengths; var averageSpeed = speedCount > 0 ? totalSpeed / nonZeroLengths : 1; CurrentSpeeds.arraySize = lengths.Length; InitialiseSpeeds(speedCount); for (int i = 0; i < lengths.Length; i++) { if (lengths[i] == 0) continue; CurrentSpeeds.GetArrayElementAtIndex(i).floatValue = averageSpeed * lengths[i] / averageLength; } TryCollapseArrays(); } public static void InitialiseSpeeds(int start) { var count = CurrentSpeeds.arraySize; while (start < count) CurrentSpeeds.GetArrayElementAtIndex(start++).floatValue = 1; } #endregion #region Sync Draws a "Sync" header.</summary> protected static void DoSyncHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Sync", "Determines which child states have their normalized times constantly synchronised"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { var syncCount = CurrentSynchroniseChildren.arraySize; var allState = syncCount == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "All", allState, (_) => CurrentSynchroniseChildren.arraySize = 0); var syncNone = syncCount == CurrentClips.arraySize; if (syncNone) { for (int i = 0; i < syncCount; i++) { if (CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue) { syncNone = false; break; } } } var noneState = syncNone ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "None", noneState, (_) => { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Invert", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentSynchroniseChildren.arraySize; for (int i = 0; i < count; i++) { var property = CurrentSynchroniseChildren.GetArrayElementAtIndex(i); property.boolValue = !property.boolValue; } var newCount = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = count; i < newCount; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Non-Stationary", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentClips.arraySize; for (int i = 0; i < count; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip == null) continue; if (i >= syncCount) { CurrentSynchroniseChildren.arraySize = i + 1; for (int j = syncCount; j < i; j++) CurrentSynchroniseChildren.GetArrayElementAtIndex(j).boolValue = true; syncCount = i + 1; } CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = clip.averageSpeed != Vector3.zero; } TryCollapseSync(); }); }); } private static void SyncNone() { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; } #endregion Draws the GUI for a header dropdown button.</summary> public static void DoHeaderDropdownGUI(Rect area, SerializedProperty property, GUIContent content, Action<GenericMenu> populateMenu) { if (property != null) EditorGUI.BeginProperty(area, GUIContent.none, property); if (populateMenu != null) { if (EditorGUI.DropdownButton(area, content, FocusType.Passive)) { var menu = new GenericMenu(); populateMenu(menu); menu.ShowAsContext(); } } else { GUI.Label(area, content); } if (property != null) EditorGUI.EndProperty(); } #endregion Calculates the height of the state at the specified `index`.</summary> protected virtual float GetElementHeight(int index) => Editor.AnimancerGUI.LineHeight; Draws the GUI of the state at the specified `index`.</summary> private void DoElementGUI(Rect area, int index, bool isActive, bool isFocused) { if (index < 0 || index > CurrentClips.arraySize) return; var clip = CurrentClips.GetArrayElementAtIndex(index); var speed = CurrentSpeeds.arraySize > 0 ? CurrentSpeeds.GetArrayElementAtIndex(index) : null; DoElementGUI(area, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected virtual void DoElementGUI(Rect area, int index, SerializedProperty clip, SerializedProperty speed) { SplitListRect(area, false, out var animationArea, out var speedArea, out var syncArea); DoElementGUI(animationArea, speedArea, syncArea, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected void DoElementGUI(Rect animationArea, Rect speedArea, Rect syncArea, int index, SerializedProperty clip, SerializedProperty speed) { EditorGUI.PropertyField(animationArea, clip, GUIContent.none); if (speed != null) { EditorGUI.PropertyField(speedArea, speed, GUIContent.none); } else { EditorGUI.BeginProperty(speedArea, GUIContent.none, CurrentSpeeds); var value = EditorGUI.FloatField(speedArea, 1); if (value != 1) { CurrentSpeeds.InsertArrayElementAtIndex(0); CurrentSpeeds.GetArrayElementAtIndex(0).floatValue = 1; CurrentSpeeds.arraySize = CurrentClips.arraySize; CurrentSpeeds.GetArrayElementAtIndex(index).floatValue = value; } EditorGUI.EndProperty(); } DoSyncToggleGUI(syncArea, index); } protected void DoSyncToggleGUI(Rect area, int index) { var syncProperty = CurrentSynchroniseChildren; var syncFlagCount = syncProperty.arraySize; var enabled = true; if (index < syncFlagCount) { syncProperty = syncProperty.GetArrayElementAtIndex(index); enabled = syncProperty.boolValue; } EditorGUI.BeginChangeCheck(); EditorGUI.BeginProperty(area, GUIContent.none, syncProperty); enabled = GUI.Toggle(area, enabled, GUIContent.none); EditorGUI.EndProperty(); if (EditorGUI.EndChangeCheck()) { if (index < syncFlagCount) { syncProperty.boolValue = enabled; } else { syncProperty.arraySize = index + 1; for (int i = syncFlagCount; i < index; i++) { syncProperty.GetArrayElementAtIndex(i).boolValue = true; } syncProperty.GetArrayElementAtIndex(index).boolValue = enabled; } } } protected virtual void OnAddElement(ReorderableList list) { var index = CurrentClips.arraySize; CurrentClips.InsertArrayElementAtIndex(index); if (CurrentSpeeds.arraySize > 0) CurrentSpeeds.InsertArrayElementAtIndex(index); } protected virtual void OnRemoveElement(ReorderableList list) { var index = list.index; Editor.Serialization.RemoveArrayElement(CurrentClips, index); if (CurrentSpeeds.arraySize > 0) Editor.Serialization.RemoveArrayElement(CurrentSpeeds, index); } protected virtual void OnReorderList(ReorderableList list, int oldIndex, int newIndex) { CurrentSpeeds.MoveArrayElement(oldIndex, newIndex); var syncCount = CurrentSynchroniseChildren.arraySize; if (Math.Max(oldIndex, newIndex) >= syncCount) { CurrentSynchroniseChildren.arraySize++; CurrentSynchroniseChildren.GetArrayElementAtIndex(syncCount).boolValue = true; CurrentSynchroniseChildren.arraySize = newIndex + 1; } CurrentSynchroniseChildren.MoveArrayElement(oldIndex, newIndex); } public static void TryCollapseArrays() { TryCollapseSpeeds(); TryCollapseSync(); } public static void TryCollapseSpeeds() { var property = CurrentSpeeds; var speedCount = property.arraySize; if (speedCount <= 0) return; for (int i = 0; i < speedCount; i++) { if (property.GetArrayElementAtIndex(i).floatValue != 1) return; } property.arraySize = 0; } public static void TryCollapseSync() { var property = CurrentSynchroniseChildren; var count = property.arraySize; var changed = false; for (int i = count - 1; i >= 0; i--) { if (property.GetArrayElementAtIndex(i).boolValue) { count = i; changed = true; } else { break; } } if (changed) property.arraySize = count; } } #endif #endregion }
c#
28
0.474075
134
52.540416
433
/// <summary> /// A serializable <see cref="ITransition"/> which can create a <see cref="ManualMixerState"/> when /// passed into <see cref="AnimancerPlayable.Play(ITransition)"/>. /// </summary> /// <remarks> /// Unfortunately the tool used to generate this documentation does not currently support nested types with /// identical names, so only one <c>Transition</c> class will actually have a documentation page. /// </remarks>
class
[CustomPropertyDrawer(typeof(Transition), true)] public class Drawer : Editor.TransitionDrawer { public static SerializedProperty CurrentProperty { get; private set; } The <see cref="Transition{TState}.Clips"/> field.</summary> public static SerializedProperty CurrentClips { get; private set; } The <see cref="Transition{TState}.Speeds"/> field.</summary> public static SerializedProperty CurrentSpeeds { get; private set; } The <see cref="Transition{TState}.SynchroniseChildren"/> field.</summary> public static SerializedProperty CurrentSynchroniseChildren { get; private set; } private readonly Dictionary<string, ReorderableList> PropertyPathToStates = new Dictionary<string, ReorderableList>(); protected virtual ReorderableList GatherDetails(SerializedProperty property) { InitialiseMode(property); GatherSubProperties(property); var propertyPath = property.propertyPath; if (!PropertyPathToStates.TryGetValue(propertyPath, out var states)) { states = new ReorderableList(CurrentClips.serializedObject, CurrentClips) { drawHeaderCallback = DoStateListHeaderGUI, elementHeightCallback = GetElementHeight, drawElementCallback = DoElementGUI, onAddCallback = OnAddElement, onRemoveCallback = OnRemoveElement, onReorderCallbackWithDetails = OnReorderList, }; PropertyPathToStates.Add(propertyPath, states); } states.serializedProperty = CurrentClips; return states; } protected virtual void GatherSubProperties(SerializedProperty property) => GatherSubPropertiesStatic(property); public static void GatherSubPropertiesStatic(SerializedProperty property) { CurrentProperty = property; CurrentClips = property.FindPropertyRelative("_Clips"); CurrentSpeeds = property.FindPropertyRelative("_Speeds"); CurrentSynchroniseChildren = property.FindPropertyRelative("_SynchroniseChildren"); if (CurrentSpeeds.arraySize != 0) CurrentSpeeds.arraySize = CurrentClips.arraySize; } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Editor.MenuFunctionState state, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, state, (property) => { GatherSubPropertiesStatic(property); function(property); }); } protected static void AddPropertyModifierFunction(GenericMenu menu, string label, Action<SerializedProperty> function) { Editor.Serialization.AddPropertyModifierFunction(menu, CurrentProperty, label, (property) => { GatherSubPropertiesStatic(property); function(property); }); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { var height = EditorGUI.GetPropertyHeight(property, label); if (property.isExpanded) { var states = GatherDetails(property); height += Editor.AnimancerGUI.StandardSpacing + states.GetHeight(); } return height; } public override void OnGUI(Rect area, SerializedProperty property, GUIContent label) { var originalProperty = property.Copy(); base.OnGUI(area, property, label); if (!originalProperty.isExpanded) return; using (TransitionContext.Get(this, property)) { if (Context.Transition == null) return; var states = GatherDetails(originalProperty); var indentLevel = EditorGUI.indentLevel; area.yMin = area.yMax - states.GetHeight(); EditorGUI.indentLevel++; area = EditorGUI.IndentedRect(area); EditorGUI.indentLevel = 0; states.DoList(area); EditorGUI.indentLevel = indentLevel; TryCollapseArrays(); } } private static float _SpeedLabelWidth; private static float _SyncLabelWidth; Splits the specified `area` into separate sections.</summary> protected static void SplitListRect(Rect area, bool isHeader, out Rect animation, out Rect speed, out Rect sync) { if (_SpeedLabelWidth == 0) _SpeedLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Speed"); if (_SyncLabelWidth == 0) _SyncLabelWidth = Editor.AnimancerGUI.CalculateWidth(EditorStyles.popup, "Sync"); var spacing = Editor.AnimancerGUI.StandardSpacing; var syncWidth = isHeader ? _SyncLabelWidth : Editor.AnimancerGUI.ToggleWidth - spacing; var speedWidth = _SpeedLabelWidth + _SyncLabelWidth - syncWidth; area.width += spacing; sync = Editor.AnimancerGUI.StealFromRight(ref area, syncWidth, spacing); speed = Editor.AnimancerGUI.StealFromRight(ref area, speedWidth, spacing); animation = area; } #region Headers Draws the headdings of the state list.</summary> protected virtual void DoStateListHeaderGUI(Rect area) { SplitListRect(area, true, out var animationArea, out var speedArea, out var syncArea); DoAnimationHeaderGUI(animationArea); DoSpeedHeaderGUI(speedArea); DoSyncHeaderGUI(syncArea); } Draws an "Animation" header.</summary> protected static void DoAnimationHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Animation", "The animations that will be used for each child state"); DoHeaderDropdownGUI(area, CurrentClips, content, null); } #region Speeds Draws a "Speed" header.</summary> protected static void DoSpeedHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Speed", "Determines how fast each child state plays (Default = 1)"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { AddPropertyModifierFunction(menu, "Reset All to 1", CurrentSpeeds.arraySize == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal, (_) => CurrentSpeeds.arraySize = 0); AddPropertyModifierFunction(menu, "Normalize Durations", Editor.MenuFunctionState.Normal, NormalizeDurations); }); } private static void NormalizeDurations(SerializedProperty property) { var speedCount = CurrentSpeeds.arraySize; var lengths = new float[CurrentClips.arraySize]; if (lengths.Length <= 1) return; int nonZeroLengths = 0; float totalLength = 0; float totalSpeed = 0; for (int i = 0; i < lengths.Length; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip != null && clip.length > 0) { nonZeroLengths++; totalLength += clip.length; lengths[i] = clip.length; if (speedCount > 0) totalSpeed += CurrentSpeeds.GetArrayElementAtIndex(i).floatValue; } } if (nonZeroLengths == 0) return; var averageLength = totalLength / nonZeroLengths; var averageSpeed = speedCount > 0 ? totalSpeed / nonZeroLengths : 1; CurrentSpeeds.arraySize = lengths.Length; InitialiseSpeeds(speedCount); for (int i = 0; i < lengths.Length; i++) { if (lengths[i] == 0) continue; CurrentSpeeds.GetArrayElementAtIndex(i).floatValue = averageSpeed * lengths[i] / averageLength; } TryCollapseArrays(); } public static void InitialiseSpeeds(int start) { var count = CurrentSpeeds.arraySize; while (start < count) CurrentSpeeds.GetArrayElementAtIndex(start++).floatValue = 1; } #endregion #region Sync Draws a "Sync" header.</summary> protected static void DoSyncHeaderGUI(Rect area) { var content = Editor.AnimancerGUI.TempContent("Sync", "Determines which child states have their normalized times constantly synchronised"); DoHeaderDropdownGUI(area, CurrentSpeeds, content, (menu) => { var syncCount = CurrentSynchroniseChildren.arraySize; var allState = syncCount == 0 ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "All", allState, (_) => CurrentSynchroniseChildren.arraySize = 0); var syncNone = syncCount == CurrentClips.arraySize; if (syncNone) { for (int i = 0; i < syncCount; i++) { if (CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue) { syncNone = false; break; } } } var noneState = syncNone ? Editor.MenuFunctionState.Selected : Editor.MenuFunctionState.Normal; AddPropertyModifierFunction(menu, "None", noneState, (_) => { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Invert", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentSynchroniseChildren.arraySize; for (int i = 0; i < count; i++) { var property = CurrentSynchroniseChildren.GetArrayElementAtIndex(i); property.boolValue = !property.boolValue; } var newCount = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = count; i < newCount; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; }); AddPropertyModifierFunction(menu, "Non-Stationary", Editor.MenuFunctionState.Normal, (_) => { var count = CurrentClips.arraySize; for (int i = 0; i < count; i++) { var clip = CurrentClips.GetArrayElementAtIndex(i).objectReferenceValue as AnimationClip; if (clip == null) continue; if (i >= syncCount) { CurrentSynchroniseChildren.arraySize = i + 1; for (int j = syncCount; j < i; j++) CurrentSynchroniseChildren.GetArrayElementAtIndex(j).boolValue = true; syncCount = i + 1; } CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = clip.averageSpeed != Vector3.zero; } TryCollapseSync(); }); }); } private static void SyncNone() { var count = CurrentSynchroniseChildren.arraySize = CurrentClips.arraySize; for (int i = 0; i < count; i++) CurrentSynchroniseChildren.GetArrayElementAtIndex(i).boolValue = false; } #endregion Draws the GUI for a header dropdown button.</summary> public static void DoHeaderDropdownGUI(Rect area, SerializedProperty property, GUIContent content, Action<GenericMenu> populateMenu) { if (property != null) EditorGUI.BeginProperty(area, GUIContent.none, property); if (populateMenu != null) { if (EditorGUI.DropdownButton(area, content, FocusType.Passive)) { var menu = new GenericMenu(); populateMenu(menu); menu.ShowAsContext(); } } else { GUI.Label(area, content); } if (property != null) EditorGUI.EndProperty(); } #endregion Calculates the height of the state at the specified `index`.</summary> protected virtual float GetElementHeight(int index) => Editor.AnimancerGUI.LineHeight; Draws the GUI of the state at the specified `index`.</summary> private void DoElementGUI(Rect area, int index, bool isActive, bool isFocused) { if (index < 0 || index > CurrentClips.arraySize) return; var clip = CurrentClips.GetArrayElementAtIndex(index); var speed = CurrentSpeeds.arraySize > 0 ? CurrentSpeeds.GetArrayElementAtIndex(index) : null; DoElementGUI(area, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected virtual void DoElementGUI(Rect area, int index, SerializedProperty clip, SerializedProperty speed) { SplitListRect(area, false, out var animationArea, out var speedArea, out var syncArea); DoElementGUI(animationArea, speedArea, syncArea, index, clip, speed); } Draws the GUI of the state at the specified `index`.</summary> protected void DoElementGUI(Rect animationArea, Rect speedArea, Rect syncArea, int index, SerializedProperty clip, SerializedProperty speed) { EditorGUI.PropertyField(animationArea, clip, GUIContent.none); if (speed != null) { EditorGUI.PropertyField(speedArea, speed, GUIContent.none); } else { EditorGUI.BeginProperty(speedArea, GUIContent.none, CurrentSpeeds); var value = EditorGUI.FloatField(speedArea, 1); if (value != 1) { CurrentSpeeds.InsertArrayElementAtIndex(0); CurrentSpeeds.GetArrayElementAtIndex(0).floatValue = 1; CurrentSpeeds.arraySize = CurrentClips.arraySize; CurrentSpeeds.GetArrayElementAtIndex(index).floatValue = value; } EditorGUI.EndProperty(); } DoSyncToggleGUI(syncArea, index); } protected void DoSyncToggleGUI(Rect area, int index) { var syncProperty = CurrentSynchroniseChildren; var syncFlagCount = syncProperty.arraySize; var enabled = true; if (index < syncFlagCount) { syncProperty = syncProperty.GetArrayElementAtIndex(index); enabled = syncProperty.boolValue; } EditorGUI.BeginChangeCheck(); EditorGUI.BeginProperty(area, GUIContent.none, syncProperty); enabled = GUI.Toggle(area, enabled, GUIContent.none); EditorGUI.EndProperty(); if (EditorGUI.EndChangeCheck()) { if (index < syncFlagCount) { syncProperty.boolValue = enabled; } else { syncProperty.arraySize = index + 1; for (int i = syncFlagCount; i < index; i++) { syncProperty.GetArrayElementAtIndex(i).boolValue = true; } syncProperty.GetArrayElementAtIndex(index).boolValue = enabled; } } } protected virtual void OnAddElement(ReorderableList list) { var index = CurrentClips.arraySize; CurrentClips.InsertArrayElementAtIndex(index); if (CurrentSpeeds.arraySize > 0) CurrentSpeeds.InsertArrayElementAtIndex(index); } protected virtual void OnRemoveElement(ReorderableList list) { var index = list.index; Editor.Serialization.RemoveArrayElement(CurrentClips, index); if (CurrentSpeeds.arraySize > 0) Editor.Serialization.RemoveArrayElement(CurrentSpeeds, index); } protected virtual void OnReorderList(ReorderableList list, int oldIndex, int newIndex) { CurrentSpeeds.MoveArrayElement(oldIndex, newIndex); var syncCount = CurrentSynchroniseChildren.arraySize; if (Math.Max(oldIndex, newIndex) >= syncCount) { CurrentSynchroniseChildren.arraySize++; CurrentSynchroniseChildren.GetArrayElementAtIndex(syncCount).boolValue = true; CurrentSynchroniseChildren.arraySize = newIndex + 1; } CurrentSynchroniseChildren.MoveArrayElement(oldIndex, newIndex); } public static void TryCollapseArrays() { TryCollapseSpeeds(); TryCollapseSync(); } public static void TryCollapseSpeeds() { var property = CurrentSpeeds; var speedCount = property.arraySize; if (speedCount <= 0) return; for (int i = 0; i < speedCount; i++) { if (property.GetArrayElementAtIndex(i).floatValue != 1) return; } property.arraySize = 0; } public static void TryCollapseSync() { var property = CurrentSynchroniseChildren; var count = property.arraySize; var changed = false; for (int i = count - 1; i >= 0; i--) { if (property.GetArrayElementAtIndex(i).boolValue) { count = i; changed = true; } else { break; } } if (changed) property.arraySize = count; } }
c#
28
0.473135
134
53.322967
418
/// <summary>[Editor-Only] Draws the Inspector GUI for a <see cref="Transition"/>.</summary>
class
public class ConnectionStringParameterValueElement : ParameterValueElement { public const String ConnectionStringKeyAttributeName = "connectionStringKey"; public const String ElementName = "connectionSetting"; public ConnectionStringParameterValueElement() { Config = ConfigurationStoreFactory.Create(); } public ConnectionStringSettings CreateValue() { Contract.Assume(String.IsNullOrWhiteSpace(ConnectionStringKey) == false); ConnectionStringSettings configurationValue = Config.GetConnectionSetting(ConnectionStringKey); if (configurationValue == null) { String message = String.Format( CultureInfo.InvariantCulture, Resources.ConnectionStringParameterValueElement_ConnectionStringKeyNotFound, ConnectionStringKey); throw new ConfigurationErrorsException(message); } return configurationValue; } public override InjectionParameterValue GetInjectionParameterValue(IUnityContainer container, Type parameterType) { if (parameterType == null) { throw new ArgumentNullException("parameterType"); } ConnectionStringSettings injectionValue = CreateValue(); if (parameterType.Equals(typeof(String))) { return new InjectionParameter(parameterType, injectionValue.ConnectionString); } if (parameterType.Equals(typeof(ConnectionStringSettings))) { return new InjectionParameter(parameterType, injectionValue); } String message = String.Format( CultureInfo.InvariantCulture, Resources.ConnectionStringParameterValueElement_InvalidParameterType, parameterType.FullName); throw new InvalidOperationException(message); } [ConfigurationProperty(ConnectionStringKeyAttributeName, IsRequired = true)] public String ConnectionStringKey { get { return (String)base[ConnectionStringKeyAttributeName]; } set { base[ConnectionStringKeyAttributeName] = value; } } private IConfigurationStore Config { get; set; } }
c#
15
0.628465
148
41.421053
57
/// <summary> /// The <see cref="ConnectionStringParameterValueElement"/> /// class is used to configure a Unity injection parameter value to be determined from a <see cref="ConnectionStringSettings"/> value. /// </summary> /// <remarks> /// <para> /// The <see cref="ConnectionStringParameterValueElement"/> is configured for a container by the <see cref="SectionExtensionInitiator"/> class. /// It only supports injection of <see cref="String"/> /// and <see cref="ConnectionStringSettings"/> parameter types. /// </para> /// <note> /// The <see cref="SectionExtensionInitiator"/> class must be configured for the container in order for the connectionSetting injection element /// to be understood. /// </note> /// <para> /// Injecting a connection string value should use a string parameter as the injection value. /// This will then decouple the dependency being created from the System.Configuration assembly. /// The only time that the ConnectionStringSettings class should be used as the injection parameter type is when the provider information /// on the connection setting is required for some application logic. /// </para> /// </remarks> /// <example> /// <para> /// The following example shows how the element is configured. /// </para> /// <code lang="xml" title="Application configuration"> /// <![CDATA[<?xml version="1.0" /// encoding="utf-8" ?> /// <configuration> /// <configSections> /// <section name="unity" /// type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> /// </configSections> /// <connectionStrings> /// <add name="TestConnection" connectionString="Data Source=localhost;Database=SomeDatabase;Integrated Security=SSPI;"/> /// </connectionStrings> /// <unity> /// <sectionExtension type="Neovolve.Toolkit.Unity.SectionExtensionInitiator, Neovolve.Toolkit.Unity"/> /// <containers> /// <container> /// <register type="Neovolve.Toolkit.Unity.IntegrationTests.IDoSomething, Neovolve.Toolkit.Unity.IntegrationTests" /// mapTo="Neovolve.Toolkit.Unity.IntegrationTests.ConnectionTest, Neovolve.Toolkit.Unity.IntegrationTests" /// name="ConnectionSettingTesting"> /// <constructor> /// <param name="connectionSetting"> /// <connectionSetting connectionStringKey="TestConnection"/> /// </param> /// </constructor> /// </register> /// </container> /// </containers> /// </unity> /// </configuration>]]> /// </code> /// </example> /// <seealso cref="SectionExtensionInitiator"/>
class
public class EffectOptions { public bool? Include { get; set; } public int? PriorityAdjustment { get; set; } }
c#
6
0.597015
52
26
5
/// <summary> /// The type of effects to apply. /// </summary>
class
public partial class AuthorizedDedicatedCircuitListResponse : OperationResponse, IEnumerable<AzureAuthorizedDedicatedCircuit> { private IList<AzureAuthorizedDedicatedCircuit> _authorizedDedicatedCircuits; public IList<AzureAuthorizedDedicatedCircuit> AuthorizedDedicatedCircuits { get { return this._authorizedDedicatedCircuits; } set { this._authorizedDedicatedCircuits = value; } } public AuthorizedDedicatedCircuitListResponse() { this.AuthorizedDedicatedCircuits = new LazyList<AzureAuthorizedDedicatedCircuit>(); } public IEnumerator<AzureAuthorizedDedicatedCircuit> GetEnumerator() { return this.AuthorizedDedicatedCircuits.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }
c#
11
0.699893
125
43.47619
21
/// <summary> /// The List Authorized Dedicated Circuit operation response. /// </summary>
class
[ToolboxItem(false)] [ToolboxBitmap(typeof(KryptonRibbonGroupGallery), "ToolboxBitmaps.KryptonGallery.bmp")] [Designer("ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGalleryDesigner, ComponentFactory.Krypton.Design, Version=125.0.0.0, Culture=neutral, PublicKeyToken=a87e673e9ecb6e8e")] [DesignerCategory("code")] [DesignTimeVisible(false)] [DefaultProperty("Visible")] public class KryptonRibbonGroupGallery : KryptonRibbonGroupContainer { #region Static Fields private static readonly Image _defaultButtonImageLarge = Properties.Resources.ButtonImageLarge; #endregion #region Instance Fields private bool _visible; private bool _enabled; private string _textLine1; private string _textLine2; private Image _imageLarge; private string _keyTip; private NeedPaintHandler _viewPaintDelegate; private KryptonGallery _gallery; private KryptonGallery _lastGallery; private IKryptonDesignObject _designer; private Control _lastParentControl; private ViewBase _galleryView; private GroupItemSize _itemSizeMax; private GroupItemSize _itemSizeMin; private GroupItemSize _itemSizeCurrent; private int _largeItemCount; private int _mediumItemCount; private int _itemCount; private int _dropButtonItemWidth; private Image _toolTipImage; private Color _toolTipImageTransparentColor; private LabelStyle _toolTipStyle; private string _toolTipTitle; private string _toolTipBody; #endregion #region Events [Category("Property Changed")] [Description("Occurs when the value of the ImageList property changes.")] public event EventHandler ImageListChanged; [Category("Property Changed")] [Description("Occurs when the value of the SelectedIndex property changes.")] public event EventHandler SelectedIndexChanged; [Category("Action")] [Description("Occurs when user is tracking over an image.")] public event EventHandler<ImageSelectEventArgs> TrackingImage; [Category("Action")] [Description("Occurs when user invokes the drop down menu.")] public event EventHandler<GalleryDropMenuEventArgs> GalleryDropMenu; [Category("Ribbon")] [Description("Occurs after the value of a property has changed.")] public event PropertyChangedEventHandler PropertyChanged; [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public event EventHandler GotFocus; [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public event EventHandler LostFocus; [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public event MouseEventHandler DesignTimeContextMenu; internal event EventHandler MouseEnterControl; internal event EventHandler MouseLeaveControl; #endregion #region Identity public KryptonRibbonGroupGallery() { _visible = true; _enabled = true; _keyTip = "X"; _itemSizeMax = GroupItemSize.Large; _itemSizeMin = GroupItemSize.Small; _itemSizeCurrent = GroupItemSize.Large; _largeItemCount = 9; _mediumItemCount = 3; _dropButtonItemWidth = 9; _imageLarge = _defaultButtonImageLarge; _textLine1 = "Gallery"; _textLine2 = string.Empty; _toolTipImageTransparentColor = Color.Empty; _toolTipTitle = string.Empty; _toolTipBody = string.Empty; _toolTipStyle = LabelStyle.SuperTip; _gallery = new KryptonGallery(); _gallery.AlwaysActive = false; _gallery.TabStop = false; _gallery.InternalPreferredItemSize = new Size(_largeItemCount, 1); _gallery.SelectedIndexChanged += new EventHandler(OnGallerySelectedIndexChanged); _gallery.ImageListChanged += new EventHandler(OnGalleryImageListChanged); _gallery.TrackingImage += new EventHandler<ImageSelectEventArgs>(OnGalleryTrackingImage); _gallery.GalleryDropMenu += new EventHandler<GalleryDropMenuEventArgs>(OnGalleryGalleryDropMenu); _gallery.GotFocus += new EventHandler(OnGalleryGotFocus); _gallery.LostFocus += new EventHandler(OnGalleryLostFocus); MonitorControl(_gallery); } #endregion #region Public [Description("Access to the actual embedded KryptonGallery instance.")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public KryptonGallery Gallery { get { return _gallery; } } [Category("Visuals")] [Description("Collection of drop down ranges")] [MergableProperty(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonGalleryRangeCollection DropButtonRanges { get { return _gallery.DropButtonRanges; } } [Category("Visuals")] [Description("Determines if scrolling is animated or a jump straight to target.")] [DefaultValue(true)] public bool SmoothScrolling { get { return _gallery.SmoothScrolling; } set { _gallery.SmoothScrolling = value; OnPropertyChanged("SmoothScrolling"); } } [Category("Visuals")] [Description("Collection of images for display and selection.")] public ImageList ImageList { get { return _gallery.ImageList; } set { if (_gallery.ImageList != value) { _gallery.ImageList = value; OnPropertyChanged("ImageList"); } } } [Category("Visuals")] [Description("The index of the selected image.")] [DefaultValue(-1)] public int SelectedIndex { get { return _gallery.SelectedIndex; } set { if (_gallery.SelectedIndex != value) { _gallery.SelectedIndex = value; OnPropertyChanged("SelectedIndex"); } } } [Category("Visuals")] [Description("Number of horizontal displayed items when in large setting.")] [DefaultValue(9)] public int LargeItemCount { get { return _largeItemCount; } set { if (_largeItemCount != value) { _largeItemCount = value; if (_largeItemCount < _mediumItemCount) _mediumItemCount = _largeItemCount; OnPropertyChanged("LargeItemCount"); } } } [Category("Visuals")] [Description("Number of horizontal displayed items when in medium setting.")] [DefaultValue(3)] public int MediumItemCount { get { return _mediumItemCount; } set { if (_mediumItemCount != value) { _mediumItemCount = value; if (_mediumItemCount > _largeItemCount) _largeItemCount = _mediumItemCount; OnPropertyChanged("MediumItemCount"); } } } [Category("Visuals")] [Description("Number of horizontal displayed items when showing drop menu from the large button.")] [DefaultValue(9)] public int DropButtonItemWidth { get { return _dropButtonItemWidth; } set { if (_dropButtonItemWidth != value) { value = Math.Max(1, value); _dropButtonItemWidth = value; OnPropertyChanged("DropButtonItemWidth"); } } } [Category("Visuals")] [Description("Maximum number of line items for the drop down menu.")] [DefaultValue(128)] public int DropMaxItemWidth { get { return _gallery.DropMaxItemWidth; } set { if (_gallery.DropMaxItemWidth != value) { _gallery.DropMaxItemWidth = value; OnPropertyChanged("DropMaxItemWidth"); } } } [Category("Visuals")] [Description("Minimum number of line items for the drop down menu.")] [DefaultValue(3)] public int DropMinItemWidth { get { return _gallery.DropMinItemWidth; } set { if (_gallery.DropMinItemWidth != value) { _gallery.DropMinItemWidth = value; OnPropertyChanged("DropMinItemWidth"); } } } [Category("Behavior")] [Description("The shortcut to display when the user right-clicks the control.")] [DefaultValue(null)] public ContextMenuStrip ContextMenuStrip { get { return _gallery.ContextMenuStrip; } set { _gallery.ContextMenuStrip = value; } } [Category("Behavior")] [Description("KryptonContextMenu to be shown when the gallery is right clicked.")] [DefaultValue(null)] public KryptonContextMenu KryptonContextMenu { get { return _gallery.KryptonContextMenu; } set { _gallery.KryptonContextMenu = value; } } [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("Ribbon group gallery key tip.")] [DefaultValue("X")] public string KeyTip { get { return _keyTip; } set { if (string.IsNullOrEmpty(value)) value = "X"; _keyTip = value.ToUpper(); } } [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("Large gallery button image.")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Image ImageLarge { get { return _imageLarge; } set { if (_imageLarge != value) { _imageLarge = value; OnPropertyChanged("ImageLarge"); } } } private bool ShouldSerializeImageLarge() { return ImageLarge != _defaultButtonImageLarge; } [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("Gallery button display text line 1.")] [RefreshPropertiesAttribute(RefreshProperties.All)] [DefaultValue("Gallery")] public string TextLine1 { get { return _textLine1; } set { if (string.IsNullOrEmpty(value)) value = "Gallery"; if (value != _textLine1) { _textLine1 = value; OnPropertyChanged("TextLine1"); } } } [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("Gallery button display text line 2.")] [RefreshPropertiesAttribute(RefreshProperties.All)] [DefaultValue("")] public string TextLine2 { get { return _textLine2; } set { if (value != _textLine2) { _textLine2 = value; OnPropertyChanged("TextLine2"); } } } [Category("Appearance")] [Description("Tooltip style for the group button.")] [DefaultValue(typeof(LabelStyle), "SuperTip")] public LabelStyle ToolTipStyle { get { return _toolTipStyle; } set { _toolTipStyle = value; } } [Bindable(true)] [Category("Appearance")] [Description("Display image associated ToolTip.")] [DefaultValue(null)] [Localizable(true)] public Image ToolTipImage { get { return _toolTipImage; } set { _toolTipImage = value; } } [Bindable(true)] [Category("Appearance")] [Description("Color to draw as transparent in the ToolTipImage.")] [KryptonDefaultColorAttribute()] [Localizable(true)] public Color ToolTipImageTransparentColor { get { return _toolTipImageTransparentColor; } set { _toolTipImageTransparentColor = value; } } [Bindable(true)] [Category("Appearance")] [Description("Title text for use in associated ToolTip.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DefaultValue("")] [Localizable(true)] public string ToolTipTitle { get { return _toolTipTitle; } set { _toolTipTitle = value; } } [Bindable(true)] [Category("Appearance")] [Description("Body text for use in associated ToolTip.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DefaultValue("")] [Localizable(true)] public string ToolTipBody { get { return _toolTipBody; } set { _toolTipBody = value; } } [Bindable(true)] [Category("Behavior")] [Description("Determines whether the group gallery is visible or hidden.")] [DefaultValue(true)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override bool Visible { get { return _visible; } set { if (value != _visible) { _visible = value; OnPropertyChanged("Visible"); } } } public void Show() { Visible = true; } public void Hide() { Visible = false; } [Bindable(true)] [Category("Behavior")] [Description("Determines whether the group gallery is enabled.")] [DefaultValue(true)] public bool Enabled { get { return _enabled; } set { if (_enabled != value) { _enabled = value; OnPropertyChanged("Enabled"); } } } [Category("Visuals")] [Description("Maximum size of the gallery.")] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [DefaultValue(typeof(GroupItemSize), "Large")] [RefreshProperties(RefreshProperties.All)] public GroupItemSize MaximumSize { get { return ItemSizeMaximum; } set { ItemSizeMaximum = value; } } [Category("Visuals")] [Description("Minimum size of the gallery.")] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [DefaultValue(typeof(GroupItemSize), "Small")] [RefreshProperties(RefreshProperties.All)] public GroupItemSize MinimumSize { get { return ItemSizeMinimum; } set { ItemSizeMinimum = value; } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeMaximum { get { return _itemSizeMax; } set { if (_itemSizeMax != value) { _itemSizeMax = value; OnPropertyChanged("ItemSizeMaximum"); } } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeMinimum { get { return _itemSizeMin; } set { if (_itemSizeMin != value) { _itemSizeMin = value; OnPropertyChanged("ItemSizeMinimum"); } } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeCurrent { get { return _itemSizeCurrent; } set { _itemSizeCurrent = value; switch (value) { case GroupItemSize.Large: _gallery.InternalPreferredItemSize = new Size(InternalItemCount, 1); break; case GroupItemSize.Medium: _gallery.InternalPreferredItemSize = new Size(MediumItemCount, 1); break; } OnPropertyChanged("ItemSizeCurrent"); } } [EditorBrowsable(EditorBrowsableState.Never)] public override ViewBase CreateView(KryptonRibbon ribbon, NeedPaintHandler needPaint) { return new ViewDrawRibbonGroupGallery(ribbon, this, needPaint); } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public IKryptonDesignObject GalleryDesigner { get { return _designer; } set { _designer = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public ViewBase GalleryView { get { return _galleryView; } set { _galleryView = value; } } #endregion #region Internal internal Control LastParentControl { get { return _lastParentControl; } set { _lastParentControl = value; } } internal KryptonGallery LastGallery { get { return _lastGallery; } set { _lastGallery = value; } } internal NeedPaintHandler ViewPaintDelegate { get { return _viewPaintDelegate; } set { _viewPaintDelegate = value; } } internal void OnDesignTimeContextMenu(MouseEventArgs e) { if (DesignTimeContextMenu != null) DesignTimeContextMenu(this, e); } internal int InternalItemCount { get { return _itemCount; } set { _itemCount = value; } } internal override LabelStyle InternalToolTipStyle { get { return ToolTipStyle; } } internal override Image InternalToolTipImage { get { return ToolTipImage; } } internal override Color InternalToolTipImageTransparentColor { get { return ToolTipImageTransparentColor; } } internal override string InternalToolTipTitle { get { return ToolTipTitle; } } internal override string InternalToolTipBody { get { return ToolTipBody; } } internal override bool ProcessCmdKey(ref Message msg, Keys keyData) { return false; } #endregion #region Protected protected virtual void OnImageListChanged(EventArgs e) { if (ImageListChanged != null) ImageListChanged(this, e); } protected virtual void OnSelectedIndexChanged(EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged(this, e); } protected virtual void OnTrackingImage(ImageSelectEventArgs e) { if (TrackingImage != null) TrackingImage(this, e); } protected virtual void OnGalleryDropMenu(GalleryDropMenuEventArgs e) { if (GalleryDropMenu != null) GalleryDropMenu(this, e); } protected virtual void OnGotFocus(EventArgs e) { if (GotFocus != null) GotFocus(this, e); } protected virtual void OnLostFocus(EventArgs e) { if (LostFocus != null) LostFocus(this, e); } protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Implementation private void MonitorControl(KryptonGallery c) { c.MouseEnter += new EventHandler(OnControlEnter); c.MouseLeave += new EventHandler(OnControlLeave); } private void UnmonitorControl(KryptonGallery c) { c.MouseEnter -= new EventHandler(OnControlEnter); c.MouseLeave -= new EventHandler(OnControlLeave); } private void OnControlEnter(object sender, EventArgs e) { if (MouseEnterControl != null) MouseEnterControl(this, e); } private void OnControlLeave(object sender, EventArgs e) { if (MouseLeaveControl != null) MouseLeaveControl(this, e); } private void OnGalleryImageListChanged(object sender, EventArgs e) { OnImageListChanged(e); } private void OnGallerySelectedIndexChanged(object sender, EventArgs e) { OnSelectedIndexChanged(e); } private void OnGalleryTrackingImage(object sender, ImageSelectEventArgs e) { OnTrackingImage(e); } private void OnGalleryGalleryDropMenu(object sender, GalleryDropMenuEventArgs e) { OnGalleryDropMenu(e); } private void OnGalleryGotFocus(object sender, EventArgs e) { OnGotFocus(e); } private void OnGalleryLostFocus(object sender, EventArgs e) { OnLostFocus(e); } #endregion }
c#
15
0.557581
185
35.228879
651
/// <summary> /// Represents a ribbon group separator. /// </summary>
class
internal class DropdownBox : AbstractWidget, IDropdownBox { private int selectedIndex; private object selectedItem; private object[] items; private string label; private string tooltip; private PropertyBinding<object, IDropdownBox> selectedItemProperty; private PropertyBinding<object[], IDropdownBox> itemsProperty; private PropertyBinding<string, IDropdownBox> labelProperty; private PropertyBinding<string, IDropdownBox> tooltipProperty; public IPropertyBinding<object, IDropdownBox> SelectedItem { get { return selectedItemProperty; } } public IPropertyBinding<object[], IDropdownBox> Items { get { return itemsProperty; } } public IPropertyBinding<string, IDropdownBox> Label { get { return labelProperty; } } public IPropertyBinding<string, IDropdownBox> Tooltip { get { return tooltipProperty; } } internal DropdownBox(ILayout parent) : base(parent) { itemsProperty = new PropertyBinding<object[], IDropdownBox>( this, value => this.items = value ); selectedItemProperty = new PropertyBinding<object, IDropdownBox>( this, value => { selectedItem = value; if (items != null) { selectedIndex = Array.IndexOf(items, value); } } ); labelProperty = new PropertyBinding<string, IDropdownBox>( this, value => this.label = value ); tooltipProperty = new PropertyBinding<string, IDropdownBox>( this, value => this.tooltip = value ); } public override void OnGUI() { var itemStrings = items != null ? items.Select(i => i.ToString()).ToArray() : new string[] {}; var guiContent = itemStrings.Select(m => new GUIContent(m, tooltip)).ToArray(); var newIndex = !String.IsNullOrEmpty(label) ? EditorGUILayout.Popup(new GUIContent(label), selectedIndex, guiContent) : EditorGUILayout.Popup(selectedIndex, guiContent); if (newIndex != selectedIndex) { selectedIndex = newIndex; selectedItem = items[selectedIndex]; selectedItemProperty.UpdateView(selectedItem); } } public override void BindViewModel(object viewModel) { selectedItemProperty.BindViewModel(viewModel); itemsProperty.BindViewModel(viewModel); labelProperty.BindViewModel(viewModel); tooltipProperty.BindViewModel(viewModel); } }
c#
19
0.574275
107
43.030769
65
/// <summary> /// Drop-down selection field. /// </summary>
class
public class FileHelper : IFileHelper { public DirectoryInfo CreateDirectory(string path) { return Directory.CreateDirectory(path); } public string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } public bool Exists(string path) { return File.Exists(path); } public bool DirectoryExists(string path) { return Directory.Exists(path); } public Stream GetStream(string filePath, FileMode mode, FileAccess access = FileAccess.ReadWrite) { return new FileStream(filePath, mode, access); } public IEnumerable<string> EnumerateFiles(string directory, string pattern, SearchOption searchOption) { var regex = new Regex(pattern, RegexOptions.IgnoreCase); return Directory.EnumerateFiles(directory, "*", searchOption).Where(f => regex.IsMatch(f)); } public FileAttributes GetFileAttributes(string path) { return new FileInfo(path).Attributes; } public void CopyFile(string sourcePath, string destinationPath) { File.Copy(sourcePath, destinationPath); } public void MoveFile(string sourcePath, string destinationPath) { File.Move(sourcePath, destinationPath); } }
c#
13
0.606511
110
34.35
40
/// <summary> /// The file helper. /// </summary>
class
public class ScriptComponentWriter : FileComponentWriter { public ScriptComponentWriter(string basePath, Dictionary<string, InstallFile> scripts, PackageInfo package) : base(basePath, scripts, package) { } protected override string CollectionNodeName { get { return "scripts"; } } protected override string ComponentType { get { return "Script"; } } protected override string ItemNodeName { get { return "script"; } } protected override void WriteFileElement(XmlWriter writer, InstallFile file) { this.Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); string type = "Install"; string version = Null.NullString; string fileName = Path.GetFileNameWithoutExtension(file.Name); if (fileName.Equals("uninstall", StringComparison.InvariantCultureIgnoreCase)) { type = "UnInstall"; version = this.Package.Version.ToString(3); } else if (fileName.Equals("install", StringComparison.InvariantCultureIgnoreCase)) { type = "Install"; version = new Version(0, 0, 0).ToString(3); } else if (fileName.StartsWith("Install")) { type = "Install"; version = fileName.Replace("Install.", string.Empty); } else { type = "Install"; version = fileName; } writer.WriteStartElement(this.ItemNodeName); writer.WriteAttributeString("type", type); if (!string.IsNullOrEmpty(file.Path)) { writer.WriteElementString("path", file.Path); } writer.WriteElementString("name", file.Name); if (!string.IsNullOrEmpty(file.SourceFileName)) { writer.WriteElementString("sourceFileName", file.SourceFileName); } writer.WriteElementString("version", version); writer.WriteEndElement(); } }
c#
15
0.516787
115
33.617647
68
/// ----------------------------------------------------------------------------- /// <summary> /// The ScriptComponentWriter class handles creating the manifest for Script /// Component(s). /// </summary> /// <remarks> /// </remarks> /// -----------------------------------------------------------------------------
class
public class NotifyPropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; protected void SetValue<T>(ref T holder, T newValue, [CallerMemberName] string? callerMemberName = null) { if (!Equals(holder, newValue)) { holder = newValue; RaisePropertyChanged(callerMemberName); } } protected void RaisePropertyChanged(string? propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
c#
12
0.692727
108
33.4375
16
/// <summary> /// Abstract class for efficiently preparing implementations of the <see cref="INotifyPropertyChanged"/> interface /// </summary> /// <seealso cref="INotifyPropertyChanged"/>
class
public class TreeNode<T> { public TreeNode(T value = default(T), TreeNode<T> parent = null, TreeNode<T> left = null, TreeNode<T> right = null) { Value = value; Right = right; Left = left; Parent = parent; } public virtual bool IsLeaf { get { return Left == null && Right == null; } } public virtual bool IsRoot { get { return Parent == null; } } public virtual TreeNode<T> Left { get; set; } public virtual TreeNode<T> Parent { get; set; } public virtual TreeNode<T> Right { get; set; } public virtual T Value { get; set; } internal bool Visited { get; set; } public override string ToString() { return Value.ToString(); } }
c#
10
0.538945
123
36.952381
21
/// <summary> /// Node class for the Binary tree /// </summary> /// <typeparam name="T">The value type</typeparam>
class
public sealed class HoconField : IHoconElement { private readonly List<HoconValue> _internalValues = new List<HoconValue>(); public HoconField(string key, HoconObject parent) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); Path = new HoconPath(parent.Path) {key}; Parent = parent; } public HoconPath Path { get; } public string Key => Path.Key; internal bool HasOldValues => _internalValues.Count > 1; public HoconValue Value { get { if (_internalValues.Count == 1) return _internalValues[0]; var lastValue = _internalValues.LastOrDefault(); if (lastValue is null) return null; if (lastValue.Type != HoconType.Object) return lastValue; var filteredValues = new List<HoconValue>(); foreach (var value in _internalValues) if (value.Type != HoconType.Object && value.Type != HoconType.Empty) filteredValues.Clear(); else filteredValues.Add(value); var returnValue = new HoconValue(this, filteredValues); return returnValue; } } public IHoconElement Parent { get; } public HoconType Type => Value == null ? HoconType.Empty : Value.Type; public string Raw => Value.Raw; public HoconObject GetObject() { return Value.GetObject(); } public string GetString() { return Value.GetString(); } public IList<HoconValue> GetArray() { return Value.GetArray(); } public IHoconElement Clone(IHoconElement newParent) { var newField = new HoconField(Key, (HoconObject) newParent); foreach (var internalValue in _internalValues) newField._internalValues.Add(internalValue.Clone(newField) as HoconValue); return newField; } public string ToString(int indent, int indentSize) { return Value.ToString(indent, indentSize); } public bool Equals(IHoconElement other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return other is HoconField field && Path.Equals(field.Path) && Value.Equals(other); } internal void EnsureFieldIsObject() { if (Type == HoconType.Object) return; var v = new HoconValue(this); var o = new HoconObject(v); v.Add(o); _internalValues.Add(v); } internal void SetValue(HoconValue value) { if (value == null) return; if (_internalValues.Any(v => ReferenceEquals(v, value))) return; if (value.Type != HoconType.Object) foreach (var item in _internalValues) { var subs = item.GetSubstitutions(); var preservedSub = value.GetSubstitutions(); foreach (var sub in subs.Except(preservedSub)) sub.Removed = true; } _internalValues.Add(value); } internal void Flatten() { var value = Value; _internalValues.Clear(); _internalValues.Add(value); } internal void RestoreOldValue() { if (HasOldValues) _internalValues.RemoveAt(_internalValues.Count - 1); } internal HoconValue OlderValueThan(IHoconElement marker) { var filteredObjectValue = new List<HoconValue>(); var index = 0; while (index < _internalValues.Count) { var value = _internalValues[index]; if (value.Any(v => ReferenceEquals(v, marker))) break; switch (value.Type) { case HoconType.Object: filteredObjectValue.Add(value); break; case HoconType.Boolean: case HoconType.Number: case HoconType.String: case HoconType.Array: filteredObjectValue.Clear(); break; } index++; } if (filteredObjectValue.Count == 0) return index == 0 ? null : _internalValues[index - 1]; var result = new HoconValue(this); foreach (var value in filteredObjectValue) result.AddRange(value); return result; } internal void ResolveValue(HoconValue value) { if (value.Type != HoconType.Empty) return; ((HoconObject) Parent).ResolveValue(this); } public override string ToString() { return ToString(0, 2); } public override bool Equals(object obj) { return obj is IHoconElement element && Equals(element); } public override int GetHashCode() { unchecked { return Path.GetHashCode() + Value.GetHashCode(); } } public static bool operator ==(HoconField left, HoconField right) { return Equals(left, right); } public static bool operator !=(HoconField left, HoconField right) { return !Equals(left, right); } }
c#
15
0.511882
133
35.726115
157
/// <summary> /// This class represents a key and value tuple representing a Hocon field. /// <code> /// root { /// items = [ /// "1", /// "2"] /// } /// </code> /// </summary>
class
class DispatchEvent : IExecutable { private Executable exe; public virtual Executable Callback { get { return exe; } protected set { exe = value; } } internal DispatchEvent() : this(null) { } internal DispatchEvent(Executable e) { exe = e; } public virtual void OnFailure(Exception e) { Tracer.WarnFormat("Encountered Exception: {0} stack: {1}.", e.Message, e.StackTrace); } public Executable GetExecutable() { return exe; } }
c#
10
0.540587
97
29.526316
19
/// <summary> /// General Dispatch Event to execute code from a DispatchExecutor. /// </summary>
class
internal class WaitableDispatchEvent : DispatchEvent, IWaitable { private ManualResetEvent handle = new ManualResetEvent(false); #region EventState protected class EventState { internal static EventState INITIAL = new EventState(0, "INITIAL"); internal static EventState SIGNALED = new EventState(1, "SIGNALED"); internal static EventState CANCELLED = new EventState(2, "CANCELLED"); internal static EventState UNKNOWN = new EventState(-1, "UNKNOWN"); private static Dictionary<int, EventState> States = new Dictionary<int, EventState>() { { INITIAL.value, INITIAL }, { SIGNALED.value, SIGNALED }, { CANCELLED.value, CANCELLED } }; private readonly int value; private readonly string name; private EventState(int ordinal, string name = null) { value = ordinal; this.name = name ?? ordinal.ToString(); } public static implicit operator int(EventState es) { return es != null ? es.value : UNKNOWN.value; } public static implicit operator EventState(int value) { if(!States.TryGetValue(value, out EventState state)) { state = UNKNOWN; } return state; } public override int GetHashCode() { return this.value; } public override bool Equals(object obj) { if(obj != null && obj is EventState) { return this.value == (obj as EventState).value; } return false; } public override string ToString() { return this.name; } } #endregion private Atomic<int> state; private Exception failureCause = null; public override Executable Callback { get => base.Callback; protected set { Executable cb; if (value == null) { cb = () => { this.Release(); }; } else { cb = () => { value.Invoke(); this.Release(); }; } base.Callback = cb; } } public bool IsComplete => EventState.SIGNALED.Equals(state.Value); public bool IsCancelled => EventState.CANCELLED.Equals(state.Value); internal WaitableDispatchEvent() : this(null) { } internal WaitableDispatchEvent(Executable e) { handle = new ManualResetEvent(false); state = new Atomic<int>(EventState.INITIAL); this.Callback = e; } public void Reset() { state.GetAndSet(EventState.INITIAL); if (!handle.Reset()) { throw new NMSException("Failed to reset Waitable Event Signal."); } } public void Cancel() { if (state.CompareAndSet(EventState.INITIAL, EventState.CANCELLED)) { if (!handle.Set()) { failureCause = new NMSException("Failed to cancel Waitable Event."); } } } private void Release() { if (state.CompareAndSet(EventState.INITIAL, EventState.SIGNALED)) { if (!handle.Set()) { state.GetAndSet(EventState.CANCELLED); failureCause = new NMSException("Failed to release Waitable Event."); } } } public bool Wait() { return Wait(TimeSpan.Zero); } public bool Wait(TimeSpan timeout) { bool signaled = (timeout.Equals(TimeSpan.Zero)) ? handle.WaitOne() : handle.WaitOne(timeout); if (state.Value == EventState.CANCELLED) { signaled = false; if (failureCause != null) { throw failureCause; } } return signaled; } }
c#
17
0.458724
105
32.518248
137
/// <summary> /// A Dispatch event that is completion aware of its current state. This allows threads other then the Dispatch Executor thread to synchronize with the dispatch event. /// </summary>
class
class DispatchExecutor : NMSResource, IDisposable { private static AtomicSequence ExecutorId = new AtomicSequence(1); private const string ExecutorName = "DispatchExecutor"; private const int DEFAULT_SIZE = 100000; private const int DEFAULT_DEQUEUE_TIMEOUT = 10000; private Queue<IExecutable> queue; private int maxSize; private bool closed=false; private Atomic<bool> closeQueued = new Atomic<bool>(false); private bool executing=false; private Semaphore suspendLock = new Semaphore(0, 10, "Suspend"); private Thread executingThread; private readonly string name; private readonly object objLock = new object(); #region Constructors public DispatchExecutor() : this(DEFAULT_SIZE) { } public DispatchExecutor(bool drain) : this(DEFAULT_SIZE, drain) { } public DispatchExecutor(int size, bool drain = false) { this.maxSize = size; this.ExecuteDrain = drain; queue = new Queue<IExecutable>(maxSize); executingThread = new Thread(new ThreadStart(this.Dispatch)); executingThread.IsBackground = true; name = ExecutorName + ExecutorId.getAndIncrement() + ":" + executingThread.ManagedThreadId; executingThread.Name = name; } ~DispatchExecutor() { try { Dispose(false); } catch (Exception ex) { Tracer.DebugFormat("Caught exception in Finalizer for Dispatcher : {0}. Exception {1}", this.name, ex); } } #endregion #region Properties protected object ThisLock { get { return objLock; } } protected bool Closing { get { return closeQueued.Value; } } public string Name { get { return name; } } internal bool ExecuteDrain { get; private set; } internal bool IsOnDispatchThread { get { string currentThreadName = Thread.CurrentThread.Name; return currentThreadName != null && currentThreadName.Equals(name); } } #endregion #region Private Suspend Resume Methods #if TRACELOCKS int scount = 0; #endif protected void Suspend() { Exception e=null; while(!AcquireSuspendLock(out e) && !closed) { if (e != null) { throw e; } } } protected bool AcquireSuspendLock() { Exception e; return AcquireSuspendLock(out e); } protected bool AcquireSuspendLock(out Exception ex) { bool signaled = false; ex = null; try { #if TRACELOCKS Tracer.InfoFormat("Aquiring Suspend Lock Count {0}", scount); #endif signaled = this.suspendLock.WaitOne(); #if TRACELOCKS scount = signaled ? scount - 1 : scount; #endif }catch(Exception e) { ex = e; } #if TRACELOCKS finally { Tracer.InfoFormat("Suspend Lock Count after aquire {0} signaled {1}", scount, signaled); } #endif return signaled; } protected void Resume() { Exception ex; int count = ReleaseSuspendLock(out ex); if (ex != null) { throw ex; } } protected int ReleaseSuspendLock() { Exception e; return ReleaseSuspendLock(out e); } protected int ReleaseSuspendLock(out Exception ex) { ex = null; int previous = -1; try { #if TRACELOCKS Tracer.InfoFormat("Suspend Lock Count before release {0}", scount); #endif previous = this.suspendLock.Release(); #if TRACELOCKS scount = previous != -1 ? scount + 1 : scount; Tracer.InfoFormat("Suspend Lock Count after release {0} previous Value {1}", scount, previous); #endif } catch (SemaphoreFullException sfe) { Tracer.DebugFormat("Multiple Resume called on running Dispatcher. Cause: {0}", sfe.Message); } catch(System.IO.IOException ioe) { Tracer.ErrorFormat("Failed resuming or starting Dispatch thread. Cause: {0}", ioe.Message); ex = ioe; } catch(UnauthorizedAccessException uae) { Tracer.Error(uae.StackTrace); ex = uae; } if(ex!=null) Console.WriteLine("Release Error {0}", ex); return previous; } #endregion #region Protected Dispatch Methods protected void CloseOnQueue() { bool ifDrain = false; bool executeDrain = false; lock (queue) { if (!closed) { Stop(); closed = true; executing = false; ifDrain = true; executeDrain = ExecuteDrain; Monitor.PulseAll(queue); Tracer.InfoFormat("DistpachExecutor: {0} Closed.", name); } } if (ifDrain) { Drain(executeDrain); } } protected IExecutable[] DrainOffQueue() { lock (queue) { ArrayList list = new ArrayList(queue.Count); while (queue.Count > 0) { list.Add(queue.Dequeue()); } return (IExecutable[])list.ToArray(typeof(IExecutable)); } } protected void Drain(bool execute = false) { IExecutable[] exes = DrainOffQueue(); if (execute) { foreach (IExecutable exe in exes) { DispatchEvent(exe); } } } protected void DispatchEvent(IExecutable dispatchEvent) { Executable exe = dispatchEvent.GetExecutable(); if (exe != null) { try { exe.Invoke(); } catch (Exception e) { dispatchEvent.OnFailure(ExceptionSupport.Wrap(e, "Dispatch Executor Error ({0}):", this.name)); } } } protected void Dispatch() { while (!closed) { bool locked = false; while (!closed && !(locked = this.AcquireSuspendLock())) { } if (locked) { int count = this.ReleaseSuspendLock(); #if TraceLocks Tracer.InfoFormat("Dispatch Suspend Lock Count {0}, Current Count {1}", count, count+1); #endif } if (closed) { break; } while (IsStarted) { IExecutable exe; if (TryDequeue(out exe, DEFAULT_DEQUEUE_TIMEOUT)) { DispatchEvent(exe); } else { Tracer.DebugFormat("Queue {0} did not dispatch due to being Suspended or Closed.", name); } } } } #endregion #region NMSResource Methods protected override void StartResource() { if (!executing) { executing = true; executingThread.Start(); Resume(); } else { Resume(); } } protected override void StopResource() { lock (queue) { if (queue.Count == 0) { Monitor.PulseAll(queue); } } Suspend(); } protected override void ThrowIfClosed() { if (closed) { throw new Apache.NMS.IllegalStateException("Illegal Operation on closed " + this.GetType().Name + "."); } } #endregion #region Public Methods public void Close() { this.Dispose(true); } public void Enqueue(IExecutable o) { if(o == null) { return; } lock (queue) { while (queue.Count >= maxSize) { if (closed) { return; } Monitor.Wait(queue); } queue.Enqueue(o); if (queue.Count == 1) { Monitor.PulseAll(queue); } } } public bool TryDequeue(out IExecutable exe, int timeout = -1) { exe = null; lock (queue) { bool signaled = true; while (queue.Count == 0) { if (closed || mode.Value.Equals(Resource.Mode.Stopping)) { return false; } signaled = (timeout > -1 ) ? Monitor.Wait(queue, timeout) : Monitor.Wait(queue); } if (!signaled) { return false; } exe = queue.Dequeue(); if (queue.Count == maxSize - 1) { Monitor.PulseAll(queue); } } return true; } #endregion #region IDispose Methods internal void Shutdown(bool join = false) { if (IsOnDispatchThread) { if (false == closeQueued.GetAndSet(true)) { this.CloseOnQueue(); } } else if (closeQueued.CompareAndSet(false, true)) { if (!IsStarted && executing) { Start(); } this.Enqueue(new DispatchEvent(this.CloseOnQueue)); if (join && executingThread != null) { if (!executingThread.ThreadState.Equals(ThreadState.Unstarted)) { executingThread.Join(); } executingThread = null; } } } protected virtual void Dispose(bool disposing) { if (closed) return; lock (queue) { if (closed) return; } if (disposing) { if (executingThread != null && executingThread.ThreadState.Equals(ThreadState.Unstarted)) { executingThread = null; } this.Shutdown(true); this.suspendLock.Dispose(); this.queue = null; } else { this.Shutdown(); this.suspendLock.Dispose(); this.queue = null; } } public void Dispose() { try { this.Close(); } catch (Exception ex) { Tracer.DebugFormat("Caught Exception during Dispose for Dispatcher {0}. Exception {1}", this.name, ex); } } #endregion }
c#
19
0.437747
119
30.022959
392
/// <summary> /// Single Thread Executor for Dispatch Event. This Encapsulates Threading restrictions for Client code serialization. /// </summary>
class
public class CircularLayout : Layout<View> { public static readonly BindableProperty OrientationProperty = BindableProperty.Create(nameof(Orientation), typeof(CircularOrientation), typeof(CircularLayout), CircularOrientation.Clockwise, BindingMode.TwoWay, propertyChanged: (bindable, oldvalue, newvalue) => ((CircularLayout)bindable).InvalidateMeasure()); public CircularOrientation Orientation { get { return (CircularOrientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } public static readonly BindableProperty AngleProperty = BindableProperty.Create(nameof(Angle), typeof(double), typeof(CircularLayout), 0.0d, BindingMode.TwoWay, null); public double Angle { get { return (double)GetValue(AngleProperty); } set { SetValue(AngleProperty, value); } } public static double GetAngle(View obj) { return (double)obj.GetValue(AngleProperty); } public static void SetAngle(View obj, double value) { obj.SetValue(AngleProperty, value); } public static readonly BindableProperty RadiusProperty = BindableProperty.Create(nameof(Radius), typeof(double), typeof(CircularLayout), 0.0d, BindingMode.TwoWay, null); public double Radius { get { return (double)GetValue(RadiusProperty); } set { SetValue(RadiusProperty, value); } } public static double GetRadius(View obj) { return (double)obj.GetValue(RadiusProperty); } public static void SetRadius(View obj, double value) { obj.SetValue(RadiusProperty, value); } protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint) { if (WidthRequest > 0) widthConstraint = Math.Min(widthConstraint, WidthRequest); if (HeightRequest > 0) heightConstraint = Math.Min(heightConstraint, HeightRequest); double internalWidth = double.IsPositiveInfinity(widthConstraint) ? double.PositiveInfinity : Math.Max(0, widthConstraint); double internalHeight = double.IsPositiveInfinity(heightConstraint) ? double.PositiveInfinity : Math.Max(0, heightConstraint); if (double.IsPositiveInfinity(widthConstraint) && double.IsPositiveInfinity(heightConstraint)) { return new SizeRequest(Size.Zero, Size.Zero); } return base.OnMeasure(widthConstraint, heightConstraint); } protected override void LayoutChildren(double x, double y, double width, double height) { CreateLayout(x, y, width, height); } private void CreateLayout(double x, double y, double width, double height) { Point panelCenter = new Point(width / 2, height / 2); foreach (View element in Children) { Point location = CreatePoint(GetAngle(element), GetRadius(element)); location.X += panelCenter.X; location.Y += panelCenter.Y; SizeRequest childSizeRequest = element.Measure(double.PositiveInfinity, double.PositiveInfinity); Rectangle elementBounds = CreateCenteralizeRectangle(location, new Size(childSizeRequest.Request.Width, childSizeRequest.Request.Height)); LayoutChildIntoBoundingRegion(element, elementBounds); } } private Rectangle CreateCenteralizeRectangle(Point point, Size size) { Rectangle result = new Rectangle( point.X - size.Width / 2, point.Y - size.Height / 2, size.Width, size.Height); return result; } private Point CreatePoint(double angle, double radius) { const int ClockwiseAngle = 90; const int CounterclockwiseAngle = 270; angle = Orientation == CircularOrientation.Clockwise ? RadianHelper.DegreeToRadian(angle - ClockwiseAngle) : -RadianHelper.DegreeToRadian(angle - CounterclockwiseAngle); Point result = new Point( radius * Math.Cos(angle), radius * Math.Sin(angle)); return result; } }
c#
19
0.616719
154
46.357895
95
/// <summary> /// The CircularLayout is a simple Layout derivative that lays out its children in a circular arrangement. /// It has some useful properties to allow some customization like the Orientation (Clockwise or Counterclockwise). /// </summary>
class
internal sealed class WcfService : BaseServiceBusComponent, IWcfService { private readonly ISubscriptionsManager _subscriptionsManager; private readonly ISendingManager _sendingManager; private readonly IReceivingManager _receivingManager; private readonly IStatisticsService _statisticsService; private readonly IObjectRepository _objectRepository; private readonly ILogger _logger; private ServiceHost _wcfServiceHost; public bool UseWcfSettingsFromConfig { get; set; } = true; public Uri Address { get; set; } public Binding Binding { get; set; } public bool PublishWSDL { get; set; } = false; public WcfService(ISubscriptionsManager subscriptionsManager, ISendingManager sendingManager, IReceivingManager receivingManager, ILogger logger, IStatisticsService statisticsService, IObjectRepository objectRepository) { if (subscriptionsManager == null) throw new ArgumentNullException(nameof(subscriptionsManager)); if (sendingManager == null) throw new ArgumentNullException(nameof(sendingManager)); if (statisticsService == null) throw new ArgumentNullException(nameof(statisticsService)); if (receivingManager == null) throw new ArgumentNullException(nameof(receivingManager)); if (logger == null) throw new ArgumentNullException(nameof(logger)); if (objectRepository == null) throw new ArgumentNullException(nameof(objectRepository)); _subscriptionsManager = subscriptionsManager; _sendingManager = sendingManager; _receivingManager = receivingManager; _logger = logger; _statisticsService = statisticsService; _objectRepository = objectRepository; } public override void Start() { var service = new SBService(_subscriptionsManager, _sendingManager, _receivingManager, _statisticsService, _objectRepository); if (UseWcfSettingsFromConfig) { _logger.LogDebugMessage(nameof(WcfService), "Creating WCF host using configuration"); _wcfServiceHost = new ServiceHost(service); } else { _logger.LogDebugMessage(nameof(WcfService), "Creating WCF host using specified binding and address"); _wcfServiceHost = new ServiceHostWithoutConfiguration(service); _wcfServiceHost.AddServiceEndpoint(typeof(IServiceBusService), Binding, Address); _wcfServiceHost.AddServiceEndpoint(typeof(IServiceBusInterop), Binding, Address); _wcfServiceHost.AddServiceEndpoint(typeof(ICallbackSubscriber), Binding, Address); if (PublishWSDL) { _wcfServiceHost.Description.Behaviors.Remove<ServiceMetadataBehavior>(); _wcfServiceHost.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetUrl = Address, HttpGetEnabled = true, }); } } _logger.LogDebugMessage(nameof(WcfService), "Opening WCF host"); _wcfServiceHost.Open(); _logger.LogDebugMessage(nameof(WcfService), "WCF host opened"); base.Start(); } public override void Stop() { if (_wcfServiceHost != null) { _logger.LogDebugMessage(nameof(WcfService), "Stopping WCF host"); _wcfServiceHost.Abort(); _wcfServiceHost = null; } base.Stop(); } private class ServiceHostWithoutConfiguration : ServiceHost { public ServiceHostWithoutConfiguration(SBService service) : base(service) { } protected override void ApplyConfiguration() { } } }
c#
17
0.610083
227
47.317647
85
/// <summary> /// Base implementation of component for providing access by WCF. /// </summary>
class
private class ServiceHostWithoutConfiguration : ServiceHost { public ServiceHostWithoutConfiguration(SBService service) : base(service) { } protected override void ApplyConfiguration() { } }
c#
7
0.534014
69
28.5
10
/// <summary> /// Special implementation of <see cref="ServiceHost"/> without data from configuration file. /// Used for configuring host from code for testing purposes of for flexible configuring Flexberry Service Bus. /// </summary>
class
public class DmnDecisionSingleResult { private readonly List<DmnExecutionVariable> variables = new List<DmnExecutionVariable>(); public IReadOnlyList<DmnExecutionVariable> Variables => variables; public static DmnDecisionSingleResult operator +(DmnDecisionSingleResult instance, DmnExecutionVariable variable) { if (instance == null) throw new ArgumentNullException(nameof(instance)); if (variable == null) throw new ArgumentNullException(nameof(variable)); instance.variables.Add(variable); return instance; } }
c#
13
0.697368
121
49.75
12
/// <summary> /// Single decision result /// </summary>
class
protected abstract class SnapshotBuilder : Disposable, IRaftLogEntry { private readonly DateTimeOffset timestamp; private long term; protected SnapshotBuilder() => timestamp = DateTimeOffset.UtcNow; protected abstract ValueTask ApplyAsync(LogEntry entry); internal ValueTask ApplyCoreAsync(LogEntry entry) { term = Math.Max(entry.Term, term); return entry.IsEmpty ? new() : ApplyAsync(entry); } [EditorBrowsable(EditorBrowsableState.Advanced)] protected internal virtual void AdjustIndex(long startIndex, long endIndex, ref long currentIndex) { } long? IDataTransferObject.Length => null; long IRaftLogEntry.Term => term; DateTimeOffset ILogEntry.Timestamp => timestamp; bool IDataTransferObject.IsReusable => false; bool ILogEntry.IsSnapshot => true; public abstract ValueTask WriteToAsync<TWriter>(TWriter writer, CancellationToken token) where TWriter : IAsyncBinaryWriter; }
c#
11
0.625654
110
48.869565
23
/// <summary> /// Represents snapshot builder. /// </summary>
class
public sealed partial class Graphics : MarshalByRefObject, IDisposable, IDeviceContext { private IntPtr _nativeHdc; public IntPtr GetHdc() { IntPtr hdc = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipGetDC(new HandleRef(this, NativeGraphics), out hdc); SafeNativeMethods.Gdip.CheckStatus(status); _nativeHdc = hdc; return _nativeHdc; } [EditorBrowsable(EditorBrowsableState.Advanced)] public void ReleaseHdc(IntPtr hdc) => ReleaseHdcInternal(hdc); public void ReleaseHdc() => ReleaseHdcInternal(_nativeHdc); public void Flush() => Flush(FlushIntention.Flush); public void Flush(FlushIntention intention) { int status = SafeNativeMethods.Gdip.GdipFlush(new HandleRef(this, NativeGraphics), intention); SafeNativeMethods.Gdip.CheckStatus(status); FlushCore(); } public void SetClip(Graphics g) => SetClip(g, CombineMode.Replace); public void SetClip(Graphics g, CombineMode combineMode) { if (g == null) { throw new ArgumentNullException(nameof(g)); } int status = SafeNativeMethods.Gdip.GdipSetClipGraphics(new HandleRef(this, NativeGraphics), new HandleRef(g, g.NativeGraphics), combineMode); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetClip(Rectangle rect) => SetClip(rect, CombineMode.Replace); public void SetClip(Rectangle rect, CombineMode combineMode) { int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, combineMode); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetClip(RectangleF rect) => SetClip(rect, CombineMode.Replace); public void SetClip(RectangleF rect, CombineMode combineMode) { int status = SafeNativeMethods.Gdip.GdipSetClipRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, combineMode); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetClip(GraphicsPath path) => SetClip(path, CombineMode.Replace); public void SetClip(GraphicsPath path, CombineMode combineMode) { if (path == null) { throw new ArgumentNullException(nameof(path)); } int status = SafeNativeMethods.Gdip.GdipSetClipPath(new HandleRef(this, NativeGraphics), new HandleRef(path, path.nativePath), combineMode); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetClip(Region region, CombineMode combineMode) { if (region == null) { throw new ArgumentNullException(nameof(region)); } int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion), combineMode); SafeNativeMethods.Gdip.CheckStatus(status); } public void IntersectClip(Rectangle rect) { int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Intersect); SafeNativeMethods.Gdip.CheckStatus(status); } public void IntersectClip(RectangleF rect) { int status = SafeNativeMethods.Gdip.GdipSetClipRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Intersect); SafeNativeMethods.Gdip.CheckStatus(status); } public void IntersectClip(Region region) { if (region == null) { throw new ArgumentNullException(nameof(region)); } int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion), CombineMode.Intersect); SafeNativeMethods.Gdip.CheckStatus(status); } public void ExcludeClip(Rectangle rect) { int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, CombineMode.Exclude); SafeNativeMethods.Gdip.CheckStatus(status); } public void ExcludeClip(Region region) { if (region == null) { throw new ArgumentNullException(nameof(region)); } int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion), CombineMode.Exclude); SafeNativeMethods.Gdip.CheckStatus(status); } public void ResetClip() { int status = SafeNativeMethods.Gdip.GdipResetClip(new HandleRef(this, NativeGraphics)); SafeNativeMethods.Gdip.CheckStatus(status); } public void TranslateClip(float dx, float dy) { int status = SafeNativeMethods.Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy); SafeNativeMethods.Gdip.CheckStatus(status); } public void TranslateClip(int dx, int dy) { int status = SafeNativeMethods.Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy); SafeNativeMethods.Gdip.CheckStatus(status); } public Region Clip { get { var region = new Region(); int status = SafeNativeMethods.Gdip.GdipGetClip(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion)); SafeNativeMethods.Gdip.CheckStatus(status); return region; } set => SetClip(value, CombineMode.Replace); } public RectangleF ClipBounds { get { var rect = new GPRECTF(); int status = SafeNativeMethods.Gdip.GdipGetClipBounds(new HandleRef(this, NativeGraphics), ref rect); SafeNativeMethods.Gdip.CheckStatus(status); return rect.ToRectangleF(); } } public bool IsClipEmpty { get { int isEmpty; int status = SafeNativeMethods.Gdip.GdipIsClipEmpty(new HandleRef(this, NativeGraphics), out isEmpty); SafeNativeMethods.Gdip.CheckStatus(status); return isEmpty != 0; } } public bool IsVisibleClipEmpty { get { int isEmpty; int status = SafeNativeMethods.Gdip.GdipIsVisibleClipEmpty(new HandleRef(this, NativeGraphics), out isEmpty); SafeNativeMethods.Gdip.CheckStatus(status); return isEmpty != 0; } } public bool IsVisible(int x, int y) => IsVisible(new Point(x, y)); public bool IsVisible(Point point) { int isVisible; int status = SafeNativeMethods.Gdip.GdipIsVisiblePointI(new HandleRef(this, NativeGraphics), point.X, point.Y, out isVisible); SafeNativeMethods.Gdip.CheckStatus(status); return isVisible != 0; } public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y)); public bool IsVisible(PointF point) { int isVisible; int status = SafeNativeMethods.Gdip.GdipIsVisiblePoint(new HandleRef(this, NativeGraphics), point.X, point.Y, out isVisible); SafeNativeMethods.Gdip.CheckStatus(status); return isVisible != 0; } public bool IsVisible(int x, int y, int width, int height) { return IsVisible(new Rectangle(x, y, width, height)); } public bool IsVisible(Rectangle rect) { int isVisible; int status = SafeNativeMethods.Gdip.GdipIsVisibleRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, out isVisible); SafeNativeMethods.Gdip.CheckStatus(status); return isVisible != 0; } public bool IsVisible(float x, float y, float width, float height) { return IsVisible(new RectangleF(x, y, width, height)); } public bool IsVisible(RectangleF rect) { int isVisible; int status = SafeNativeMethods.Gdip.GdipIsVisibleRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y, rect.Width, rect.Height, out isVisible); SafeNativeMethods.Gdip.CheckStatus(status); return isVisible != 0; } public Matrix Transform { get { var matrix = new Matrix(); int status = SafeNativeMethods.Gdip.GdipGetWorldTransform(new HandleRef(this, NativeGraphics), new HandleRef(matrix, matrix.nativeMatrix)); SafeNativeMethods.Gdip.CheckStatus(status); return matrix; } set { int status = SafeNativeMethods.Gdip.GdipSetWorldTransform(new HandleRef(this, NativeGraphics), new HandleRef(value, value.nativeMatrix)); SafeNativeMethods.Gdip.CheckStatus(status); } } public void ResetTransform() { int status = SafeNativeMethods.Gdip.GdipResetWorldTransform(new HandleRef(this, NativeGraphics)); SafeNativeMethods.Gdip.CheckStatus(status); } public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix == null) { throw new ArgumentNullException(nameof(matrix)); } int status = SafeNativeMethods.Gdip.GdipMultiplyWorldTransform(new HandleRef(this, NativeGraphics), new HandleRef(matrix, matrix.nativeMatrix), order); SafeNativeMethods.Gdip.CheckStatus(status); } public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend); public void TranslateTransform(float dx, float dy, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipTranslateWorldTransform(new HandleRef(this, NativeGraphics), dx, dy, order); SafeNativeMethods.Gdip.CheckStatus(status); } public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend); public void ScaleTransform(float sx, float sy, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipScaleWorldTransform(new HandleRef(this, NativeGraphics), sx, sy, order); SafeNativeMethods.Gdip.CheckStatus(status); } public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend); public void RotateTransform(float angle, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipRotateWorldTransform(new HandleRef(this, NativeGraphics), angle, order); SafeNativeMethods.Gdip.CheckStatus(status); } }
c#
18
0.585352
161
47.170635
252
/// <summary> /// Encapsulates a GDI+ drawing surface. /// </summary>
class
[CreateNodeMenu("Convert/Continuous-Boolean", 0)] public class TileMapContToBoolNode : BaseNode { [SerializeField, Input] private Types.TileMapCont _TileMapIn; [SerializeField, Input, Range(0, 1)] private float _Threshold = 0.5f; [SerializeField, Output] private Types.TileMapBool _TileMapOut; private float _CurrentThreshold = 0f; private long _TileMapInIDBuffer = 0L; private Types.TileMapBool _TileMapOutBuffer; private void Reset() { name = "Tile-Map (Continuous-Boolean)"; } public override object GetValue(NodePort port) { if (port.fieldName == "_TileMapOut") { GetTileMapInput<Types.TileMapCont, Types.TileMapBool>( "_TileMapIn", "_TileMapOut", ref _TileMapOutBuffer, ref _TileMapInIDBuffer, _CurrentThreshold != GetThreshold() ); return _TileMapOutBuffer; } return null; } protected override void UpdateTileMapOutput(string portName) { if (portName == "_TileMapOut") { _CurrentThreshold = GetThreshold(); Types.TileMapCont matrixIn = GetInputValue<Types.TileMapCont>("_TileMapIn"); _TileMapOutBuffer = _Graph.functionLibrary.tileMapCast.CastContToBool(matrixIn, _Threshold, GPUEnabled); } } private float GetThreshold() { return GetInputValue<float>("_Threshold", _Threshold); } }
c#
15
0.574627
120
39.225
40
/// <summary> Type cast node for converting from Cont to Bool. </summary>
class
[TestClass] public class ApiTesting { [TestMethod] public void GenericType() => RoslynTestHelper.CheckApi(); [TestMethod] public void ArrayTypes() => RoslynTestHelper.CheckApi(); [TestMethod] public void Unsafe() => RoslynTestHelper.CheckApi(); [TestMethod] public void NestedTypes() => RoslynTestHelper.CheckApi(); [TestMethod] public void NamespaceOrdering() => RoslynTestHelper.CheckApi(); [TestMethod] public void NamespaceMemberAccessibility() => RoslynTestHelper.CheckApi(); [TestMethod] public void AccessibilityOrdering() => RoslynTestHelper.CheckApi(); [TestMethod] public void Tuples() => RoslynTestHelper.CheckApi(); [TestMethod] public void Parameters() => RoslynTestHelper.CheckApi(); [TestMethod] public void NullableContext() => RoslynTestHelper.CheckApi(); [TestMethod] public void ReferenceNullable() => RoslynTestHelper.CheckApi(); }
c#
7
0.641001
82
39
26
/// <summary> /// Tests various API portions of the application. /// </summary>
class
public class PhoneStatus : Element { public PhoneStatus() { this.TagName = "phone-status"; this.Namespace = Uri.JIVESOFTWARE_PHONE; } public PhoneStatusType Status { set { SetAttribute("status", value.ToString()); } get { return (PhoneStatusType)GetAttributeEnum("status", typeof(PhoneStatusType)); } } }
c#
13
0.465447
92
24.947368
19
/// <summary> /// A user's presence is updated when on a phone call. /// The Jive Messenger/Asterisk implementation will update the user's presence automatically /// by adding the following packet extension to the user's presence: /// &lt;phone-status xmlns="http://jivesoftware.com/xmlns/phone" status="ON_PHONE" &gt; /// Jive Messenger can also be configured to change the user's availability /// to "Away -- on the phone" when the user is on a call (in addition to the packet extension). /// This is useful when interacting with clients that don't understand the extended presence information /// or when using transports to other IM networks where extended presence information is not available. /// </summary>
class
public class HttpClientFactory : IHttpClientFactory { public HttpClientFactory(IConfiguration configuration, HttpClientHandler httpClientHandler) { if (configuration is null) throw new ArgumentNullException(nameof(configuration)); if (httpClientHandler is null) throw new ArgumentNullException(nameof(httpClientHandler)); Configuration = configuration; HttpClientHandler = httpClientHandler; } protected IConfiguration Configuration { get; } protected HttpClientHandler HttpClientHandler { get; } public virtual HttpClient Create() { var httpClient = new HttpClient(HttpClientHandler); var url = Configuration.GetValue<string>(ConfigurationPath.ServerUrl); var token = Configuration.GetValue<string>(ConfigurationPath.ServerAuthenticationUuid); httpClient.BaseAddress = new Uri(url).Normalize(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); httpClient.DefaultRequestHeaders.Add("User-Agent", ".NET Reporter"); var timeout = GetTimeout(); if (timeout.HasValue) { httpClient.Timeout = timeout.Value; } return httpClient; } protected virtual TimeSpan? GetTimeout() { TimeSpan? timeout = null; var seconds = Configuration.GetValue("Server:Timeout", double.NaN); if (!double.IsNaN(seconds)) { timeout = TimeSpan.FromSeconds(seconds); } return timeout; } }
c#
13
0.633826
113
45.871795
39
/// <summary> /// Class to create <see cref="HttpClient"/> instance based on <see cref="IConfiguration"/> object. /// </summary>
class
public class Pair : Pair<object, object> { public Pair(object o1, object o2) : base(o1, o2) { } }
c#
7
0.601852
40
14.571429
7
/// <summary> /// A simple 2-tuple class that can be used to generically represent a pair /// of object instances /// </summary>
class
public class Pair<F, S> { public F Object1; public S Object2; public Pair(F o1, S o2) { Object1 = o1; Object2 = o2; } public override bool Equals(object obj) { Pair<F, S> other = obj as Pair<F, S>; return (other != null && (object)other.Object1 == (object)Object1 && (object)other.Object2 == (object)Object2); } public override int GetHashCode() { return Object1.GetHashCode() + Object2.GetHashCode(); } }
c#
12
0.620309
56
20.619048
21
/// <summary> /// A simple 2-tuple class that can be used to generically represent a pair /// of object instances /// </summary>
class
public static partial class AppServicePlansOperationsExtensions { public static async Task<IPage<AppServicePlanInner>> ListAsync(this IAppServicePlansOperations operations, bool? detailed = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(detailed, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<AppServicePlanInner>> ListByResourceGroupAsync(this IAppServicePlansOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<AppServicePlanInner> GetAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<AppServicePlanInner> CreateOrUpdateAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, AppServicePlanInner appServicePlan, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, appServicePlan, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task DeleteAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)).Dispose(); } public static async Task<AppServicePlanInner> UpdateAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, AppServicePlanPatchResource appServicePlan, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, name, appServicePlan, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IList<CapabilityInner>> ListCapabilitiesAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListCapabilitiesWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<HybridConnectionInner> GetHybridConnectionAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetHybridConnectionWithHttpMessagesAsync(resourceGroupName, name, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task DeleteHybridConnectionAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteHybridConnectionWithHttpMessagesAsync(resourceGroupName, name, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } public static async Task<HybridConnectionKeyInner> ListHybridConnectionKeysAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListHybridConnectionKeysWithHttpMessagesAsync(resourceGroupName, name, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<string>> ListWebAppsByHybridConnectionAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string namespaceName, string relayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWebAppsByHybridConnectionWithHttpMessagesAsync(resourceGroupName, name, namespaceName, relayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<HybridConnectionLimitsInner> GetHybridConnectionPlanLimitAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetHybridConnectionPlanLimitWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<HybridConnectionInner>> ListHybridConnectionsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListHybridConnectionsWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<ResourceMetricDefinition>> ListMetricDefintionsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricDefintionsWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<ResourceMetric>> ListMetricsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, bool? details = default(bool?), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricsWithHttpMessagesAsync(resourceGroupName, name, details, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task RestartWebAppsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, bool? softRestart = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.RestartWebAppsWithHttpMessagesAsync(resourceGroupName, name, softRestart, null, cancellationToken).ConfigureAwait(false)).Dispose(); } public static async Task<IPage<SiteInner>> ListWebAppsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string skipToken = default(string), string filter = default(string), string top = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWebAppsWithHttpMessagesAsync(resourceGroupName, name, skipToken, filter, top, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<object> GetServerFarmSkusAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetServerFarmSkusWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<CsmUsageQuota>> ListUsagesAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListUsagesWithHttpMessagesAsync(resourceGroupName, name, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IList<VnetInfoInner>> ListVnetsAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListVnetsWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<VnetInfoInner> GetVnetFromServerFarmAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetVnetFromServerFarmWithHttpMessagesAsync(resourceGroupName, name, vnetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<VnetGatewayInner> GetVnetGatewayAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetVnetGatewayWithHttpMessagesAsync(resourceGroupName, name, vnetName, gatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<VnetGatewayInner> UpdateVnetGatewayAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string gatewayName, VnetGatewayInner connectionEnvelope, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateVnetGatewayWithHttpMessagesAsync(resourceGroupName, name, vnetName, gatewayName, connectionEnvelope, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IList<VnetRouteInner>> ListRoutesForVnetAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRoutesForVnetWithHttpMessagesAsync(resourceGroupName, name, vnetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IList<VnetRouteInner>> GetRouteForVnetAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string routeName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRouteForVnetWithHttpMessagesAsync(resourceGroupName, name, vnetName, routeName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<VnetRouteInner> CreateOrUpdateVnetRouteAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string routeName, VnetRouteInner route, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateVnetRouteWithHttpMessagesAsync(resourceGroupName, name, vnetName, routeName, route, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task DeleteVnetRouteAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string routeName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteVnetRouteWithHttpMessagesAsync(resourceGroupName, name, vnetName, routeName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } public static async Task<VnetRouteInner> UpdateVnetRouteAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string vnetName, string routeName, VnetRouteInner route, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateVnetRouteWithHttpMessagesAsync(resourceGroupName, name, vnetName, routeName, route, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task RebootWorkerAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, string workerName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.RebootWorkerWithHttpMessagesAsync(resourceGroupName, name, workerName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } public static async Task<AppServicePlanInner> BeginCreateOrUpdateAsync(this IAppServicePlansOperations operations, string resourceGroupName, string name, AppServicePlanInner appServicePlan, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, appServicePlan, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<AppServicePlanInner>> ListNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<AppServicePlanInner>> ListByResourceGroupNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<string>> ListWebAppsByHybridConnectionNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWebAppsByHybridConnectionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<HybridConnectionInner>> ListHybridConnectionsNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListHybridConnectionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<ResourceMetricDefinition>> ListMetricDefintionsNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricDefintionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<ResourceMetric>> ListMetricsNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListMetricsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<SiteInner>> ListWebAppsNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWebAppsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } public static async Task<IPage<CsmUsageQuota>> ListUsagesNextAsync(this IAppServicePlansOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListUsagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } }
c#
15
0.686514
319
76.102362
254
/// <summary> /// Extension methods for AppServicePlansOperations. /// </summary>
class
public class FollowersClient : ApiClient, IFollowersClient { public FollowersClient(IApiConnection apiConnection) : base(apiConnection) { } public Task<IReadOnlyList<User>> GetAllForCurrent() { return ApiConnection.GetAll<User>(ApiUrls.Followers()); } public Task<IReadOnlyList<User>> GetAll(string login) { Ensure.ArgumentNotNullOrEmptyString(login, "login"); return ApiConnection.GetAll<User>(ApiUrls.Followers(login)); } public Task<IReadOnlyList<User>> GetAllFollowingForCurrent() { return ApiConnection.GetAll<User>(ApiUrls.Following()); } public Task<IReadOnlyList<User>> GetAllFollowing(string login) { Ensure.ArgumentNotNullOrEmptyString(login, "login"); return ApiConnection.GetAll<User>(ApiUrls.Following(login)); } public async Task<bool> IsFollowingForCurrent(string following) { Ensure.ArgumentNotNullOrEmptyString(following, "following"); try { var response = await Connection.Get<object>(ApiUrls.IsFollowing(following), null, null) .ConfigureAwait(false); return response.HttpResponse.IsTrue(); } catch (NotFoundException) { return false; } } public async Task<bool> IsFollowing(string login, string following) { Ensure.ArgumentNotNullOrEmptyString(login, "login"); Ensure.ArgumentNotNullOrEmptyString(following, "following"); try { var response = await Connection.Get<object>(ApiUrls.IsFollowing(login, following), null, null) .ConfigureAwait(false); return response.HttpResponse.IsTrue(); } catch (NotFoundException) { return false; } } public async Task<bool> Follow(string login) { Ensure.ArgumentNotNullOrEmptyString(login, "login"); try { var requestData = new { }; var response = await Connection.Put<object>(ApiUrls.IsFollowing(login), requestData) .ConfigureAwait(false); if (response.HttpResponse.StatusCode != HttpStatusCode.NoContent) { throw new ApiException("Invalid Status Code returned. Expected a 204", response.HttpResponse.StatusCode); } return response.HttpResponse.StatusCode == HttpStatusCode.NoContent; } catch (NotFoundException) { return false; } } public Task Unfollow(string login) { Ensure.ArgumentNotNullOrEmptyString(login, "login"); return ApiConnection.Delete(ApiUrls.IsFollowing(login)); } }
c#
20
0.551535
125
39.207792
77
/// <summary> /// A client for GitHub's User Followers API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/users/followers/">Followers API documentation</a> for more information. ///</remarks>
class
internal class DeflateStream : System.IO.Stream { private ZlibBaseStream _baseStream; private bool _disposed; <param name="stream">The stream which will be read.</param> public DeflateStream(System.IO.Stream stream) : this(stream, false) { } Create a <c>DeflateStream</c> and explicitly specify whether the stream should be left open after Inflation. <remarks> <para> This constructor allows the application to request that the captive stream remain open after the inflation occurs. By default, after <c>Close()</c> is called on the stream, the captive stream is also closed. In some cases this is not desired, for example if the stream is a memory stream that will be re-read after compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream open. </para> <para> The <c>DeflateStream</c> will use the default compression level. </para> <para> See the other overloads of this constructor for example code. </para> </remarks> <param name="stream"> The stream which will be read. This is called the "captive" stream in other places in this documentation. </param> <param name="leaveOpen">true if the application would like the stream to remain open after inflation.</param> public DeflateStream(System.IO.Stream stream, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.DEFLATE, leaveOpen); } #region System.IO.Stream methods Dispose the stream. <remarks> <para> This may or may not result in a <c>Close()</c> call on the captive stream. See the constructors that have a <c>leaveOpen</c> parameter for more information. </para> <para> Application code won't call this code directly. This method may be invoked in two distinct scenarios. If disposing == true, the method has been called directly or indirectly by a user's code, for example via the public Dispose() method. In this case, both managed and unmanaged resources can be referenced and disposed. If disposing == false, the method has been called by the runtime from inside the object finalizer and this method should not reference other objects; in that case only unmanaged resources must be referenced or disposed. </para> </remarks> <param name="disposing"> true if the Dispose method was invoked by user code. </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Dispose(); _disposed = true; } } finally { base.Dispose(disposing); } } Indicates whether the stream can be read. <remarks> The return value depends on whether the captive stream supports reading. </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanRead; } } Indicates whether the stream supports Seek operations. <remarks> Always returns false. </remarks> public override bool CanSeek { get { return false; } } Indicates whether the stream can be written. <remarks> The return value depends on whether the captive stream supports writing. </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanWrite; } } Flush the stream. public override void Flush() { if (_disposed) throw new ObjectDisposedException("DeflateStream"); _baseStream.Flush(); } Reading this property always throws a <see cref="NotImplementedException"/>. public override long Length { get { throw new NotImplementedException(); } } The position of the stream pointer. <remarks> Setting this property always throws a <see cref="NotImplementedException"/>. Reading will return the total bytes read in. The count may refer to compressed bytes or uncompressed bytes, depending on how you've used the stream. </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotImplementedException(); } } Read data from the stream. <remarks> <para> If you wish to use the <c>DeflateStream</c> to compress data while reading, you can create a <c>DeflateStream</c> with <c>CompressionMode.Compress</c>, providing an uncompressed data stream. Then call Read() on that <c>DeflateStream</c>, and the data read will be compressed as you read. If you wish to use the <c>DeflateStream</c> to decompress data while reading, you can create a <c>DeflateStream</c> with <c>CompressionMode.Decompress</c>, providing a readable compressed data stream. Then call Read() on that <c>DeflateStream</c>, and the data read will be decompressed as you read. </para> <para> A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. </para> </remarks> <param name="buffer">The buffer into which the read data should be placed.</param> <param name="offset">the offset within that data array to put the first byte read.</param> <param name="count">the number of bytes to read.</param> <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream.Read(buffer, offset, count); } Calling this method always throws a <see cref="NotImplementedException"/>. <param name="offset">this is irrelevant, since it will always throw!</param> <param name="origin">this is irrelevant, since it will always throw!</param> <returns>irrelevant!</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); } Calling this method always throws a <see cref="NotImplementedException"/>. <param name="value">this is irrelevant, since it will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } Not implemented. <param name="buffer">The buffer holding data to write to the stream.</param> <param name="offset">the offset within that data array to find the first byte to write.</param> <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } #endregion }
c#
32
0.584674
104
42.435484
186
/// <summary> /// A class for decompressing streams using the Deflate algorithm. /// </summary> /// /// <remarks> /// /// <para> /// The DeflateStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds DEFLATE decompression to any stream. /// </para> /// /// <para> /// Using this stream, applications can decompress data via stream /// <c>Read</c> operations. The compression format used is /// DEFLATE, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.". /// </para> /// /// </remarks> /// /// <seealso cref="GZipStream" />
class
public static class ExtensionMethods { public static string GetDescription(this Enum value) { return ((DescriptionAttribute)Attribute.GetCustomAttribute( value.GetType().GetFields(BindingFlags.Public | BindingFlags.Static) .Single(x => x.GetValue(null).Equals(value)), typeof(DescriptionAttribute)))?.Description ?? value.ToString(); } public static string GetUnixTimeStamp(this DateTime baseDateTime) { var dtOffset = new DateTimeOffset(baseDateTime); return dtOffset.ToUnixTimeMilliseconds().ToString(); } public static bool IsValidJson(this string stringValue) { if (string.IsNullOrWhiteSpace(stringValue)) { return false; } var value = stringValue.Trim(); if ((value.StartsWith("{") && value.EndsWith("}")) || (value.StartsWith("[") && value.EndsWith("]"))) { try { var obj = JToken.Parse(value); return true; } catch (JsonReaderException) { return false; } } return false; } }
c#
22
0.501124
84
35.108108
37
/// <summary> /// Class to define extension methods. /// </summary>
class
[Serializable] public class XmppException : Exception { public XmppErrorCode ErrorCode { get; private set; } public XmppException() { } public XmppException(string message) : base(message) { } public XmppException(string message, Exception inner) : base(message ?? inner?.Message, inner) { } public XmppException(XmppErrorCode errorCode) : base(DefaultMessage(errorCode)) { ErrorCode = errorCode; } public XmppException(XmppErrorCode errorCode, string message) : base(DefaultMessage(errorCode, message)) { ErrorCode = errorCode; } public XmppException(XmppErrorCode errorCode, Exception inner) : base(DefaultMessage(errorCode, inner?.Message)) { ErrorCode = errorCode; } public XmppException(XmppErrorCode errorCode, string message, Exception inner) : base(DefaultMessage(errorCode, message ?? inner?.Message), inner) { ErrorCode = errorCode; } protected XmppException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { ErrorCode = (XmppErrorCode)info.GetInt32("ErrorCode"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ErrorCode", (int)ErrorCode); } internal static string DefaultMessage(XmppErrorCode errorCode, string message = null) { if (!string.IsNullOrEmpty(message)) return message; switch (errorCode) { case XmppErrorCode.UnrecognizedStream: return Properties.Resources.XmppErrorCode_UnrecognizedStream; case XmppErrorCode.BadFormat: return Properties.Resources.XmppErrorCode_BadFormat; case XmppErrorCode.BadNamespacePrefix: return Properties.Resources.XmppErrorCode_BadNamespacePrefix; case XmppErrorCode.Conflict: return Properties.Resources.XmppErrorCode_Conflict; case XmppErrorCode.ConnectionTimeout: return Properties.Resources.XmppErrorCode_ConnectionTimeout; case XmppErrorCode.HostGone: return Properties.Resources.XmppErrorCode_HostGone; case XmppErrorCode.HostUnknown: return Properties.Resources.XmppErrorCode_HostUnknown; case XmppErrorCode.ImproperAddressing: return Properties.Resources.XmppErrorCode_ImproperAddressing; case XmppErrorCode.InternalServerError: return Properties.Resources.XmppErrorCode_InternalServerError; case XmppErrorCode.InvalidFrom: return Properties.Resources.XmppErrorCode_InvalidFrom; case XmppErrorCode.InvalidID: return Properties.Resources.XmppErrorCode_InvalidID; case XmppErrorCode.InvalidNamespace: return Properties.Resources.XmppErrorCode_InvalidNamespace; case XmppErrorCode.InvalidXml: return Properties.Resources.XmppErrorCode_InvalidXml; case XmppErrorCode.NotAuthorized: return Properties.Resources.XmppErrorCode_NotAuthorized; case XmppErrorCode.PolicyViolation: return Properties.Resources.XmppErrorCode_PolicyViolation; case XmppErrorCode.RemoteConnectionFailed: return Properties.Resources.XmppErrorCode_RemoteConnectionFailed; case XmppErrorCode.ResourceConstraint: return Properties.Resources.XmppErrorCode_ResourceConstraint; case XmppErrorCode.RestrictedXml: return Properties.Resources.XmppErrorCode_RestrictedXml; case XmppErrorCode.SeeOtherHost: return Properties.Resources.XmppErrorCode_SeeOtherHost; case XmppErrorCode.SystemShutdown: return Properties.Resources.XmppErrorCode_SystemShutdown; case XmppErrorCode.UnsupportedEncoding: return Properties.Resources.XmppErrorCode_UnsupportedEncoding; case XmppErrorCode.UnsupportedStanzaType: return Properties.Resources.XmppErrorCode_UnsupportedStanzaType; case XmppErrorCode.UnsupportedVersion: return Properties.Resources.XmppErrorCode_UnsupportedVersion; case XmppErrorCode.XmlNotWellFormed: return Properties.Resources.XmppErrorCode_XmlNotWellFormed; case XmppErrorCode.RequiredFeatureUnknown: return Properties.Resources.XmppErrorCode_RequiredFeatureUnknown; case XmppErrorCode.AuthenticationFailed: return Properties.Resources.XmppErrorCode_AuthenticationFailed; case XmppErrorCode.AuthenticationAborted: return Properties.Resources.XmppErrorCode_AuthenticationAborted; case XmppErrorCode.AccountDisabled: return Properties.Resources.XmppErrorCode_AccountDisabled; case XmppErrorCode.CredentialsExpired: return Properties.Resources.XmppErrorCode_CredentialsExpired; case XmppErrorCode.EncryptionRequired: return Properties.Resources.XmppErrorCode_EncryptionRequired; case XmppErrorCode.InvalidImpersonation: return Properties.Resources.XmppErrorCode_InvalidImpersonation; case XmppErrorCode.InvalidMechanism: return Properties.Resources.XmppErrorCode_InvalidMechanism; case XmppErrorCode.MalformedRequest: return Properties.Resources.XmppErrorCode_MalformedRequest; case XmppErrorCode.MechanismTooWeak: return Properties.Resources.XmppErrorCode_MechanismTooWeak; case XmppErrorCode.TemporaryAuthFailure: return Properties.Resources.XmppErrorCode_TemporaryAuthFailure; case XmppErrorCode.Stanza: return Properties.Resources.XmppErrorCode_Stanza; default: return Properties.Resources.XmppErrorCode_Unknown; } } }
c#
12
0.706019
124
62.494737
95
/// <summary> /// Represents an exception about an XMPP connection. /// </summary>
class
public sealed class HeadersCollection { readonly IDictionary<string, string> _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public string this[string name] { get { string value; if (_values.TryGetValue(name, out value)) return value; return null; } set { if (value != null) { _values[name] = value; } else if (_values.ContainsKey(name)) { _values.Remove(name); } } } public int Count { get { return this._values.Count; } } public ICollection<string> Keys { get { return _values.Keys; } } public string CacheControl { get { return this["Cache-Control"]; } set { this["Cache-Control"] = value; } } public string ContentDisposition { get { return this["Content-Disposition"]; } set { this["Content-Disposition"] = value; } } public string ContentEncoding { get { return this["Content-Encoding"]; } set { this["Content-Encoding"] = value; } } public long ContentLength { get { string str = this["Content-Length"]; if (string.IsNullOrEmpty(str)) return -1; return long.Parse(str, CultureInfo.InvariantCulture); } set { this["Content-Length"] = value.ToString(CultureInfo.InvariantCulture); } } public string ContentMD5 { get { return this["Content-MD5"]; } set { this["Content-MD5"] = value; } } public string ContentType { get { return this["Content-Type"]; } set { this["Content-Type"] = value; } } internal bool IsSetContentType() { return !string.IsNullOrEmpty(this.ContentType); } public DateTime? ExpiresUtc { get { if (this["Expires"] == null) return null; return DateTime.Parse(this["Expires"], CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); } set { if (value == null) this["Expires"] = null; this["Expires"] = value.GetValueOrDefault().ToUniversalTime().ToString(Amazon.Util.AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture); } } [Obsolete("Setting this property results in non-UTC DateTimes not being marshalled correctly. Use ExpiresUtc instead.", false)] public DateTime? Expires { get { return ExpiresUtc?.ToLocalTime(); } set { ExpiresUtc = value == null ? (DateTime?)null : new DateTime(value.Value.Ticks, DateTimeKind.Utc); } } }
c#
15
0.479225
160
32.010309
97
/// <summary> /// This class contains the headers for an S3 object. /// </summary>
class
public sealed class YuiCssMinifier : YuiMinifierBase, ICssMinifier { private readonly YuiCssMinificationSettings _settings; private CssCompressor _originalCssMinifier; private readonly object _minificationSynchronizer = new object(); public YuiCssMinifier() : this(new YuiCssMinificationSettings()) { } public YuiCssMinifier(YuiCssMinificationSettings settings) { _settings = settings; } private static CssCompressor CreateOriginalCssMinifierInstance(YuiCssMinificationSettings settings) { var originalMinifier = new CssCompressor(); ApplyCommonSettingsToOriginalMinifier(originalMinifier, settings); originalMinifier.RemoveComments = settings.RemoveComments; return originalMinifier; } #region ICssMinifier implementation public bool IsInlineCodeMinificationSupported { get { return true; } } public CodeMinificationResult Minify(string content, bool isInlineCode) { return Minify(content, isInlineCode, TextEncodingShortcuts.Default); } public CodeMinificationResult Minify(string content, bool isInlineCode, Encoding encoding) { if (string.IsNullOrWhiteSpace(content)) { return new CodeMinificationResult(string.Empty); } string newContent = string.Empty; var errors = new List<MinificationErrorInfo>(); try { lock (_minificationSynchronizer) { if (_originalCssMinifier == null) { _originalCssMinifier = CreateOriginalCssMinifierInstance(_settings); } newContent = _originalCssMinifier.Compress(content); } } catch (ArgumentOutOfRangeException) { errors.Add(new MinificationErrorInfo(CoreStrings.ErrorMessage_UnknownError, 0, 0, string.Empty)); } return new CodeMinificationResult(newContent, errors); } #endregion }
c#
16
0.758329
101
31.218182
55
/// <summary> /// Minifier, which produces minifiction of CSS-code by using the YUI CSS Compressor for .NET /// </summary>
class
[ConfigGroup("ForgeConfig", "Forge.cfg")] public static class ForgeSettings { [ConfigItem(4)] public static int LogLevel { get; set; } [ConfigItem("Info.log")] public static string InfoLogFile { get; set; } [ConfigItem("Critical.log")] public static string CriticalLogFile { get; set; } [ConfigItem("Warning.log")] public static string WarningLogFile { get; set; } [ConfigItem("Logs")] public static string LogDirectory { get; set; } }
c#
9
0.607211
58
36.714286
14
/// <summary> /// This class contains all global Forge related config settings. /// </summary>
class
[ComVisible(true), ToolboxItem(false)] public partial class BasePropertyPage : System.Windows.Forms.UserControl, IPropertyPage2 { #region Private data members private static readonly Dictionary<string, string> customControls = new Dictionary<string, string>(); private static readonly List<BasePropertyPage> propertyPages = new List<BasePropertyPage>(); private bool isDirty; #endregion #region Properties internal static List<BasePropertyPage> AllPropertyPages => propertyPages; protected virtual bool IsValid => true; protected string Title { get; set; } protected string HelpKeyword { get; set; } protected bool IsBinding { get; set; } protected internal bool IsDirty { get => isDirty; set { ThreadHelper.ThrowIfNotOnUIThread(); if(isDirty != value && !this.IsBinding) { isDirty = value; if(this.PropertyPageSite != null) this.PropertyPageSite.OnStatusChange((uint)(isDirty ? PropPageStatus.Dirty : PropPageStatus.Clean)); } } } protected IPropertyPageSite PropertyPageSite { get; private set; } protected ProjectNode ProjectMgr { get; private set; } protected ReadOnlyCollection<ProjectConfig> ProjectConfigs { get; private set; } <para><b>NOTE:</b>You only need to add controls to this property if it is not derived from one of the standard edit controls (see <see cref="BindProperties"/> for more information).</para> <para>This property is static so it can be populated once at start-up for use throughout the application's lifetime.</para></remarks> <example> <code language="cs"> // Use the PeristablePath property for binding in controls of type // SandcastleBuilder.WPF.PropertyPages.FilePathUserControl. This control is // not derived from a standard control so we need to add it manually. BasePropertyPage.CustomControls.Add( "Sandcastle.Platform.Windows.UserControls.FilePathUserControl", "PersistablePath"); </code> </example> public static Dictionary<string, string> CustomControls => customControls; #endregion #region Constructor Constructor public BasePropertyPage() { InitializeComponent(); } #endregion #region Method overrides <inheritdoc /> protected override bool ProcessMnemonic(char charCode) { return base.ProcessMnemonic(charCode); } This is overridden to handle the F1 key to show help for the page and to process mnemonics <param name="keyData">The key data to check</param> <returns>True if the key was handled, false if not</returns> <remarks>This appears to be necessary because the <c>IPropertyPage2.TranslateAccelerator</c> method is never called. As such, Visual Studio invokes help on F1 rather than us getting a <c>HelpRequested</c> event and it invokes menus if a mnemonic matches a menu hot key rather than focusing the associated control.</remarks> protected override bool ProcessDialogKey(WinFormsKeys keyData) { if(keyData == WinFormsKeys.F1) { if(this.ShowHelp()) return true; } else if((keyData & ~WinFormsKeys.KeyCode) == WinFormsKeys.Alt) { WinFormsKeys key = (keyData & ~WinFormsKeys.Alt); if(((Char.IsLetterOrDigit((char)((ushort)key)) && (key < WinFormsKeys.F1 || key > WinFormsKeys.F24)) || (key >= WinFormsKeys.NumPad0 && key <= WinFormsKeys.Divide)) && this.ProcessMnemonic((char)((ushort)key))) return true; } return base.ProcessDialogKey(keyData); } #endregion #region Methods This can be overridden to perform custom initialization for the property page protected virtual void Initialize() { } Derived classes can connect the change event on custom controls to this method to notify the page of changes in the control's value. <param name="sender">The sender of the event</param> <param name="e">The event arguments</param> protected void OnPropertyChanged(object sender, EventArgs e) { if(!this.IsBinding) { #pragma warning disable VSTHRD010 this.IsDirty = true; #pragma warning restore VSTHRD010 this.RefreshControlState(sender, e); } } This can be overridden to specify whether the property value is escaped or not. <param name="propertyName">The property name</param> <returns>True if the property contains an escaped value, false if not. When bound, an escaped property's value is unescaped before it is assigned to the control. When stored, the new value is escaped before it is stored.</returns> protected virtual bool IsEscapedProperty(string propertyName) { return false; } This can be overridden to bind a control to a property in a manner other than the default handling supplied by the base class. <param name="propertyName">The name of the property to bind</param> <returns>True if the method bound the control or it should be ignored, false if the base class should attempt to bind it in the default manner.</returns> protected virtual bool BindControlValue(string propertyName) { return false; } This can be overridden to store a control value in a property in a manner other than the default handling supplied by the base class. <param name="propertyName">The name of the property to store</param> <returns>True if the method stored the control value or it should be ignored, false if the base class should attempt to store the value in the default manner.</returns> protected virtual bool StoreControlValue(string propertyName) { return false; } This can be overridden to refresh the control state when certain events occur <param name="sender">The sender of the event</param> <param name="e">The event arguments</param> protected virtual void RefreshControlState(object sender, EventArgs e) { } This can be overridden to display help for the property page <returns>True if a keyword has been set and help was shown or false if not</returns> public virtual bool ShowHelp() { if(!String.IsNullOrEmpty(this.HelpKeyword)) { UiUtility.ShowHelpTopic(this.HelpKeyword); return true; } return false; } This is used to bind the controls in the given collection to their associated project properties <param name="controls">The control collection from which to get the bound controls. WPF controls and their children in an <see cref="ElementHost"/> are bound if they declare a property name using the <see cref="P:SandcastleBuilder.WPF.PropertyPages.PropertyPageBinding.ProjectPropertyName"/> attached property.</param> protected void BindProperties(System.Windows.Forms.Control.ControlCollection controls) { Type t; PropertyInfo pi; string typeName, boundProperty; try { this.IsBinding = true; foreach(var control in controls.OfType<ElementHost>().Select(h => (FrameworkElement)h.Child)) { foreach(var c in control.AllChildElements().Where(c => !String.IsNullOrWhiteSpace(PropertyPageBinding.GetProjectPropertyName(c)))) { t = c.GetType(); typeName = t.FullName; boundProperty = PropertyPageBinding.GetProjectPropertyName(c); if(customControls.ContainsKey(typeName)) { var changedEvent = t.GetEvents().Where(ev => ev.Name == customControls[typeName] + "Changed").FirstOrDefault(); if(changedEvent != null) { Delegate h; if(changedEvent.EventHandlerType == typeof(RoutedPropertyChangedEventHandler<object>)) { h = new RoutedPropertyChangedEventHandler<object>(OnWpfPropertyChanged); } else h = new EventHandler(OnPropertyChanged); changedEvent.RemoveEventHandler(c, h); changedEvent.AddEventHandler(c, h); } pi = t.GetProperty(customControls[typeName], BindingFlags.Public | BindingFlags.Instance); } else if(c is Label) { pi = t.GetProperty("Content", BindingFlags.Public | BindingFlags.Instance); } else if(c is TextBoxBase tb) { tb.TextChanged -= OnPropertyChanged; tb.TextChanged += OnPropertyChanged; pi = t.GetProperty("Text", BindingFlags.Public | BindingFlags.Instance); } else if(c is Selector sel) { sel.SelectionChanged -= OnPropertyChanged; sel.SelectionChanged += OnPropertyChanged; pi = t.GetProperty("SelectedValue", BindingFlags.Public | BindingFlags.Instance); } else if(c is CheckBox cb) { cb.Click -= OnPropertyChanged; cb.Click += OnPropertyChanged; pi = t.GetProperty("IsChecked", BindingFlags.Public | BindingFlags.Instance); } else pi = null; if(!this.BindControlValue(boundProperty) && pi != null) this.Bind(c, pi, boundProperty); } } } finally { this.IsBinding = false; } } Bind the control to the property value by setting the property to the current value from the project <param name="control">The control to bind</param> <param name="propertyInfo">The property information</param> <param name="boundProperty">The project property name</param> private void Bind(object control, PropertyInfo propertyInfo, string boundProperty) { string propValue = null; object controlValue; if(this.ProjectMgr != null) { var projProp = this.ProjectMgr.BuildProject.GetProperty(boundProperty); if(projProp != null) { while(projProp.IsImported && projProp.Predecessor != null) projProp = projProp.Predecessor; propValue = projProp.UnevaluatedValue; } if(propValue == null) return; if(this.IsEscapedProperty(boundProperty)) propValue = EscapeValueAttribute.Unescape(propValue); TypeCode typeCode = Type.GetTypeCode(propertyInfo.PropertyType); if(typeCode == TypeCode.Object && propertyInfo.PropertyType.GenericTypeArguments.Length != 0) typeCode = Type.GetTypeCode(propertyInfo.PropertyType.GenericTypeArguments[0]); switch(typeCode) { case TypeCode.Object: case TypeCode.String: controlValue = propValue; break; case TypeCode.Char: controlValue = propValue[0]; break; case TypeCode.Byte: controlValue = Convert.ToByte(propValue[0]); break; case TypeCode.SByte: controlValue = Convert.ToSByte(propValue[0]); break; case TypeCode.Decimal: controlValue = Convert.ToDecimal(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Double: controlValue = Convert.ToDouble(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Single: controlValue = Convert.ToSingle(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Int16: controlValue = Convert.ToInt16(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Int32: controlValue = Convert.ToInt32(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Int64: controlValue = Convert.ToInt64(propValue, CultureInfo.CurrentCulture); break; case TypeCode.UInt16: controlValue = Convert.ToUInt16(propValue, CultureInfo.CurrentCulture); break; case TypeCode.UInt32: controlValue = Convert.ToUInt32(propValue, CultureInfo.CurrentCulture); break; case TypeCode.UInt64: controlValue = Convert.ToUInt64(propValue, CultureInfo.CurrentCulture); break; case TypeCode.Boolean: controlValue = Convert.ToBoolean(propValue, CultureInfo.CurrentCulture); break; case TypeCode.DateTime: controlValue = Convert.ToDateTime(propValue, CultureInfo.CurrentCulture); break; default: return; } propertyInfo.SetValue(control, controlValue, null); } } This is used to store the control values in the given collection to their associated project properties. <param name="controls">The control collection from which to get the bound controls. WPF controls and their children in an <see cref="ElementHost"/> are bound if they declare a property name using the <see cref="P:SandcastleBuilder.WPF.PropertyPages.PropertyPageBinding.ProjectPropertyName"/> attached property.</param> protected void StoreProperties(System.Windows.Forms.Control.ControlCollection controls) { Type t; PropertyInfo pi; object controlValue; string typeName, boundProperty, propValue; foreach(var control in controls.OfType<ElementHost>().Select(h => (FrameworkElement)h.Child)) { foreach(var c in control.AllChildElements().Where(c => !String.IsNullOrWhiteSpace(PropertyPageBinding.GetProjectPropertyName(c)))) { t = c.GetType(); typeName = t.FullName; boundProperty = PropertyPageBinding.GetProjectPropertyName(c); if(customControls.ContainsKey(typeName)) pi = t.GetProperty(customControls[typeName], BindingFlags.Public | BindingFlags.Instance); else if(c is TextBoxBase) pi = t.GetProperty("Text", BindingFlags.Public | BindingFlags.Instance); else if(c is Selector) pi = t.GetProperty("SelectedValue", BindingFlags.Public | BindingFlags.Instance); else if(c is CheckBox) pi = t.GetProperty("IsChecked", BindingFlags.Public | BindingFlags.Instance); else pi = null; we if(!this.StoreControlValue(boundProperty) && pi != null) { controlValue = pi.GetValue(c, null); if(controlValue == null) propValue = String.Empty; else propValue = controlValue.ToString(); if(propValue.Length != 0 || this.ProjectMgr.BuildProject.GetProperty(boundProperty) != null) { if(this.IsEscapedProperty(boundProperty)) propValue = EscapeValueAttribute.Escape(propValue); this.ProjectMgr.SetProjectProperty(boundProperty, propValue); } } } } } This handles property changed events for certain WPF custom controls <param name="sender">The sender of the event</param> <param name="e">The event arguments</param> private void OnWpfPropertyChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { #pragma warning disable VSTHRD010 this.OnPropertyChanged(sender, e); #pragma warning restore VSTHRD010 } This is used to determine the minimum size of the property page based on the content pane <param name="c">The content pane control</param> <returns>The minimum size of the property page</returns> <remarks>Even though the WPF control will be scaled correctly, the containing host control does not always have an appropriate minimum size. As such, the host control is created with a smaller size than needed and this is called to set the minimum size on the host control based on the minimum size reported by the child WPF control. The WPF control's minimum size is converted to pixels based on the current system's DPI.</remarks> protected static System.Drawing.Size DetermineMinimumSize(System.Windows.Controls.Control c) { double pixelWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width / System.Windows.SystemParameters.WorkArea.Width, pixelHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height / System.Windows.SystemParameters.WorkArea.Height; return new System.Drawing.Size((int)(c.MinWidth * pixelWidth), (int)(c.MinHeight * pixelHeight)); } #endregion #region IPropertyPage Members Called when the environment wants us to create our property page. <param name="hWndParent">The HWND of the parent window.</param> <param name="pRect">The bounds of the area that we should fill.</param> <param name="bModal">Indicates whether the dialog box is shown modally or not.</param> void IPropertyPage.Activate(IntPtr hWndParent, RECT[] pRect, int bModal) { ThreadHelper.ThrowIfNotOnUIThread(); this.CreateControl(); this.Initialize(); propertyPages.Add(this); NativeMethods.SetParent(this.Handle, hWndParent); ((IPropertyPage)this).Move(pRect); this.BindProperties(this.Controls); } Applies the changes made on the property page to the bound objects. <returns><b>S_OK</b> if the changes were successfully applied and the property page is current with the bound objects or <b>S_FALSE</b> if the changes were applied, but the property page cannot determine if its state is current with the objects.</returns> int IPropertyPage.Apply() { if(this.IsDirty) { if(this.ProjectMgr == null) { Debug.Assert(false); return VSConstants.E_INVALIDARG; } if(this.IsValid) { this.StoreProperties(this.Controls); #pragma warning disable VSTHRD010 this.IsDirty = false; #pragma warning restore VSTHRD010 } else return VSConstants.S_FALSE; } return VSConstants.S_OK; } The environment calls this to notify us that we should clean up our resources. void IPropertyPage.Deactivate() { if(!this.IsDisposed) { propertyPages.Remove(this); this.Dispose(); } } The environment calls this to get the parameters to describe the property page. <param name="pPageInfo">The parameters are returned in this one-sized array.</param> void IPropertyPage.GetPageInfo(PROPPAGEINFO[] pPageInfo) { pPageInfo[0] = new PROPPAGEINFO { cb = (uint)Marshal.SizeOf(typeof(PROPPAGEINFO)), dwHelpContext = 0, pszDocString = null, pszHelpFile = null, pszTitle = this.Title ?? String.Empty, SIZE = new SIZE { cx = this.Width, cy = this.Height } }; } Invokes the property page help in response to an end-user request. <param name="pszHelpDir">String under the HelpDir key in the property page's CLSID information in the registry. If HelpDir does not exist, this will be the path found in the InProcServer32 entry minus the server filename.</param> void IPropertyPage.Help(string pszHelpDir) { } Indicates whether this property page has changed its state since the last call to <see cref="IPropertyPage.Apply"/>. The property sheet uses this information to enable or disable the Apply button in the dialog box. <returns>Returns <b>S_OK</b> if the value state of the property page is dirty, that is, it has changed and is different from the state of the bound objects. Returns <b>S_FALSE</b> if the value state of the page has not changed and is current with that of the bound objects.</returns> int IPropertyPage.IsPageDirty() { return (this.IsDirty ? VSConstants.S_OK : VSConstants.S_FALSE); } Repositions and resizes the property page dialog box according to the contents of <paramref name="pRect"/>. The rectangle specified by <paramref name="pRect"/> is treated identically to that passed to <see cref="IPropertyPage.Activate"/>. <param name="pRect">The bounds of the area that we should fill.</param> void IPropertyPage.Move(RECT[] pRect) { RECT r = pRect[0]; this.Bounds = new Rectangle(r.left, r.top, Math.Max(r.right - r.left, this.MinimumSize.Width), Math.Max(r.bottom - r.top, this.MinimumSize.Height)); } The environment calls this to set the currently selected objects that the property page should show. <param name="cObjects">The count of elements in <paramref name="ppunk"/>.</param> <param name="ppunk">An array of <b>IUnknown</b> objects to show in the property page.</param> <remarks>We are supposed to cache these objects until we get another call with <paramref name="cObjects"/> = 0. Also, the environment is supposed to call this before calling <see cref="IPropertyPage.Activate"/>, but don't count on it.</remarks> void IPropertyPage.SetObjects(uint cObjects, object[] ppunk) { ThreadHelper.ThrowIfNotOnUIThread(); if(cObjects == 0) { this.ProjectMgr = null; return; } if(ppunk[0] is ProjectConfig) { List<ProjectConfig> configs = new List<ProjectConfig>(); for(int i = 0; i < cObjects; i++) { ProjectConfig config = (ProjectConfig)ppunk[i]; if(this.ProjectMgr == null) this.ProjectMgr = config.ProjectMgr; configs.Add(config); } this.ProjectConfigs = new ReadOnlyCollection<ProjectConfig>(configs); } else if(ppunk[0] is NodeProperties) { if(this.ProjectMgr == null) this.ProjectMgr = (ppunk[0] as NodeProperties).Node.ProjectMgr; Dictionary<string, ProjectConfig> configsMap = new Dictionary<string, ProjectConfig>(); for(int i = 0; i < cObjects; i++) { NodeProperties property = (NodeProperties)ppunk[i]; ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out IVsCfgProvider provider)); uint[] expected = new uint[1]; ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null)); if(expected[0] > 0) { ProjectConfig[] configs = new ProjectConfig[expected[0]]; uint[] actual = new uint[1]; provider.GetCfgs(expected[0], configs, actual, null); foreach(ProjectConfig config in configs) if(!configsMap.ContainsKey(config.ConfigName)) configsMap.Add(config.ConfigName, config); } } if(configsMap.Count > 0) this.ProjectConfigs = new ReadOnlyCollection<ProjectConfig>(configsMap.Values.ToArray()); } if(!this.IsDisposed && this.ProjectMgr != null) { this.BindProperties(this.Controls); this.IsDirty = false; } } Initializes a property page and provides the property page object with the <see cref="IPropertyPageSite"/> interface through which the property page communicates with the property frame. <param name="pPageSite">The <see cref="IPropertyPageSite"/> that manages and provides services to this property page within the entire property sheet.</param> void IPropertyPage.SetPageSite(IPropertyPageSite pPageSite) { this.PropertyPageSite = pPageSite; } Makes the property page dialog box visible or invisible according to the <paramref name="nCmdShow"/> parameter. If the page is made visible, the page should set the focus to itself, specifically to the first property on the page. <param name="nCmdShow">Command describing whether to become visible (SW_SHOW or SW_SHOWNORMAL) or hidden (SW_HIDE). No other values are valid for this parameter.</param> void IPropertyPage.Show(uint nCmdShow) { if(nCmdShow == 0 ) this.Visible = false; else { this.Visible = true; this.Show(); } } Instructs the property page to process the keystroke described in <paramref name="pMsg"/>. <param name="pMsg">Describes the keystroke to process.</param> <returns> <list type="table"> <item><term>S_OK</term><description>The property page handles the accelerator.</description></item> <item><term>S_FALSE</term><description>The property page handles accelerators, but this one was not useful to it.</description></item> <item><term>E_NOTIMPL</term><description>The property page does not handle accelerators.</description></item> </list> </returns> int IPropertyPage.TranslateAccelerator(MSG[] pMsg) { MSG msg = pMsg[0]; if((msg.message < NativeMethods.WM_KEYFIRST || msg.message > NativeMethods.WM_KEYLAST) && (msg.message < NativeMethods.WM_MOUSEFIRST || msg.message > NativeMethods.WM_MOUSELAST)) return VSConstants.S_FALSE; return (NativeMethods.IsDialogMessageA(this.Handle, ref msg)) ? VSConstants.S_OK : VSConstants.S_FALSE; } #endregion #region IPropertyPage2 Members <inheritdoc /> void IPropertyPage2.Activate(IntPtr hWndParent, RECT[] pRect, int bModal) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Activate(hWndParent, pRect, bModal); } <inheritdoc /> void IPropertyPage2.Apply() { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Apply(); } <inheritdoc /> void IPropertyPage2.Deactivate() { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Deactivate(); } <inheritdoc /> void IPropertyPage2.EditProperty(int DISPID) { } <inheritdoc /> void IPropertyPage2.GetPageInfo(PROPPAGEINFO[] pPageInfo) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).GetPageInfo(pPageInfo); } <inheritdoc /> void IPropertyPage2.Help(string pszHelpDir) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Help(pszHelpDir); } <inheritdoc /> int IPropertyPage2.IsPageDirty() { ThreadHelper.ThrowIfNotOnUIThread(); return ((IPropertyPage)this).IsPageDirty(); } <inheritdoc /> void IPropertyPage2.Move(RECT[] pRect) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Move(pRect); } <inheritdoc /> void IPropertyPage2.SetObjects(uint cObjects, object[] ppunk) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).SetObjects(cObjects, ppunk); } <inheritdoc /> void IPropertyPage2.SetPageSite(IPropertyPageSite pPageSite) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).SetPageSite(pPageSite); } <inheritdoc /> void IPropertyPage2.Show(uint nCmdShow) { ThreadHelper.ThrowIfNotOnUIThread(); ((IPropertyPage)this).Show(nCmdShow); } <inheritdoc /> int IPropertyPage2.TranslateAccelerator(MSG[] pMsg) { ThreadHelper.ThrowIfNotOnUIThread(); return ((IPropertyPage)this).TranslateAccelerator(pMsg); } #endregion }
c#
40
0.566679
141
49.086888
633
/// <summary> /// This is used as a base class for package property pages /// </summary> /// <remarks>This control handles the common tasks of a property page such as binding controls to project /// properties and storing the values when they change. The property "binding" is done by specifying the /// project property name using the <see cref="P:SandcastleBuilder.WPF.PropertyPages.PropertyPageBinding.ProjectPropertyName"/> /// attached property on the necessary WPF controls.</remarks>
class
public class SeedCell { #region Constructors [JetBrains.Annotations.UsedImplicitlyAttribute] public SeedCell() { this.HighlightPenBrush = Brushes.DarkRed; } #endregion #region Properties - Coordinates Gets or sets the left. </summary> public double Left { get; set; } Gets or sets the top. </summary> public double Top { get; set; } Gets or sets the height. </summary> public double Height { get; set; } Gets or sets the top. </summary> public double Width { get; set; } #endregion #region Properties - Main raster Gets or sets the zero-based index of the line. </summary> public int LineIndex { get; set; } Gets or sets the zero-based index of the bar. </summary> public int BarIndex { get; set; } #endregion #region Properties - Drawing Gets or sets the rectangle. </summary> public Rect Rectangle { get; set; } public bool IsHighlighted { get; set; } #endregion #region Properties - Brushes Gets or sets the pen brush. </summary> public Brush PenBrush { get; set; } Gets or sets the highlight pen brush. </summary> public Brush HighlightPenBrush { get; set; } Gets or sets the content brush. </summary> public Brush ContentBrush { get; set; } #endregion #region Public methods - virtual public virtual void Copy() { } public virtual void Paste() { } #endregion #region Public methods Query if 'p' contains point. </summary> public bool ContainsPoint(Point p) { return this.Left <= p.X && this.Left + this.Width >= p.X && this.Top <= p.Y && this.Top + this.Height >= p.Y; } #endregion }
c#
13
0.572862
121
36.9
50
/// <summary> A seed cell. </summary>
class
[Serializable] public class XQueryException : Exception { public XQueryException(string message, string query, int index, int length) : base(message) { this.Query = query; if (index >= query.Length) { index = query.Length - 1; } this.Index = index; if (index + length >= query.Length) { length = query.Length - index; } this.Length = length; } public string Query { get; set; } public int Index { get; set; } public int Length { get; set; } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Query", this.Query); info.AddValue("Index", this.Index); info.AddValue("Length", this.Length); } }
c#
11
0.533078
92
33.8
30
/// <summary> /// Implements an XQuery exception /// </summary>
class
public sealed partial class Context : IDisposable { public const int GRAPH_MODE = 0; public const int EAGER_MODE = 1; int defaultExecutionMode = EAGER_MODE; public string DeviceName { get; set; } = ""; public string ScopeName { get; set; } = ""; bool initialized = false; ContextSwitchStack context_switches; public FunctionCallOptions FunctionCallOptions { get; } SafeContextHandle _handle; public SafeContextHandle Handle => _handle; public Context() { _device_policy = ContextDevicePlacementPolicy.DEVICE_PLACEMENT_SILENT; context_switches = new ContextSwitchStack(defaultExecutionMode == EAGER_MODE, false); initialized = false; FunctionCallOptions = new FunctionCallOptions(); } public void ensure_initialized() { if (initialized) return; Config = MergeConfig(); FunctionCallOptions.Config = Config; var config_str = Config.ToByteArray(); using var opts = new ContextOptions(); using var status = new Status(); c_api.TFE_ContextOptionsSetConfig(opts.Handle, config_str, (ulong)config_str.Length, status.Handle); status.Check(true); c_api.TFE_ContextOptionsSetDevicePlacementPolicy(opts.Handle, _device_policy); _handle = c_api.TFE_NewContext(opts.Handle, status.Handle); status.Check(true); initialized = true; } public void start_step() => c_api.TFE_ContextStartStep(_handle); public void end_step() => c_api.TFE_ContextEndStep(_handle); public bool executing_eagerly() { if(context_switches.Count() == 0) tf.enable_eager_execution(); return context_switches.Current().EagerMode; } public bool is_build_function() => context_switches.Current().IsBuildingFunction; public string shared_name(string name = null) => !string.IsNullOrEmpty(name) || !executing_eagerly() ? name : "cd2c89b7-88b7-44c8-ad83-06c2a9158347"; public void graph_mode(bool isFunc = false) => context_switches.Push(false, isFunc); public void eager_mode(bool isFunc = false) => context_switches.Push(true, isFunc); public bool switched_to_graph(params object[] args) { var switching_to_graph = has_graph_arg(args) && tf.Context.executing_eagerly(); if (switching_to_graph) tf.Context.graph_mode(tf.Context.is_build_function()); return switching_to_graph; } public bool has_graph_arg(params object[] args) { var flatten_args = nest.flatten<object>(args); bool has_graph_arg = false; foreach (var el in flatten_args) { if (el is Tensor tensor && !tensor.IsEagerTensor) { has_graph_arg = true; break; } } return has_graph_arg; } public void restore_mode() { context_switches.Pop(); tf.get_default_graph(); } public void reset_context() { ops.reset_uid(); ops.reset_default_graph(); context_switches.Clear(); if (_handle != null) c_api.TFE_ContextClearCaches(_handle); } public void Dispose() => _handle.Dispose(); }
c#
13
0.553523
112
38.815217
92
/// <summary> /// Environment in which eager operations execute. /// </summary>
class
public sealed class PointsToAnalysisResult : DataFlowAnalysisResult<PointsToBlockAnalysisResult, PointsToAbstractValue> { private readonly ImmutableDictionary<IOperation, ImmutableHashSet<AbstractLocation>> _escapedLocationsThroughOperationsMap; private readonly ImmutableDictionary<IOperation, ImmutableHashSet<AbstractLocation>> _escapedLocationsThroughReturnValuesMap; private readonly ImmutableDictionary<AnalysisEntity, ImmutableHashSet<AbstractLocation>> _escapedLocationsThroughEntitiesMap; private readonly ImmutableHashSet<AnalysisEntity> _trackedEntities; private readonly ImmutableHashSet<PointsToAbstractValue> _trackedPointsToValues; internal PointsToAnalysisResult( DataFlowAnalysisResult<PointsToBlockAnalysisResult, PointsToAbstractValue> corePointsToAnalysisResult, ImmutableDictionary<IOperation, ImmutableHashSet<AbstractLocation>> escapedLocationsThroughOperationsMap, ImmutableDictionary<IOperation, ImmutableHashSet<AbstractLocation>> escapedLocationsThroughReturnValuesMap, ImmutableDictionary<AnalysisEntity, ImmutableHashSet<AbstractLocation>> escapedLocationsThroughEntitiesMap, TrackedEntitiesBuilder trackedEntitiesBuilder) : base(corePointsToAnalysisResult) { _escapedLocationsThroughOperationsMap = escapedLocationsThroughOperationsMap; _escapedLocationsThroughReturnValuesMap = escapedLocationsThroughReturnValuesMap; _escapedLocationsThroughEntitiesMap = escapedLocationsThroughEntitiesMap; (_trackedEntities, _trackedPointsToValues) = trackedEntitiesBuilder.ToImmutable(); PointsToAnalysisKind = trackedEntitiesBuilder.PointsToAnalysisKind; } public PointsToAnalysisKind PointsToAnalysisKind { get; } public ImmutableHashSet<AbstractLocation> GetEscapedAbstractLocations(IOperation operation) => GetEscapedAbstractLocations(operation, _escapedLocationsThroughOperationsMap) .AddRange(GetEscapedAbstractLocations(operation, _escapedLocationsThroughReturnValuesMap)); public ImmutableHashSet<AbstractLocation> GetEscapedAbstractLocations(AnalysisEntity analysisEntity) => GetEscapedAbstractLocations(analysisEntity, _escapedLocationsThroughEntitiesMap); private static ImmutableHashSet<AbstractLocation> GetEscapedAbstractLocations<TKey>( TKey key, ImmutableDictionary<TKey, ImmutableHashSet<AbstractLocation>> map) where TKey : class { if (map.TryGetValue(key, out var escapedLocations)) { return escapedLocations; } return ImmutableHashSet<AbstractLocation>.Empty; } internal bool IsTrackedEntity(AnalysisEntity analysisEntity) => _trackedEntities.Contains(analysisEntity); internal bool IsTrackedPointsToValue(PointsToAbstractValue value) => _trackedPointsToValues.Contains(value); }
c#
11
0.762873
133
69.930233
43
/// <summary> /// Analysis result from execution of <see cref="PointsToAnalysis"/> on a control flow graph. /// </summary>
class
[TestFixture] public class MapTests { private Map map; [SetUp] public void SetUp() { this.map = new Map(typeof(Source), typeof(Destination)); } [Test] [TestCase(15)] [TestCase(0)] [TestCase(-15)] [TestCase(123124)] [TestCase(-3312321)] public void SetMappingAction_SetCustomMappingAction_ActionReturnCorrectObject(int value) { var mapFromSourceToInt = new Map(typeof(Source), typeof(int)); var sourceObject = new Source() { IntToFloatProperty = value }; mapFromSourceToInt.SetMappingAction((obj) => { return ((Source)obj).IntToFloatProperty; }); var result = mapFromSourceToInt.MappingAction(sourceObject); Assert.AreEqual(value, result); } [Test] [TestCase(-15)] [TestCase(1)] [TestCase(15)] [TestCase(123124)] public void SetMappingAction_CustomTypeToInternalType_ReturnDefaultValueOfInternalType(int value) { var mapFromSourceToInt = new Map(typeof(Source), typeof(int)); var sourceObject = new Source() { IntToFloatProperty = value }; var result = mapFromSourceToInt.MappingAction(sourceObject); Assert.AreEqual(default(int), result); Assert.AreNotEqual(value, result); } [Test] public void DefaultMappingAction_CustomTypeToCustomType_ReturnCorrectValues() { var sourceObject = new Source() { IntToFloatProperty = 13, DoubleToIntProperty = 42.7, IntToStringProperty = 10, StringProperty = "Just a string", StringToInt = "22", ArrayProperty = new int[2] { -23, 21 }, ListProperty = new List<int> { 12, -32 } }; var result = this.map.DefaultMappingAction(sourceObject); Assert.IsInstanceOf(typeof(Destination), result); Assert.AreEqual(13.0f, ((Destination)result).IntToFloatProperty); Assert.AreEqual(43, ((Destination)result).DoubleToIntProperty); Assert.AreEqual("10", ((Destination)result).IntToStringProperty); Assert.AreEqual("Just a string", ((Destination)result).StringProperty); Assert.AreEqual(22, ((Destination)result).StringToInt); Assert.AreEqual(new int[2] { -23, 21 }, ((Destination)result).ArrayProperty); Assert.AreEqual(new List<int> { 12, -32 }, ((Destination)result).ListProperty); } [Test] public void DefaultMappingAction_CustomTypeToInternalType_ReturnDefaultInternalValues() { var mapFromSourceToInt = new Map(typeof(Source), typeof(int)); var sourceObject = new Source() { IntToFloatProperty = 13, DoubleToIntProperty = 42.7, IntToStringProperty = 10, StringProperty = "Just a string", StringToInt = "22", ArrayProperty = new int[2] { -23, 21 }, ListProperty = new List<int> { 12, -32 } }; var result = mapFromSourceToInt.DefaultMappingAction(sourceObject); Assert.IsInstanceOf(typeof(int), result); Assert.AreEqual(default(int), result); } [Test] public void DefaultMappingAction_IncorrectStringToInt_FormatExceptionIsThrown() { Assert.Throws( typeof(FormatException), new TestDelegate(() => { var sourceObject = new Source() { StringToInt = "2sd2sd", }; map.DefaultMappingAction(sourceObject); })); } [Test] public void DefaultMappingAction_PropertyIsNull_InvalidCastExceptionIsThrown() { Assert.Throws( typeof(InvalidCastException), new TestDelegate(() => { var mapFromTestSourceToDestination = new Map(typeof(TestSource), typeof(Destination)); var sourceObject = new TestSource(); mapFromTestSourceToDestination.DefaultMappingAction(sourceObject); })); } [Test] public void GetHashCode_CompareMaps_MapsAreEqual() { var mapFromIntToFloat = new Map(typeof(int), typeof(float)); var mapStringToSource = new Map(typeof(string), typeof(Source)); var intToFloatPair = new KeyValuePair<Type, Type>(typeof(int), typeof(float)); var stringToSourcePair = new KeyValuePair<Type, Type>(typeof(string), typeof(Source)); var sourceToDestinationPair = new KeyValuePair<Type, Type>(typeof(Source), typeof(Destination)); var intToFloatHashCode = intToFloatPair.GetHashCode(); var stringToSourceHashCode = stringToSourcePair.GetHashCode(); var sourceToDestinationHashCode = sourceToDestinationPair.GetHashCode(); var mapIntToFloatHashCode = mapFromIntToFloat.GetHashCode(); var mapStringToSourceHashCode = mapStringToSource.GetHashCode(); var mapSourceToDestinationHashCode = this.map.GetHashCode(); Assert.AreEqual(intToFloatHashCode, mapIntToFloatHashCode); Assert.AreEqual(stringToSourceHashCode, mapStringToSourceHashCode); Assert.AreEqual(sourceToDestinationHashCode, mapSourceToDestinationHashCode); } [Test] public void Equals_CompareMapsByMappingTypes_MapsAreEqualWhenMappingTypesAreSame() { var mapFromIntToFloat = new Map(typeof(int), typeof(float)); var mapFromSourceToDestination = new Map(typeof(Source), typeof(Destination)); var mapFromStringToSource = new Map(typeof(string), typeof(Source)); bool isSameTypesEqual = this.map.Equals(mapFromSourceToDestination); bool isIntToFloatEqualsSourceToDestination = mapFromIntToFloat.Equals(this.map); bool isIntToFloatEqualsStringToSource = mapFromIntToFloat.Equals(mapFromStringToSource); Assert.IsTrue(isSameTypesEqual); Assert.IsFalse(isIntToFloatEqualsSourceToDestination); Assert.IsFalse(isIntToFloatEqualsStringToSource); } public class TestSource { public List<string> ArrayProperty { get; } = new List<string>() { "13d", "2s" }; } }
c#
22
0.589862
108
44.459459
148
/// <summary> /// Unit tests of class Map /// </summary>
class
public class TestSource { public List<string> ArrayProperty { get; } = new List<string>() { "13d", "2s" }; }
c#
7
0.522059
92
33.25
4
/// <summary> /// Class which helps test situation when properties with same name have incompatible types /// </summary>
class
public abstract class ListUpdated<T> : SerializedNotification where T : class { public ListItemChangeType Type { get; init; } = ListItemChangeType.ItemUpdated; public T Item { get; init; } }
c#
6
0.657658
87
36.166667
6
/// <summary> /// Notification about a list being updated /// </summary>
class
public sealed class ImageFormatting { private static readonly HttpClient _httpClient = new HttpClient(); sealed class ImageFormat { public string Name { get; set; } public int Width { get; set; } public int Height { get; set; } } public static async Task<FormattedImage[]> FormatAsync(Uri imageUrl, string publishStorageContainerName, string filenamePrefix, CancellationToken cancel) { Helpers.Argument.ValidateIsAbsoluteUrl(imageUrl, nameof(imageUrl)); Helpers.Argument.ValidateIsNotNullOrWhitespace(publishStorageContainerName, nameof(publishStorageContainerName)); Helpers.Argument.ValidateIsNotNullOrWhitespace(filenamePrefix, nameof(filenamePrefix)); var formats = new List<ImageFormat>(); Program.Configuration.GetSection("ImageFormats").Bind(formats); var log = _rootLog.CreateChildSource(imageUrl.ToString()); log.Info($"Formatting with {formats.Count} formats."); var duration = Stopwatch.StartNew(); try { using (var imageMagick = new ImageMagick()) using (var workingDirectory = new TemporaryDirectory()) { log.Debug("Downloading input image."); var inputPath = Path.Combine(workingDirectory.Path, "Input.bin"); using (var inputStream = await _httpClient.GetStreamAsync(imageUrl).WithAbandonment(cancel)) using (var inputFile = File.Create(inputPath)) await inputStream.CopyToAsync(inputFile, 81920 , cancel); log.Debug("Starting formatting subtasks."); var formatSubtasks = new List<(ImageFormat format, string filename, string outputPath, Task resizeTask)>(); foreach (var format in formats) { var outputFilename = filenamePrefix + $"-{format.Height}p.jpg"; var outputPath = Path.Combine(workingDirectory.Path, outputFilename); var resizeTask = imageMagick.ResizeAsync(inputPath, outputPath, format.Width, format.Height); formatSubtasks.Add((format, outputFilename, outputPath, resizeTask)); } await Task.WhenAll(formatSubtasks.Select(subtask => subtask.resizeTask)); log.Debug("Connecting to Azure."); var storageAccount = CloudStorageAccount.Parse(Program.Configuration["AzureStorageConnectionString"]); var blobClient = storageAccount.CreateCloudBlobClient(); var storageContainer = blobClient.GetContainerReference(publishStorageContainerName); await storageContainer.CreateIfNotExistsAsync(default, default, default, cancel); log.Debug("Starting upload subtasks."); var uploadSubtasks = new List<(ImageFormat format, Task<string> uploadTask)>(); foreach (var formatTask in formatSubtasks) { var blob = storageContainer.GetBlockBlobReference(formatTask.filename); var uploadTask = Task.Run(async delegate { await blob.UploadFromFileAsync(formatTask.outputPath, default, default, default, cancel); var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddDays(365 * 25), SharedAccessStartTime = DateTimeOffset.UtcNow.AddDays(-1) }); return blob.Uri + sas; }); uploadSubtasks.Add((formatTask.format, uploadTask)); } await Task.WhenAll(uploadSubtasks.Select(subtask => subtask.uploadTask)); log.Info($"Finished image formatting in {duration.Elapsed.TotalSeconds:F2} seconds."); return uploadSubtasks .Select(subtask => new FormattedImage(subtask.format.Name, new Uri(subtask.uploadTask.Result))) .ToArray(); } } catch (Exception ex) { log.Error(ex.Demystify().ToString()); throw; } } public sealed class FormattedImage { public string FormatName { get; } public Uri Url { get; } public FormattedImage(string formatName, Uri url) { Helpers.Argument.ValidateIsNotNullOrWhitespace(formatName, nameof(formatName)); Helpers.Argument.ValidateIsAbsoluteUrl(url, nameof(url)); FormatName = formatName; Url = url; } } private static readonly LogSource _rootLog = Log.Default.CreateChildSource(nameof(ImageFormatting)); }
c#
35
0.571292
161
57.876404
89
/// <summary> /// This class contains the actual core logic used for image formatting. /// </summary>
class
public class DbStackStringService : IStackStringService { private readonly StackContext _db = new StackContext(); private static StackDirection _stackDirection = StackDirection.IN_ORDER; private static readonly object _lock = new object(); public DbStackStringService() { loadConfiguration(); } private void loadConfiguration() { if (!_db.Configurations.Any()) { _db.Configurations.Add(new StackConfiguration(_stackDirection)); _db.SaveChanges(); } else { var loadedConfiguration = _db.Configurations.FirstOrDefault(); if (loadedConfiguration != null) { _stackDirection = loadedConfiguration.StackDirection; } } } public string Pop() { lock (_lock) { string ret = null; if (!_db.StackStrings.Any()) { return null; } if (_stackDirection == StackDirection.IN_ORDER) { var left = _db.StackStrings .SingleOrDefault(s => s.LeftId == StackString.LEFT_ID); if (left != null) { ret = left.Content; var newLeft = _db.StackStrings .SingleOrDefault(s => s.LeftId == left.StackStringId); if (newLeft != null) { newLeft.LeftId = StackString.LEFT_ID; } _db.StackStrings.Remove(left); _db.SaveChanges(); } } else { var right = _db.StackStrings .SingleOrDefault(s => s.RightId == StackString.RIGHT_ID); if (right != null) { ret = right.Content; var newRight = _db.StackStrings .SingleOrDefault(s => s.RightId == right.StackStringId); if (newRight != null) { newRight.RightId = StackString.RIGHT_ID; } _db.StackStrings.Remove(right); _db.SaveChanges(); } } return ret; } } public string Pick() { lock (_lock) { if (!_db.StackStrings.Any()) { return null; } if (_stackDirection == StackDirection.IN_ORDER) { var left = _db.StackStrings .SingleOrDefault(s => s.LeftId == StackString.LEFT_ID); if (left != null) { return left.Content; } } else { var right = _db.StackStrings .SingleOrDefault(s => s.RightId == StackString.RIGHT_ID); if (right != null) { return right.Content; } } return null; } } public bool Revert() { lock (_lock) { if (!_db.StackStrings.Any()) { return false; } _stackDirection = _stackDirection switch { StackDirection.IN_ORDER => StackDirection.REVERTED, StackDirection.REVERTED => StackDirection.IN_ORDER, _ => throw new ArgumentOutOfRangeException() }; var loadedConfiguration = _db.Configurations.FirstOrDefault(); if (loadedConfiguration != null) { loadedConfiguration.StackDirection = _stackDirection; _db.SaveChanges(); } return true; } } public void Push(string newString) { lock (_lock) { var stackString = new StackString(newString); var record = _db.StackStrings.Add(stackString); _db.SaveChanges(); if (_stackDirection == StackDirection.IN_ORDER) { var left = _db.StackStrings .SingleOrDefault(s => s.LeftId == StackString.LEFT_ID); if (left != null) { left.LeftId = stackString.StackStringId; stackString.RightId = left.StackStringId; stackString.LeftId = StackString.LEFT_ID; } } else { var right = _db.StackStrings .SingleOrDefault(s => s.RightId == StackString.RIGHT_ID); if (right != null) { right.RightId = stackString.StackStringId; stackString.LeftId = right.StackStringId; stackString.RightId = StackString.RIGHT_ID; } } if (stackString.LeftId == StackString.INVALID_ID || stackString.RightId == StackString.INVALID_ID) { stackString.LeftId = StackString.LEFT_ID; stackString.RightId = StackString.RIGHT_ID; } _db.SaveChanges(); } } }
c#
21
0.399833
84
35.919753
162
/// <summary> /// EF implementation of the service /// TODO: add DB access abstraction layer for CRUD operations so DB instance /// could be injected via dotnet IOC DI mechanism /// /// NOTE: All exceptions and DB connection issues are being handled in upper layers (by design) /// </summary>
class
public class PropertyListViewCtrl : System.Windows.Forms.UserControl { private System.Windows.Forms.ListView PropertiesLV; private System.Windows.Forms.MenuItem RemoveMI; private System.Windows.Forms.MenuItem EditMI; private System.Windows.Forms.MenuItem CopyMI; private System.ComponentModel.Container components = null; public PropertyListViewCtrl() { InitializeComponent(); PropertiesLV.SmallImageList = Resources.Instance.ImageList; SetColumns(ColumnNames); } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code private void InitializeComponent() { this.PropertiesLV = new System.Windows.Forms.ListView(); this.CopyMI = new System.Windows.Forms.MenuItem(); this.EditMI = new System.Windows.Forms.MenuItem(); this.RemoveMI = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); PropertiesLV this.PropertiesLV.Dock = System.Windows.Forms.DockStyle.Fill; this.PropertiesLV.FullRowSelect = true; this.PropertiesLV.Location = new System.Drawing.Point(0, 0); this.PropertiesLV.MultiSelect = false; this.PropertiesLV.Name = "PropertiesLV"; this.PropertiesLV.Size = new System.Drawing.Size(432, 272); this.PropertiesLV.TabIndex = 0; this.PropertiesLV.UseCompatibleStateImageBehavior = false; this.PropertiesLV.View = System.Windows.Forms.View.Details; this.PropertiesLV.DoubleClick += new System.EventHandler(this.ViewMI_Click); this.PropertiesLV.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PropertiesLV_MouseDown); CopyMI this.CopyMI.Index = -1; this.CopyMI.Text = ""; EditMI this.EditMI.Index = -1; this.EditMI.Text = ""; RemoveMI this.RemoveMI.Index = -1; this.RemoveMI.Text = ""; PropertyListViewCtrl this.AllowDrop = true; this.Controls.Add(this.PropertiesLV); this.Name = "PropertyListViewCtrl"; this.Size = new System.Drawing.Size(432, 272); this.ResumeLayout(false); } #endregion /<summary> /Constants used to identify the list view columns. private const int ID = 0; private const int DESCRIPTION = 1; private const int VALUE = 2; private const int DATA_TYPE = 3; private const int ITEM_PATH = 4; private const int ITEM_NAME = 5; private const int ERROR = 6; /<summary> /The list view column names. private readonly string[] ColumnNames = new string[] { "ID", "Description", "Value", "Data Type", "Item Path", "Item Name", "Result" }; /<summary> /The browse element containin the properties being displayed. private TsCDaBrowseElement m_element = null; /<summary> /Initializes the control with a set of identified results. public void Initialize(TsCDaBrowseElement element) { PropertiesLV.Items.Clear(); check if there is nothing to do. if (element == null || element.Properties == null) return; m_element = element; foreach (TsCDaItemProperty property in element.Properties) { AddProperty(property); } adjust the list view columns to fit the data. AdjustColumns(); } /<summary> /Sets the columns shown in the list view. private void SetColumns(string[] columns) { PropertiesLV.Clear(); foreach (string column in columns) { ColumnHeader header = new ColumnHeader(); header.Text = column; PropertiesLV.Columns.Add(header); } AdjustColumns(); } /<summary> /Adjusts the columns shown in the list view. private void AdjustColumns() { adjust column widths. for (int ii = 0; ii < PropertiesLV.Columns.Count; ii++) { always show the property id and value column. if (ii == ID || ii == VALUE) { PropertiesLV.Columns[ii].Width = -2; continue; } adjust to width of contents if column not empty. bool empty = true; foreach (ListViewItem current in PropertiesLV.Items) { if (current.SubItems[ii].Text != "") { empty = false; PropertiesLV.Columns[ii].Width = -2; break; } } set column width to zero if no data it in. if (empty) PropertiesLV.Columns[ii].Width = 0; } /* get total width int width = 0; foreach (ColumnHeader column in PropertiesLV.Columns) width += column.Width; expand parent form to display all columns. if (width > PropertiesLV.Width) { width = ParentForm.Width + (width - PropertiesLV.Width) + 4; ParentForm.Width = (width > 1024)?1024:width; } */ } /<summary> /Returns the value of the specified field. private object GetFieldValue(TsCDaItemProperty property, int fieldID) { if (property != null) { switch (fieldID) { case ID: { return property.ID.ToString(); } case DESCRIPTION: { return property.Description; } case VALUE: { return property.Value; } case DATA_TYPE: { return (property.Value != null) ? property.Value.GetType() : null; } case ITEM_PATH: { return property.ItemPath; } case ITEM_NAME: { return property.ItemName; } case ERROR: { return property.Result; } } } return null; } /<summary> /Adds an item to the list view. private void AddProperty(TsCDaItemProperty property) { create list view item. ListViewItem listItem = new ListViewItem((string)GetFieldValue(property, ID), Resources.IMAGE_PROPERTY); add appropriate sub-items. listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, DESCRIPTION))); listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, VALUE))); listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, DATA_TYPE))); listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, ITEM_PATH))); listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, ITEM_NAME))); listItem.SubItems.Add(OpcClientSdk.OpcConvert.ToString(GetFieldValue(property, ERROR))); save item object as list view item tag. listItem.Tag = property; add to list view. PropertiesLV.Items.Add(listItem); } /<summary> /Shows a detailed view for array values. private void ViewMI_Click(object sender, System.EventArgs e) { if (PropertiesLV.SelectedItems.Count > 0) { object tag = PropertiesLV.SelectedItems[0].Tag; if (tag != null && tag.GetType() == typeof(TsCDaItemProperty)) { TsCDaItemProperty property = (TsCDaItemProperty)tag; if (property.Value != null) { if (property.ID == TsDaProperty.VALUE) { } else if (property.Value.GetType().IsArray) { } } } } } /<summary> /Enables/disables items in the popup menu before it is displayed. private void PropertiesLV_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { ignore left button actions. if (e.Button != MouseButtons.Right) return; selects the item that was right clicked on. ListViewItem clickedItem = PropertiesLV.GetItemAt(e.X, e.Y); no item clicked on - do nothing. if (clickedItem == null) return; force selection to clicked node. clickedItem.Selected = true; } }
c#
16
0.643887
116
33.537778
225
/// <summary> /// A control used to display a list of item properties. /// </summary>
class
internal class TransportFileUploadResponseModel { [JsonProperty("id")] public string FileId { get; set; } [JsonProperty("name")] public string FileName { get; set; } [JsonProperty("fileType")] public string FileType { get; set; } [JsonProperty("parentId")] public string FolderId { get; set; } [JsonProperty("dateAdded")] public DateTime DateAdded { get; set; } [JsonProperty("fileSizeString")] public string FileSizeString { get; set; } [JsonProperty("fileSize")] public long FileSize { get; set; } [JsonProperty("error")] public string Error { get; set; } }
c#
9
0.588489
50
35.631579
19
/// <summary> /// This class represents the <see cref="TransportFileUploadResponseModel"/> that's received after uploading files to Transport. /// </summary>
class
public class VerticalRecyclingSystem : RecyclingSystem { private readonly IRecyclableScrollRectDataSource _dataSource; private readonly int _coloumns; private float _cellWidth, _cellHeight; private List<RectTransform> _cellPool; private List<ICell> _cachedCells; private Bounds _recyclableViewBounds; private readonly Vector3[] _corners = new Vector3[4]; private bool _recycling; private int currentItemCount; private int topMostCellIndex, bottomMostCellIndex; private int _topMostCellColoumn, _bottomMostCellColoumn; private Vector2 zeroVector = Vector2.zero; #region INIT public VerticalRecyclingSystem(RectTransform prototypeCell, RectTransform viewport, RectTransform content, IRecyclableScrollRectDataSource dataSource, bool isGrid, int coloumns) { PrototypeCell = prototypeCell; Viewport = viewport; Content = content; _dataSource = dataSource; IsGrid = isGrid; _coloumns = isGrid ? coloumns : 1; _recyclableViewBounds = new Bounds(); } public override IEnumerator InitCoroutine(System.Action onInitialized) { SetTopAnchor(Content); Content.anchoredPosition = Vector3.zero; yield return null; SetRecyclingBounds(); CreateCellPool(); currentItemCount = _cellPool.Count; topMostCellIndex = 0; bottomMostCellIndex = _cellPool.Count - 1; int noOfRows = (int)Mathf.Ceil((float)_cellPool.Count / (float)_coloumns); float contentYSize = noOfRows * _cellHeight; Content.sizeDelta = new Vector2(Content.sizeDelta.x, contentYSize); SetTopAnchor(Content); if (onInitialized != null) onInitialized(); } private void SetRecyclingBounds() { Viewport.GetWorldCorners(_corners); float threshHold = RecyclingThreshold * (_corners[2].y - _corners[0].y); _recyclableViewBounds.min = new Vector3(_corners[0].x, _corners[0].y - threshHold); _recyclableViewBounds.max = new Vector3(_corners[2].x, _corners[2].y + threshHold); } private void CreateCellPool() { if (_cellPool != null) { _cellPool.ForEach((RectTransform item) => UnityEngine.Object.Destroy(item.gameObject)); _cellPool.Clear(); _cachedCells.Clear(); } else { _cachedCells = new List<ICell>(); _cellPool = new List<RectTransform>(); } PrototypeCell.gameObject.SetActive(true); if (IsGrid) { SetTopLeftAnchor(PrototypeCell); } else { SetTopAnchor(PrototypeCell); } float currentPoolCoverage = 0; int poolSize = 0; float posX = 0; float posY = 0; _cellWidth = Content.rect.width / _coloumns; _cellHeight = PrototypeCell.sizeDelta.y / PrototypeCell.sizeDelta.x * _cellWidth; float requriedCoverage = MinPoolCoverage * Viewport.rect.height; int minPoolSize = Math.Min(MinPoolSize, _dataSource.GetItemCount()); while ((poolSize < minPoolSize || currentPoolCoverage < requriedCoverage) && poolSize < _dataSource.GetItemCount()) { RectTransform item = (UnityEngine.Object.Instantiate(PrototypeCell.gameObject)).GetComponent<RectTransform>(); item.name = "Cell"; item.sizeDelta = new Vector2(_cellWidth, _cellHeight); _cellPool.Add(item); item.SetParent(Content, false); if (IsGrid) { posX = _bottomMostCellColoumn * _cellWidth; item.anchoredPosition = new Vector2(posX, posY); if (++_bottomMostCellColoumn >= _coloumns) { _bottomMostCellColoumn = 0; posY -= _cellHeight; currentPoolCoverage += item.rect.height; } } else { item.anchoredPosition = new Vector2(0, posY); posY = item.anchoredPosition.y - item.rect.height; currentPoolCoverage += item.rect.height; } _cachedCells.Add(item.GetComponent<ICell>()); _dataSource.SetCell(_cachedCells[_cachedCells.Count - 1], poolSize); poolSize++; } if (IsGrid) { _bottomMostCellColoumn = (_bottomMostCellColoumn - 1 + _coloumns) % _coloumns; } if (PrototypeCell.gameObject.scene.IsValid()) { PrototypeCell.gameObject.SetActive(false); } } #endregion #region RECYCLING public override Vector2 OnValueChangedListener(Vector2 direction) { if (_recycling || _cellPool == null || _cellPool.Count == 0) return zeroVector; SetRecyclingBounds(); if (direction.y > 0 && _cellPool[bottomMostCellIndex].MaxY() > _recyclableViewBounds.min.y) { return RecycleTopToBottom(); } else if (direction.y < 0 && _cellPool[topMostCellIndex].MinY() < _recyclableViewBounds.max.y) { return RecycleBottomToTop(); } return zeroVector; } private Vector2 RecycleTopToBottom() { _recycling = true; int n = 0; float posY = IsGrid ? _cellPool[bottomMostCellIndex].anchoredPosition.y : 0; float posX = 0; int additionalRows = 0; while (_cellPool[topMostCellIndex].MinY() > _recyclableViewBounds.max.y && currentItemCount < _dataSource.GetItemCount()) { if (IsGrid) { if (++_bottomMostCellColoumn >= _coloumns) { n++; _bottomMostCellColoumn = 0; posY = _cellPool[bottomMostCellIndex].anchoredPosition.y - _cellHeight; additionalRows++; } posX = _bottomMostCellColoumn * _cellWidth; _cellPool[topMostCellIndex].anchoredPosition = new Vector2(posX, posY); if (++_topMostCellColoumn >= _coloumns) { _topMostCellColoumn = 0; additionalRows--; } } else { posY = _cellPool[bottomMostCellIndex].anchoredPosition.y - _cellPool[bottomMostCellIndex].sizeDelta.y; _cellPool[topMostCellIndex].anchoredPosition = new Vector2(_cellPool[topMostCellIndex].anchoredPosition.x, posY); } _dataSource.SetCell(_cachedCells[topMostCellIndex], currentItemCount); bottomMostCellIndex = topMostCellIndex; topMostCellIndex = (topMostCellIndex + 1) % _cellPool.Count; currentItemCount++; if (!IsGrid) n++; } if (IsGrid) { Content.sizeDelta += additionalRows * Vector2.up * _cellHeight; if (additionalRows > 0) { n -= additionalRows; } } _cellPool.ForEach((RectTransform cell) => cell.anchoredPosition += n * Vector2.up * _cellPool[topMostCellIndex].sizeDelta.y); Content.anchoredPosition -= n * Vector2.up * _cellPool[topMostCellIndex].sizeDelta.y; _recycling = false; return -new Vector2(0, n * _cellPool[topMostCellIndex].sizeDelta.y); } private Vector2 RecycleBottomToTop() { _recycling = true; int n = 0; float posY = IsGrid ? _cellPool[topMostCellIndex].anchoredPosition.y : 0; float posX = 0; int additionalRows = 0; while (_cellPool[bottomMostCellIndex].MaxY() < _recyclableViewBounds.min.y && currentItemCount > _cellPool.Count) { if (IsGrid) { if (--_topMostCellColoumn < 0) { n++; _topMostCellColoumn = _coloumns - 1; posY = _cellPool[topMostCellIndex].anchoredPosition.y + _cellHeight; additionalRows++; } posX = _topMostCellColoumn * _cellWidth; _cellPool[bottomMostCellIndex].anchoredPosition = new Vector2(posX, posY); if (--_bottomMostCellColoumn < 0) { _bottomMostCellColoumn = _coloumns - 1; additionalRows--; } } else { posY = _cellPool[topMostCellIndex].anchoredPosition.y + _cellPool[topMostCellIndex].sizeDelta.y; _cellPool[bottomMostCellIndex].anchoredPosition = new Vector2(_cellPool[bottomMostCellIndex].anchoredPosition.x, posY); n++; } currentItemCount--; _dataSource.SetCell(_cachedCells[bottomMostCellIndex], currentItemCount - _cellPool.Count); topMostCellIndex = bottomMostCellIndex; bottomMostCellIndex = (bottomMostCellIndex - 1 + _cellPool.Count) % _cellPool.Count; } if (IsGrid) { Content.sizeDelta += additionalRows * Vector2.up * _cellHeight; if (additionalRows > 0) { n -= additionalRows; } } _cellPool.ForEach((RectTransform cell) => cell.anchoredPosition -= n * Vector2.up * _cellPool[topMostCellIndex].sizeDelta.y); Content.anchoredPosition += n * Vector2.up * _cellPool[topMostCellIndex].sizeDelta.y; _recycling = false; return new Vector2(0, n * _cellPool[topMostCellIndex].sizeDelta.y); } #endregion #region HELPERS private void SetTopAnchor(RectTransform rectTransform) { float width = rectTransform.rect.width; float height = rectTransform.rect.height; rectTransform.anchorMin = new Vector2(0.5f, 1); rectTransform.anchorMax = new Vector2(0.5f, 1); rectTransform.pivot = new Vector2(0.5f, 1); rectTransform.sizeDelta = new Vector2(width, height); } private void SetTopLeftAnchor(RectTransform rectTransform) { float width = rectTransform.rect.width; float height = rectTransform.rect.height; rectTransform.anchorMin = new Vector2(0, 1); rectTransform.anchorMax = new Vector2(0, 1); rectTransform.pivot = new Vector2(0, 1); rectTransform.sizeDelta = new Vector2(width, height); } #endregion #region TESTING public void OnDrawGizmos() { Gizmos.color = Color.green; Gizmos.DrawLine(_recyclableViewBounds.min - new Vector3(2000, 0), _recyclableViewBounds.min + new Vector3(2000, 0)); Gizmos.color = Color.red; Gizmos.DrawLine(_recyclableViewBounds.max - new Vector3(2000, 0), _recyclableViewBounds.max + new Vector3(2000, 0)); } #endregion }
c#
19
0.538033
185
44.386973
261
/// <summary> /// Recyling system for Vertical type. /// </summary>
class
public class ClickableImpl : IClickable { public bool Clicked { get; private set; } = false; CollidesOn CollidesOn; Position LastClick; public ClickableImpl(CollidesOn collidesOn) { this.CollidesOn = collidesOn; } public void Click(float x, float y) { LastClick.X = x; LastClick.Y = y; if (this.CollidesOn(x, y)) { Clicked = true; } } public void ClickMove(float x, float y) { LastClick.X = x; LastClick.Y = y; if (Clicked && !this.CollidesOn(x, y)) { Clicked = false; } } public void ClickRelease() { if (Clicked) { Clicked = false; } } public void Act() { if (Clicked && !this.CollidesOn(LastClick.X, LastClick.Y)) { Clicked = false; } } }
c#
12
0.594954
61
15.755556
45
/// <summary> /// Implements clickability support. /// </summary>
class
public sealed partial class MainPage : UniversalPage, MainViewModelCallbacks { private static string BG_TASK_TIMED_NAME = "Momentum.TimedUpdaterTask"; private static string BG_TASK_TOAST_NAME = "Momentum.ToastNotificationSaveTask"; private IBackgroundTaskService _backgroundTaskService; private IToastService _toastService; private IDeviceInfoService _deviceInfoService; public MainViewModel ViewModel { get; private set; } public MainPage() { InitializeComponent(); ConfigureAdverts(); ViewModel = new MainViewModel(this); DataContext = ViewModel; _backgroundTaskService = Injector.Get<IBackgroundTaskService>(); _toastService = Injector.Get<IToastService>(); _deviceInfoService = Injector.Get <IDeviceInfoService>(); Loaded += (s, e) => { RegisterBackgroundTask(); _toastService.ClearHistory(); }; } private async void RegisterBackgroundTask() { if (_backgroundTaskService.RegistrationExists(BG_TASK_TIMED_NAME)) _backgroundTaskService.Unregister(BG_TASK_TIMED_NAME); if (await _backgroundTaskService.RequestAccessAsync()) { _backgroundTaskService.Register(BG_TASK_TIMED_NAME, "Momentum.Tasks.TimedUpdaterTask", new TimeTrigger(60, false), new SystemCondition(SystemConditionType.InternetAvailable)); _backgroundTaskService.Register(BG_TASK_TOAST_NAME, "Momentum.Tasks.ToastNotificationSaveTask", new ToastNotificationActionTrigger()); } } private void NameDoulbeTapped(object sender, Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs e) { NavigationService.Navigate(typeof(SettingsPage), SettingsPage.PARAM_CHANGE_NAME); } void MainViewModelCallbacks.NotifyImageLoaded() { ShowBackgroundImage.Begin(); StartupAnimation.Begin(); } void MainViewModelCallbacks.NotifyQuoteLoaded() { ShowQuote.Begin(); } private void ClearFocusClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { FocusTextBox.Text = string.Empty; } private void QuoteTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { var viewModel = DataContext as MainViewModel; if (viewModel != null) { viewModel.ReadQuoteCommand.Execute(null); } } #region Adverts private const int AD_WIDTH = 320; private const int AD_HEIGHT = 50; private const int HOUSE_AD_WEIGHT = 5; private const int AD_REFRESH_SECONDS = 35; private const int MAX_ERRORS_PER_REFRESH = 3; private const string WAPPLICATIONID = "891da8fa-fe3b-4aab-b9f5-8da90fceb155"; private const string WADUNITID_PAID = "251980"; private const string WADUNITID_HOUSE = "252004"; private const string MAPPLICATIONID = "574b9a13-5c75-4ef8-9776-6f50d7734a7c"; private const string MADUNITID_PAID = "251977"; private const string MADUNITID_HOUSE = "252008"; private const string ADDUPLEX_APPKEY = "4e7ab990-2cf9-4a79-8a35-0b8e1f4a671a"; private const string ADDUPLEX_ADUNIT = "172239"; private DispatcherTimer myAdRefreshTimer = new DispatcherTimer(); private Random randomGenerator = new Random(); private int errorCountCurrentRefresh = 0; private int adDuplexWeight = 0; private AdControl myMicrosoftBanner = null; private AdDuplex.AdControl myAdDuplexBanner = null; private string myMicrosoftAppId = WAPPLICATIONID; private string myMicrosoftPaidUnitId = WADUNITID_PAID; private string myMicrosoftHouseUnitId = WADUNITID_HOUSE; public void ConfigureAdverts() { myAdGrid.Width = AD_WIDTH; myAdGrid.Height = AD_HEIGHT; adDuplexWeight = 0; RefreshBanner(); myAdRefreshTimer.Interval = new TimeSpan(0, 0, AD_REFRESH_SECONDS); myAdRefreshTimer.Tick += myAdRefreshTimer_Tick; myAdRefreshTimer.Start(); if ("Windows.Mobile" == AnalyticsInfo.VersionInfo.DeviceFamily) { myMicrosoftAppId = MAPPLICATIONID; myMicrosoftPaidUnitId = MADUNITID_PAID; myMicrosoftHouseUnitId = MADUNITID_HOUSE; } } private void ActivateMicrosoftBanner() { if (errorCountCurrentRefresh >= MAX_ERRORS_PER_REFRESH) { return; } string myAdUnit = myMicrosoftPaidUnitId; int houseWeight = HOUSE_AD_WEIGHT; int randomInt = randomGenerator.Next(0, 100); if (randomInt < houseWeight) { myAdUnit = myMicrosoftHouseUnitId; } if (null != myAdDuplexBanner) { myAdGrid.Children.Remove(myAdDuplexBanner); myAdDuplexBanner = null; } if (null == myMicrosoftBanner) { myMicrosoftBanner = new AdControl(); myMicrosoftBanner.ApplicationId = myMicrosoftAppId; myMicrosoftBanner.AdUnitId = myAdUnit; myMicrosoftBanner.Width = AD_WIDTH; myMicrosoftBanner.Height = AD_HEIGHT; myMicrosoftBanner.IsAutoRefreshEnabled = false; myMicrosoftBanner.AdRefreshed += myMicrosoftBanner_AdRefreshed; myMicrosoftBanner.ErrorOccurred += myMicrosoftBanner_ErrorOccurred; myAdGrid.Children.Add(myMicrosoftBanner); } else { myMicrosoftBanner.AdUnitId = myAdUnit; myMicrosoftBanner.Visibility = Visibility.Visible; myMicrosoftBanner.Refresh(); } } private void ActivateAdDuplexBanner() { if (errorCountCurrentRefresh >= MAX_ERRORS_PER_REFRESH) { return; } if (null != myMicrosoftBanner) { myMicrosoftBanner.Visibility = Visibility.Collapsed; myAdGrid.Children.Remove(myMicrosoftBanner); myMicrosoftBanner = null; } if (null == myAdDuplexBanner) { myAdDuplexBanner = new AdDuplex.AdControl(); myAdDuplexBanner.AppKey = ADDUPLEX_APPKEY; myAdDuplexBanner.AdUnitId = ADDUPLEX_ADUNIT; myAdDuplexBanner.Width = AD_WIDTH; myAdDuplexBanner.Height = AD_HEIGHT; myAdDuplexBanner.RefreshInterval = AD_REFRESH_SECONDS; myAdDuplexBanner.AdLoaded += myAdDuplexBanner_AdLoaded; myAdDuplexBanner.AdCovered += myAdDuplexBanner_AdCovered; myAdDuplexBanner.AdLoadingError += myAdDuplexBanner_AdLoadingError; myAdDuplexBanner.NoAd += myAdDuplexBanner_NoAd; myAdGrid.Children.Add(myAdDuplexBanner); } myAdDuplexBanner.Visibility = Visibility.Visible; } private void myAdRefreshTimer_Tick(object sender, object e) { RefreshBanner(); } private void RefreshBanner() { errorCountCurrentRefresh = 0; ActivateMicrosoftBanner(); } private void myMicrosoftBanner_AdRefreshed(object sender, RoutedEventArgs e) { } private void myMicrosoftBanner_ErrorOccurred(object sender, AdErrorEventArgs e) { errorCountCurrentRefresh++; ActivateAdDuplexBanner(); } private void myAdDuplexBanner_AdLoaded(object sender, AdDuplex.Banners.Models.BannerAdLoadedEventArgs e) { } private void myAdDuplexBanner_NoAd(object sender, AdDuplex.Common.Models.NoAdEventArgs e) { errorCountCurrentRefresh++; ActivateMicrosoftBanner(); } private void myAdDuplexBanner_AdLoadingError(object sender, AdDuplex.Common.Models.AdLoadingErrorEventArgs e) { errorCountCurrentRefresh++; ActivateMicrosoftBanner(); } private void myAdDuplexBanner_AdCovered(object sender, AdDuplex.Banners.Core.AdCoveredEventArgs e) { errorCountCurrentRefresh++; ActivateMicrosoftBanner(); } #endregion }
c#
15
0.607599
191
42.648241
199
/// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary>
class
public class ValueProcessorFactory : IValueProcessorFactory { [NotNull] private readonly ITypeValueProcessorRegistry valueProcessorRegistry; [NotNull] private readonly IInstanceFactory instanceFactory; public ValueProcessorFactory([NotNull] ITypeValueProcessorRegistry valueProcessorRegistry, [NotNull] IInstanceFactory instanceFactory) { if (valueProcessorRegistry == null) { throw new ArgumentNullException(nameof(valueProcessorRegistry)); } if (instanceFactory == null) { throw new ArgumentNullException(nameof(instanceFactory)); } this.valueProcessorRegistry = valueProcessorRegistry; this.instanceFactory = instanceFactory; } public virtual IValueProcessor GetUrlValueProcessorForType(Type propertyType) { if (propertyType == null) { throw new ArgumentNullException(nameof(propertyType)); } IValueProcessor lookupResult; if (this.valueProcessorRegistry.TryLookup(propertyType, out lookupResult)) { return lookupResult; } if (propertyType.IsGenericType) { var singleGenericType = propertyType.GetSingleGenericParameter(); var innerUrlValueProcessor = this.GetUrlValueProcessorForType(singleGenericType); if (propertyType.IsLazy()) { return new LazyValueProcessor(innerUrlValueProcessor); } if (propertyType.IsGenericIEnumerable() && !propertyType.IsPrimitive()) { return new EnumerableValueProcessor(innerUrlValueProcessor); } } if (propertyType.IsIEnumerable() && !propertyType.IsPrimitive()) { return new EnumerableValueProcessor(new DefaultValueProcessor()); } if (propertyType.IsEnum) { if (propertyType.HasAttribute<UseEnumValueNameAttribute>()) { return new EnumMemberAsNameValueProcessor(); } return new EnumMemberAsUnderlyingTypeValueProcessor(); } return new DefaultValueProcessor(); } public virtual IValueProcessor GetUrlValueProcessor(Type propertyType, Type valueProcessorType) { if (propertyType == null) { throw new ArgumentNullException(nameof(propertyType)); } if (valueProcessorType == null) { return this.GetUrlValueProcessorForType(propertyType); } if (valueProcessorType == typeof (ValueProcessorTypeConverterAdapter)) { var valueConverter = TypeDescriptor.GetConverter(valueProcessorType); return new ValueProcessorTypeConverterAdapter(valueConverter); } return this.instanceFactory.CreateInstance<IValueProcessor>(valueProcessorType); } }
c#
14
0.59192
142
41.586667
75
/// <summary> /// The <see cref="ValueProcessorFactory"/> class provides implementations of the <see cref="IValueProcessor"/> by reusing the built-in ValueProcessors. /// </summary>
class
public class LocalStep { public string Target { get; set; } public string Value { get; set; } public string Command { get; set; } public int? Type { get; set; } public String Name { get; set; } public String Condition { get; set; } public String Browser { get; set; } public int? TimeBetweenSteps { get; set; } public int? TimedOutValue { get; set; } public LocalStep(string target, string value) { Value = value; Target = target; } public LocalStep(string command, string target, string value, int? type, String name, int? TimeBetweenSteps, int? timedOutValue, string browsers, string condition) { Command = command; Value = value; Target = target; Type = type; Name = name; TimedOutValue = timedOutValue; Browser = browsers; Condition = condition; } }
c#
8
0.546454
171
34.785714
28
/// <summary> /// Represents a step in a Scenario /// </summary>
class
internal class InputModeState { private readonly IVimGlobalSettings _globalSettings; private bool _synchronizingSettings; public InputModeState(IVimGlobalSettings globalSettings) { _globalSettings = globalSettings; _synchronizingSettings = false; } public bool SynchronizingSettings { get { return _synchronizingSettings; } } public InputMethodState this[InputMode inputMode] { get { return GetState(inputMode); } set { SynchronizeState(inputMode, value); } } private InputMethodState GetState(InputMode inputMode) { switch (inputMode) { case InputMode.Command: if (_globalSettings.ImeCommand) { return GetState(InputMode.Insert); } else { return InputMethodState.Off; } case InputMode.Insert: if (_globalSettings.ImeInsert == 2) { return InputMethodState.On; } else { return InputMethodState.Off; } case InputMode.Search: if (_globalSettings.ImeSearch == -1) { return GetState(InputMode.Insert); } else { if (_globalSettings.ImeSearch == 2) { return InputMethodState.On; } else { return InputMethodState.Off; } } default: throw new ArgumentException(nameof(inputMode)); } } private void SynchronizeState(InputMode inputMode, InputMethodState state) { try { _synchronizingSettings = true; SetState(inputMode, state); } finally { _synchronizingSettings = false; } } private void SetState(InputMode inputMode, InputMethodState state) { switch (inputMode) { case InputMode.Command: if (_globalSettings.ImeCommand) { SetState(InputMode.Insert, state); } break; case InputMode.Insert: switch (state) { case InputMethodState.On: _globalSettings.ImeInsert = 2; break; case InputMethodState.Off: _globalSettings.ImeInsert = 0; break; case InputMethodState.DoNotCare: break; default: throw new ArgumentException(nameof(state)); } break; case InputMode.Search: if (_globalSettings.ImeSearch == -1) { SetState(InputMode.Insert, state); } else { switch (state) { case InputMethodState.On: _globalSettings.ImeSearch = 2; break; case InputMethodState.Off: _globalSettings.ImeSearch = 0; break; case InputMethodState.DoNotCare: break; default: throw new ArgumentException(nameof(state)); } } break; default: throw new ArgumentException(nameof(inputMode)); } } }
c#
20
0.333069
86
36.977444
133
/// <summary> /// A mapping from input mode to IME state using the /// global IME-related settings as a backing store /// </summary>
class
public static partial class GetRaidDetailsResponseReflection { #region Descriptor public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GetRaidDetailsResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjxQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0dldFJhaWREZXRh", "aWxzUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5SZXNw", "b25zZXMaIFBPR09Qcm90b3MvRGF0YS9SYWlkL0xvYmJ5LnByb3RvGiNQT0dP", "UHJvdG9zL0RhdGEvQmF0dGxlL0JhdHRsZS5wcm90bxojUE9HT1Byb3Rvcy9E", "YXRhL1JhaWQvUmFpZEluZm8ucHJvdG8i5wQKFkdldFJhaWREZXRhaWxzUmVz", "cG9uc2USKgoFbG9iYnkYASABKAsyGy5QT0dPUHJvdG9zLkRhdGEuUmFpZC5M", "b2JieRIzCgtyYWlkX2JhdHRsZRgCIAEoCzIeLlBPR09Qcm90b3MuRGF0YS5C", "YXR0bGUuQmF0dGxlEh0KFXBsYXllcl9jYW5fam9pbl9sb2JieRgDIAEoCBJO", "CgZyZXN1bHQYBCABKA4yPi5QT0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVzcG9u", "c2VzLkdldFJhaWREZXRhaWxzUmVzcG9uc2UuUmVzdWx0EjEKCXJhaWRfaW5m", "bxgFIAEoCzIeLlBPR09Qcm90b3MuRGF0YS5SYWlkLlJhaWRJbmZvEhMKC3Rp", "Y2tldF91c2VkGAYgASgIEh0KFWZyZWVfdGlja2V0X2F2YWlsYWJsZRgHIAEo", "CBIYChB0aHJvd3NfcmVtYWluaW5nGAggASgFEhgKEHJlY2VpdmVkX3Jld2Fy", "ZHMYCSABKAgSHAoUbnVtX3BsYXllcnNfaW5fbG9iYnkYCiABKAUSEQoJc2Vy", "dmVyX21zGAsgASgDIrABCgZSZXN1bHQSCQoFVU5TRVQQABILCgdTVUNDRVNT", "EAESFgoSRVJST1JfTk9UX0lOX1JBTkdFEAISGAoURVJST1JfUkFJRF9DT01Q", "TEVURUQQAxIaChZFUlJPUl9SQUlEX1VOQVZBSUxBQkxFEAQSJAogRVJST1Jf", "UExBWUVSX0JFTE9XX01JTklNVU1fTEVWRUwQBRIaChZFUlJPUl9QT0lfSU5B", "Q0NFU1NJQkxFEAZiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Data.Raid.LobbyReflection.Descriptor, global::POGOProtos.Data.Battle.BattleReflection.Descriptor, global::POGOProtos.Data.Raid.RaidInfoReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.GetRaidDetailsResponse), global::POGOProtos.Networking.Responses.GetRaidDetailsResponse.Parser, new[]{ "Lobby", "RaidBattle", "PlayerCanJoinLobby", "Result", "RaidInfo", "TicketUsed", "FreeTicketAvailable", "ThrowsRemaining", "ReceivedRewards", "NumPlayersInLobby", "ServerMs" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.GetRaidDetailsResponse.Types.Result) }, null) })); } #endregion }
c#
28
0.766292
474
73.194444
36
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/GetRaidDetailsResponse.proto</summary>
class
[global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Result { [pbr::OriginalName("UNSET")] Unset = 0, [pbr::OriginalName("SUCCESS")] Success = 1, [pbr::OriginalName("ERROR_NOT_IN_RANGE")] ErrorNotInRange = 2, [pbr::OriginalName("ERROR_RAID_COMPLETED")] ErrorRaidCompleted = 3, [pbr::OriginalName("ERROR_RAID_UNAVAILABLE")] ErrorRaidUnavailable = 4, [pbr::OriginalName("ERROR_PLAYER_BELOW_MINIMUM_LEVEL")] ErrorPlayerBelowMinimumLevel = 5, [pbr::OriginalName("ERROR_POI_INACCESSIBLE")] ErrorPoiInaccessible = 6, } }
c#
11
0.674961
97
52.666667
12
/// <summary>Container for nested types declared in the GetRaidDetailsResponse message type.</summary>
class
public class ChartData { public string Title { get; set; } public List<ChartSeries> Series { get; set; } }
c#
6
0.584615
53
25.2
5
/// <summary> /// Chart element model data /// </summary>
class
public class Digest { public string Create(string data) { using (HashAlgorithm algorithm = new SHA256Managed()) { var bytes = Encoding.GetEncoding("UTF-8").GetBytes(data); var hash = algorithm.ComputeHash(bytes); return Convert.ToBase64String(hash); } } }
c#
17
0.522911
73
30
12
/// <summary> /// This class is used to create a digest. /// </summary>
class
public class PushbackReader : FilterReader { private char[] _buf; private int _pos; public PushbackReader(TextReader inp, int size) : base(inp) { if (size <= 0) { throw new ArgumentException("size <= 0"); } _buf = new char[size]; _pos = size; } public PushbackReader(TextReader inp) : this(inp, 1) { } private void EnsureOpen() { if (_buf == null) { throw new IOException("Stream closed"); } } public override int Read() { EnsureOpen(); if (_pos < _buf.Length) { return _buf[_pos++]; } return base.Read(); } public override int Read(char[] cbuf, int off, int len) { EnsureOpen(); try { if (len <= 0) { if (len < 0) { throw new IndexOutOfRangeException(); } if ((off < 0) || (off > cbuf.Length)) { throw new IndexOutOfRangeException(); } return 0; } int avail = _buf.Length - _pos; if (avail > 0) { if (len < avail) { avail = len; } Array.Copy(_buf, _pos, cbuf, off, avail); _pos += avail; off += avail; len -= avail; } if (len > 0) { len = base.Read(cbuf, off, len); if (len == -1) { return (avail == 0) ? -1 : avail; } return avail + len; } return avail; } catch (IndexOutOfRangeException) { throw new IndexOutOfRangeException(); } } public virtual void Unread(int c) { EnsureOpen(); if (_pos == 0) { throw new IOException("Pushback buffer overflow"); } _buf[--_pos] = (char) c; } public virtual void Unread(char[] cbuf, int off, int len) { EnsureOpen(); if (len > _pos) { throw new IOException("Pushback buffer overflow"); } _pos -= len; Array.Copy(cbuf, off, _buf, _pos, len); } public virtual void Unread(char[] cbuf) { Unread(cbuf, 0, cbuf.Length); } public override void Close() { base.Close(); _buf = null; } }
c#
15
0.382321
67
31.738095
84
/// <summary> /// A character-stream reader that allows characters to be pushed back into the /// stream. /// /// @author Mark Reinhold /// @since JDK1.1 /// </summary>
class
internal class Cell : InternalBase { #region Constructor private Cell(CellQuery cQuery, CellQuery sQuery, CellLabel label, int cellNumber) { Debug.Assert(label != null, "Cell lacks label"); m_cQuery = cQuery; m_sQuery = sQuery; m_label = label; m_cellNumber = cellNumber; Debug.Assert(m_sQuery.NumProjectedSlots == m_cQuery.NumProjectedSlots, "Cell queries disagree on the number of projected fields"); } internal Cell(Cell source) { m_cQuery = new CellQuery(source.m_cQuery); m_sQuery = new CellQuery(source.m_sQuery); m_label = new CellLabel(source.m_label); m_cellNumber = source.m_cellNumber; } #endregion #region Fields private CellQuery m_cQuery; private CellQuery m_sQuery; private int m_cellNumber; private CellLabel m_label; private ViewCellRelation m_viewCellRelation; #endregion #region Properties internal CellQuery CQuery { get { return m_cQuery; } } internal CellQuery SQuery { get { return m_sQuery; } } internal CellLabel CellLabel { get { return m_label; } } internal int CellNumber { get { return m_cellNumber; } } internal string CellNumberAsString { get { return StringUtil.FormatInvariant("V{0}", CellNumber); } } #endregion #region Methods internal void GetIdentifiers(CqlIdentifiers identifiers) { m_cQuery.GetIdentifiers(identifiers); m_sQuery.GetIdentifiers(identifiers); } internal Set<EdmProperty> GetCSlotsForTableColumns(IEnumerable<MemberPath> columns) { List<int> fieldNums = SQuery.GetProjectedPositions(columns); if (fieldNums == null) { return null; } Set<EdmProperty> cSideMembers = new Set<EdmProperty>(); foreach (int fieldNum in fieldNums) { ProjectedSlot projectedSlot = CQuery.ProjectedSlotAt(fieldNum); MemberProjectedSlot slot = projectedSlot as MemberProjectedSlot; if (slot != null) { cSideMembers.Add((EdmProperty)slot.MemberPath.LeafEdmMember); } else { return null; } } return cSideMembers; } for ViewTarget.QueryView and S query for ViewTarget.UpdateView internal CellQuery GetLeftQuery(ViewTarget side) { return side == ViewTarget.QueryView ? m_cQuery : m_sQuery; } for ViewTarget.QueryView and C query for ViewTarget.UpdateView internal CellQuery GetRightQuery(ViewTarget side) { return side == ViewTarget.QueryView ? m_sQuery : m_cQuery; } internal ViewCellRelation CreateViewCellRelation(int cellNumber) { if (m_viewCellRelation != null) { return m_viewCellRelation; } GenerateCellRelations(cellNumber); return m_viewCellRelation; } private void GenerateCellRelations(int cellNumber) { List<ViewCellSlot> projectedSlots = new List<ViewCellSlot>(); Debug.Assert(CQuery.NumProjectedSlots == SQuery.NumProjectedSlots, "Cell queries in cell have a different number of slots"); for (int i = 0; i < CQuery.NumProjectedSlots; i++) { ProjectedSlot cSlot = CQuery.ProjectedSlotAt(i); ProjectedSlot sSlot = SQuery.ProjectedSlotAt(i); Debug.Assert(cSlot != null, "Has cell query been normalized?"); Debug.Assert(sSlot != null, "Has cell query been normalized?"); Debug.Assert(cSlot is MemberProjectedSlot, "cSlot is expected to be MemberProjectedSlot"); Debug.Assert(sSlot is MemberProjectedSlot, "sSlot is expected to be MemberProjectedSlot"); MemberProjectedSlot cJoinSlot = (MemberProjectedSlot)cSlot; MemberProjectedSlot sJoinSlot = (MemberProjectedSlot)sSlot; ViewCellSlot slot = new ViewCellSlot(i, cJoinSlot, sJoinSlot); projectedSlots.Add(slot); } m_viewCellRelation = new ViewCellRelation(this, projectedSlots, cellNumber); } internal override void ToCompactString(StringBuilder builder) { CQuery.ToCompactString(builder); builder.Append(" = "); SQuery.ToCompactString(builder); } internal override void ToFullString(StringBuilder builder) { CQuery.ToFullString(builder); builder.Append(" = "); SQuery.ToFullString(builder); } public override string ToString() { return ToFullString(); } internal static void CellsToBuilder(StringBuilder builder, IEnumerable<Cell> cells) { builder.AppendLine(); builder.AppendLine("========================================================================="); foreach (Cell cell in cells) { builder.AppendLine(); StringUtil.FormatStringBuilder(builder, "Mapping Cell V{0}:", cell.CellNumber); builder.AppendLine(); builder.Append("C: "); cell.CQuery.ToFullString(builder); builder.AppendLine(); builder.AppendLine(); builder.Append("S: "); cell.SQuery.ToFullString(builder); builder.AppendLine(); } } #endregion #region Factory methods internal static Cell CreateCS(CellQuery cQuery, CellQuery sQuery, CellLabel label, int cellNumber) { return new Cell(cQuery, sQuery, label, cellNumber); } #endregion }
c#
16
0.554473
108
38.13125
160
/// <summary> /// This class contains a pair of cell queries which is essentially a /// constraint that they are equal. A cell is initialized with a C or an /// S Query which it exposes as properties but it also has the notion of /// "Left" and "Right" queries -- left refers to the side for which a /// view is being generated /// For example, to /// specify a mapping for CPerson to an SPerson table, we have /// /// [(p type Person) in P : SPerson] /// (p.pid, pid) /// (p.name, name) /// /// This really denotes the equality of two queries: /// (C) SELECT (p type Person) AS D1, p.pid, p.name FROM p in P WHERE D1 /// (S) SELECT True AS D1, pid, name FROM SPerson WHERE D1 /// /// For more details, see the design doc /// </summary>
class
public class AssertLastExceptionTypeStep : ITestRunStep { public void Run(TestRunExecutionContext context) { throw new NotImplementedException(); } public JObject Save() { throw new NotImplementedException(); } }
c#
8
0.589041
56
25.636364
11
/// <summary> /// Asserts last exception type name. /// </summary>
class
internal class ParametersAdjustmentMiddleware : IAsyncMiddleware<ParametersManagementContext> { private readonly IPgSettings pgSettings; public ParametersAdjustmentMiddleware(IPgSettings pgSettings) => this.pgSettings = pgSettings; async Task IAsyncMiddleware<ParametersManagementContext>.Run( ParametersManagementContext context, Func<ParametersManagementContext, Task> next) { await pgSettings.FlushAsync(); await next(context); } }
c#
10
0.812227
96
37.25
12
/// <summary> /// Pipeline component which is responsible /// for database server parameters adjustment. /// </summary>
class
public class SocialPlusAuthManager : CommonAuthManager, IAuthManager { private readonly ISessionTokenManager sessionTokenManager; public SocialPlusAuthManager(ILog log, IAppsManager appsManager, IUsersManager usersManager, ISessionTokenManager sessionTokenManager) : base(log, appsManager, usersManager) { this.sessionTokenManager = sessionTokenManager ?? throw new ArgumentNullException("SocialPlusAuthManager constructor: sessionTokenManager is null"); } public Task<List<IPrincipal>> GetFriends(string auth) { return null; } public async Task<List<IPrincipal>> ValidateAuthParameter(string authParameter) { string token; var authDictionary = new Dictionary<string, string>(); this.ParseAuthParameter(authParameter, authDictionary); authDictionary.TryGetValue("tk", out token); var principals = await this.sessionTokenManager.ValidateToken(token); AppPrincipal appPrincipal = null; UserPrincipal userPrincipal = null; foreach (var p in principals) { if (p is AppPrincipal) { appPrincipal = p as AppPrincipal; } else { userPrincipal = p as UserPrincipal; } } var task1 = this.ValidateAppKey(appPrincipal.AppKey); var task2 = this.ValidateUserPrincipal(userPrincipal, appPrincipal.AppHandle); await Task.WhenAll(task1, task2); if (task1.Result == false) { string errorMessage = $"Invalid AppKey. AppPrincipal={appPrincipal.ToString()}"; this.Log.LogException(errorMessage); } if (task2.Result == false) { string errorMessage = $"Invalid UserPrincipal. UserPrincipal={userPrincipal.ToString()}, AppHandle={appPrincipal.AppHandle}"; this.Log.LogException(errorMessage); } return principals; } }
c#
15
0.596939
160
43.9375
48
/// <summary> /// Authentication functionality for SocialPlus session tokens /// </summary>
class
public abstract class AsyncCommandBase : IAsyncCommand { protected AsyncCommandBase() { } public event EventHandler? CanExecuteChanged; protected virtual bool IgnoreCanExecuteOnExecute => false; public bool CanExecute(object? parameter) { return CanExecute(); } public virtual bool CanExecute() { return true; } public async void Execute(object? parameter) { await ExecuteAsync(parameter); } public abstract Task Execute(); public async Task ExecuteAsync() { await ExecuteAsync(null); } public async Task ExecuteAsync(object? parameter) { if (IgnoreCanExecuteOnExecute || CanExecute()) await Execute(); } protected void RaiseCanExecuteChanged(object sender, EventArgs e) { _ = Dispatcher.UIThread.InvokeAsync(() => CanExecuteChanged?.Invoke(sender, e)); } }
c#
14
0.568421
92
29.764706
34
/// <summary> /// This class is an easy way to implement an asynchronous command without parameters that can be executed asynchronously. /// </summary>
class
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Generic representation can be in same file.")] public abstract class AsyncCommandBase<T> : IAsyncCommand { protected AsyncCommandBase() { } public event EventHandler? CanExecuteChanged; protected virtual bool IgnoreCanExecuteOnExecute => false; protected virtual bool ThrowExceptionOnWrongParamType => true; public bool CanExecute(object? parameter) { return CanExecute(GetParameterValue(parameter)); } public virtual bool CanExecute(T? parameter) { return true; } public async void Execute(object? parameter) { await ExecuteAsync(parameter); } public abstract Task Execute(T? parameter); public async Task ExecuteAsync(object? parameter) { var parameterValue = GetParameterValue(parameter); if (IgnoreCanExecuteOnExecute || CanExecute(parameterValue)) await Execute(parameterValue); } protected void RaiseCanExecuteChanged(object sender, EventArgs e) { _ = Dispatcher.UIThread.InvokeAsync(() => CanExecuteChanged?.Invoke(sender, e)); } private T? GetParameterValue(object? parameter) { if (ThrowExceptionOnWrongParamType) return (T?)parameter; else return parameter?.GetType().IsCastableTo(typeof(T)) == true ? (T)parameter : default; } }
c#
14
0.622291
166
39.4
40
/// <summary> /// This class is an easy way to implement an asynchronous command with parameters of a specific type. /// </summary> /// <typeparam name="T">The parameter type for this <see cref="IAsyncCommand"/>.</typeparam>
class