content stringlengths 23 1.05M |
|---|
using Microsoft.Extensions.Configuration;
namespace NUnit.DFM.Interfaces
{
public interface IConfigurationBuilderSetup
{
IConfigurationRoot Create();
}
}
|
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using ComboRox.Core.Utilities.SimpleGuard;
namespace Html2Amp.Sanitization.Implementation
{
public class AudioSanitizer : MediaSanitizer
{
public override bool CanSanitize(IElement element)
{
return element != null && element is IHtmlAudioElement;
}
public override IElement Sanitize(IDocument document, IElement htmlElement)
{
return this.SanitizeCore<IHtmlAudioElement>(document, htmlElement, "amp-audio");
}
protected override void SetMediaElementLayout(IElement element, IElement ampElement)
{
Guard.Requires(element, "element").IsNotNull();
Guard.Requires(ampElement, "ampElement").IsNotNull();
if (!ampElement.HasAttribute("layout"))
{
if (ampElement.HasAttribute("height"))
{
if (ampElement.HasAttribute("width"))
{
if (ampElement.GetAttribute("width") == "auto")
{
ampElement.SetAttribute("layout", "responsive");
}
else
{
ampElement.SetAttribute("layout", "fixed");
}
}
else
{
ampElement.SetAttribute("layout", "fixed-height");
}
}
}
}
protected override bool ShoulRequestResourcesOnlyViaHttps
{
get { return true; }
}
}
} |
using System;
using UltimaOnline;
using UltimaOnline.Mobiles;
using UltimaOnline.Items;
using UltimaOnline.Gumps;
using UltimaOnline.Engines.Quests;
namespace UltimaOnline.Engines.Quests.Ninja
{
public class Zoel : BaseQuester
{
[Constructable]
public Zoel() : base("the Masterful Tactician")
{
}
public override void InitBody()
{
InitStats(100, 100, 25);
Hue = 0x83FE;
Female = false;
Body = 0x190;
Name = "Elite Ninja Zoel";
}
public override void InitOutfit()
{
HairItemID = 0x203B;
HairHue = 0x901;
AddItem(new HakamaShita(0x1));
AddItem(new NinjaTabi());
AddItem(new TattsukeHakama());
AddItem(new Bandana());
AddItem(new LeatherNinjaBelt());
Tekagi tekagi = new Tekagi();
tekagi.Movable = false;
AddItem(tekagi);
}
public override int TalkNumber { get { return -1; } }
public override int GetAutoTalkRange(PlayerMobile pm)
{
return 2;
}
public override bool CanTalkTo(PlayerMobile to)
{
return to.Quest is EminosUndertakingQuest;
}
public override void OnTalk(PlayerMobile player, bool contextMenu)
{
QuestSystem qs = player.Quest;
if (qs is EminosUndertakingQuest)
{
QuestObjective obj = qs.FindObjective(typeof(FindZoelObjective));
if (obj != null && !obj.Completed)
obj.Complete();
}
}
public override bool OnDragDrop(Mobile from, Item dropped)
{
PlayerMobile player = from as PlayerMobile;
if (player != null)
{
QuestSystem qs = player.Quest;
if (qs is EminosUndertakingQuest)
{
if (dropped is NoteForZoel)
{
QuestObjective obj = qs.FindObjective(typeof(GiveZoelNoteObjective));
if (obj != null && !obj.Completed)
{
dropped.Delete();
obj.Complete();
return true;
}
}
}
}
return base.OnDragDrop(from, dropped);
}
public override void OnMovement(Mobile m, Point3D oldLocation)
{
base.OnMovement(m, oldLocation);
if (!m.Frozen && !m.Alive && InRange(m, 4) && !InRange(oldLocation, 4) && InLOS(m))
{
if (m.Map == null || !m.Map.CanFit(m.Location, 16, false, false))
{
m.SendLocalizedMessage(502391); // Thou can not be resurrected there!
}
else
{
Direction = GetDirectionTo(m);
m.PlaySound(0x214);
m.FixedEffect(0x376A, 10, 16);
m.CloseGump(typeof(ResurrectGump));
m.SendGump(new ResurrectGump(m, ResurrectMessage.Healer));
}
}
}
public Zoel(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} |
using System;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Parameters;
using DB = Autodesk.Revit.DB;
namespace RhinoInside.Revit.GH.Components.Material
{
public class MaterialIdentity : TransactionalChainComponent
{
public override Guid ComponentGuid => new Guid("222B42DF-16F6-4866-B065-FB77AADBD973");
public override GH_Exposure Exposure => GH_Exposure.primary;
public MaterialIdentity()
: base
(
"Material Identity",
"Identity",
"Material Identity Data.",
"Revit",
"Material"
)
{ }
protected override ParamDefinition[] Inputs => inputs;
static readonly ParamDefinition[] inputs =
{
ParamDefinition.Create<Parameters.Material>("Material", "M"),
ParamDefinition.Create<Param_String>("Description", "D", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Class", "CL", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Comments", "C", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Manufacturer", "MAN", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Model", "MOD", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Number>("Cost", "COS", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("URL", "URL", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Keynote", "KN", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Mark", "MK", optional: true, relevance: ParamRelevance.Primary),
};
protected override ParamDefinition[] Outputs => outputs;
static readonly ParamDefinition[] outputs =
{
ParamDefinition.Create<Parameters.Material>("Material", "M", relevance: ParamRelevance.Occasional),
ParamDefinition.Create<Param_String>("Name", "N", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Description", "D", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Class", "CL", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Comments", "C", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Manufacturer", "MAN", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Model", "MOD", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Number>("Cost", "COS", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("URL", "URL", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Keynote", "KN", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_String>("Mark", "MK", relevance: ParamRelevance.Primary),
};
protected override void TrySolveInstance(IGH_DataAccess DA)
{
if (!Params.GetData(DA, "Material", out Types.Material material, x => x.IsValid))
return;
bool update = false;
update |= Params.GetData(DA, "Name", out string name);
update |= Params.GetData(DA, "Description", out string descritpion);
update |= Params.GetData(DA, "Class", out string materialClass);
update |= Params.GetData(DA, "Comments", out string comments);
update |= Params.GetData(DA, "Manufacturer", out string manufacturer);
update |= Params.GetData(DA, "Model", out string model);
update |= Params.GetData(DA, "Cost", out double? cost);
update |= Params.GetData(DA, "URL", out string url);
update |= Params.GetData(DA, "Keynote", out string keynote);
update |= Params.GetData(DA, "Mark", out string mark);
if (update)
{
StartTransaction(material.Document);
material.Description = descritpion;
material.MaterialClass = materialClass;
material.Comments = comments;
material.Manufacturer = manufacturer;
material.Model = model;
material.Cost = cost;
material.Url = url;
material.Keynote = keynote;
material.Mark = mark;
}
Params.TrySetData(DA, "Material", () => material);
Params.TrySetData(DA, "Name", () => material.Name);
Params.TrySetData(DA, "Description", () => material.Description);
Params.TrySetData(DA, "Class", () => material.MaterialClass);
Params.TrySetData(DA, "Comments", () => material.Comments);
Params.TrySetData(DA, "Manufacturer", () => material.Manufacturer);
Params.TrySetData(DA, "Model", () => material.Model);
Params.TrySetData(DA, "Cost", () => material.Cost);
Params.TrySetData(DA, "URL", () => material.Url);
Params.TrySetData(DA, "Keynote", () => material.Keynote);
Params.TrySetData(DA, "Mark", () => material.Mark);
}
}
namespace Obsolete
{
[Obsolete("Since 2020-09-25")]
public class MaterialIdentity : Component
{
public override Guid ComponentGuid => new Guid("06E0CF55-B10C-433A-B6F7-AAF3885055DB");
public override GH_Exposure Exposure => GH_Exposure.primary | GH_Exposure.hidden;
protected override string IconTag => "ID";
public MaterialIdentity() : base
(
name: "Material Identity",
nickname: "Identity",
description: "Query material identity information",
category: "Revit",
subCategory: "Material"
)
{ }
protected override void RegisterInputParams(GH_InputParamManager manager)
{
manager.AddParameter(new Parameters.Material(), "Material", "Material", string.Empty, GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_OutputParamManager manager)
{
manager.AddTextParameter("Class", "Class", "Material class", GH_ParamAccess.item);
manager.AddTextParameter("Name", "Name", "Material name", GH_ParamAccess.item);
}
protected override void TrySolveInstance(IGH_DataAccess DA)
{
var material = default(DB.Material);
if (!DA.GetData("Material", ref material))
return;
DA.SetData("Class", material?.MaterialClass);
DA.SetData("Name", material?.Name);
}
}
}
}
|
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
{
class DHKeyGeneratorHelper
{
internal static readonly DHKeyGeneratorHelper Instance = new DHKeyGeneratorHelper();
private DHKeyGeneratorHelper()
{
}
internal BigInteger CalculatePrivate(
DHParameters dhParams,
SecureRandom random)
{
int limit = dhParams.L;
if (limit != 0)
{
int minWeight = limit >> 2;
for (;;)
{
BigInteger x = new BigInteger(limit, random).SetBit(limit - 1);
if (WNafUtilities.GetNafWeight(x) >= minWeight)
{
return x;
}
}
}
BigInteger min = BigInteger.Two;
int m = dhParams.M;
if (m != 0)
{
min = BigInteger.One.ShiftLeft(m - 1);
}
BigInteger q = dhParams.Q;
if (q == null)
{
q = dhParams.P;
}
BigInteger max = q.Subtract(BigInteger.Two);
{
int minWeight = max.BitLength >> 2;
for (;;)
{
BigInteger x = BigIntegers.CreateRandomInRange(min, max, random);
if (WNafUtilities.GetNafWeight(x) >= minWeight)
{
return x;
}
}
}
}
internal BigInteger CalculatePublic(
DHParameters dhParams,
BigInteger x)
{
return dhParams.G.ModPow(x, dhParams.P);
}
}
}
#pragma warning restore
#endif
|
namespace EmailSender.Services.SmtpService.Models;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
public class EmailData
{
public string From { get; set; }
public List<string> To { get; set; }
public List<string> Cc { get; set; }
public List<string> Bcc { get; set; }
public string Subject { get; set; }
public string PlainText { get; set; }
public string HtmlBody { get; set; }
} |
using Assets.Core.Controller;
using Assets.Core.Controller.Handlers.app;
using Assets.Core.Utils;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Core.View
{
public class LoginPopupView : MonoBehaviour
{
[Header("Inputs")]
public TMP_InputField emailInput;
public TMP_InputField passwordInput;
[Header("Buttons")]
public Button cancelButton;
public Button loginButton;
[Header("Response Textbox")]
public TextMeshProUGUI responseBox;
private void InitializeGameObjects()
{
responseBox.gameObject.SetActive(false);
cancelButton.onClick.AddListener(() => Destroy(gameObject));
loginButton.onClick.AddListener(() => VerifyLogin());
}
private void Awake() =>
InitializeGameObjects();
private void VerifyLogin()
{
responseBox.gameObject.SetActive(true);
if (!GU.IsValidEmail(emailInput.text))
{
responseBox.text = "<color=red>Invalid email!";
return;
}
if (string.IsNullOrEmpty(passwordInput.text))
{
responseBox.text = "<color=red>Please enter a password!";
return;
}
var verify = new VerifyHandler(emailInput.text, passwordInput.text);
if (verify.SendRequest())
{
responseBox.text = "<color=green>Successfully logged in!";
AccountController.set(emailInput.text, passwordInput.text);
AccountController.onAccountChange();
Destroy(gameObject);
}
else responseBox.text = "<color=red>Invalid Login!";
}
}
}
|
namespace SpanJson.Formatters.Dynamic
{
static class DynamicExtensions
{
public static string ToJsonValue(this object input)
{
if (input is ISpanJsonDynamic dyn)
{
return dyn.ToJsonValue();
}
return input?.ToString();
}
}
}
|
using EasySharpWpf.ViewModels.Rails.Edit.Core;
using EasySharpWpf.Views.ValidationRules.Core;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Windows.Data;
using EasySharpStandardMvvm.ViewModels.Rails.Edit.Core;
namespace EasySharpWpf.ViewModels.Rails.Edit.Implementation
{
internal class RailsBindCreator : RailsEditViewModelPathDefinition, IRailsBindCreator
{
public Binding CreateRailsBinding(PropertyInfo propertyInfo)
{
var bindingPath = this.GetRailsPropertyPath(propertyInfo);
var binding = new Binding(bindingPath)
{
Mode = BindingMode.TwoWay,
ValidatesOnNotifyDataErrors = true
};
return binding;
}
private static void AddValidationRule(Binding binding, ValidationAttribute validationAttribute)
{
// TODO: support input value validation.
switch (validationAttribute)
{
case RequiredAttribute required:
binding.ValidationRules.Add(new RequiredValidationRule(required));
break;
case RangeAttribute rangeAttribute:
binding.ValidationRules.Add(new RangeValidationRule(rangeAttribute));
break;
// TODO StringLengthAttribute
// TODO RegularExpressionAttribute
// TODO CustomValidationAttribute
default:
binding.ValidationRules.Add(new ValidationAttributeRuleBase(validationAttribute));
break;
}
}
}
}
|
@{
ViewBag.Title = "Game Play";
}
<h2>Game Play</h2>
<form action="/Home/FireTop">
Top: <input type="range" name="possition" min="0" max="100" />
<input type="submit" value="Fire Top"/>
</form>
<form action="/Home/FireBottom">
Bottom: <input type="range" name="possition" min="0" max="100" />
<input type="submit" value="Fire Bottom" />
</form>
<form action="/Home/Reset">
<input type="submit" value="New Game"/>
</form> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Collections;
using Sandbox.Common;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Definitions;
using Sandbox.Engine;
using Sandbox.Game;
using Sandbox.ModAPI;
using VRage.Game.ModAPI.Interfaces;
using VRage;
using VRage.ObjectBuilders;
using VRage.Game;
using VRage.ModAPI;
using VRage.Game.Components;
using VRageMath;
using Sandbox.Engine.Multiplayer;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Game.ModAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LSE
{
[MyEntityComponentDescriptor(typeof(MyObjectBuilder_OreDetector), true, new string[] { "TransporterSingle" })]
class TransporterSingle : LSE.Teleporter.Teleporter
{
public override void Init(MyObjectBuilder_EntityBase objectBuilder)
{
TeleporterDiameter = 1.25; // meters
TeleporterCenter = new Vector3(0.0f, -0.9f, 0.0f);
TeleporterPads = new List<Vector3>() {
new Vector3(0.0f, -0.9f, 0.0f)
};
Subtype = "TransporterSingle";
if (!s_Configs.ContainsKey(Subtype))
{
var message = new LSE.TransporterNetwork.MessageConfig ();
message.Side = LSE.TransporterNetwork.MessageSide.ClientSide;
message.GPSTargetRange = 5.0; // meters
message.MaximumRange = 60 * 1000; // meters
message.PowerPerKilometer = 1; // megawatt
message.ValidTypes = new List<int>() {0, 1, 2, 3, 4, 5, 6};
message.Subtype = Subtype;
SetConfig (Subtype, message);
}
base.Init(objectBuilder);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class VelocityEverywhereExtension
{
public static Vector3 GetVelocity(this GameObject gameObject)
{
var rigidBody = gameObject.GetComponent<Rigidbody>();
if (rigidBody)
return rigidBody.velocity;
var velocityComponent = gameObject.GetComponent<Velocity>();
if (velocityComponent)
return velocityComponent.velocity;
//next measure will be correct
gameObject.AddComponent<Velocity>();
return Vector3.zero;
}
}
public class Velocity : MonoBehaviour
{
public Vector3 velocity { get; private set; }
private Vector3 previousPosition;
void Start()
{
previousPosition = transform.position;
}
void FixedUpdate()
{
velocity = (transform.position - previousPosition) / Time.fixedDeltaTime;
previousPosition = transform.position;
}
}
|
using System;
namespace Adriva.Extensions.Reporting.Abstractions
{
public sealed class FilterNameComparer : StringComparer
{
public override int Compare(string x, string y)
{
if (string.IsNullOrWhiteSpace(x) && string.IsNullOrWhiteSpace(y)) return 0;
if (string.IsNullOrWhiteSpace(x)) return -1;
if (string.IsNullOrWhiteSpace(y)) return 1;
if (x.StartsWith("@", StringComparison.Ordinal)) x = x.Substring(1);
if (y.StartsWith("@", StringComparison.Ordinal)) y = y.Substring(1);
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(string x, string y)
{
return 0 == this.Compare(x, y);
}
public override int GetHashCode(string obj)
{
if (null == obj) return 0;
if (obj.StartsWith("@", StringComparison.Ordinal))
{
obj = obj.Substring(1);
}
if (string.IsNullOrWhiteSpace(obj)) return 0;
return obj.ToUpperInvariant().GetHashCode();
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attacker : MonoBehaviour
{
[Range(0f, 4f)] [SerializeField] float walkSpeed = 1f;
[SerializeField] float attack = 3f;
bool canMove = false;
Animator animator;
LevelController levelController;
GameObject currentTarget;
private void Awake()
{
levelController = FindObjectOfType<LevelController>();
levelController.AttackerSpawned();
}
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
if (canMove)
{
transform.Translate(Vector2.left * Time.deltaTime * walkSpeed);
}
UpdateAnimationState();
}
private void OnDestroy()
{
if (levelController)
{
levelController.AttackerKilled();
}
}
private void UpdateAnimationState()
{
if (!currentTarget)
{
animator.SetBool("isAttacking", false);
}
}
public void ToggleMovement(int canMove)
{
this.canMove = canMove != 0;
}
public void Attack(GameObject target)
{
animator.SetBool("isAttacking", true);
currentTarget = target;
}
public void StrikeTarget()
{
if (!currentTarget)
{
return;
}
Health hp = currentTarget.GetComponent<Health>();
if (hp)
{
hp.DealDamage(attack);
}
}
}
|
using Newtonsoft.Json;
using System;
namespace This4That_library.Models.Integration
{
[Serializable]
public abstract class APIRequestDTO
{
private string userID;
[JsonProperty(PropertyName = "userId", Required = Required.Always)]
public string UserID
{
get
{
return userID;
}
set
{
userID = value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Voxell.Rasa
{
public enum RasaState { Idle = 0, Running = 1, Success = 2, Failure = 3 }
public enum CapacityInfo { Single = 0, Multi = 1 }
public struct PortInfo
{
public CapacityInfo capacityInfo;
public Type portType;
public string portName;
public Color color;
public PortInfo(CapacityInfo capacityInfo, Type portType, string portName, Color color)
{
this.capacityInfo = capacityInfo;
this.portType = portType;
this.portName = portName;
this.color = color;
}
}
[Serializable]
public class Connection
{
public List<RasaNode> rasaNodes;
public List<string> fieldNames;
public Connection()
{
this.rasaNodes = new List<RasaNode>();
this.fieldNames = new List<string>();
}
public void Add(ref RasaNode rasaNode, string fieldName)
{
rasaNodes.Add(rasaNode);
fieldNames.Add(fieldName);
}
public void RemoveAt(int idx)
{
rasaNodes.RemoveAt(idx);
fieldNames.RemoveAt(idx);
}
public object GetValue(int idx)
=> rasaNodes[idx].GetType().GetField(fieldNames[idx]).GetValue(rasaNodes[idx]);
}
}
|
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Windows.Controls;
namespace System.ComponentModel
{
#region taa_added
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "Exception(SerializationInfo, StreamingContext) does not exist in Silverlight, so neither can the derived InvalidEnumArgumentException constructor")]
public class InvalidEnumArgumentException : Exception
{
public InvalidEnumArgumentException() : base()
{
}
public InvalidEnumArgumentException(string message) : base(message)
{
}
public InvalidEnumArgumentException(string message, Exception innerException) : base(message, innerException)
{
}
public InvalidEnumArgumentException(string argumentName, int invalidValue, System.Type enumClass)
: base(String.Format(CultureInfo.CurrentCulture, Resource.InvalidEnumArgumentException_InvalidEnumArgument, argumentName, invalidValue.ToString(CultureInfo.CurrentCulture), enumClass.Name))
{
}
}
#endregion
/// <summary>
/// Defines a property and direction to sort a list by.
/// </summary>
public struct SortDescription
{
//------------------------------------------------------
//
// Public Constructors
//
//------------------------------------------------------
#region Public Constructors
/// <summary>
/// Create a sort description.
/// </summary>
/// <param name="propertyName">Property to sort by</param>
/// <param name="direction">Specifies the direction of sort operation</param>
/// <exception cref="InvalidEnumArgumentException"> direction is not a valid value for ListSortDirection </exception>
public SortDescription(string propertyName, ListSortDirection direction)
{
if (direction != ListSortDirection.Ascending && direction != ListSortDirection.Descending)
throw new InvalidEnumArgumentException("direction", (int)direction, typeof(ListSortDirection));
_propertyName = propertyName;
_direction = direction;
_sealed = false;
}
#endregion Public Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// Property name to sort by.
/// </summary>
public string PropertyName
{
get { return _propertyName; }
set
{
if (_sealed)
throw new InvalidOperationException("SortDescription");
_propertyName = value;
}
}
/// <summary>
/// Sort direction.
/// </summary>
public ListSortDirection Direction
{
get { return _direction; }
set
{
if (_sealed)
throw new InvalidOperationException("SortDescription");
if (value < ListSortDirection.Ascending || value > ListSortDirection.Descending)
throw new InvalidEnumArgumentException("value", (int)value, typeof(ListSortDirection));
_direction = value;
}
}
/// <summary>
/// Returns true if the SortDescription is in use (sealed).
/// </summary>
public bool IsSealed
{
get { return _sealed; }
}
#endregion Public Properties
//------------------------------------------------------
//
// Public methods
//
//------------------------------------------------------
#region Public Methods
/// <summary> Override of Object.Equals </summary>
public override bool Equals(object obj)
{
return (obj is SortDescription) ? (this == (SortDescription)obj) : false;
}
/// <summary> Equality operator for SortDescription. </summary>
public static bool operator==(SortDescription sd1, SortDescription sd2)
{
return sd1.PropertyName == sd2.PropertyName &&
sd1.Direction == sd2.Direction;
}
/// <summary> Inequality operator for SortDescription. </summary>
public static bool operator!=(SortDescription sd1, SortDescription sd2)
{
return !(sd1 == sd2);
}
/// <summary> Override of Object.GetHashCode </summary>
public override int GetHashCode()
{
int result = Direction.GetHashCode();
if (PropertyName != null)
{
result = unchecked(PropertyName.GetHashCode() + result);
}
return result;
}
#endregion Public Methods
//------------------------------------------------------
//
// Internal methods
//
//------------------------------------------------------
#region Internal Methods
internal void Seal()
{
_sealed = true;
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private string _propertyName;
private ListSortDirection _direction;
bool _sealed;
#endregion Private Fields
}
}
|
namespace Cofoundry.Domain
{
/// <summary>
/// A document asset is a non-image file that has been uploaded to the
/// CMS. The name could be misleading here as any file type except
/// images are supported, but at least it is less ambigous than the
/// term 'file'.
/// </summary>
public sealed class DocumentAssetEntityDefinition : IEntityDefinition
{
public const string DefinitionCode = "COFDOC";
public string EntityDefinitionCode { get { return DefinitionCode; } }
public string Name { get { return "Document"; } }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Innovator.Client.QueryModel
{
public class NegationOperator : UnaryOperator, INormalize
{
public override int Precedence => (int)PrecedenceLevel.Negation;
public override void Visit(IExpressionVisitor visitor)
{
visitor.Visit(this);
}
public IExpression Normalize()
{
if (Expressions.TryGetLong(Arg, out var i))
{
return new IntegerLiteral(-1 * i);
}
else if (Expressions.TryGetDouble(Arg, out var d))
{
return new FloatLiteral(-1 * d);
}
return this;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ServerLib
{
/// <summary>
/// 提供Model层与mysql的接口
/// </summary>
public class ModelBasic
{
public MySqlConnection connect;
public ModelBasic(MySqlConnection connect)
{
this.connect = connect;
}
protected ModelResult Query(string query)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = query;
var reader = cmd.ExecuteReader();
var result = new ModelResult();
while(reader.Read())
{
var sub_result = new Dictionary<string, string>();
for (int i=0;i<reader.FieldCount;i++)
{
sub_result[reader.GetName(i)] = reader.GetValue(i).ToString();
}
result.Add(sub_result);
}
reader.Close();
result.InsertID = cmd.LastInsertedId;
return result;
}
protected ModelResult QueryStmt(string query,params string [] values)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = query;
cmd.Prepare();
for(int i=0;i<values.Length;i++)
{
cmd.Parameters.AddWithValue("@"+i.ToString(), values[i]);
}
var reader = cmd.ExecuteReader();
var result = new ModelResult();
while (reader.Read())
{
var sub_result = new Dictionary<string, string>();
for (int i = 0; i < reader.FieldCount; i++)
{
sub_result[reader.GetName(i)] = reader.GetString(i);
}
result.Add(sub_result);
}
reader.Close();
result.InsertID = cmd.LastInsertedId;
return result;
}
}
}
|
using IRunes.App.Controllers;
using MiniServer.HTTP;
using MiniServer.WebServer;
using System.IO;
namespace IRunes.App
{
public class Launcher
{
public static void Main(string[] args)
{
// Web Server Routing Table
ServerRoutingTable routes = new ServerRoutingTable();
// Home
routes.Add(HttpRequestMethod.Get, "/", request => new RedirectResult("/Home/Index"));
routes.Add(HttpRequestMethod.Get, "/Home/Index", request => new HomeController().Index(request));
// Albums
routes.Add(HttpRequestMethod.Get, "/Albums/All", request => new AlbumsController().All(request));
routes.Add(HttpRequestMethod.Get, "/Albums/Details", request => new AlbumsController().Details(request));
routes.Add(HttpRequestMethod.Get, "/Albums/Create", request => new AlbumsController().Create(request));
routes.Add(HttpRequestMethod.Post, "/Albums/Create", request => new AlbumsController().CreateConfirm(request));
// Resources
routes.Add(HttpRequestMethod.Get, "/Home/css/bootstrap.min.css", request =>
new HtmlResult(File.ReadAllText("Resources/css/bootstrap.min.css"), HttpResponseStatusCode.Ok));
routes.Add(HttpRequestMethod.Get, "/Home/js/bootstrap.min.js", request =>
new HtmlResult(File.ReadAllText("Resources/js/bootstrap.min.js"), HttpResponseStatusCode.Ok));
routes.Add(HttpRequestMethod.Get, "/Home/js/jquery-3.4.1.min.js", request =>
new HtmlResult(File.ReadAllText("Resources/js/jquery-3.4.1.min.js"), HttpResponseStatusCode.Ok));
routes.Add(HttpRequestMethod.Get, "/Home/js/popper.min.js", request =>
new HtmlResult(File.ReadAllText("Resources/js/popper.min.js"), HttpResponseStatusCode.Ok));
// Web Server
Server server = new Server(8080, routes);
server.Run();
}
}
}
|
using BankApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace BankApi.Repositories
{
public class CustomerRepository : ICustomerRepository
{
private readonly BankdbContext _bankdbContext;
public CustomerRepository(BankdbContext bankdbContext)
{
_bankdbContext = bankdbContext;
}
public Customer Create(Customer customer)
{
_bankdbContext.Add(customer);
_bankdbContext.SaveChanges();
return customer;
}
public void Delete(int id)
{
var deleteCustomer = Read(id);
_bankdbContext.Remove(deleteCustomer);
_bankdbContext.SaveChanges();
return;
}
public List<Customer> Read()
{
return _bankdbContext.Customer
.AsNoTracking()
.Include(a => a.Account)
.ToList();
}
public Customer Read(int id)
{
return _bankdbContext.Customer.FirstOrDefault(c => c.Id == id);
}
public Customer Update(Customer customer)
{
_bankdbContext.Update(customer);
_bankdbContext.SaveChanges();
return customer;
}
}
}
|
using System.Security.Cryptography;
namespace BingoX.Security
{
/// <summary>
/// 非对称加密密钥结构
/// </summary>
public struct AsymmetricKey
{
/// <summary>
/// 公钥(XML格式)
/// </summary>
public string Public { get; set; }
/// <summary>
/// 私钥(XML格式)
/// </summary>
public string Private { get; set; }
/// <summary>
/// 获取支持的密钥长度信息。单位:bit
/// </summary>
public KeySizes[] LegalKeySizes { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using neobooru.Models;
using neobooru.Utilities.Attributes;
namespace neobooru.ViewModels
{
public class PostUploadViewModel
{
[ValidImage(allowedContentTypes: new string[] { "jpg", "jpeg", "pjpeg", "png", "x-png" })]
[Required]
public IFormFile File { get; set; }
[Required]
public string Name { get; set; }
public string Author { get; set; }
public string Source { get; set; }
[Required]
public Art.ArtRating Rating { get; set; }
[Required]
public string TagString { get; set; }
}
}
|
// CamelliaWrapEngine
using Org.BouncyCastle.Crypto.Engines;
public class CamelliaWrapEngine : Rfc3394WrapEngine
{
public CamelliaWrapEngine()
: base(new CamelliaEngine())
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Abp.Extensions
{
public static class EnumExtensions
{
public static string GetDisplayName(FieldInfo field)
{
DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);
if (display != null)
{
string name = display.GetName();
if (!String.IsNullOrEmpty(name))
{
return name;
}
}
return field.Name;
}
}
}
|
using ERP.Domain.Core.GuardClauses;
using ERP.Domain.Core.Models;
namespace ERP.Domain.Modules.Roles
{
public class RolePermission : BaseAuditableEntity
{
public RolePermission()
{ }
private RolePermission(Guid roleId, int permissionId, Guid createdBy)
{
RoleId = roleId;
PermissionId = permissionId;
CreatedBy = createdBy;
CreatedOn = DateTimeOffset.UtcNow;
}
#region Behaviours
public static RolePermission CreateRolePermission(Guid roleId, int permissionId, Guid createdBy)
{
Guard.Against.Null(roleId, "Role Id");
Guard.Against.Null(permissionId, "Permission Id");
Guard.Against.NumberLessThan(permissionId, "Permission Id", 0);
Guard.Against.Null(createdBy, "Created By");
return new RolePermission(roleId, permissionId, createdBy);
}
public void RemoveRolePermission(Guid modifiedBy)
{
Guard.Against.Null(modifiedBy, "Modified By");
IsDeleted = true;
ModifiedBy = modifiedBy;
ModifiedOn = DateTimeOffset.UtcNow;
}
#endregion
#region States
public Guid Id { get; set; }
public Guid RoleId { get; set; }
public int PermissionId { get; set; }
public Role Role { get; set; }
public Permission Permission { get; set; }
#endregion
}
} |
using System;
namespace MobilePhone
{
using static GSM_Test.PseudoTestGSM;
class Engine
{
static void Main()
{
DisplayGSMsInfo();
DisplayIPhone4sInfo();
}
}
} |
namespace dto.endpoint.auth.silentlogin
{
public class SilentLoginRequest{
///<Summary>
///Whether this is a newly created client logging into demo for the very first time after account creation.
///</Summary>
public bool firstTimeDemoLogin { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delight
{
/** Utilities for encoding and decoding data using Base64 and variants thereof */
public sealed partial class Base64 : Delight.Shim.Shimmed_PHPOnly
{
/**
* The last three characters from the alphabet of the standard implementation
*
* @var string
*/
const string LAST_THREE_STANDARD = "+/=";
/**
* The last three characters from the alphabet of the URL-safe implementation
*
* @var string
*/
const string LAST_THREE_URL_SAFE = "-_~";
private static string base64_encode(byte[] data) => System.Convert.ToBase64String(data);
private static byte[] base64_decode(string b64, bool strict) => System.Convert.FromBase64String(b64);
/**
* Encodes the supplied data to Base64
*
* @param mixed data
* @return string
* @throws EncodingError if the input has been invalid
*/
public static string encode(byte[] data)
{
var encoded = base64_encode(data);
if (encoded == null) {
throw new EncodingError();
}
return encoded;
}
/**
* Decodes the supplied data from Base64
*
* @param string data
* @return mixed
* @throws DecodingError if the input has been invalid
*/
public static byte[] decode(string data)
{
var decoded = base64_decode(data, true);
if (decoded == null) {
throw new DecodingError();
}
return decoded;
}
/**
* Encodes the supplied data to a URL-safe variant of Base64
*
* @param mixed data
* @return string
* @throws EncodingError if the input has been invalid
*/
public static string encodeUrlSafe(byte[] data)
{
var encoded = encode(data);
return strtr(
encoded,
LAST_THREE_STANDARD,
LAST_THREE_URL_SAFE
);
}
/**
* Decodes the supplied data from a URL-safe variant of Base64
*
* @param string data
* @return mixed
* @throws DecodingError if the input has been invalid
*/
public static byte[] decodeUrlSafe(string data)
{
data = strtr(
data,
LAST_THREE_URL_SAFE,
LAST_THREE_STANDARD
);
return decode(data);
}
/**
* Encodes the supplied data to a URL-safe variant of Base64 without padding
*
* @param mixed data
* @return string
* @throws EncodingError if the input has been invalid
*/
public static string encodeUrlSafeWithoutPadding(byte[] data)
{
var encoded = encode(data);
encoded = rtrim(
encoded,
substr(LAST_THREE_STANDARD, -1)
);
return strtr(
encoded,
substr(LAST_THREE_STANDARD, 0, -1),
substr(LAST_THREE_URL_SAFE, 0, -1)
);
}
public static string encodeUrlSafeWithoutPadding(string data)
=> encodeUrlSafeWithoutPadding(Encoding.UTF8.GetBytes(data));
/**
* Decodes the supplied data from a URL-safe variant of Base64 without padding
*
* @param string data
* @return mixed
* @throws DecodingError if the input has been invalid
*/
public static byte[] decodeUrlSafeWithoutPadding(string data)
{
return decodeUrlSafe(data);
}
}
}
|
using UnityEngine;
namespace PlayFab.Internal
{
//public to be accessible by Unity engine
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
private static T m_instance;
public static T instance
{
get
{
if (m_instance == null)
{
//find existing instance
m_instance = GameObject.FindObjectOfType<T> ();
if (m_instance == null)
{
//create new instance
GameObject go = new GameObject (typeof (T).Name);
m_instance = go.AddComponent<T> ();
DontDestroyOnLoad (go);
}
//initialize instance if necessary
if (!m_instance.initialized)
{
m_instance.Initialize ();
m_instance.initialized = true;
}
}
return m_instance;
}
}
private void Awake ()
{
//check if instance already exists when reloading original scene
if (m_instance != null)
{
DestroyImmediate (gameObject);
}
}
protected bool initialized { get; set; }
protected virtual void Initialize ()
{}
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace __Primitives__
{
partial class WinAPI
{
partial class COM
{
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("89c31040-846b-11ce-97d3-00aa0055595a")]
[SuppressUnmanagedCodeSecurity]
public interface IEnumMediaTypes
{
void Next(
uint cMediaTypes,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
AM_MEDIA_TYPE[] ppMediaTypes,
out uint pcFetched);
void Skip(uint cMediaTypes);
void Reset();
void Clone(out IEnumMediaTypes ppEnum);
}
}
}
}
|
using Repo1.Core.ns11.Configuration;
namespace Repo1.D8Uploader.Lib45.Configuration
{
public class UploaderCfg : DownloaderCfg
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class missile : MonoBehaviour
{
public Transform target;
private Rigidbody2D rb;
public float speed = 5f;
public float firespeed = 100f;
public float rotationSpeed = 0f;
public float firerotationSpeed = 500f;
public GameObject explositionEffect;
float time = 1.5f;
float countdown = 0f;
public ParticleSystem trail;
public ParticleSystem emission;
public GameObject[] searchEnemy;
public missileLaunch fired;
float flag = 1;
// Start is called before the first frame update
void Start()
{
searchEnemy = GameObject.FindGameObjectsWithTag("Enemy");
if (searchEnemy.Length < 2)
{
target = searchEnemy[0].transform;
}
countdown = time;
rb = GetComponent<Rigidbody2D>();
}
void search()
{
searchEnemy = GameObject.FindGameObjectsWithTag("Enemy");
if (searchEnemy.Length < 2)
{
target = searchEnemy[0].transform;
}
}
// Update is called once per frame
void FixedUpdate()
{
countdown -= Time.deltaTime;
if (countdown < 0)
{
speed = firespeed;
rotationSpeed = firerotationSpeed;
}
if (fired.fired&&flag==1)
{
search();
flag = 0;
}
if (fired.fired)
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotationAmount = Vector3.Cross(direction, transform.up).z;
rb.angularVelocity = -rotationAmount * rotationSpeed;
rb.velocity = transform.up * speed;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
GameObject missileinst = Instantiate(explositionEffect, transform.position, transform.rotation);
Destroy(gameObject);
Destroy(missileinst, 2.5f);
}
}
}
|
namespace aspnetcore_custom_exception_middleware.Infrastructure.Extensions
{
using Microsoft.AspNetCore.Builder;
using Middleware;
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseNumberChecker(this IApplicationBuilder app) =>
app.UseMiddleware<NumberCheckerMiddleware>();
public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder app) =>
app.UseMiddleware<ExceptionMiddleware>();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces;
using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes;
namespace CyPhy2Modelica_v2.Modelica
{
public class Metric : IComparable<Metric>
{
public string Name { get; set; }
public string Description { get; set; }
public bool PostProcessing { get; set; }
public int CompareTo(Metric other)
{
return this.Name.CompareTo(other.Name);
}
}
}
|
namespace Weasel.SqlServer.SqlGeneration
{
// TODO -- move to Weasel
public class WhereInSubQuery : ISqlFragment
{
private readonly string _tableName;
public WhereInSubQuery(string tableName)
{
_tableName = tableName;
}
public void Apply(CommandBuilder builder)
{
builder.Append("id in (select id from ");
builder.Append(_tableName);
builder.Append(")");
}
public bool Contains(string sqlText)
{
return false;
}
}
} |
using System.ComponentModel;
namespace LineReadyApi.Models
{
public class FormField
{
public const string DefaultType = "string";
public string Label { get; set; }
public int? MaxLength { get; set; }
public int? MinLength { get; set; }
public string Name { get; set; }
public FormFieldOption[] Options { get; set; }
public string Pattern { get; set; }
public bool Required { get; set; }
public bool Secret { get; set; }
[DefaultValue(DefaultType)]
public string Type { get; set; } = DefaultType;
public object Value { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace JwtSecureWebApi
{
public static class Constants
{
public static string Issure = "hemant.shelar";
public static string Audience = "my.audience";
public static string SecurityKey = @"This_is_my_super_strong_and_secure_signing_key";
}
}
|
// Based on https://github.com/aspnet/EntityFrameworkCore
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
public class CypherModelCustomizer: RelationalModelCustomizer {
public CypherModelCustomizer(
[NotNull] ModelCustomizerDependencies dependencies
) : base(dependencies)
{
}
protected override void FindSets(ModelBuilder modelBuilder, DbContext context)
{
foreach (var setInfo in Dependencies.SetFinder.FindSets(context))
{
modelBuilder.Entity(setInfo.ClrType);
}
}
}
} |
/*
* Copyright(c) 2019 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.ComponentModel;
namespace Tizen.NUI.Components
{
/// <summary>
/// SliderAttributes is a class which saves Slider's ux data.
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public class SliderAttributes : ViewAttributes
{
/// <summary>
/// Creates a new instance of a SliderAttributes.
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public SliderAttributes() : base()
{
IndicatorType = Slider.IndicatorType.None;
}
/// <summary>
/// Creates a new instance of a SliderAttributes with attributes.
/// </summary>
/// <param name="attributes">Create SliderAttributes by attributes customized by user.</param>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public SliderAttributes(SliderAttributes attributes) : base(attributes)
{
if(attributes == null)
{
return;
}
if (attributes.BackgroundTrackAttributes != null)
{
BackgroundTrackAttributes = attributes.BackgroundTrackAttributes.Clone() as ImageAttributes;
}
if (attributes.SlidedTrackAttributes != null)
{
SlidedTrackAttributes = attributes.SlidedTrackAttributes.Clone() as ImageAttributes;
}
if (attributes.ThumbBackgroundAttributes != null)
{
ThumbBackgroundAttributes = attributes.ThumbBackgroundAttributes.Clone() as ImageAttributes;
}
if (attributes.ThumbAttributes != null)
{
ThumbAttributes = attributes.ThumbAttributes.Clone() as ImageAttributes;
}
if (attributes.LowIndicatorImageAttributes != null)
{
LowIndicatorImageAttributes = attributes.LowIndicatorImageAttributes.Clone() as ImageAttributes;
}
if (attributes.HighIndicatorImageAttributes != null)
{
HighIndicatorImageAttributes = attributes.HighIndicatorImageAttributes.Clone() as ImageAttributes;
}
if (attributes.LowIndicatorTextAttributes != null)
{
LowIndicatorTextAttributes = attributes.LowIndicatorTextAttributes.Clone() as TextAttributes;
}
if (attributes.HighIndicatorTextAttributes != null)
{
HighIndicatorTextAttributes = attributes.HighIndicatorTextAttributes.Clone() as TextAttributes;
}
if (attributes.TrackThickness != null)
{
TrackThickness = attributes.TrackThickness;
}
if (attributes.SpaceBetweenTrackAndIndicator != null)
{
SpaceBetweenTrackAndIndicator = attributes.SpaceBetweenTrackAndIndicator;
}
IndicatorType = attributes.IndicatorType;
}
/// <summary>
/// Get or set background track attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes BackgroundTrackAttributes
{
get;
set;
}
/// <summary>
/// Get or set slided track attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes SlidedTrackAttributes
{
get;
set;
}
/// <summary>
/// Get or set thumb attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes ThumbAttributes
{
get;
set;
}
/// <summary>
/// Get or set thumb background attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes ThumbBackgroundAttributes
{
get;
set;
}
/// <summary>
/// Get or set low indicator image attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes LowIndicatorImageAttributes
{
get;
set;
}
/// <summary>
/// Get or set high indicator image attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImageAttributes HighIndicatorImageAttributes
{
get;
set;
}
/// <summary>
/// Get or low indicator text attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public TextAttributes LowIndicatorTextAttributes
{
get;
set;
}
/// <summary>
/// Get or set high indicator text attributes
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public TextAttributes HighIndicatorTextAttributes
{
get;
set;
}
/// <summary>
/// Get or set track thickness
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public uint? TrackThickness
{
get;
set;
}
/// <summary>
/// Get or set space between track and indicator
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public uint? SpaceBetweenTrackAndIndicator
{
get;
set;
}
/// <summary>
/// Get or set Indicator type
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public Slider.IndicatorType IndicatorType
{
get;
set;
}
/// <summary>
/// Attributes's clone function.
/// </summary>
/// <since_tizen> 6 </since_tizen>
/// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
[EditorBrowsable(EditorBrowsableState.Never)]
public override Attributes Clone()
{
return new SliderAttributes(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OAHub.Base.Models.OrganizationModels
{
public class ApiMember
{
public string UserId { get; set; }
public string Position { get; set; }
public DateTime JoinAt { get; set; }
public bool IsLocked { get; set; }
}
}
|
using UnityEngine;
[System.Serializable, CreateAssetMenu(menuName = "Framework Data/Variable/Integer", order = 2)]
public class IntVariable : DataVariable<int>
{
MinMaxClamp<int> ClampValue = null;
#region PRIVATE METHODS
private void InternalClamping()
{
RuntimeValue = Mathf.Clamp(RuntimeValue, ClampValue.Min, ClampValue.Max);
}
private void GenerateMinMaxClampValue()
{
if (ClampValue == null)
{
ClampValue = new MinMaxClamp<int>();
ClampValue.Min = CreateInstance<IntVariable>();
ClampValue.Max = CreateInstance<IntVariable>();
}
ActiveValueClamping(true);
}
#endregion
#region PUBLIC METHODS
public void Increment()
{
Value++;
}
public void Decrement()
{
Value--;
}
public void ActiveValueClamping(bool active)
{
if (ClampValue == null)
{
return;
}
if (active)
{
OnValueChanged -= InternalClamping;
OnValueChanged += InternalClamping;
}
else
{
OnValueChanged -= InternalClamping;
}
}
public void ActiveValueClamping(int min, int max)
{
GenerateMinMaxClampValue();
ClampValue.Min.Value = min;
ClampValue.Max.Value = max;
}
public void ActiveValueClamping(IntVariable min, IntVariable max)
{
if (!min || !max)
{
Debug.Log("[ERROR]<" + this + ">: Trying to ActiveValueClamping with invalid min or max");
return;
}
GenerateMinMaxClampValue();
ClampValue.Min = min;
ClampValue.Max = max;
}
public void ActiveValueClamping(int min, IntVariable max)
{
if (!max)
{
Debug.Log("[ERROR]<" + this + ">: Trying to ActiveValueClamping with invalid max!");
return;
}
GenerateMinMaxClampValue();
ClampValue.Min.Value = min;
ClampValue.Max = max;
}
public void ActiveValueClamping(IntVariable min, int max)
{
if (!min)
{
Debug.Log("[ERROR]<" + this + ">: Trying to ActiveValueClamping with invalid min!");
return;
}
GenerateMinMaxClampValue();
ClampValue.Min = min;
ClampValue.Max.Value = max;
}
#endregion
}
|
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor;
using NativeMedia;
using Sample.Helpers;
namespace Sample.ViewModels
{
public class MediaFileInfoVM : BaseVM
{
public MediaFileInfoVM(IMediaFile file)
{
File = file;
IsImage = file?.Type == MediaFileType.Image;
IsVideo = file?.Type == MediaFileType.Video;
}
public IMediaFile File { get; }
public string Path { get; private set; }
public string Metadata { get; private set; }
public bool IsImage { get; }
public bool IsVideo { get; }
public bool IsBusy { get; private set; }
public override void OnAppearing()
{
base.OnAppearing();
Task.Run(async () =>
{
IsBusy = true;
try
{
using var stream = await File.OpenReadAsync();
var name = (string.IsNullOrWhiteSpace(File.NameWithoutExtension)
? Guid.NewGuid().ToString()
: File.NameWithoutExtension)
+ $".{File.Extension}";
Path = await FilesHelper.SaveToCacheAsync(stream, name);
stream.Position = 0;
await ReadMeta(stream);
}
catch (Exception ex)
{
await DisplayAlertAsync(ex.Message);
}
IsBusy = false;
});
}
async Task ReadMeta(Stream stream)
{
var metaSB = new StringBuilder();
try
{
var directories = ImageMetadataReader.ReadMetadata(stream);
foreach (var directory in directories)
{
foreach (var tag in directory.Tags)
metaSB.AppendLine(tag.ToString());
foreach (var error in directory.Errors)
metaSB.AppendLine("ERROR: " + error);
}
}
catch (Exception ex)
{
await DisplayAlertAsync(ex.Message);
}
Metadata = metaSB.ToString();
}
}
}
|
using System;
namespace DirectX12GameEngine.Core
{
public static class MemoryExtensions
{
public static unsafe void CopyTo(this IntPtr source, IntPtr destination, int sizeInBytesToCopy)
{
CopyTo(new ReadOnlySpan<byte>(source.ToPointer(), sizeInBytesToCopy), destination);
}
public static unsafe void CopyTo<T>(this Span<T> source, IntPtr destination) where T : unmanaged
{
source.CopyTo(new Span<T>(destination.ToPointer(), source.Length));
}
public static unsafe void CopyTo<T>(this ReadOnlySpan<T> source, IntPtr destination) where T : unmanaged
{
source.CopyTo(new Span<T>(destination.ToPointer(), source.Length));
}
public static unsafe void CopyTo<T>(this IntPtr source, Span<T> destination) where T : unmanaged
{
new Span<T>(source.ToPointer(), destination.Length).CopyTo(destination);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnTile : MonoBehaviour
{
public GameObject tileToSpawn;
public GameObject referenceObject;
public float timeOffset = 0.4f;
public float distanceBetweenTiles = 5.0F;
public float randomValue = 0.8f;
private Vector3 previousTilePosition;
private float startTime;
private Vector3 direction, mainDirection = new Vector3(0, 0, 1), otherDirection = new Vector3(1, 0, 0);
// Start is called before the first frame update
void Start()
{
previousTilePosition = referenceObject.transform.position;
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (GameController.instance.gameStarted && !GameController.instance.gamePaused)
{
if (Time.time - startTime > timeOffset)
{
if (Random.value < randomValue)
direction = mainDirection;
else
{
Vector3 temp = direction;
direction = otherDirection;
mainDirection = direction;
otherDirection = temp;
}
Vector3 spawnPos = previousTilePosition + distanceBetweenTiles * direction;
startTime = Time.time;
Instantiate(tileToSpawn, spawnPos, Quaternion.Euler(0, 0, 0));
previousTilePosition = spawnPos;
}
}
}
}
|
using System;
using Iviz.Controllers;
using Iviz.Core;
using Iviz.Displays;
using Iviz.Resources;
using Iviz.XmlRpc;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Iviz.App.ARDialogs
{
[RequireComponent(typeof(BoxCollider))]
public sealed class ARButton : MarkerResource, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
[SerializeField] Texture2D[] icons;
[SerializeField] TextMesh text;
[SerializeField] MeshRenderer iconMeshRenderer;
[SerializeField] Color backgroundColor = new Color(0, 0.2f, 0.5f);
[SerializeField] MeshMarkerResource background = null;
[SerializeField] BoxCollider colliderForFrame = null;
Material material;
[NotNull]
Material Material => material != null ? material : (material = Instantiate(iconMeshRenderer.material));
[CanBeNull] BoundaryFrame frame;
public event Action Clicked;
public enum ButtonIcon
{
Cross,
Ok,
Forward,
Backward
}
public Color BackgroundColor
{
get => backgroundColor;
set
{
backgroundColor = value;
if (background != null)
{
// TODO
}
}
}
public string Caption
{
get => text.text;
set => text.text = value;
}
public bool Active
{
get => gameObject.activeSelf;
set => gameObject.SetActive(value);
}
ButtonIcon icon;
public ButtonIcon Icon
{
get => icon;
set
{
icon = value;
Material.mainTexture = value == ButtonIcon.Backward
? icons[(int) ButtonIcon.Forward]
: icons[(int) value];
(float x, _, float z) = iconMeshRenderer.transform.localRotation.eulerAngles;
Quaternion rotation;
switch (value)
{
case ButtonIcon.Cross:
rotation = Quaternion.Euler(x, 45, z);
break;
case ButtonIcon.Backward:
rotation = Quaternion.Euler(x, 0, z);
break;
default:
rotation = Quaternion.Euler(x, 180, z);
break;
}
iconMeshRenderer.transform.localRotation = rotation;
}
}
protected override void Awake()
{
Icon = ButtonIcon.Cross;
iconMeshRenderer.material = Material;
if (Settings.IsHololens)
{
var meshRenderers = transform.GetComponentsInChildren<MeshRenderer>();
foreach (var meshRenderer in meshRenderers)
{
meshRenderer.material = Resource.Materials.Lit.Object;
}
}
}
public void OnPointerClick(PointerEventData eventData)
{
Clicked?.Invoke();
}
public void ClearSubscribers()
{
Clicked = null;
}
public void OnPointerEnter(PointerEventData eventData)
{
frame = ResourcePool.RentDisplay<BoundaryFrame>(transform);
frame.Color = Color.white.WithAlpha(0.5f);
frame.Bounds = new Bounds(colliderForFrame.center,
Vector3.Scale(colliderForFrame.size, colliderForFrame.transform.localScale));
}
public void OnPointerExit(PointerEventData eventData)
{
frame.ReturnToPool();
frame = null;
}
public void OnDialogSuspended()
{
if (frame != null)
{
frame.ReturnToPool();
frame = null;
}
}
public override void Suspend()
{
base.Suspend();
if (frame != null)
{
frame.ReturnToPool();
frame = null;
}
}
}
} |
using Dapper.Contrib.Extensions;
using Fap.Core.Infrastructure.Metadata;
using System;
using System.Collections.Generic;
using System.Text;
namespace Fap.Core.Infrastructure.Config
{
/// <summary>
/// 配置项
/// </summary>
[Serializable]
public class FapConfig : BaseModel
{
/// <summary>
/// 名称
/// </summary>
public string ParamName { get; set; }
/// <summary>
/// 键
/// </summary>
public string ParamKey { get; set; }
/// <summary>
/// 值
/// </summary>
public string ParamValue { get; set; }
/// <summary>
/// 配置组
/// </summary>
public string ConfigGroup { get; set; }
/// <summary>
/// 配置组 的显性字段MC
/// </summary>
[ComputedAttribute]
public string ConfigGroupMC { get; set; }
/// <summary>
/// 控件类型
/// </summary>
public string CtrlType { get; set; }
/// <summary>
/// 控件类型 的显性字段MC
/// </summary>
[ComputedAttribute]
public string CtrlTypeMC { get; set; }
/// <summary>
/// 关联组件
/// </summary>
public string AssoComponent { get; set; }
/// <summary>
/// 关联组件 的显性字段MC
/// </summary>
[Computed]
public string AssoComponentMC { get; set; }
/// <summary>
/// 启用
/// </summary>
public int Enabled { get; set; }
/// <summary>
/// 参数组
/// </summary>
public string ParamGroup { get; set; }
/// <summary>
/// 编码项
/// </summary>
public string DictList { get; set; }
/// <summary>
/// 编码数据源
/// </summary>
[Computed]
public List<SelectModel> DictSource { get; set; }
/// <summary>
/// 排序字段
/// </summary>
public int SortBy { get; set; }
}
public class SelectModel
{
public string Code { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
/// <summary>
/// 分组后的配置
/// </summary>
public class GrpConfig
{
public string Grp { get; set; }
public List<FapConfig> Configs { get; set; }
}
}
|
using System;
using System.Collections;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using static UnityEditorInternal.ReorderableList;
using UnityEngine;
using UObject = UnityEngine.Object;
namespace XT.Base {
internal static class PaneGUI {
public static void Space(float pixels) {
GUILayout.Space(pixels);
}
static bool firstElement = true;
public static void Header(string text) {
Space(4);
if (firstElement) {
Space(-5);
firstElement = false;
}
EditorGUILayout.LabelField(text, EditorStyles.boldLabel);
Space(2);
}
public static void DrawSettings(Setting[] settings) {
foreach (Setting setting in settings) {
SettingField(setting);
}
}
public static void SettingField(Setting setting) {
if (setting == null) {
return;
}
HeaderAttribute headerAttr = setting.field.GetCustomAttribute<HeaderAttribute>();
if (headerAttr != null) {
Header(headerAttr.header);
}
bool delayed = setting.field.GetCustomAttribute<DelayedAttribute>() != null;
if (setting.type == typeof(string)) {
string stringValue = (string)setting.field.GetValue(setting.obj);
stringValue = !delayed ?
EditorGUILayout.TextField(setting.label, stringValue) :
EditorGUILayout.DelayedTextField(setting.label, stringValue);
setting.field.SetValue(setting.obj, stringValue);
} else
if (setting.type == typeof(int)) {
int intValue = (int)setting.field.GetValue(setting.obj);
RangeAttribute rangeAttr = setting.field.GetCustomAttribute<RangeAttribute>();
if (rangeAttr != null) {
intValue = EditorGUILayout.IntSlider(setting.label, intValue,
(int)rangeAttr.min, (int)rangeAttr.max);
} else {
intValue = !delayed ?
EditorGUILayout.IntField(setting.label, intValue) :
EditorGUILayout.DelayedIntField(setting.label, intValue);
MinAttribute minAttr = setting.field.GetCustomAttribute<MinAttribute>();
if (minAttr != null) {
intValue = intValue < (int)minAttr.min ? (int)minAttr.min : intValue;
}
}
setting.field.SetValue(setting.obj, intValue);
} else
if (setting.type == typeof(float)) {
float floatValue = (float)setting.field.GetValue(setting.obj);
RangeAttribute rangeAttr = setting.field.GetCustomAttribute<RangeAttribute>();
if (rangeAttr != null) {
floatValue = EditorGUILayout.Slider(setting.label, floatValue, rangeAttr.min,
rangeAttr.max);
} else {
floatValue = !delayed ?
EditorGUILayout.FloatField(setting.label, floatValue) :
EditorGUILayout.DelayedFloatField(setting.label, floatValue);
MinAttribute minAttr = setting.field.GetCustomAttribute<MinAttribute>();
if (minAttr != null) {
floatValue = floatValue < minAttr.min ? minAttr.min : floatValue;
}
}
setting.field.SetValue(setting.obj, floatValue);
} else
if (setting.type == typeof(bool)) {
bool boolValue = (bool)setting.field.GetValue(setting.obj);
boolValue = EditorGUILayout.Toggle(setting.label, boolValue);
setting.field.SetValue(setting.obj, boolValue);
} else
if (setting.type == typeof(Color)) {
Color colorValue = (Color)setting.field.GetValue(setting.obj);
colorValue = EditorGUILayout.ColorField(setting.label, colorValue);
setting.field.SetValue(setting.obj, colorValue);
} else
if (setting.type.IsEnum) {
Enum enumValue = (Enum)setting.field.GetValue(setting.obj);
int intValue = Convert.ToInt32(enumValue);
string[] enumOptions = EnumCache.GetOptions(setting.type);
Array enumValues = EnumCache.GetValues(setting.type);
if (!setting.toggle) {
intValue = EditorGUILayout.IntPopup(setting.label, intValue, enumOptions,
(int[])enumValues);
setting.field.SetValue(setting.obj, intValue);
} else {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(setting.label);
int i = ArrayUtility.IndexOf<string>(enumOptions, enumValue.ToString());
i = GUILayout.Toolbar(i, enumOptions);
EditorGUILayout.EndHorizontal();
setting.field.SetValue(setting.obj, i);
}
} else
if (setting.type.IsGenericList()) {
SettingList(setting);
} else
if (typeof(PartSettings).IsAssignableFrom(setting.type)) {
PartSettings partSettings = (PartSettings)setting.field.GetValue(setting.obj);
EditorGUI.BeginChangeCheck();
partSettings.OnGUI(setting);
if (EditorGUI.EndChangeCheck()) {
partSettings.OnChange();
}
}
firstElement = false;
}
public static int SettingField(Setting setting, int selectedIndex, string[] options) {
if (setting == null) {
return 0;
}
int newIndex = EditorGUILayout.Popup(setting.label, selectedIndex, options);
setting.field.SetValue(setting.obj, options[newIndex]);
return newIndex;
}
public static void SettingField(Setting setting, Func<string, string> callback) {
if (setting == null) {
return;
}
TextAreaAttribute textAreaAttr = setting.field.GetCustomAttribute<TextAreaAttribute>();
if (setting.type == typeof(string)) {
string stringValue = (string)setting.field.GetValue(setting.obj);
EditorGUILayout.BeginHorizontal();
if (textAreaAttr != null) {
stringValue = EditorGUILayout.TextArea(setting.label, stringValue);
} else {
stringValue = EditorGUILayout.TextField(setting.label, stringValue);
}
if (GUILayout.Button("...", Styles.buttonStyle)) {
stringValue = callback?.Invoke(stringValue);
}
EditorGUILayout.EndHorizontal();
setting.field.SetValue(setting.obj, stringValue);
}
firstElement = false;
}
public static bool BeginPart(string title, PartSettings settings) {
EditorGUILayout.BeginVertical(Styles.groupStyle);
EditorGUIUtility.labelWidth = 200;
settings.foldout = EditorGUILayout.Foldout(settings.foldout, title, Styles.groupTitle);
EditorGUILayout.BeginVertical(settings.foldout ?
Styles.groupInnerStyle : EditorStyles.inspectorFullWidthMargins);
return settings.foldout;
}
public static void EndPart() {
Space(2);
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
}
public static void HelpBox(string message, MessageType type = MessageType.Info) {
EditorStyles.helpBox.richText = true;
EditorGUILayout.HelpBox(message, type);
EditorStyles.helpBox.richText = false;
}
// ---------------------------------------------------------------------------------------------
// reorderable list
static Setting setting;
static ReorderableList rlist;
public static void SettingList(Setting setting, ElementCallbackDelegate OnDrawElement = null,
float elementHeight = 0) {
// setup the list
PaneGUI.setting = setting;
rlist = rlist ?? new ReorderableList(null, typeof(IList));
rlist.list = (IList)setting.field.GetValue(setting.obj);
rlist.headerHeight = 2;
rlist.elementHeight = elementHeight > 0 ? elementHeight :
EditorGUIUtility.singleLineHeight + 4;
rlist.footerHeight = EditorGUIUtility.singleLineHeight + 3;
rlist.drawElementCallback = OnDrawElement ?? PaneGUI.OnDrawElement;
rlist.onAddCallback = OnAddElement;
rlist.onRemoveCallback = OnRemoveElement;
rlist.onReorderCallback = OnReorder;
rlist.drawNoneElementCallback = OnEmptyList;
rlist.showDefaultBackground = true;
// draw the reorderable list
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(setting.label);
GUILayout.BeginVertical(Styles.listStyle);
GUILayout.Space(1);
rlist.DoLayoutList();
GUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
static void OnEmptyList(Rect rect) {
EditorGUI.LabelField(rect, "No items", EditorStyles.centeredGreyMiniLabel);
}
static void OnDrawElement(Rect rect, int index, bool isActive, bool isFocused) {
rect.y += 2;
rect.width += 2;
rect.height = EditorGUIUtility.singleLineHeight;
if (setting.type == typeof(string)) {
rlist.list[index] = EditorGUI.TextField(rect, (string)rlist.list[index]);
} else
if (setting.type == typeof(UObject)) {
rlist.list[index] = EditorGUI.ObjectField(rect, rlist.list[index] as UObject,
setting.type, false);
} else
if (setting.type.IsEnum) {
int intValue = Convert.ToInt32(rlist.list[index]);
string[] enumOptions = EnumCache.GetOptions(setting.type);
Array enumValues = EnumCache.GetValues(setting.type);
intValue = EditorGUI.IntPopup(rect, "", intValue, enumOptions, (int[])enumValues);
rlist.list[index] = intValue;
}
}
static void OnAddElement(ReorderableList rlist) {
if (setting.type.IsGenericList()) {
Type valueType = setting.type.GetGenericArguments()[0];
if (valueType.IsEnum) {
rlist.list.Add(setting.defaultValue);
} else {
rlist.list.Add(Activator.CreateInstance(valueType));
}
} else {
rlist.list.Add(setting.defaultValue);
}
rlist.index = rlist.list.Count - 1;
GUI.changed = true;
}
static void OnRemoveElement(ReorderableList rlist) {
// keep the list focused
int index = rlist.index;
if (index == rlist.count - 1) {
if (rlist.count > 0) {
rlist.index--;
}
}
rlist.list.RemoveAt(index);
GUI.changed = true;
}
static void OnReorder(ReorderableList rlist) {
GUI.changed = true;
}
public static void FocusListElementAt(int index) {
rlist.index = index;
}
}
} |
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using API.Client;
using DLCS.Mediatr.Behaviours;
using MediatR;
using Microsoft.Extensions.Logging;
namespace Portal.Behaviours
{
/// <summary>
/// Audits request by logging message type/contents and UserId
/// </summary>
public class AuditBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IAuditable
{
private readonly ILogger<AuditBehaviour<TRequest, TResponse>> logger;
private readonly ClaimsPrincipal claimsPrincipal;
public AuditBehaviour(ILogger<AuditBehaviour<TRequest, TResponse>> logger, ClaimsPrincipal claimsPrincipal)
{
this.logger = logger;
this.claimsPrincipal = claimsPrincipal;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
var response = await next();
logger.LogInformation("User '{UserId}': req:{@Request} - res:{@Response}", claimsPrincipal.GetUserId(),
request, response);
return response;
}
}
} |
// ==========================================================================
// AppEventDispatcher.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System.Linq;
using Squidex.Domain.Apps.Core.Apps;
namespace Squidex.Domain.Apps.Events.Apps.Utils
{
public static class AppEventDispatcher
{
public static void Apply(this AppContributors contributors, AppContributorRemoved @event)
{
contributors.Remove(@event.ContributorId);
}
public static void Apply(this AppContributors contributors, AppContributorAssigned @event)
{
contributors.Assign(@event.ContributorId, @event.Permission);
}
public static void Apply(this LanguagesConfig languagesConfig, AppLanguageAdded @event)
{
languagesConfig.Set(new LanguageConfig(@event.Language));
}
public static void Apply(this LanguagesConfig languagesConfig, AppLanguageRemoved @event)
{
languagesConfig.Remove(@event.Language);
}
public static void Apply(this AppClients clients, AppClientAttached @event)
{
clients.Add(@event.Id, @event.Secret);
}
public static void Apply(this AppClients clients, AppClientRevoked @event)
{
clients.Revoke(@event.Id);
}
public static void Apply(this AppClients clients, AppClientRenamed @event)
{
if (clients.TryGetValue(@event.Id, out var client))
{
client.Rename(@event.Name);
}
}
public static void Apply(this AppClients clients, AppClientUpdated @event)
{
if (clients.TryGetValue(@event.Id, out var client))
{
client.Update(@event.Permission);
}
}
public static void Apply(this LanguagesConfig languagesConfig, AppLanguageUpdated @event)
{
var fallback = @event.Fallback;
if (fallback != null && fallback.Count > 0)
{
var existingLangauges = languagesConfig.OfType<LanguageConfig>().Select(x => x.Language);
fallback = fallback.Intersect(existingLangauges).ToList();
}
languagesConfig.Set(new LanguageConfig(@event.Language, @event.IsOptional, fallback));
if (@event.IsMaster)
{
languagesConfig.MakeMaster(@event.Language);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Binary_Tree_Printer;
namespace CPrintTester
{
class Program
{
private class Node : IPrintableBinaryNode
{
private readonly int _num;
public Node Left { get; set; }
public Node Right { get; set; }
public Node(int num) { this._num = num; }
public IPrintableBinaryNode GetLeft() { return Left; }
public IPrintableBinaryNode GetRight() { return Right; }
public String GetString() { return "" + _num; }
}
private class ExampleBalancedTree
{
public readonly Node Head = new Node(0);
public ExampleBalancedTree()
{
Head.Left = new Node(1) {Left = new Node(3), Right = new Node(4)};
Head.Right = new Node(2) {Left = new Node(5), Right = new Node(6)};
}
}
private class ExampleUnBalancedTree
{
public readonly Node Head = new Node(0);
public ExampleUnBalancedTree()
{
Head.Left = new Node(1) {Left = new Node(2) { Left = new Node(4), Right = null }, Right = new Node(3)};
}
}
static void Main(string[] args)
{
Console.WriteLine("Balanced");
BinaryTreePrinter.Print(new ExampleBalancedTree().Head,1);
Console.WriteLine("Unbalanced");
BinaryTreePrinter.Print(new ExampleUnBalancedTree().Head,1);
}
}
}
|
namespace BullOak.Repositories.EventStore.Test.Integration.Contexts
{
using BullOak.Repositories.EventStore.Test.Integration.Components;
using BullOak.Repositories.Session;
using System;
using System.Collections.Generic;
internal class TestDataContext
{
internal Guid CurrentStreamId { get; set; } = Guid.NewGuid();
public Exception RecordedException { get; internal set; }
public IHoldHigherOrder LatestLoadedState { get; internal set; }
public Dictionary<string, IManageSessionOf<IHoldHigherOrder>> NamedSessions { get; internal set; } =
new Dictionary<string, IManageSessionOf<IHoldHigherOrder>>();
public Dictionary<string, List<Exception>> NamedSessionsExceptions { get; internal set; } =
new Dictionary<string, List<Exception>>();
public int LastConcurrencyId { get; set; }
internal MyEvent[] LastGeneratedEvents;
internal void ResetStream()
{
CurrentStreamId = Guid.NewGuid();
}
}
}
|
namespace Telerik.UI.Xaml.Controls.Input
{
/// <summary>
/// Provides a set of predefined font weights as static property values.
/// </summary>
public enum FontWeightName
{
/// <summary>
/// Specifies a "Black" font weight.
/// </summary>
Black,
/// <summary>
/// Specifies a "Bold" font weight.
/// </summary>
Bold,
/// <summary>
/// Specifies an "ExtraBlack" font weight.
/// </summary>
ExtraBlack,
/// <summary>
/// Specifies an "ExtraBold" font weight.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ExtraBold")]
ExtraBold,
/// <summary>
/// Specifies an "ExtraLight" font weight.
/// </summary>
ExtraLight,
/// <summary>
/// Specifies a "Light" font weight.
/// </summary>
Light,
/// <summary>
/// Specifies a "Medium" font weight.
/// </summary>
Medium,
/// <summary>
/// Specifies a "Normal" font weight.
/// </summary>
Normal,
/// <summary>
/// Specifies a "SemiBold" font weight.
/// </summary>
SemiBold,
/// <summary>
/// Specifies a "SemiLight" font weight.
/// </summary>
SemiLight,
/// <summary>
/// Specifies a "Thin" font weight.
/// </summary>
Thin
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class DelayTest
{
[UnityTest]
public IEnumerator DelayIgnore() => UniTask.ToCoroutine(async () =>
{
var time = Time.realtimeSinceStartup;
Time.timeScale = 0.5f;
try
{
await UniTask.Delay(TimeSpan.FromSeconds(3), DelayType.Realtime);
var elapsed = Time.realtimeSinceStartup - time;
Assert.AreEqual(3,
(int) Math.Round(TimeSpan.FromSeconds(elapsed).TotalSeconds, MidpointRounding.ToEven));
}
finally
{
Time.timeScale = 1.0f;
}
});
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Detective.Query.Rank;
using Detective.Query.Result;
namespace Detective.Search.Rank
{
public class DefaultRanker
{
public ScoredMatch[] Rank(CandidateRecordSet candidateRecordSet)
{
if(candidateRecordSet.Count == 0)
return new ScoredMatch[0];
var scoredMatchList = new List<ScoredMatch>();
foreach (var candidateRecord in candidateRecordSet)
{
var uid = candidateRecord.Key;
var record = candidateRecord.Value;
var scoredMatch = Rank(uid, record);
if(scoredMatch != null && scoredMatch.Score > 0)
scoredMatchList.Add(scoredMatch);
}
var scoredMatches = scoredMatchList.OrderByDescending(i => i.Score).ToArray();
return scoredMatches;
}
public ScoredMatch Rank(int uid, CandidateName record)
{
var candidateMatches = new List<ScoredMatch>();
var featurizer = new MatchFeaturizer();
foreach (var recordName in record)
{
var nameIndex = recordName.Key;
var candidateTermSet = recordName.Value;
var features = featurizer.Featurize(uid, nameIndex, candidateTermSet);
var scorer = ScorerFactory.CreateScorer(features);
var scoredMatch = scorer.Score(features);
if(scoredMatch != null)
candidateMatches.Add(scoredMatch);
}
var topMatch = candidateMatches.OrderByDescending(i => i.Score).FirstOrDefault();
return topMatch;
}
}
}
|
using System;
using UnityEngine;
using UnityEngine.Assertions;
using Grove.Actions;
using Grove.Common;
using Grove.Properties;
namespace Grove.Properties
{
public abstract class PropertySetter<T, TProperty> : ActionBase
where TProperty : Property<T>
{
[SerializeField]
protected TProperty m_Target;
protected sealed override void DoExecute(IContext context)
{
if (m_Target == null)
{
Debug.LogAssertion("Target is not set", context.GetBehaviour());
}
else
{
m_Target.Store(context, Evaluate(context));
}
}
protected abstract T Evaluate(IContext context);
}
}
|
namespace MyApp.Core;
public interface ICharacterRepository
{
Task<CharacterDetailsDto> CreateAsync(CharacterCreateDto character);
Task<Option<CharacterDetailsDto>> ReadAsync(int characterId);
Task<IReadOnlyCollection<CharacterDto>> ReadAsync();
Task<Status> UpdateAsync(int id, CharacterUpdateDto character);
Task<Status> DeleteAsync(int characterId);
}
|
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Git.CredentialManager.Interop
{
/// <summary>
/// Marshaler for converting between .NET strings (UTF-16) and byte arrays (UTF-8).
/// Uses <seealso cref="U8StringConverter"/> internally.
/// </summary>
public class U8StringMarshaler : ICustomMarshaler
{
// We need to clean up strings that we marshal to native, but should not clean up strings that
// we marshal to managed.
private static readonly U8StringMarshaler NativeInstance = new U8StringMarshaler(true);
private static readonly U8StringMarshaler ManagedInstance = new U8StringMarshaler(false);
private readonly bool _cleanup;
public const string NativeCookie = "U8StringMarshaler.Native";
public const string ManagedCookie = "U8StringMarshaler.Managed";
public static ICustomMarshaler GetInstance(string cookie)
{
switch (cookie)
{
case NativeCookie:
return NativeInstance;
case ManagedCookie:
return ManagedInstance;
default:
throw new ArgumentException("Invalid marshaler cookie");
}
}
private U8StringMarshaler(bool cleanup)
{
_cleanup = cleanup;
}
public int GetNativeDataSize()
{
return -1;
}
public IntPtr MarshalManagedToNative(object value)
{
switch (value)
{
case null:
return IntPtr.Zero;
case string str:
return U8StringConverter.ToNative(str);
default:
throw new MarshalDirectiveException("Cannot marshal a non-string");
}
}
public unsafe object MarshalNativeToManaged(IntPtr ptr)
{
return U8StringConverter.ToManaged((byte*) ptr);
}
public void CleanUpManagedData(object value)
{
}
public virtual void CleanUpNativeData(IntPtr ptr)
{
if (ptr != IntPtr.Zero && _cleanup)
{
Marshal.FreeHGlobal(ptr);
}
}
}
}
|
namespace ByrneLabs.TestoRoboto.HttpServices
{
public enum OAuth2TokenLocation
{
Headers,
QueryParameters
}
}
|
using OpenAL;
namespace Bronze.Audio
{
public class Sound
{
internal uint Buffer { get; }
public AudioType Type
{
get
{
Al.GetBufferi(Buffer, Al.Channels, out int channels);
return channels == 1 ? AudioType.Positional : AudioType.Stereo;
}
}
public float Duration
{
get
{
Al.GetBufferi(Buffer, Al.Size, out int sizeInBytes);
Al.GetBufferi(Buffer, Al.Channels, out int channels);
Al.GetBufferi(Buffer, Al.Bits, out int bits);
int lengthInSamples = sizeInBytes * 8 / (channels * bits);
Al.GetBufferi(Buffer, Al.Frequency, out int frequency);
return (float) lengthInSamples / frequency;
}
}
internal Sound(uint buffer) => Buffer = buffer;
internal Sound(int format, short[] soundData, int sampleRate)
{
Al.GenBuffer(out uint buffer);
Buffer = buffer;
unsafe
{
fixed(short* dataPtr = soundData)
{
Al.BufferData(Buffer, format, dataPtr, soundData.Length * sizeof(short), sampleRate);
}
}
}
}
} |
namespace Svg
{
/// <summary>
/// Represents a list of re-usable SVG components.
/// </summary>
[SvgElement("defs")]
public partial class SvgDefinitionList : SvgElement
{
public override SvgElement DeepCopy()
{
return DeepCopy<SvgDefinitionList>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KeyGame
{
class Stats
{
public int Total = 0;
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
public void Update(bool correctKey)
{
Total++;
if (!correctKey)
{
Missed++;
}
else
{
Correct++;
}
Accuracy = 100 * Correct / Total;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bss.Optimization.Appetizers.Entities
{
public class MenuItemCollection : List<MenuItem>
{
public MenuItemCollection()
{
this.Add(new MenuItem() { Id = 0, Name = "Mixed Fruit", Price = 2.15, Cost = 2.00 });
this.Add(new MenuItem() { Id = 1, Name = "French Fries", Price = 2.75, Cost = 0.75 });
this.Add(new MenuItem() { Id = 2, Name = "Side Salad", Price = 3.35, Cost = 1.75 });
// this.Add(new MenuItem() { Id = 2, Name = "Side Salad", Price = 3.01, Cost = 1.75 });
this.Add(new MenuItem() { Id = 3, Name = "Hot Wings", Price = 3.55, Cost = 2.20 });
this.Add(new MenuItem() { Id = 4, Name = "Cheese Sticks", Price = 4.20, Cost = 3.07 });
this.Add(new MenuItem() { Id = 5, Name = "Sampler Plate", Price = 5.80, Cost = 3.60 });
}
}
}
|
using SecureApp.Licensing;
namespace Demo
{
internal static class Program
{
private static readonly Base Base = new Base();
public static void Main()
{
for (;;)
{}
}
}
} |
//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Exception Handling Application Block
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability.Adm;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.Manageability.Tests
{
[TestClass]
public class ExceptionHandlingSettingsManageabilityProvideFixture
{
ExceptionHandlingSettingsManageabilityProvider provider;
MockRegistryKey machineKey;
MockRegistryKey userKey;
IList<ConfigurationSetting> wmiSettings;
ExceptionHandlingSettings section;
DictionaryConfigurationSource configurationSource;
[TestInitialize]
public void SetUp()
{
provider =
new ExceptionHandlingSettingsManageabilityProvider(
new Dictionary<Type, ConfigurationElementManageabilityProvider>(0));
machineKey = new MockRegistryKey(true);
userKey = new MockRegistryKey(true);
wmiSettings = new List<ConfigurationSetting>();
section = new ExceptionHandlingSettings();
configurationSource = new DictionaryConfigurationSource();
configurationSource.Add(ExceptionHandlingSettings.SectionName, section);
}
[TestCleanup]
public void TearDown()
{
// preventive unregister to work around WMI.NET 2.0 issues with appdomain unloading
ManagementEntityTypesRegistrar.UnregisterAll();
}
[TestMethod]
public void ManageabilityProviderIsProperlyRegistered()
{
ConfigurationSectionManageabilityProviderAttribute selectedAttribute = null;
Assembly assembly = typeof(ExceptionHandlingSettingsManageabilityProvider).Assembly;
foreach (ConfigurationSectionManageabilityProviderAttribute providerAttribute
in assembly.GetCustomAttributes(typeof(ConfigurationSectionManageabilityProviderAttribute), false))
{
if (providerAttribute.SectionName.Equals(ExceptionHandlingSettings.SectionName))
{
selectedAttribute = providerAttribute;
break;
}
}
Assert.IsNotNull(selectedAttribute);
Assert.AreSame(typeof(ExceptionHandlingSettingsManageabilityProvider), selectedAttribute.ManageabilityProviderType);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ProviderThrowsWithConfigurationObjectOfWrongType()
{
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(new TestsConfigurationSection(), true, machineKey, userKey,
true, wmiSettings);
}
[TestMethod]
public void CanApplyMachinePolicyOverridesToExistingPolicyType()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey machinePoliciesKey = new MockRegistryKey(false);
machineKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, machinePoliciesKey);
MockRegistryKey machinePolicy1Key = new MockRegistryKey(false);
machinePoliciesKey.AddSubKey("policy1", machinePolicy1Key);
MockRegistryKey machinePolicy1TypesKey = new MockRegistryKey(false);
machinePolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName,
machinePolicy1TypesKey);
MockRegistryKey machinePolicy1Type1Key = new MockRegistryKey(false);
machinePolicy1TypesKey.AddSubKey("type1", machinePolicy1Type1Key);
machinePolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, null, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.NotifyRethrow, exceptionType1.PostHandlingAction);
Assert.IsTrue(
MockRegistryKey.CheckAllClosed(machinePoliciesKey, machinePolicy1Key, machinePolicy1TypesKey, machinePolicy1Type1Key));
}
[TestMethod]
public void MachineOverridesForMissingPolicyCausesNoProblems()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey machinePoliciesKey = new MockRegistryKey(false);
machineKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, machinePoliciesKey);
MockRegistryKey machinePolicy1Key = new MockRegistryKey(false);
machinePoliciesKey.AddSubKey("policy2", machinePolicy1Key);
MockRegistryKey machinePolicy1TypesKey = new MockRegistryKey(false);
machinePolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName,
machinePolicy1TypesKey);
MockRegistryKey machinePolicy1Type1Key = new MockRegistryKey(false);
machinePolicy1TypesKey.AddSubKey("type1", machinePolicy1Type1Key);
machinePolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, null, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.None, exceptionType1.PostHandlingAction);
Assert.IsTrue(
MockRegistryKey.CheckAllClosed(machinePoliciesKey, machinePolicy1Key, machinePolicy1TypesKey, machinePolicy1Type1Key));
}
[TestMethod]
public void CanApplyMachinePolicyOverridesToExistingPolicyTyqpeWhenMultiplePolicyOverridesExist()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey machinePoliciesKey = new MockRegistryKey(false);
machineKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, machinePoliciesKey);
MockRegistryKey machinePolicy0Key = new MockRegistryKey(false);
machinePoliciesKey.AddSubKey("policy0", machinePolicy0Key);
MockRegistryKey machinePolicy0TypesKey = new MockRegistryKey(false);
machinePolicy0Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName,
machinePolicy0TypesKey);
MockRegistryKey machinePolicy0Type1Key = new MockRegistryKey(false);
machinePolicy0TypesKey.AddSubKey("type1", machinePolicy0Type1Key);
machinePolicy0Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.ThrowNewException.ToString());
MockRegistryKey machinePolicy1Key = new MockRegistryKey(false);
machinePoliciesKey.AddSubKey("policy1", machinePolicy1Key);
MockRegistryKey machinePolicy1TypesKey = new MockRegistryKey(false);
machinePolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName,
machinePolicy1TypesKey);
MockRegistryKey machinePolicy1Type1Key = new MockRegistryKey(false);
machinePolicy1TypesKey.AddSubKey("type1", machinePolicy1Type1Key);
machinePolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, null, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.NotifyRethrow, exceptionType1.PostHandlingAction);
Assert.IsTrue(MockRegistryKey.CheckAllClosed(machinePoliciesKey,
machinePolicy0Key, machinePolicy0TypesKey, machinePolicy0Type1Key,
machinePolicy1Key, machinePolicy1TypesKey, machinePolicy1Type1Key));
}
[TestMethod]
public void CanApplyUserPolicyOverridesToExistingPolicyType()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy1", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type1Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type1", userPolicy1Type1Key);
userPolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, null, userKey, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.NotifyRethrow, exceptionType1.PostHandlingAction);
Assert.IsTrue(
MockRegistryKey.CheckAllClosed(userPoliciesKey, userPolicy1Key, userPolicy1TypesKey, userPolicy1Type1Key));
}
[TestMethod]
public void UserOverridesForMissingPolicyCausesNoProblems()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy2", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type1Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type1", userPolicy1Type1Key);
userPolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, null, userKey, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.None, exceptionType1.PostHandlingAction);
Assert.IsTrue(
MockRegistryKey.CheckAllClosed(userPoliciesKey, userPolicy1Key, userPolicy1TypesKey, userPolicy1Type1Key));
}
[TestMethod]
public void CanApplyUserPolicyOverridesToExistingPolicyTyqpeWhenMultiplePolicyOverridesExist()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy0Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy0", userPolicy0Key);
MockRegistryKey userPolicy0TypesKey = new MockRegistryKey(false);
userPolicy0Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy0TypesKey);
MockRegistryKey userPolicy0Type1Key = new MockRegistryKey(false);
userPolicy0TypesKey.AddSubKey("type1", userPolicy0Type1Key);
userPolicy0Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.ThrowNewException.ToString());
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy1", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type1Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type1", userPolicy1Type1Key);
userPolicy1Type1Key.AddStringValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
PostHandlingAction.NotifyRethrow.ToString());
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, null, userKey, false, wmiSettings);
Assert.AreEqual(PostHandlingAction.NotifyRethrow, exceptionType1.PostHandlingAction);
Assert.IsTrue(MockRegistryKey.CheckAllClosed(userPoliciesKey,
userPolicy0Key, userPolicy0TypesKey, userPolicy0Type1Key,
userPolicy1Key, userPolicy1TypesKey, userPolicy1Type1Key));
}
[TestMethod]
public void ExceptionTypeWithDisabledPolicyIsRemoved()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType11 = new ExceptionTypeData("type11", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType11);
ExceptionTypeData exceptionType12 = new ExceptionTypeData("type12", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType12);
ExceptionPolicyData policy2 = new ExceptionPolicyData("policy2");
section.ExceptionPolicies.Add(policy2);
ExceptionTypeData exceptionType21 = new ExceptionTypeData("type21", typeof(Exception), PostHandlingAction.None);
policy2.ExceptionTypes.Add(exceptionType21);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy1", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type11Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type11", userPolicy1Type11Key);
userPolicy1Type11Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, false);
userPolicy1Type11Key.AddEnumValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName, PostHandlingAction.None);
MockRegistryKey userPolicy1Type12Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type12", userPolicy1Type12Key);
userPolicy1Type12Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, true);
userPolicy1Type12Key.AddEnumValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName, PostHandlingAction.None);
MockRegistryKey userPolicy2Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy2", userPolicy2Key);
MockRegistryKey userPolicy2TypesKey = new MockRegistryKey(false);
userPolicy2Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy2TypesKey);
MockRegistryKey userPolicy2Type21Key = new MockRegistryKey(false);
userPolicy2TypesKey.AddSubKey("type21", userPolicy2Type21Key);
userPolicy2Type21Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, false);
userPolicy2Type21Key.AddEnumValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName, PostHandlingAction.None);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(2, section.ExceptionPolicies.Count);
Assert.IsNotNull(section.ExceptionPolicies.Get("policy1"));
Assert.AreEqual(1, section.ExceptionPolicies.Get("policy1").ExceptionTypes.Count);
Assert.IsNotNull(section.ExceptionPolicies.Get("policy1").ExceptionTypes.Get("type12"));
Assert.IsNotNull(section.ExceptionPolicies.Get("policy2"));
Assert.AreEqual(0, section.ExceptionPolicies.Get("policy2").ExceptionTypes.Count);
Assert.IsTrue(MockRegistryKey.CheckAllClosed(userPoliciesKey,
userPolicy1Key, userPolicy1TypesKey, userPolicy1Type11Key,
userPolicy1Type12Key,
userPolicy2Key, userPolicy2TypesKey, userPolicy2Type21Key));
}
[TestMethod]
public void ExceptionTypeWithDisabledPolicyIsNotRemovedIfGroupPoliciesAreDisabled()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType11 = new ExceptionTypeData("type11", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType11);
ExceptionTypeData exceptionType12 = new ExceptionTypeData("type12", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType12);
ExceptionPolicyData policy2 = new ExceptionPolicyData("policy2");
section.ExceptionPolicies.Add(policy2);
ExceptionTypeData exceptionType21 = new ExceptionTypeData("type21", typeof(Exception), PostHandlingAction.None);
policy2.ExceptionTypes.Add(exceptionType21);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy1", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type11Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type11", userPolicy1Type11Key);
userPolicy1Type11Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, false);
MockRegistryKey userPolicy1Type12Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type12", userPolicy1Type12Key);
userPolicy1Type12Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, true);
MockRegistryKey userPolicy2Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy2", userPolicy2Key);
MockRegistryKey userPolicy2TypesKey = new MockRegistryKey(false);
userPolicy2Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy2TypesKey);
MockRegistryKey userPolicy2Type21Key = new MockRegistryKey(false);
userPolicy2TypesKey.AddSubKey("type21", userPolicy2Type21Key);
userPolicy2Type21Key.AddBooleanValue(ExceptionHandlingSettingsManageabilityProvider.PolicyValueName, false);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(2, section.ExceptionPolicies.Count);
Assert.IsNotNull(section.ExceptionPolicies.Get("policy1"));
Assert.AreEqual(2, section.ExceptionPolicies.Get("policy1").ExceptionTypes.Count);
Assert.IsNotNull(section.ExceptionPolicies.Get("policy1").ExceptionTypes.Get("type11"));
Assert.IsNotNull(section.ExceptionPolicies.Get("policy1").ExceptionTypes.Get("type12"));
Assert.IsNotNull(section.ExceptionPolicies.Get("policy2"));
Assert.AreEqual(1, section.ExceptionPolicies.Get("policy2").ExceptionTypes.Count);
Assert.IsNotNull(section.ExceptionPolicies.Get("policy2").ExceptionTypes.Get("type21"));
Assert.IsTrue(MockRegistryKey.CheckAllClosed(userPoliciesKey,
userPolicy1Key, userPolicy1TypesKey, userPolicy1Type11Key,
userPolicy1Type12Key,
userPolicy2Key, userPolicy2TypesKey, userPolicy2Type21Key));
}
[TestMethod]
public void RegisteredHandlerDataProviderIsCalledWithNoOverrides()
{
MockConfigurationElementManageabilityProvider registeredProvider
= new MockConfigurationElementManageabilityProvider();
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ReplaceHandlerData), registeredProvider);
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
ExceptionHandlerData handlerData1 =
new ReplaceHandlerData("handler1", "msg", typeof(ArgumentException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handlerData1);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, userKey, false, wmiSettings);
Assert.IsTrue(registeredProvider.called);
Assert.AreSame(handlerData1, registeredProvider.LastConfigurationObject);
Assert.AreEqual(null, registeredProvider.machineKey);
Assert.AreEqual(null, registeredProvider.userKey);
}
[TestMethod]
public void RegisteredHandlerDataProviderIsCalledWithCorrectOverrides()
{
MockConfigurationElementManageabilityProvider registeredProvider
= new MockConfigurationElementManageabilityProvider();
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ReplaceHandlerData), registeredProvider);
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
ExceptionHandlerData handlerData1 =
new ReplaceHandlerData("handler1", "msg", typeof(ArgumentException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handlerData1);
MockRegistryKey machinePoliciesKey = new MockRegistryKey(false);
machineKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, machinePoliciesKey);
MockRegistryKey machinePolicy1Key = new MockRegistryKey(false);
machinePoliciesKey.AddSubKey("policy1", machinePolicy1Key);
MockRegistryKey machinePolicy1TypesKey = new MockRegistryKey(false);
machinePolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName,
machinePolicy1TypesKey);
MockRegistryKey machinePolicy1Type1Key = new MockRegistryKey(false);
machinePolicy1TypesKey.AddSubKey("type1", machinePolicy1Type1Key);
MockRegistryKey machineHandlersKey = new MockRegistryKey(false);
machinePolicy1Type1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypeHandlersPropertyName,
machineHandlersKey);
machinePolicy1Type1Key.AddEnumValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName, PostHandlingAction.None);
MockRegistryKey machineHandlerKey = new MockRegistryKey(false);
machineHandlersKey.AddSubKey("handler1", machineHandlerKey);
MockRegistryKey userPoliciesKey = new MockRegistryKey(false);
userKey.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PoliciesKeyName, userPoliciesKey);
MockRegistryKey userPolicy1Key = new MockRegistryKey(false);
userPoliciesKey.AddSubKey("policy1", userPolicy1Key);
MockRegistryKey userPolicy1TypesKey = new MockRegistryKey(false);
userPolicy1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypesPropertyName, userPolicy1TypesKey);
MockRegistryKey userPolicy1Type1Key = new MockRegistryKey(false);
userPolicy1TypesKey.AddSubKey("type1", userPolicy1Type1Key);
MockRegistryKey userHandlersKey = new MockRegistryKey(false);
userPolicy1Type1Key.AddSubKey(ExceptionHandlingSettingsManageabilityProvider.PolicyTypeHandlersPropertyName,
userHandlersKey);
userPolicy1Type1Key.AddEnumValue(
ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName, PostHandlingAction.None);
MockRegistryKey userHandlerKey = new MockRegistryKey(false);
userHandlersKey.AddSubKey("handler1", userHandlerKey);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, true, machineKey, userKey, false, wmiSettings);
Assert.IsTrue(registeredProvider.called);
Assert.AreSame(handlerData1, registeredProvider.LastConfigurationObject);
Assert.AreSame(machineHandlerKey, registeredProvider.machineKey);
Assert.AreSame(userHandlerKey, registeredProvider.userKey);
Assert.IsTrue(MockRegistryKey.CheckAllClosed(machinePoliciesKey,
machinePolicy1Key, machinePolicy1TypesKey, machinePolicy1Type1Key,
machineHandlersKey, machineHandlerKey,
userPolicy1Key, userPolicy1TypesKey, userPolicy1Type1Key,
userHandlersKey, userHandlerKey));
}
[TestMethod]
public void WmiSettingsAreNotGeneratedIfWmiIsDisabled()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, false, wmiSettings);
Assert.AreEqual(0, wmiSettings.Count);
}
[TestMethod]
public void WmiSettingsForPolicyAreGeneratedIfWmiIsEnabled()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(1, wmiSettings.Count);
Assert.AreSame(typeof(ExceptionPolicySetting), wmiSettings[0].GetType());
Assert.AreEqual("policy1", ((ExceptionPolicySetting)wmiSettings[0]).Name);
}
[TestMethod]
public void WmiSettingsForExceptionTypeAreGeneratedIfWmiIsEnabled()
{
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
// TODO change so that order is not important
Assert.AreEqual(2, wmiSettings.Count);
Assert.AreSame(typeof(ExceptionTypeSetting), wmiSettings[0].GetType());
Assert.AreEqual("type1", ((ExceptionTypeSetting)wmiSettings[0]).Name);
Assert.AreEqual(typeof(Exception).AssemblyQualifiedName, ((ExceptionTypeSetting)wmiSettings[0]).ExceptionTypeName);
Assert.AreEqual(PostHandlingAction.None.ToString(), ((ExceptionTypeSetting)wmiSettings[0]).PostHandlingAction);
Assert.AreEqual("policy1", ((ExceptionTypeSetting)wmiSettings[0]).Policy);
Assert.AreSame(typeof(ExceptionPolicySetting), wmiSettings[1].GetType());
Assert.AreEqual("policy1", ((ExceptionPolicySetting)wmiSettings[1]).Name);
}
[TestMethod]
public void WmiSettingsForExceptionHandlerAreGeneratedWithCorrectPolicyAndTypeIfWmiIsEnabled()
{
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ReplaceHandlerData), new ReplaceHandlerDataManageabilityProvider());
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
ReplaceHandlerData handler1 =
new ReplaceHandlerData("handler1", "message", typeof(ArgumentNullException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handler1);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(3, wmiSettings.Count);
IDictionary<String, ExceptionHandlerSetting> handlerSettings =
SelectWmiSettings<ExceptionHandlerSetting>(wmiSettings);
Assert.AreEqual(1, handlerSettings.Count);
Assert.IsTrue(handlerSettings.ContainsKey("handler1"));
Assert.AreEqual("message", ((ReplaceHandlerSetting)handlerSettings["handler1"]).ExceptionMessage);
Assert.AreEqual(typeof(ArgumentNullException).AssemblyQualifiedName,
((ReplaceHandlerSetting)handlerSettings["handler1"]).ReplaceExceptionType);
Assert.AreEqual("policy1", handlerSettings["handler1"].Policy);
Assert.AreEqual("type1", handlerSettings["handler1"].ExceptionType);
Assert.AreEqual(0, handlerSettings["handler1"].Order);
}
[TestMethod]
public void WmiSettingsForMultipleExceptionHandlersAreGeneratedWithCorrectPolicyAndTypeIfWmiIsEnabled()
{
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ReplaceHandlerData), new ReplaceHandlerDataManageabilityProvider());
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
ReplaceHandlerData handler1 =
new ReplaceHandlerData("handler1", "message", typeof(ArgumentNullException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handler1);
ReplaceHandlerData handler2 =
new ReplaceHandlerData("handler2", "message2", typeof(ArgumentException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handler2);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(4, wmiSettings.Count);
IDictionary<String, ExceptionHandlerSetting> handlerSettings =
SelectWmiSettings<ExceptionHandlerSetting>(wmiSettings);
Assert.AreEqual(2, handlerSettings.Count);
Assert.IsTrue(handlerSettings.ContainsKey("handler1"));
Assert.AreEqual("message", ((ReplaceHandlerSetting)handlerSettings["handler1"]).ExceptionMessage);
Assert.AreEqual(typeof(ArgumentNullException).AssemblyQualifiedName,
((ReplaceHandlerSetting)handlerSettings["handler1"]).ReplaceExceptionType);
Assert.AreEqual("policy1", handlerSettings["handler1"].Policy);
Assert.AreEqual("type1", handlerSettings["handler1"].ExceptionType);
Assert.AreEqual(0, handlerSettings["handler1"].Order);
Assert.IsTrue(handlerSettings.ContainsKey("handler2"));
Assert.AreEqual("message2", ((ReplaceHandlerSetting)handlerSettings["handler2"]).ExceptionMessage);
Assert.AreEqual(typeof(ArgumentException).AssemblyQualifiedName,
((ReplaceHandlerSetting)handlerSettings["handler2"]).ReplaceExceptionType);
Assert.AreEqual("policy1", handlerSettings["handler2"].Policy);
Assert.AreEqual("type1", handlerSettings["handler2"].ExceptionType);
Assert.AreEqual(1, handlerSettings["handler2"].Order);
}
[TestMethod]
public void WmiSettingsForMultipleExceptionHandlersOnDifferentTypesAreGeneratedWithCorrectPolicyAndTypeIfWmiIsEnabled()
{
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ReplaceHandlerData), new ReplaceHandlerDataManageabilityProvider());
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType1 = new ExceptionTypeData("type1", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType1);
ReplaceHandlerData handler1 =
new ReplaceHandlerData("handler1", "message", typeof(ArgumentNullException).AssemblyQualifiedName);
exceptionType1.ExceptionHandlers.Add(handler1);
ExceptionTypeData exceptionType2 =
new ExceptionTypeData("type2", typeof(NullReferenceException), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType2);
ReplaceHandlerData handler2 =
new ReplaceHandlerData("handler2", "message2", typeof(ArgumentException).AssemblyQualifiedName);
exceptionType2.ExceptionHandlers.Add(handler2);
provider.OverrideWithGroupPoliciesAndGenerateWmiObjects(section, false, machineKey, userKey, true, wmiSettings);
Assert.AreEqual(5, wmiSettings.Count);
IDictionary<String, ExceptionHandlerSetting> handlerSettings =
SelectWmiSettings<ExceptionHandlerSetting>(wmiSettings);
Assert.AreEqual(2, handlerSettings.Count);
Assert.IsTrue(handlerSettings.ContainsKey("handler1"));
Assert.AreEqual("message", ((ReplaceHandlerSetting)handlerSettings["handler1"]).ExceptionMessage);
Assert.AreEqual(typeof(ArgumentNullException).AssemblyQualifiedName,
((ReplaceHandlerSetting)handlerSettings["handler1"]).ReplaceExceptionType);
Assert.AreEqual("policy1", handlerSettings["handler1"].Policy);
Assert.AreEqual("type1", handlerSettings["handler1"].ExceptionType);
Assert.AreEqual(0, handlerSettings["handler1"].Order);
Assert.IsTrue(handlerSettings.ContainsKey("handler2"));
Assert.AreEqual("message2", ((ReplaceHandlerSetting)handlerSettings["handler2"]).ExceptionMessage);
Assert.AreEqual(typeof(ArgumentException).AssemblyQualifiedName,
((ReplaceHandlerSetting)handlerSettings["handler2"]).ReplaceExceptionType);
Assert.AreEqual("policy1", handlerSettings["handler2"].Policy);
Assert.AreEqual("type2", handlerSettings["handler2"].ExceptionType);
Assert.AreEqual(0, handlerSettings["handler2"].Order);
}
[TestMethod]
public void ManageabilityProviderGeneratesProperAdmContent()
{
DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
configurationSource.Add(ExceptionHandlingSettings.SectionName, section);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType11 = new ExceptionTypeData("type11", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType11);
ExceptionTypeData exceptionType12 = new ExceptionTypeData("type12", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType12);
ExceptionPolicyData policy2 = new ExceptionPolicyData("policy2");
section.ExceptionPolicies.Add(policy2);
ExceptionTypeData exceptionType21 = new ExceptionTypeData("type21", typeof(Exception), PostHandlingAction.None);
policy2.ExceptionTypes.Add(exceptionType21);
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
MockAdmContentBuilder contentBuilder = new MockAdmContentBuilder();
provider.AddAdministrativeTemplateDirectives(contentBuilder, section, configurationSource, "TestApp");
MockAdmContent content = contentBuilder.GetMockContent();
IEnumerator<AdmCategory> categoriesEnumerator = content.Categories.GetEnumerator();
Assert.IsTrue(categoriesEnumerator.MoveNext());
IEnumerator<AdmCategory> subCategoriesEnumerator = categoriesEnumerator.Current.Categories.GetEnumerator();
Assert.IsTrue(subCategoriesEnumerator.MoveNext());
Assert.AreEqual(policy1.Name, subCategoriesEnumerator.Current.Name);
IEnumerator<AdmPolicy> policyPoliciesEnumerator = subCategoriesEnumerator.Current.Policies.GetEnumerator();
Assert.IsTrue(policyPoliciesEnumerator.MoveNext());
IEnumerator<AdmPart> partsEnumerator = policyPoliciesEnumerator.Current.Parts.GetEnumerator();
Assert.IsTrue(partsEnumerator.MoveNext());
Assert.AreSame(typeof(AdmDropDownListPart), partsEnumerator.Current.GetType());
Assert.IsNull(partsEnumerator.Current.KeyName);
Assert.AreEqual(ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
partsEnumerator.Current.ValueName);
Assert.IsTrue(partsEnumerator.MoveNext());
Assert.AreSame(typeof(AdmTextPart), partsEnumerator.Current.GetType());
Assert.IsFalse(partsEnumerator.MoveNext());
Assert.IsTrue(policyPoliciesEnumerator.MoveNext());
Assert.IsFalse(policyPoliciesEnumerator.MoveNext());
Assert.IsTrue(subCategoriesEnumerator.MoveNext());
Assert.AreEqual(policy2.Name, subCategoriesEnumerator.Current.Name);
policyPoliciesEnumerator = subCategoriesEnumerator.Current.Policies.GetEnumerator();
Assert.IsTrue(policyPoliciesEnumerator.MoveNext());
Assert.IsFalse(policyPoliciesEnumerator.MoveNext());
Assert.IsFalse(subCategoriesEnumerator.MoveNext());
IEnumerator<AdmPolicy> sectionPoliciesEnumerator = categoriesEnumerator.Current.Policies.GetEnumerator();
Assert.IsTrue(sectionPoliciesEnumerator.MoveNext());
partsEnumerator = sectionPoliciesEnumerator.Current.Parts.GetEnumerator();
Assert.IsFalse(partsEnumerator.MoveNext());
Assert.IsFalse(sectionPoliciesEnumerator.MoveNext());
Assert.IsFalse(categoriesEnumerator.MoveNext());
}
[TestMethod]
public void ManageabilityProviderGeneratesProperAdmContentWithRegisteredProviders()
{
DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
configurationSource.Add(ExceptionHandlingSettings.SectionName, section);
ExceptionPolicyData policy1 = new ExceptionPolicyData("policy1");
section.ExceptionPolicies.Add(policy1);
ExceptionTypeData exceptionType11 = new ExceptionTypeData("type11", typeof(Exception), PostHandlingAction.None);
policy1.ExceptionTypes.Add(exceptionType11);
ExceptionHandlerData handler11 = new ExceptionHandlerData("handler11", typeof(object));
exceptionType11.ExceptionHandlers.Add(handler11);
MockConfigurationElementManageabilityProvider subProvider =
new MockConfigurationElementManageabilityProvider(false, true);
Dictionary<Type, ConfigurationElementManageabilityProvider> subProviders
= new Dictionary<Type, ConfigurationElementManageabilityProvider>();
subProviders.Add(typeof(ExceptionHandlerData), subProvider);
provider = new ExceptionHandlingSettingsManageabilityProvider(subProviders);
MockAdmContentBuilder contentBuilder = new MockAdmContentBuilder();
provider.AddAdministrativeTemplateDirectives(contentBuilder, section, configurationSource, "TestApp");
MockAdmContent content = contentBuilder.GetMockContent();
IEnumerator<AdmCategory> categoriesEnumerator = content.Categories.GetEnumerator();
Assert.IsTrue(categoriesEnumerator.MoveNext());
IEnumerator<AdmCategory> subCategoriesEnumerator = categoriesEnumerator.Current.Categories.GetEnumerator();
Assert.IsTrue(subCategoriesEnumerator.MoveNext());
Assert.AreEqual(policy1.Name, subCategoriesEnumerator.Current.Name);
IEnumerator<AdmPolicy> policyPoliciesEnumerator = subCategoriesEnumerator.Current.Policies.GetEnumerator();
Assert.IsTrue(policyPoliciesEnumerator.MoveNext());
IEnumerator<AdmPart> partsEnumerator = policyPoliciesEnumerator.Current.Parts.GetEnumerator();
Assert.IsTrue(partsEnumerator.MoveNext());
Assert.AreSame(typeof(AdmDropDownListPart), partsEnumerator.Current.GetType());
Assert.IsNull(partsEnumerator.Current.KeyName);
Assert.AreEqual(ExceptionHandlingSettingsManageabilityProvider.PolicyTypePostHandlingActionPropertyName,
partsEnumerator.Current.ValueName);
Assert.IsTrue(partsEnumerator.MoveNext());
Assert.AreSame(typeof(AdmTextPart), partsEnumerator.Current.GetType());
Assert.IsTrue(partsEnumerator.MoveNext());
Assert.AreSame(typeof(AdmTextPart), partsEnumerator.Current.GetType());
Assert.AreEqual(MockConfigurationElementManageabilityProvider.Part, partsEnumerator.Current.PartName);
Assert.IsFalse(partsEnumerator.MoveNext());
Assert.IsFalse(policyPoliciesEnumerator.MoveNext());
Assert.IsFalse(subCategoriesEnumerator.MoveNext());
Assert.IsFalse(categoriesEnumerator.MoveNext());
}
static IDictionary<String, T> SelectWmiSettings<T>(IEnumerable<ConfigurationSetting> wmiSettings)
where T : ExceptionHandlerSetting
{
Dictionary<String, T> result = new Dictionary<string, T>();
foreach (ConfigurationSetting setting in wmiSettings)
{
T namedSetting = setting as T;
if (namedSetting != null)
{
result.Add(namedSetting.Name, namedSetting);
}
}
return result;
}
}
}
|
using System.Threading.Tasks;
using MyLab.Search.Delegate;
using MyLab.Search.Delegate.Models;
using MyLab.Search.Delegate.Services;
using MyLab.Search.Delegate.Tools;
using Nest;
using Newtonsoft.Json;
using Xunit;
namespace UnitTests
{
public partial class RequestBuilderBehavior
{
[Theory]
[InlineData("firstname middlename lastname 123")]
[InlineData("Супер Иванович Администратор")]
[InlineData("Проверяющий Тест Тестович")]
[InlineData("Провер")]
[InlineData("942 Ефим")]
public async Task ShouldBuildRequestByQuery(string query)
{
//Arrange
var opt = new DelegateOptions
{
QueryStrategy = QuerySearchStrategy.Must,
Namespaces = new []
{
new DelegateOptions.Namespace
{
Name = "test"
}
}
};
var reqBuilder = new EsRequestBuilder(opt,
new TestSortProvider(),
new TestFilterProvider(),
new TestIndexMappingService());
var sReq = new ClientSearchRequestV2()
{
Query= query
};
//Act
var esReq = await reqBuilder.BuildAsync(sReq, "test", null);
var str = await EsSerializer.Instance.SerializeAsync(esReq);
_output.WriteLine(str);
//Assert
}
[Fact]
public async Task ShouldUseDefaultQueryStrategyOr()
{
//Arrange
var opt = new DelegateOptions
{
QueryStrategy = QuerySearchStrategy.Should,
Namespaces = new[]
{
new DelegateOptions.Namespace
{
Name = "test"
}
}
};
var reqBuilder = new EsRequestBuilder(opt,
new TestSortProvider(),
new TestFilterProvider(),
new TestIndexMappingService());
var sReq = new ClientSearchRequestV2()
{
Query = "nomater"
};
//Act
var esReq = await reqBuilder.BuildAsync(sReq, "test", null);
var boolQuery = ((IQueryContainer)esReq.Query).Bool;
//Assert
Assert.NotNull(boolQuery.Should);
Assert.Null(boolQuery.Must);
}
[Fact]
public async Task ShouldUseDefaultQueryStrategyAnd()
{
//Arrange
var opt = new DelegateOptions
{
QueryStrategy = QuerySearchStrategy.Must,
Namespaces = new[]
{
new DelegateOptions.Namespace
{
Name = "test"
}
}
};
var reqBuilder = new EsRequestBuilder(opt,
new TestSortProvider(),
new TestFilterProvider(),
new TestIndexMappingService());
var sReq = new ClientSearchRequestV2()
{
Query = "nomater"
};
//Act
var esReq = await reqBuilder.BuildAsync(sReq, "test", null);
var boolQuery = ((IQueryContainer)esReq.Query).Bool;
//Assert
Assert.NotNull(boolQuery.Must);
Assert.Null(boolQuery.Should);
}
[Fact]
public async Task ShouldUseNamespaceQueryStrategy()
{
//Arrange
var opt = new DelegateOptions
{
QueryStrategy = QuerySearchStrategy.Must,
Namespaces = new[]
{
new DelegateOptions.Namespace
{
Name = "test",
QueryStrategy = QuerySearchStrategy.Should
}
}
};
var reqBuilder = new EsRequestBuilder(opt,
new TestSortProvider(),
new TestFilterProvider(),
new TestIndexMappingService());
var sReq = new ClientSearchRequestV2()
{
Query = "nomater"
};
//Act
var esReq = await reqBuilder.BuildAsync(sReq, "test", null);
var boolQuery = ((IQueryContainer)esReq.Query).Bool;
//Assert
Assert.NotNull(boolQuery.Should);
Assert.Null(boolQuery.Must);
}
}
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.Linq;
namespace Dolittle.Queries
{
/// <summary>
/// Represents an implementation of a <see cref="IQueryProviderFor{T}"/> for <see cref="IQueryable"/>
/// </summary>
public class QueryableProvider : IQueryProviderFor<IQueryable>
{
/// <inheritdoc/>
public QueryProviderResult Execute(IQueryable query, PagingInfo paging)
{
var result = new QueryProviderResult();
result.TotalItems = query.Count();
if (paging.Enabled)
{
var start = paging.Size * paging.Number;
var end = paging.Size;
if (query.IsTakeEndIndex()) end += start;
query = query.Skip(start).Take(end);
}
result.Items = query;
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entity
{
public class Invoice
{
public int InvoiceId { get; set; }
[Required]
[StringLength(100)]
public string InvoiceNumber { get; set; }
[Required]
public Company Company { get; set; }
[NotMapped]
public string CompanyName
{
get { return Company.Name; }
}
[NotMapped]
public string CompanyAddress
{
get { return Company.Address; }
}
[NotMapped]
public string CompanyCity
{
get { return Company.City; }
}
[Required]
public Customer Customer { get; set; }
[NotMapped]
public string CustomerName
{
get { return Customer.Name; }
}
[NotMapped]
public string CustomerAddress
{
get { return Customer.Address; }
}
[NotMapped]
public string CustomerCity
{
get { return Customer.City; }
}
[Required]
public DateTime InvoiceDate { get; set; }
[Required]
public DateTime InvoiceDueDate { get; set; }
[Required]
public Tax Tax { get; set; }
public double Total { get; set; }
public double Discount { get; set; }
public double BeforeTax { get; set; }
public double TaxAmount { get; set; }
public double GrandTotal { get; set; }
public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }
}
}
|
namespace Assistant.Modules.CodeExec
{
public interface ICompiledLanguage : ILanguage
{
public string CompileCommand { get; }
}
}
|
namespace OmniXaml.Wpf
{
using System.Xaml;
public class ObjectWriterFactory : IXamlObjectWriterFactory
{
public XamlObjectWriterSettings GetParentSettings()
{
return new XamlObjectWriterSettings();
}
public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings)
{
var xamlSchemaContext = new XamlSchemaContext();
var xamlObjectWriter = new XamlObjectWriter(xamlSchemaContext, settings);
return xamlObjectWriter;
}
}
} |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.Debugger.Interop;
using AndroidPlusPlus.Common;
using AndroidPlusPlus.VsDebugCommon;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace AndroidPlusPlus.VsDebugEngine
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// This class represents a document context to the debugger. A document context represents a location within a source file.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class DebuggeeDocumentContext : IDebugDocumentContext2
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected readonly DebugEngine m_engine;
protected readonly string m_fileName;
protected readonly TEXT_POSITION m_beginPosition;
protected readonly TEXT_POSITION m_endPosition;
protected DebuggeeCodeContext m_codeContext;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public DebuggeeDocumentContext (DebugEngine engine, string fileName, TEXT_POSITION beginPosition, TEXT_POSITION endPosition)
{
m_engine = engine;
m_fileName = PathUtils.ConvertPathCygwinToWindows (fileName);
m_beginPosition = beginPosition;
m_endPosition = endPosition;
m_codeContext = null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int SetCodeContext (DebuggeeCodeContext codeContext)
{
LoggingUtils.PrintFunction ();
m_codeContext = codeContext;
return Constants.S_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region IDebugDocumentContext2 Members
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int Compare (enum_DOCCONTEXT_COMPARE compare, IDebugDocumentContext2 [] documentContexts, uint documentContextsLength, out uint matchIndex)
{
//
// Compares this document context to a given array of document contexts.
// Returns via 'matchIndex' the index into the 'documentContexts' array of the first document context that satisfies the comparison.
//
LoggingUtils.PrintFunction ();
try
{
matchIndex = 0;
throw new NotImplementedException ();
//return Constants.S_OK;
}
catch (NotImplementedException e)
{
LoggingUtils.HandleException (e);
matchIndex = 0;
return Constants.E_NOTIMPL;
}
catch (Exception e)
{
LoggingUtils.HandleException (e);
matchIndex = 0;
return Constants.E_FAIL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int EnumCodeContexts (out IEnumDebugCodeContexts2 enumCodeContexts)
{
//
// Retrieves a list of all code contexts associated with this document context.
//
LoggingUtils.PrintFunction ();
try
{
IDebugCodeContext2 [] codeContexts;
if (m_codeContext != null)
{
codeContexts = new IDebugCodeContext2 [] { m_codeContext };
}
else
{
codeContexts = new IDebugCodeContext2 [0];
}
enumCodeContexts = new DebuggeeCodeContext.Enumerator (codeContexts);
return Constants.S_OK;
}
catch (Exception e)
{
LoggingUtils.HandleException (e);
enumCodeContexts = null;
return Constants.E_FAIL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetDocument (out IDebugDocument2 document)
{
//
// Gets the document that contains this document context.
// This method is for those debug engines that supply documents directly to the IDE. Otherwise, this method should return E_NOTIMPL.
//
LoggingUtils.PrintFunction ();
document = null;
return Constants.E_NOTIMPL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetLanguageInfo (ref string languageName, ref Guid languageGuid)
{
//
// Gets the language associated with this document context.
//
LoggingUtils.PrintFunction ();
languageGuid = DebugEngineGuids.guidLanguageCpp;
languageName = DebugEngineGuids.GetLanguageName (languageGuid);
return Constants.S_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetName (enum_GETNAME_TYPE type, out string name)
{
//
// Gets the displayable name of the document that contains this document context.
//
LoggingUtils.PrintFunction ();
name = string.Empty;
try
{
switch (type)
{
case enum_GETNAME_TYPE.GN_NAME:
{
//
// Specifies a friendly name of the document or context.
//
name = Path.GetFileNameWithoutExtension (m_fileName);
break;
}
case enum_GETNAME_TYPE.GN_FILENAME:
{
//
// Specifies the full path of the document or context.
//
name = m_fileName;
break;
}
case enum_GETNAME_TYPE.GN_BASENAME:
{
//
// Specifies a base file name instead of a full path of the document or context.
//
name = Path.GetFileName (m_fileName);
break;
}
case enum_GETNAME_TYPE.GN_MONIKERNAME:
{
//
// Specifies a unique name of the document or context in the form of a moniker.
//
name = m_fileName;
break;
}
case enum_GETNAME_TYPE.GN_URL:
{
//
// Specifies a URL name of the document or context.
//
name = "file://" + m_fileName.Replace ("\\", "/");
break;
}
case enum_GETNAME_TYPE.GN_TITLE:
{
//
// Specifies a title of the document, if one exists.
//
name = Path.GetFileName (m_fileName);
break;
}
case enum_GETNAME_TYPE.GN_STARTPAGEURL:
{
//
// Gets the starting page URL for processes.
//
name = "file://" + m_fileName.Replace ("\\", "/");
break;
}
}
if (string.IsNullOrEmpty (name))
{
throw new InvalidOperationException ();
}
return Constants.S_OK;
}
catch (Exception e)
{
LoggingUtils.HandleException (e);
return Constants.E_FAIL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetSourceRange (TEXT_POSITION [] beginPosition, TEXT_POSITION [] endPosition)
{
//
// Gets the source code range of this document context.
// A source range is the entire range of source code, from the current statement back to just after the previous statement that contributed code.
// The source range is typically used for mixing source statements, including comments, with code in the disassembly window.
//
LoggingUtils.PrintFunction ();
try
{
throw new NotImplementedException ();
}
catch (NotImplementedException e)
{
LoggingUtils.HandleException (e);
return Constants.E_NOTIMPL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int GetStatementRange (TEXT_POSITION [] beginPosition, TEXT_POSITION [] endPosition)
{
//
// Gets the file statement range of the document context.
// A statement range is the range of the lines that contributed the code to which this document context refers.
//
LoggingUtils.PrintFunction ();
try
{
beginPosition [0].dwLine = m_beginPosition.dwLine;
beginPosition [0].dwColumn = m_beginPosition.dwColumn;
endPosition [0].dwLine = m_endPosition.dwLine;
endPosition [0].dwColumn = m_endPosition.dwColumn;
return Constants.S_OK;
}
catch (Exception e)
{
LoggingUtils.HandleException (e);
return Constants.E_FAIL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public int Seek (int nCount, out IDebugDocumentContext2 ppDocContext)
{
//
// Moves the document context by a given number of statements or lines.
//
LoggingUtils.PrintFunction ();
ppDocContext = null;
return Constants.E_NOTIMPL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
using System.Collections.Generic;
using System.IO.Packaging;
using IOPath = System.IO.Path;
namespace PdfSharp.Xps.XpsModel
{
/// <summary>
/// Binds an ordered sequence of fixed pages together into a single multi-page document.
/// </summary>
public class FixedDocument : XpsElement
{
/// <summary>
/// Gets the number of fixed pages in this document.
/// </summary>
public int PageCount => PageContentUriStrings.Count;
/// <summary>
/// Gets the XPS document that owns this document.
/// </summary>
public XpsDocument XpsDocument => fpayload.XpsDocument;
/// <summary>
/// Gets the path to this document.
/// </summary>
public string UriString
{
get => uriString;
internal set => uriString = value;
}
string uriString;
/// <summary>
/// Gets the fixed payload that owns this document.
/// </summary>
internal FixedPayload Payload
{
get => fpayload;
set => fpayload = value;
}
FixedPayload fpayload;
/// <summary>
/// Gets the underlying ZIP package.
/// </summary>
internal ZipPackage Package => Payload.Package;
internal List<string> PageContentUriStrings = new List<string>();
//internal string partUri;
/// <summary>
/// Gets a read-only collection of the fixed pages of this fixed documents .
/// </summary>
public FixedPageCollection Pages
{
get
{
if (pages == null)
pages = new FixedPageCollection(this);
return pages;
}
}
FixedPageCollection pages;
/// <summary>
/// Gets the fixed page with the specified index.
/// </summary>
public FixedPage GetFixedPage(int index)
{
if (FixedPages == null)
FixedPages = new FixedPage[PageContentUriStrings.Count];
// Parse on demand
FixedPage fpage = FixedPages[index];
if (fpage == null)
{
string source = IOPath.Combine(UriString, PageContentUriStrings[index]);
source = source.Replace('\\', '/');
fpage = Parsing.XpsParser.Parse(XpsDocument.GetPartAsXmlReader(Package, source)) as FixedPage;
if (fpage != null)
{
fpage.Parent = this;
fpage.Document = this;
source = IOPath.GetDirectoryName(source);
source = source.Replace('\\', '/');
fpage.UriString = source;
fpage.LoadResources();
FixedPages[index] = fpage;
}
}
return fpage;
}
/// <summary>
/// A collection of document references.
/// </summary>
//internal XpsElementCollection<PageContent> PageContents;
FixedPage[] FixedPages;
}
} |
using System;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
namespace HotPlate.WinForms
{
public partial class Main : Form
{
private readonly Core.HotPlate hotPlate;
private int turns;
public Main()
{
InitializeComponent();
hotPlate = new Core.HotPlate(6);
PrintHotPlate();
}
private void btnStart_Click(object sender, EventArgs e)
{
bgHotPlateIterations.RunWorkerAsync();
btnStart.Enabled = false;
}
private void bgHotPlateIterations_DoWork(object sender, DoWorkEventArgs e)
{
do
{
turns++;
hotPlate.NextState();
bgHotPlateIterations.ReportProgress(0);
Thread.Sleep(1000);
} while (hotPlate.HighestDiff >= 0.001);
}
private void bgHotPlateIterations_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
PrintHotPlate();
}
private void PrintHotPlate()
{
grdHotPlate.Rows.Clear();
grdHotPlate.ColumnCount = 6;
for (var i = 0; i < 6; i++)
{
grdHotPlate.Rows.Add(new DataGridViewRow());
for (var j = 0; j < 6; j++)
{
grdHotPlate.Rows[i].Cells[j].Value = hotPlate[i, j];
}
}
lblStatus.Text = $"Turns: {turns} | Diff: {hotPlate.HighestDiff}";
}
private void bgHotPlateIterations_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnStart.Enabled = true;
}
}
}
|
using System;
using System.Windows;
namespace Dynamo.Wpf.ViewModels.Watch3D
{
[Flags]
internal enum DynamoMeshShaderStates
{
None = 0,
/// <summary>
/// Used to determine if alpha should be lowered.
/// </summary>
IsFrozen = 1,
/// <summary>
/// Used to determine if selection color should be set.
/// </summary>
IsSelected = 2,
/// <summary>
/// Used to determine if alpha should be lowered.
/// </summary>
IsIsolated = 4,
/// <summary>
/// Used to mark a mesh as coming from a special or meta(gizmo) render package.
/// </summary>
IsSpecialRenderPackage = 8,
/// <summary>
/// Currently this flag is not used in the shader.
/// </summary>
HasTransparency = 16,
/// <summary>
/// Used to determine if vertex colors should be displayed with shading.
/// </summary>
RequiresPerVertexColor = 32,
/// <summary>
/// Currently this flag is not used in the shader.
/// </summary>
FlatShade = 64
}
internal class DynamoRenderCoreDataStore {
public delegate bool FuncRef<T>(ref T item, T val);
readonly FuncRef<bool> updateAction;
public DynamoRenderCoreDataStore(FuncRef<bool> onUpdateDataAction)
{
updateAction = onUpdateDataAction;
}
private bool isFrozenData;
/// <summary>
/// Is this model Frozen.
/// </summary>
public bool IsFrozenData { get { return isFrozenData; } internal set { updateAction(ref isFrozenData, value); } }
private bool isSelectedData;
/// <summary>
/// Is this model currently selected.
/// </summary>
public bool IsSelectedData { get { return isSelectedData; } internal set { updateAction(ref isSelectedData, value); } }
private bool isIsolatedData;
/// <summary>
/// Is IsolationMode active.
/// </summary>
public bool IsIsolatedData { get { return isIsolatedData; } internal set { updateAction(ref isIsolatedData, value); } }
private bool isSpecialData;
/// <summary>
/// Is this model marked as a special render package.
/// </summary>
public bool IsSpecialRenderPackageData { get { return isSpecialData; } internal set { updateAction(ref isSpecialData, value); } }
private bool hasTransparencyData;
/// <summary>
/// Does this model have alpha less than 255.
/// </summary>
public bool HasTransparencyData { get { return hasTransparencyData; } internal set { updateAction(ref hasTransparencyData, value); } }
private bool requiresPerVertexColor;
/// <summary>
/// Should this model display vertex colors.
/// </summary>
public bool RequiresPerVertexColor { get { return requiresPerVertexColor; } internal set { updateAction(ref requiresPerVertexColor, value); } }
private bool isFlatShaded;
/// <summary>
/// Should this model disregard lighting calculations and display unlit texture or vertex colors.
/// </summary>
public bool IsFlatShaded { get { return isFlatShaded; } internal set { updateAction(ref isFlatShaded, value); } }
/// <summary>
/// Generates an int that packs all enum flags into a single int.
/// Can be decoded using binary &
/// ie - Flags & 1 = IsFrozen
/// - if flags == 000000 - all flags are off
/// - if flags == 000001 - frozen is enabled
/// - if flags == 100001 - frozen and flatshade are enabled.
/// </summary>
/// <returns></returns>
public int GenerateEnumFromState()
{
var finalFlag = (int)(DynamoMeshShaderStates.None)
+ (int)(IsFrozenData ? DynamoMeshShaderStates.IsFrozen : 0)
+ (int)(IsSelectedData ? DynamoMeshShaderStates.IsSelected : 0)
+ (int)(IsIsolatedData ? DynamoMeshShaderStates.IsIsolated : 0)
+ (int)(IsSpecialRenderPackageData ? DynamoMeshShaderStates.IsSpecialRenderPackage : 0)
+ (int)(HasTransparencyData ? DynamoMeshShaderStates.HasTransparency : 0)
+ (int)(RequiresPerVertexColor ? DynamoMeshShaderStates.RequiresPerVertexColor : 0)
+ (int)(IsFlatShaded ? DynamoMeshShaderStates.FlatShade : 0);
return finalFlag;
}
internal void SetPropertyData(DependencyPropertyChangedEventArgs args)
{
var depType = args.Property;
var argval = (bool)args.NewValue;
//use dependencyProperty to determine which data to set.
if (depType == AttachedProperties.ShowSelectedProperty)
{
IsSelectedData = argval;
}
else if (depType == AttachedProperties.IsFrozenProperty)
{
IsFrozenData = argval;
}
else if (depType == AttachedProperties.IsolationModeProperty)
{
IsIsolatedData = argval;
}
else if (depType == AttachedProperties.IsSpecialRenderPackageProperty)
{
IsSpecialRenderPackageData = argval;
}
else if (depType == AttachedProperties.HasTransparencyProperty)
{
HasTransparencyData = argval;
}
else if (depType == DynamoGeometryModel3D.RequiresPerVertexColorationProperty)
{
RequiresPerVertexColor = argval;
}
//TODO we need to add FlatShader to AttachedProperties if we want to use it.
//and add a case here.
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gherkin.Ast;
using Gherkin.AstGenerator;
using NUnit.Framework;
namespace Gherkin.Specs
{
[TestFixture]
public class ParserErrorsTest
{
[Test, TestCaseSource(typeof(TestFileProvider), "GetInvalidTestFiles")]
public void TestParserErrors(string testFeatureFile)
{
var featureFileFolder = Path.GetDirectoryName(testFeatureFile);
Debug.Assert(featureFileFolder != null);
var expectedErrorsFile = testFeatureFile + ".errors";
try
{
var parser = new Parser();
parser.Parse(testFeatureFile);
Assert.Fail("ParserException expected");
}
catch (ParserException parserException)
{
var errorsText = LineEndingHelper.NormalizeLineEndings(parserException.Message);
var expectedErrorsText = LineEndingHelper.NormalizeLineEndings(File.ReadAllText(expectedErrorsFile));
Assert.AreEqual(expectedErrorsText, errorsText);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Social.Base
{
public class WallEntry
{
public string Id;
public string FromId;
public string FromName;
public string Message;
public WallEntryType Type;
public int Likes;
public int CommentsCount;
public List<WallComment> Comments;
public string UserPic;
public DateTime CreatedTime;
public DateTime UpdatedTime;
public string EntryUrl;
public string Application;
public bool IsPage; //true - page, false - man
//for links
public string Name;
public string Caption;
public string Description;
public string Picture;
public string Link;
}
}
|
namespace Solrevdev.InstagramBasicDisplay.Core.Instagram
{
/// <summary>
/// A typed version of appsettings used for configuration, It is common to have development
/// and production credentials when consuming the basic display api
/// </summary>
public class InstagramCredentials
{
/// <summary>
/// A friendly name also used as a user agent http header when talking to instagram and to
/// help differentiate between development and production credentials
/// </summary>
public string Name { get; set; }
/// <summary>
/// The instagram client-id credentials
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// The instagram client-secret credentials
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// The redirect-url to match what has been set in the instagram app.
/// </summary>
public string RedirectUrl { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
namespace Rolodex
{
public partial class CompanyEditUoW
{
private CompanyEditUoW() { }
#region Factory Methods
public static CompanyEditUoW GetCompanyEdit(int companyID)
{
var command = new CompanyEditUoW();
command.LoadProperty(CompanyIDProperty, companyID);
return DataPortal.Execute<CompanyEditUoW>(command);
}
protected override void DataPortal_Execute()
{
if (CompanyID > 0)
{
LoadProperty(CompanyProperty, CompanyEdit.GetCompanyEdit(CompanyID));
}
else
{
LoadProperty(CompanyProperty, CompanyEdit.NewCompanyEdit());
}
LoadProperty(StatusesProperty, EmployeeStatusInfoList.GetEmployeeStatusInfoList());
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TwitchAPI.Models;
namespace TwitchAPI.Data
{
public interface ITwitchRepository
{
bool SaveChanges();
IEnumerable<User> GetAllUsers();
User GetUserByUserId(int id);
User GetUserByDBId(int id);
void CreateUser(User user);
void DeleteUser(User user);
public App GetApp();
void CreateApp(App app);
void DeleteApp(App app);
}
}
|
using LineageServer.Server;
using System;
using System.IO;
namespace LineageServer.Serverpackets
{
class S_Emblem : ServerBasePacket
{
private const string S_EMBLEM = "[S] S_Emblem";
public S_Emblem(int emblemId)
{
string emblem_file = emblemId.ToString();
FileInfo file = new FileInfo("emblem/" + emblem_file);
if (file.Exists)
{
WriteC(Opcodes.S_OPCODE_EMBLEM);
WriteD(emblemId);
FileStream stream = file.OpenRead();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
stream.Dispose();
WriteByte(buffer);
}
}
public override string Type
{
get
{
return S_EMBLEM;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Destructor_01
{
class Program
{
static void Main(string[] args)
{
Third t = new Third();
/* Run with F5 then check Output Window
* Third's destructor is called.
Second's destructor is called.
First's destructor is called.
*/
}
}
class First
{
~First()
{
System.Diagnostics.Trace.WriteLine("First's destructor is called.");
}
}
class Second : First
{
~Second()
{
System.Diagnostics.Trace.WriteLine("Second's destructor is called.");
}
}
class Third : Second
{
~Third()
{
System.Diagnostics.Trace.WriteLine("Third's destructor is called.");
}
}
}
|
using MediatR;
using System;
using System.Collections.Generic;
namespace Watchster.Application.Features.Commands
{
public class CreateMovieCommand : IRequest<int>
{
public int TMDbId { get; set; }
public string Title { get; set; }
public DateTime? ReleaseDate { get; set; }
public IEnumerable<string> Genres { get; set; }
public string PosterUrl { get; set; }
public double Popularity { get; set; }
public double TMDbVoteAverage { get; set; }
public string Overview { get; set; }
}
}
|
using SF.IP.Domain.Common;
using SF.IP.Domain.ValueObjects;
using System;
using System.Collections.Generic;
namespace SF.IP.Domain.Entities;
// This will work as AggregateRoot
public class InsurancePolicy : BaseEntity //, Some IAggregateInterface
{
public InsurancePolicy()
{
//Id = Guid.NewGuid();
Events = new List<DomainEvent>();
}
//public Guid Id { get; set; }
//public List<DomainEvent> Events { get; set; }
public DateTime EffectiveDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
/*
* Sample LicenseNumbers
* D6101-40706-60905
* D6101 40706 60905
*
*/
public string LicenseNumber { get; set; }
public Address Address { get; set; }
public DateTime ExpirationDate { get; set; }
public PremiumPrice PremiumPrice { get; set; }
public Guid VehicleDetailId { get; set; }
public Vehicle VehicleDetail { get; set; }
public override string ToString()
{
return $"{LicenseNumber}:{FirstName}-{LastName}:{EffectiveDate.ToString("dd MMMM yyyy")}";
}
}
|
#addin "Cake.Markdownlint"
#addin "Cake.Issues&prerelease"
#addin "Cake.Issues.MsBuild&prerelease"
#addin "Cake.Issues.Markdownlint&prerelease"
#addin "Cake.Issues.DupFinder&prerelease"
#addin "Cake.Issues.InspectCode&prerelease"
#addin "Cake.Issues.Reporting&prerelease"
#addin "Cake.Issues.Reporting.Generic&prerelease"
#tool "nuget:?package=JetBrains.ReSharper.CommandLineTools"
#load build/build/build.cake
#load build/analyze/analyze.cake
#load build/create-reports/create-reports.cake
var target = Argument("target", "Default");
public class BuildData
{
public DirectoryPath RepoRootFolder { get; }
public DirectoryPath SourceFolder { get; }
public DirectoryPath DocsFolder { get; }
public DirectoryPath TemplateGalleryFolder { get; }
public List<IIssue> Issues { get; }
public BuildData(ICakeContext context)
{
this.RepoRootFolder = context.MakeAbsolute(context.Directory("./"));
this.SourceFolder = this.RepoRootFolder.Combine("src");
this.DocsFolder = this.RepoRootFolder.Combine("docs");
this.TemplateGalleryFolder = this.RepoRootFolder.Combine("../../docs/templates");
this.Issues = new List<IIssue>();
}
}
Setup<BuildData>(setupContext =>
{
return new BuildData(setupContext);
});
Task("Default")
.IsDependentOn("Create-Reports");
RunTarget(target);
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
//trabalhando com imagens
using System.Drawing;
namespace Azzi_Sprite_Compiler_v2
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
//Agrupando array de bytes
public static byte[] groupByteArray(byte[] myarray, byte[] add)
{
byte[] retorna = new byte[myarray.Length + add.Length];
for (int i = 0; i < myarray.Length; i++)
{
retorna[i] = myarray[i];
}
int j = 0;
for (int i = myarray.Length; i < retorna.Length; i++)
{
retorna[i] = add[j];
j++;
}
return retorna;
}
public static Bitmap nullimage;
[STAThread]
static void Main()
{
byte[] magenta = new byte[3072];
for (int j = 0; j < 3072; j++)
{
magenta[j] = 255; j++;
magenta[j] = 0; j++;
magenta[j] = 255;
}
nullimage = SprDecompiler.CopyDataToBitmap(magenta);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
|
using System.Runtime.Serialization;
using DvachBrowser4.Core.Models.Other;
namespace DvachBrowser4.Core.Models.Links
{
/// <summary>
/// Информация об избранном треде.
/// </summary>
[DataContract(Namespace = CoreConstants.DvachBrowserNamespace)]
public class FavoriteThreadInfo : ShortThreadInfo
{
/// <summary>
/// Информация о количестве постов.
/// </summary>
[DataMember]
public PostCountInfo CountInfo { get; set; }
/// <summary>
/// Клонировать.
/// </summary>
/// <returns>Клон.</returns>
public override ShortThreadInfo DeepClone()
{
return new FavoriteThreadInfo()
{
CountInfo = CountInfo?.DeepClone(),
ViewDate = ViewDate,
Title = Title,
CreatedDate = CreatedDate,
UpdatedDate = UpdatedDate,
AddedDate = AddedDate,
SmallImage = SmallImage?.DeepClone()
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using UBaseline.Shared.Property;
using Uintra.Features.Breadcrumbs.Models;
using Uintra.Features.Navigation.Models;
namespace Uintra.Core.Article
{
public class ArticlePageViewModel : UBaseline.Shared.ArticlePage.ArticlePageViewModel
{
public PropertyViewModel<bool> ShowInSubMenu { get; set; }
public Guid? GroupId { get; set; }
public IEnumerable<BreadcrumbViewModel> Breadcrumbs { get; set; } = Enumerable.Empty<BreadcrumbViewModel>();
public SubNavigationMenuItemModel SubNavigation { get; set; }
}
} |
using Marten.Schema;
using Marten.Storage;
namespace Marten.Events
{
public class StreamsTable : Table
{
public StreamsTable(EventGraph events) : base(new DbObjectName(events.DatabaseSchemaName, "mt_streams"))
{
AddPrimaryKey(events.StreamIdentity == StreamIdentity.AsGuid
? new TableColumn("id", "uuid")
: new TableColumn("id", "varchar"));
AddColumn("type", "varchar", "NULL");
AddColumn("version", "integer", "NOT NULL");
AddColumn("timestamp", "timestamptz", "default (now()) NOT NULL");
AddColumn("snapshot", "jsonb");
AddColumn("snapshot_version", "integer");
AddColumn("created", "timestamptz", "default (now()) NOT NULL");
AddColumn<TenantIdColumn>();
}
}
} |
namespace Esfa.Vacancy.Api.Types
{
public struct GeoPoint
{
public GeoPoint(double latitude, double longitude)
{
Longitude = (decimal)longitude;
Latitude = (decimal)latitude;
}
/// <summary>
/// The longitude.
/// </summary>
public decimal? Longitude { get; set; }
/// <summary>
/// The latitude.
/// </summary>
public decimal? Latitude { get; set; }
}
}
|
using Newtonsoft.Json;
namespace Notion.Client
{
public class NumberProperty : Property
{
public override PropertyType Type => PropertyType.Number;
[JsonProperty("number")]
public Number Number { get; set; }
}
public class Number
{
[JsonProperty("format")]
public string Format { get; set; }
}
}
|
using System.Threading.Tasks;
using Nervestaple.EntityFrameworkCore.Models.Criteria;
using Nervestaple.EntityFrameworkCore.Models.Entities;
using Nervestaple.EntityFrameworkCore.Models.Parameters;
namespace Nervestaple.WebService.Services {
/// <summary>
/// Provides an interface that the all read only service must implement.
/// </summary>
public interface IReadOnlyService<T, K>
where T: IEntity<K>
where K: struct {
/// <summary>
/// Returns the instance with the matching unique identifier.
/// </summary>
/// <param name="id">unique identifier</param>
/// <returns>matching instance</returns>
T GetById(K id);
/// <summary>
/// Returns the instance with the matching unique identifier.
/// </summary>
/// <param name="id">unique identifier</param>
/// <returns>matching instance</returns>
Task<T> GetByIdAsync(K id);
/// <summary>
/// Returns a page of instances.
/// </summary>
/// <param name="pageParameters">parameters used when fetching page</param>
/// <returns>page of instances</returns>
PagedEntities<T> Get(IPageParameters pageParameters);
/// <summary>
/// Returns a page of instances.
/// </summary>
/// <param name="pageParameters">parameters used when fetching page</param>
/// <returns>page of instances</returns>
Task<PagedEntities<T>> GetAsync(IPageParameters pageParameters);
/// <summary>
/// Queries the instances according tot he provided search criteris and
/// returns a page of the matching instances.
/// </summary>
/// <param name="searchCriteria">search criteria</param>
/// <param name="pageParameters">parameters used when fetching page</param>
/// <returns>page of instances</returns>
PagedEntities<T> Query(ISearchCriteria<T, K> searchCriteria, IPageParameters pageParameters);
/// <summary>
/// Queries the instances according tot he provided search criteris and
/// returns a page of the matching instances.
/// </summary>
/// <param name="searchCriteria">search criteria</param>
/// <param name="pageParameters">parameters used when fetching page</param>
/// <returns>page of instances</returns>
Task<PagedEntities<T>> QueryAsync(ISearchCriteria<T, K> searchCriteria, IPageParameters pageParameters);
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Liath.Vor.Contracts.DataAccess;
using Liath.Vor.DataAccess.Extensions;
using Liath.Vor.Models;
using Liath.Vor.Session;
using Liath.Vor.DataAccess.Extensions.IDataReaderExtensions;
namespace Liath.Vor.DataAccess
{
public class SecurityDataAccess : ISecurityDataAccess
{
private readonly ISessionManager _sessionManager;
public SecurityDataAccess(ISessionManager sessionManager)
{
if (sessionManager == null) throw new ArgumentNullException(nameof(sessionManager));
_sessionManager = sessionManager;
}
public UserAccount GetOrCreateUserAccount(string domainName)
{
using (var cmd = _sessionManager.GetCurrentUnitOfWork().CreateSPCommand("USR_GetOrCreateUser"))
{
using (var dr = cmd.CreateAndAddParameter("DomainName", DbType.String, domainName).ExecuteReader())
{
if (dr.Read())
{
var user = new UserAccount();
user.UserAccountID = dr.GetInt32("UserAccountID");
user.DomainName = dr.GetString("DomainName");
user.Firstname = dr.GetString("Firstname", true);
user.Lastname = dr.GetString("Lastname", true);
return user;
}
}
}
return null;
}
public UserAccount GetUserAccount(int userId)
{
UserAccount user = null;
using (var cmd = _sessionManager.GetCurrentUnitOfWork().CreateSPCommand("USR_GetUser"))
{
using (var dr = cmd.CreateAndAddParameter("UserAccountID", DbType.Int32, userId).ExecuteReader())
{
if (dr.Read())
{
user = new UserAccount();
user.UserAccountID = dr.GetInt32("UserAccountID");
user.DomainName = dr.GetString("DomainName");
user.Firstname = dr.GetString("Firstname", true);
user.Lastname = dr.GetString("Lastname", true);
}
}
}
return user;
}
}
}
|
using System;
using System.Collections;
using Tamir.SharpSsh;
using System.IO;
namespace sharpSshTest.sharpssh_samples
{
/// <summary>
/// Summary description for SshExeTest.
/// </summary>
public class SshExpectTest
{
public static void RunExample()
{
try
{
SshConnectionInfo input = Util.GetInput();
SshShell ssh = new SshShell(input.Host, input.User);
if(input.Pass != null) ssh.Password = input.Pass;
if(input.IdentityFile != null) ssh.AddIdentityFile( input.IdentityFile );
Console.Write("Connecting...");
ssh.Connect();
Console.WriteLine("OK");
Console.Write("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: ");
string pattern = Console.ReadLine();
ssh.ExpectPattern = pattern;
ssh.RemoveTerminalEmulationCharacters = true;
Console.WriteLine();
Console.WriteLine( ssh.Expect( pattern ) );
while(ssh.ShellOpened)
{
Console.WriteLine();
Console.Write("Enter some data to write ['Enter' to cancel]: ");
string data = Console.ReadLine();
if(data=="")break;
ssh.WriteLine(data);
string output = ssh.Expect( pattern );
Console.WriteLine( output );
}
Console.Write("Disconnecting...");
ssh.Close();
Console.WriteLine("OK");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace YC.Micro.Core
{
public static class AppServiceExtensions
{
/// <summary>
/// 注册应用程序域中所有有AppService特性的服务
/// </summary>
/// <param name="services"></param>
public static void AddAppServices(this IServiceCollection services)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
var serviceAttribute = type.GetCustomAttribute<AppServiceAttribute>();
if (serviceAttribute != null)
{
var serviceType = serviceAttribute.ServiceType;
if (serviceType == null && serviceAttribute.InterfaceServiceType)
{
serviceType = type.GetInterfaces().FirstOrDefault();
}
if (serviceType == null)
{
serviceType = type;
}
switch (serviceAttribute.Lifetime)
{
case ServiceLifetime.Singleton:
services.AddSingleton(serviceType, type);
break;
case ServiceLifetime.Scoped:
services.AddScoped(serviceType, type);
break;
case ServiceLifetime.Transient:
services.AddTransient(serviceType, type);
break;
default:
break;
}
}
}
}
}
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
#elif UNITY_5_6_OR_NEWER
using UnityEditor.Build;
#endif
namespace AlmostEngine.Screenshot
{
public static class FrameworkDependency
{
public static void AddiOSPhotosFrameworkDependency()
{
string pluginPath = AssetUtils.FindAssetPath("iOSUtils.m");
if (pluginPath != "")
{
FrameworkDependency.AddFrameworkDependency(pluginPath, BuildTarget.iOS, "Photos");
}
else
{
Debug.LogError("iOSUtils plugin not found.");
}
}
public static string frameworkDependenciesKey = "FrameworkDependencies";
public static void AddFrameworkDependency(string pluginPath, BuildTarget target, string framework)
{
PluginImporter plugin = AssetImporter.GetAtPath(pluginPath) as PluginImporter;
if (plugin == null)
return;
plugin.SetCompatibleWithPlatform(BuildTarget.iOS, true);
string dependencies = plugin.GetPlatformData(target, frameworkDependenciesKey);
if (!dependencies.Contains(framework))
{
plugin.SetPlatformData(target, frameworkDependenciesKey, dependencies + ";" + framework);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("Adding framework dependency to " + target + ": " + framework);
}
}
}
#if UNITY_2018_1_OR_NEWER && UNITY_IOS
class iOSFrameworkDependencyPreprocess : IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }
public void OnPreprocessBuild(BuildReport report)
{
FrameworkDependency.AddiOSPhotosFrameworkDependency();
}
}
#elif UNITY_5_6_OR_NEWER && UNITY_IOS
class iOSFrameworkDependencyPreprocess : IPreprocessBuild
{
public int callbackOrder { get { return 0; } }
public void OnPreprocessBuild(BuildTarget target, string path)
{
FrameworkDependency.AddiOSPhotosFrameworkDependency();
}
}
#endif
} |
using System;
namespace Contract.Architecture.Backend.Core.Contract.Logic.Modules.SessionManagement.Sessions
{
public interface ISession
{
DateTime ExpiresOn { get; set; }
string Name { get; set; }
string Token { get; set; }
Guid? EmailUserId { get; set; }
}
} |
using System;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
namespace Swashbuckle.AspNetCore.SwaggerGen.Test
{
public class VendorExtensionsDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
context.SchemaRegistry.GetOrRegister(typeof(DateTime));
swaggerDoc.Extensions.Add("X-property1", new OpenApiString("value"));
}
}
} |
using MonitorWang.Core.Geckoboard.DataProvider;
using MonitorWang.Core.Geckoboard.Entities;
namespace MonitorWang.Core.Geckoboard
{
public interface IGeckoboardDataServiceImpl
{
/// <summary>
///
/// </summary>
/// <returns></returns>
GeckoPieChart GetGeckoboardPieChartForAllSites();
/// <summary>
///
/// </summary>
/// <returns></returns>
GeckoPieChart GetGeckoboardPieChartForSite(string site);
/// <summary>
///
/// </summary>
/// <returns></returns>
GeckoPieChart GetGeckoboardPieChartForCheck(PieChartArgs args);
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
GeckoLineChart GetGeckoboardLineChartForCheckRate(LineChartArgs args);
/// <summary>
/// This will get the min, max and average resultcount for a specific site and check
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
GeckoMeter GetGeckoboardGeckoMeterForSiteCheck(GeckometerArgs args);
/// <summary>
/// This will get the last and previous to last resultcount for a specific site and check
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
GeckoComparison GetGeckoboardComparisonForSiteCheck(ComparisonArgs args);
/// <summary>
/// This will get the number of days interval from or to a date supplied
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
GeckoComparison GetGeckoboardDayInterval(string date);
}
} |
using System;
using System.Collections.Generic;
using Autofac;
using SlackNet.Handlers;
namespace SlackNet.Autofac
{
public class AutofacSlackServiceConfiguration : FactorySlackServiceConfigurationWithDependencyResolver<AutofacSlackServiceConfiguration, IComponentContext>
{
private readonly ContainerBuilder _containerBuilder;
private AutofacSlackServiceConfiguration(ContainerBuilder containerBuilder) => _containerBuilder = containerBuilder;
internal static void Configure(ContainerBuilder containerBuilder, Action<AutofacSlackServiceConfiguration> configure = null)
{
var config = new AutofacSlackServiceConfiguration(containerBuilder);
containerBuilder.Register(c => new AutofacSlackServiceProvider(config.CreateServiceFactory, c.Resolve<ILifetimeScope>()))
.As<ISlackServiceProvider>()
.SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetHttp()).As<IHttp>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetJsonSettings()).As<SlackJsonSettings>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetTypeResolver()).As<ISlackTypeResolver>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetUrlBuilder()).As<ISlackUrlBuilder>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetLogger()).As<ILogger>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetWebSocketFactory()).As<IWebSocketFactory>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetRequestListeners()).As<IEnumerable<ISlackRequestListener>>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetHandlerFactory()).As<ISlackHandlerFactory>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetApiClient()).As<ISlackApiClient>().SingleInstance();
containerBuilder.Register(c => c.Resolve<ISlackServiceProvider>().GetSocketModeClient()).As<ISlackSocketModeClient>().SingleInstance();
config.UseRequestListener<AutofacSlackRequestListener>();
configure?.Invoke(config);
}
protected override Func<ISlackServiceProvider, TService> GetServiceFactory<TService, TImplementation>()
{
if (ShouldRegisterType<TImplementation>())
_containerBuilder.RegisterType<TImplementation>().As<TService>().SingleInstance();
return serviceFactory => ((AutofacSlackServiceProvider)serviceFactory).Resolve<TService>();
}
protected override Func<SlackRequestContext, THandler> GetRequestHandlerFactory<THandler, TImplementation>()
{
if (ShouldRegisterType<TImplementation>())
_containerBuilder.RegisterType<TImplementation>().As<THandler>().InstancePerLifetimeScope();
return requestContext => requestContext.LifetimeScope().Resolve<THandler>();
}
protected override Func<SlackRequestContext, THandler> GetRegisteredHandlerFactory<THandler>()
{
if (ShouldRegisterType<THandler>())
_containerBuilder.RegisterType<THandler>().InstancePerLifetimeScope();
return requestContext => requestContext.LifetimeScope().Resolve<THandler>();
}
protected override Func<ISlackServiceProvider, TService> GetServiceFactory<TService>(Func<IComponentContext, TService> getService)
{
_containerBuilder.Register(getService).SingleInstance();
return serviceFactory => ((AutofacSlackServiceProvider)serviceFactory).Resolve<TService>();
}
protected override Func<SlackRequestContext, THandler> GetRequestHandlerFactory<THandler>(Func<IComponentContext, THandler> getHandler) =>
requestContext => getHandler(requestContext.LifetimeScope());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.