content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//----------------------------------------------------------------------- // <copyright file="ActorPath.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Util; using Newtonsoft.Json; namespace Akka.Actor { /// <summary> /// Actor path is a unique path to an actor that shows the creation path /// up through the actor tree to the root actor. /// ActorPath defines a natural ordering (so that ActorRefs can be put into /// collections with this requirement); this ordering is intended to be as fast /// as possible, which owing to the bottom-up recursive nature of ActorPath /// is sorted by path elements FROM RIGHT TO LEFT, where RootActorPath > /// ChildActorPath in case the number of elements is different. /// Two actor paths are compared equal when they have the same name and parent /// elements, including the root address information. That does not necessarily /// mean that they point to the same incarnation of the actor if the actor is /// re-created with the same path. In other words, in contrast to how actor /// references are compared the unique id of the actor is not taken into account /// when comparing actor paths. /// </summary> public abstract class ActorPath : IEquatable<ActorPath>, IComparable<ActorPath>, ISurrogated { public class Surrogate : ISurrogate, IEquatable<Surrogate>, IEquatable<ActorPath> { public Surrogate(string path) { Path = path; } public string Path { get; private set; } public ISurrogated FromSurrogate(ActorSystem system) { ActorPath path; if (TryParse(Path, out path)) { return path; } return null; } #region Implicit conversion operators public static implicit operator ActorPath(Surrogate surrogate) { ActorPath parse; TryParse(surrogate.Path, out parse); return parse; } public static implicit operator Surrogate(ActorPath path) { return (Surrogate)path.ToSurrogate(null); } #endregion #region Equality public bool Equals(Surrogate other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(Path, other.Path); } public bool Equals(ActorPath other) { if (other == null) return false; return Equals(other.ToSurrogate(null)); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var actorPath = obj as ActorPath; return Equals(actorPath); } public override int GetHashCode() { return Path.GetHashCode(); } #endregion } /** INTERNAL API */ internal static char[] ValidSymbols = @"""-_.*$+:@&=,!~';""()".ToCharArray(); /// <summary> /// Method that checks if actor name conforms to RFC 2396, http://www.ietf.org/rfc/rfc2396.txt /// Note that AKKA JVM does not allow parenthesis ( ) but, according to RFC 2396 those are allowed, and /// since we use URL Encode to create valid actor names, we must allow them. /// </summary> public static bool IsValidPathElement(string s) { if (String.IsNullOrEmpty(s)) { return false; } return !s.StartsWith("$") && Validate(s.ToCharArray(), s.Length); } private static bool Validate(IReadOnlyList<char> chars, int len) { Func<char, bool> isValidChar = c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || ValidSymbols.Contains(c); Func<char, bool> isHexChar = c => (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9'); var pos = 0; while (pos < len) { if (isValidChar(chars[pos])) { pos = pos + 1; } else if (chars[pos] == '%' && pos + 2 < len && isHexChar(chars[pos + 1]) && isHexChar(chars[pos + 2])) { pos = pos + 3; } else { return false; } } return true; } private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="ActorPath" /> class. /// </summary> /// <param name="address"> The address. </param> /// <param name="name"> The name. </param> protected ActorPath(Address address, string name) { _name = name; Address = address; } /// <summary> /// Initializes a new instance of the <see cref="ActorPath" /> class. /// </summary> /// <param name="parentPath"> The parent path. </param> /// <param name="name"> The name. </param> /// <param name="uid"> The uid. </param> protected ActorPath(ActorPath parentPath, string name, long uid) { Address = parentPath.Address; Uid = uid; _name = name; } /// <summary> /// Gets the uid. /// </summary> /// <value> The uid. </value> public long Uid { get; private set; } /// <summary> /// Gets the elements. /// </summary> /// <value> The elements. </value> public IReadOnlyList<string> Elements { get { var current = this; var elements = new List<string>(); while (!(current is RootActorPath)) { elements.Add(current.Name); current = current.Parent; } elements.Reverse(); return elements.AsReadOnly(); } } /// <summary> /// Gets the name. /// </summary> /// <value> The name. </value> public string Name { get { return _name; } } /// <summary> /// The Address under which this path can be reached; walks up the tree to /// the RootActorPath. /// </summary> /// <value> The address. </value> public Address Address { get; private set; } public abstract ActorPath Root { get; } public abstract ActorPath Parent { get; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other"> An object to compare with this object. </param> /// <returns> true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. </returns> public bool Equals(ActorPath other) { if (other == null) return false; return Address.Equals(other.Address) && Elements.SequenceEqual(other.Elements); } public abstract int CompareTo(ActorPath other); /// <summary> /// Withes the uid. /// </summary> /// <param name="uid"> The uid. </param> /// <returns> ActorPath. </returns> public abstract ActorPath WithUid(long uid); /// <summary> /// Create a new child actor path. /// </summary> /// <param name="path"> The path. </param> /// <param name="name"> The name. </param> /// <returns> The result of the operator. </returns> public static ActorPath operator /(ActorPath path, string name) { return new ChildActorPath(path, name, 0); } /// <summary> /// Recursively create a descendant’s path by appending all child names. /// </summary> /// <param name="path"> The path. </param> /// <param name="name"> The name. </param> /// <returns> The result of the operator. </returns> public static ActorPath operator /(ActorPath path, IEnumerable<string> name) { var a = path; foreach (string element in name) { if(!string.IsNullOrEmpty(element)) a = a / element; } return a; } public static ActorPath Parse(string path) { ActorPath actorPath; if (TryParse(path, out actorPath)) { return actorPath; } throw new UriFormatException("Can not parse an ActorPath: " + path); } /// <summary> /// Tries to parse the uri, which should be a full uri, i.e containing protocol. /// For example "akka://System/user/my-actor" /// </summary> public static bool TryParse(string path, out ActorPath actorPath) { actorPath = null; Address address; Uri uri; if (!TryParseAddress(path, out address, out uri)) return false; var pathElements = uri.AbsolutePath.Split('/'); actorPath = new RootActorPath(address) / pathElements.Skip(1); return true; } public static bool TryParseAddress(string path, out Address address) { Uri uri; return TryParseAddress(path, out address, out uri); } private static bool TryParseAddress(string path, out Address address, out Uri uri) { //This code corresponds to AddressFromURIString.unapply uri = null; address = null; if (!Uri.TryCreate(path, UriKind.Absolute, out uri)) return false; var protocol = uri.Scheme; //Typically "akka" if (!protocol.StartsWith("akka", StringComparison.OrdinalIgnoreCase)) { // Protocol must start with 'akka.* return false; } string systemName; string host = null; int? port = null; if (string.IsNullOrEmpty(uri.UserInfo)) { // protocol://SystemName/Path1/Path2 if (uri.Port > 0) { //port may not be specified for these types of paths return false; } //System name is in the "host" position. According to rfc3986 host is case //insensitive, but should be produced as lowercase, so if we use uri.Host //we'll get it in lower case. //So we'll extract it ourselves using the original path. //We skip the protocol and "://" var systemNameLength = uri.Host.Length; systemName = path.Substring(protocol.Length + 3, systemNameLength); } else { // protocol://SystemName@Host:port/Path1/Path2 systemName = uri.UserInfo; host = uri.Host; port = uri.Port; } address = new Address(protocol, systemName, host, port); return true; } /// <summary> /// Joins this instance. /// </summary> /// <returns> System.String. </returns> private string Join() { var joined = string.Join("/", Elements); return "/" + joined; } /// <summary> /// String representation of the path elements, excluding the address /// information. The elements are separated with "/" and starts with "/", /// e.g. "/user/a/b". /// </summary> /// <returns> System.String. </returns> public string ToStringWithoutAddress() { return Join(); } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> A <see cref="System.String" /> that represents this instance. </returns> public override string ToString() { return ToStringWithAddress(); } /// <summary> /// Returns a string representation of this instance including uid. /// </summary> /// <returns></returns> public string ToStringWithUid() { var uid = Uid; if (uid == ActorCell.UndefinedUid) return ToStringWithAddress(); return ToStringWithAddress() + "#" + uid; } /// <summary> /// Creates a child with the specified name /// </summary> /// <param name="childName"> Name of the child. </param> /// <returns> ActorPath. </returns> public ActorPath Child(string childName) { return this / childName; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. </returns> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj"> The object to compare with the current object. </param> /// <returns> /// <c> true </c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, /// <c> false </c>. /// </returns> public override bool Equals(object obj) { var other = obj as ActorPath; return Equals(other); } //public bool Equals(Surrogate other) //{ // if (other == null) return false; // return other.Equals(ToSurrogate(null)); //} public static bool operator ==(ActorPath left, ActorPath right) { return Equals(left, right); } public static bool operator !=(ActorPath left, ActorPath right) { return !Equals(left, right); } /// <summary> /// Generate String representation, with the address in the RootActorPath. /// </summary> /// <returns> System.String. </returns> public string ToStringWithAddress() { return ToStringWithAddress(Address); } public string ToSerializationFormat() { return ToStringWithAddress(); } /// <summary> /// Generate String representation, replacing the Address in the RootActorPath /// with the given one unless this path’s address includes host and port /// information. /// </summary> /// <param name="address"> The address. </param> /// <returns> System.String. </returns> public string ToStringWithAddress(Address address) { if (Address.Host != null && Address.Port.HasValue) return string.Format("{0}{1}", Address, Join()); return string.Format("{0}{1}", address, Join()); } public static string FormatPathElements(IEnumerable<string> pathElements) { return String.Join("/", pathElements); } public ISurrogate ToSurrogate(ActorSystem system) { return new Surrogate(ToSerializationFormat()); } } /// <summary> /// Class RootActorPath. /// </summary> public class RootActorPath : ActorPath { /// <summary> /// Initializes a new instance of the <see cref="RootActorPath" /> class. /// </summary> /// <param name="address"> The address. </param> /// <param name="name"> The name. </param> public RootActorPath(Address address, string name = "") : base(address, name) { } public override ActorPath Parent { get { return null; } } [JsonIgnore] public override ActorPath Root { get { return this; } } /// <summary> /// Withes the uid. /// </summary> /// <param name="uid"> The uid. </param> /// <returns> ActorPath. </returns> /// <exception cref="System.NotSupportedException"> RootActorPath must have undefinedUid </exception> public override ActorPath WithUid(long uid) { if (uid == 0) return this; throw new NotSupportedException("RootActorPath must have undefinedUid"); } public override int CompareTo(ActorPath other) { if (other is ChildActorPath) return 1; return String.Compare(ToString(), other.ToString(), StringComparison.Ordinal); } } /// <summary> /// Class ChildActorPath. /// </summary> public class ChildActorPath : ActorPath { private readonly string _name; private readonly ActorPath _parent; /// <summary> /// Initializes a new instance of the <see cref="ChildActorPath" /> class. /// </summary> /// <param name="parentPath"> The parent path. </param> /// <param name="name"> The name. </param> /// <param name="uid"> The uid. </param> public ChildActorPath(ActorPath parentPath, string name, long uid) : base(parentPath, name, uid) { _name = name; _parent = parentPath; } public override ActorPath Parent { get { return _parent; } } public override ActorPath Root { get { var current = _parent; while (current is ChildActorPath) { current = ((ChildActorPath)current)._parent; } return current.Root; } } /// <summary> /// Creates a copy of the given ActorPath and applies a new Uid /// </summary> /// <param name="uid"> The uid. </param> /// <returns> ActorPath. </returns> public override ActorPath WithUid(long uid) { if (uid == Uid) return this; return new ChildActorPath(_parent, _name, uid); } public override int CompareTo(ActorPath other) { return InternalCompareTo(this, other); } private int InternalCompareTo(ActorPath left, ActorPath right) { if (ReferenceEquals(left, right)) return 0; var leftRoot = left as RootActorPath; if (leftRoot != null) return leftRoot.CompareTo(right); var rightRoot = right as RootActorPath; if (rightRoot != null) return -rightRoot.CompareTo(left); var nameCompareResult = String.Compare(left.Name, right.Name, StringComparison.Ordinal); if (nameCompareResult != 0) return nameCompareResult; return InternalCompareTo(left.Parent, right.Parent); } } }
33.73064
151
0.519465
[ "Apache-2.0" ]
EnterpriseProductsLP/akka.net
src/core/Akka/Actor/ActorPath.cs
20,042
C#
using System; using System.Collections.Generic; using System.Text; public class Company { public string Name { get; private set; } public string Department { get; private set; } public decimal Salary { get; private set; } public Company(string compName,string dep,decimal salary) { this.Name = compName; this.Department = dep; this.Salary = salary; } }
21.315789
61
0.659259
[ "MIT" ]
ewgeni-dinew/06.C_Sharp-OOP_I
OOP-Fundamentals/01.DefiningClasses/08.Google/Company.cs
407
C#
using System; using GeoAPI.Geometries; namespace NetTopologySuite.Geometries { /// <summary> /// Specifies the precision model of the <c>Coordinate</c>s in a <c>Geometry</c>. /// In other words, specifies the grid of allowable /// points for all <c>Geometry</c>s. /// </summary> /// <remarks> /// The <c>MakePrecise</c> method allows rounding a coordinate to /// a "precise" value; that is, one whose /// precision is known exactly. /// Coordinates are assumed to be precise in geometries. /// That is, the coordinates are assumed to be rounded to the /// precision model given for the point. /// NTS input routines automatically round coordinates to the precision model /// before creating Geometries. /// All internal operations /// assume that coordinates are rounded to the precision model. /// Constructive methods (such as bool operations) always round computed /// coordinates to the appropriate precision model. /// Currently three types of precision model are supported: /// <para> /// Floating: represents full double precision floating point. /// This is the default precision model used in NTS /// FloatingSingle: represents single precision floating point. /// Fixed: represents a model with a fixed number of decimal places. /// </para> /// A Fixed Precision Model is specified by a scale factor. /// The scale factor specifies the size of the grid which numbers are rounded to. /// Input coordinates are mapped to fixed coordinates according to the following /// equations: /// <list> /// <item>jtsPt.x = round( (inputPt.x * scale ) / scale</item> /// <item>jtsPt.y = round( (inputPt.y * scale ) / scale</item> /// </list> /// <para> /// For example, to specify 3 decimal places of precision, use a scale factor /// of 1000. To specify -3 decimal places of precision (i.e. rounding to /// the nearest 1000), use a scale factor of 0.001. /// </para> /// Coordinates are represented internally as Java double-precision values. /// Since .NET uses the IEEE-394 floating point standard, this /// provides 53 bits of precision. (Thus the maximum precisely representable /// <i>integer</i> is 9,007,199,254,740,992 - or almost 16 decimal digits of precision). /// <para/> /// NTS binary methods currently do not handle inputs which have different precision models. /// The precision model of any constructed geometric value is undefined. /// </remarks> #if HAS_SYSTEM_SERIALIZABLEATTRIBUTE [Serializable] #endif public class PrecisionModel : IPrecisionModel { ///<summary> /// Determines which of two <see cref="IPrecisionModel"/>s is the most precise ///</summary> /// <param name="pm1">A precision model</param> /// <param name="pm2">A precision model</param> /// <returns>The PrecisionModel which is most precise</returns> public static IPrecisionModel MostPrecise(IPrecisionModel pm1, IPrecisionModel pm2) { if (pm1.CompareTo(pm2) >= 0) return pm1; return pm2; } private const int FloatingPrecisionDigits = 16; private const int FloatingSinglePrecisionDigits = 6; private const int FixedPrecisionDigits = 1; /// <summary> /// The maximum precise value representable in a double. Since IEE754 /// double-precision numbers allow 53 bits of mantissa, the value is equal to /// 2^53 - 1. This provides <i>almost</i> 16 decimal digits of precision. /// </summary> public const double MaximumPreciseValue = 9007199254740992.0; /// <summary> /// The type of PrecisionModel this represents. /// </summary> private readonly PrecisionModels _modelType; /// <summary> /// The scale factor which determines the number of decimal places in fixed precision. /// </summary> private readonly double _scale; /// <summary> /// Creates a <c>PrecisionModel</c> with a default precision /// of Floating. /// </summary> public PrecisionModel() { // default is floating precision _modelType = PrecisionModels.Floating; } /// <summary> /// Creates a <c>PrecisionModel</c> that specifies /// an explicit precision model type. /// If the model type is Fixed the scale factor will default to 1. /// </summary> /// <param name="modelType"> /// The type of the precision model. /// </param> public PrecisionModel(PrecisionModels modelType) { _modelType = modelType; if (modelType == PrecisionModels.Fixed) _scale = 1.0; } /// <summary> /// Creates a <c>PrecisionModel</c> that specifies Fixed precision. /// Fixed-precision coordinates are represented as precise internal coordinates, /// which are rounded to the grid defined by the scale factor. /// </summary> /// <param name="scale"> /// Amount by which to multiply a coordinate after subtracting /// the offset, to obtain a precise coordinate /// </param> /// <param name="offsetX">Not used.</param> /// <param name="offsetY">Not used.</param> [Obsolete("Offsets are no longer supported, since internal representation is rounded floating point")] // ReSharper disable UnusedParameter.Local public PrecisionModel(double scale, double offsetX, double offsetY) // ReSharper restore UnusedParameter.Local { _modelType = PrecisionModels.Fixed; _scale = scale; } /// <summary> /// Creates a <c>PrecisionModel</c> that specifies Fixed precision. /// Fixed-precision coordinates are represented as precise internal coordinates, /// which are rounded to the grid defined by the scale factor. /// </summary> /// <param name="scale"> /// Amount by which to multiply a coordinate after subtracting /// the offset, to obtain a precise coordinate. /// </param> public PrecisionModel(double scale) { _modelType = PrecisionModels.Fixed; _scale = scale; } /// <summary> /// Copy constructor to create a new <c>PrecisionModel</c> /// from an existing one. /// </summary> /// <param name="pm"></param> public PrecisionModel(PrecisionModel pm) { _modelType = pm._modelType; _scale = pm._scale; } /// <summary> /// Return HashCode. /// </summary> public override int GetHashCode() { return _modelType.GetHashCode() ^ _scale.GetHashCode(); } /// <summary> /// Tests whether the precision model supports floating point. /// </summary> /// <returns><c>true</c> if the precision model supports floating point.</returns> public bool IsFloating => _modelType == PrecisionModels.Floating || _modelType == PrecisionModels.FloatingSingle; /// <summary> /// Returns the maximum number of significant digits provided by this /// precision model. /// Intended for use by routines which need to print out precise values. /// </summary> /// <returns> /// The maximum number of decimal places provided by this precision model. /// </returns> public int MaximumSignificantDigits { get { switch (_modelType) { case PrecisionModels.Floating: return FloatingPrecisionDigits; case PrecisionModels.FloatingSingle: return FloatingSinglePrecisionDigits; case PrecisionModels.Fixed: return FixedPrecisionDigits + (int)Math.Ceiling(Math.Log(Scale) / Math.Log(10)); default: throw new ArgumentOutOfRangeException(_modelType.ToString()); } } } /// <summary> /// Returns the scale factor used to specify a fixed precision model. /// </summary> /// <remarks> /// The number of decimal places of precision is /// equal to the base-10 logarithm of the scale factor. /// Non-integral and negative scale factors are supported. /// Negative scale factors indicate that the places /// of precision is to the left of the decimal point. /// </remarks> /// <returns> /// The scale factor for the fixed precision model /// </returns> public double Scale { get => _scale; set => throw new NotSupportedException(); } ///// <summary> ///// Gets the type of this PrecisionModel. ///// </summary> ///// <returns></returns> //public PrecisionModels GetPrecisionModelType() //{ // return _modelType; //} /// <summary> /// Gets the type of this PrecisionModel. /// </summary> /// <returns></returns> public PrecisionModels PrecisionModelType => _modelType; /// <summary> /// Returns the x-offset used to obtain a precise coordinate. /// </summary> /// <returns> /// The amount by which to subtract the x-coordinate before /// multiplying by the scale. /// </returns> [Obsolete("Offsets are no longer used")] public double OffsetX => 0; /// <summary> /// Returns the y-offset used to obtain a precise coordinate. /// </summary> /// <returns> /// The amount by which to subtract the y-coordinate before /// multiplying by the scale /// </returns> [Obsolete("Offsets are no longer used")] public double OffsetY => 0; /// <summary> /// Sets <c>internal</c> to the precise representation of <c>external</c>. /// </summary> /// <param name="cexternal">The original coordinate.</param> /// <param name="cinternal"> /// The coordinate whose values will be changed to the /// precise representation of <c>external</c>. /// </param> [Obsolete("Use MakePrecise instead")] public void ToInternal(Coordinate cexternal, Coordinate cinternal) { if (IsFloating) { cinternal.X = cexternal.X; cinternal.Y = cexternal.Y; } else { cinternal.X = MakePrecise(cexternal.X); cinternal.Y = MakePrecise(cexternal.Y); } cinternal.Z = cexternal.Z; } /// <summary> /// Returns the precise representation of <c>external</c>. /// </summary> /// <param name="cexternal">The original coordinate.</param> /// <returns> /// The coordinate whose values will be changed to the precise /// representation of <c>external</c> /// </returns> [Obsolete("Use MakePrecise instead")] public Coordinate ToInternal(Coordinate cexternal) { var cinternal = new Coordinate(cexternal); MakePrecise(cinternal); return cinternal; } /// <summary> /// Returns the external representation of <c>internal</c>. /// </summary> /// <param name="cinternal">The original coordinate.</param> /// <returns> /// The coordinate whose values will be changed to the /// external representation of <c>internal</c>. /// </returns> [Obsolete("No longer needed, since internal representation is same as external representation")] public Coordinate ToExternal(Coordinate cinternal) { var cexternal = new Coordinate(cinternal); return cexternal; } /// <summary> /// Sets <c>external</c> to the external representation of <c>internal</c>. /// </summary> /// <param name="cinternal">The original coordinate.</param> /// <param name="cexternal"> /// The coordinate whose values will be changed to the /// external representation of <c>internal</c>. /// </param> [Obsolete("No longer needed, since internal representation is same as external representation")] public void ToExternal(Coordinate cinternal, Coordinate cexternal) { cexternal.X = cinternal.X; cexternal.Y = cinternal.Y; } /// <summary> /// Rounds a numeric value to the PrecisionModel grid. /// Symmetric Arithmetic Rounding is used, to provide /// uniform rounding behaviour no matter where the number is /// on the number line. /// </summary> /// <remarks> /// This method has no effect on NaN values /// </remarks> /// <param name="val"></param> public double MakePrecise(double val) { // don't change NaN values if (double.IsNaN(val)) return val; if (_modelType == PrecisionModels.FloatingSingle) { float floatSingleVal = (float)val; return floatSingleVal; } if (_modelType == PrecisionModels.Fixed) { /*.Net's default rounding algorithm is "Bankers Rounding" which turned * out to be no good for JTS/NTS geometry operations */ // return Math.Round(val * scale) / scale; // This is "Asymmetric Arithmetic Rounding" // http://en.wikipedia.org/wiki/Rounding#Round_half_up return Math.Floor(val * _scale + 0.5d) / _scale; } return val; // modelType == FLOATING - no rounding necessary } /// <summary> /// Rounds a Coordinate to the PrecisionModel grid. /// </summary> /// <param name="coord"></param> public void MakePrecise(Coordinate coord) { // optimization for full precision if (_modelType == PrecisionModels.Floating) return; coord.X = MakePrecise(coord.X); coord.Y = MakePrecise(coord.Y); //MD says it's OK that we're not makePrecise'ing the z [Jon Aquino] } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { string description = "UNKNOWN"; if (_modelType == PrecisionModels.Floating) description = "Floating"; else if (_modelType == PrecisionModels.FloatingSingle) description = "Floating-Single"; else if (_modelType == PrecisionModels.Fixed) description = "Fixed (Scale=" + Scale + ")"; return description; } /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public override bool Equals(object other) { if (other == null) return false; if (!(other is IPrecisionModel)) return false; return Equals((IPrecisionModel)other); } /// <summary> /// /// </summary> /// <param name="otherPrecisionModel"></param> /// <returns></returns> public bool Equals(IPrecisionModel otherPrecisionModel) { return _modelType == otherPrecisionModel.PrecisionModelType && _scale == otherPrecisionModel.Scale; } /// <summary> /// /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> public static bool operator ==(PrecisionModel obj1, PrecisionModel obj2) { return Equals(obj1, obj2); } /// <summary> /// /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> /// <returns></returns> public static bool operator !=(PrecisionModel obj1, PrecisionModel obj2) { return !(obj1 == obj2); } /// <summary> /// Compares this <c>PrecisionModel</c> object with the specified object for order. /// A PrecisionModel is greater than another if it provides greater precision. /// The comparison is based on the value returned by the /// {getMaximumSignificantDigits) method. /// This comparison is not strictly accurate when comparing floating precision models /// to fixed models; however, it is correct when both models are either floating or fixed. /// </summary> /// <param name="o"> /// The <c>PrecisionModel</c> with which this <c>PrecisionModel</c> /// is being compared. /// </param> /// <returns> /// A negative integer, zero, or a positive integer as this <c>PrecisionModel</c> /// is less than, equal to, or greater than the specified <c>PrecisionModel</c>. /// </returns> public int CompareTo(object o) { return CompareTo((IPrecisionModel)o); } /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(IPrecisionModel other) { int sigDigits = MaximumSignificantDigits; int otherSigDigits = other.MaximumSignificantDigits; return (sigDigits).CompareTo(otherSigDigits); } } }
38.061181
121
0.571365
[ "EPL-1.0" ]
ChaplinMarchais/NetTopologySuite
NetTopologySuite/Geometries/PrecisionModel.cs
18,043
C#
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion //[assembly: Elmah.Scc("$Id: DataBoundAssertion.cs 566 2009-05-11 10:37:10Z azizatif $")] using System; namespace ElmahCore.Assertions { #region Imports #endregion internal abstract class DataBoundAssertion : IAssertion { private readonly IContextExpression _expression; protected DataBoundAssertion(IContextExpression expression) { if (expression == null) throw new ArgumentNullException("expression"); _expression = expression; } protected IContextExpression Expression { get { return _expression; } } public virtual bool Test(object context) { if (context == null) throw new ArgumentNullException("context"); return TestResult(Expression.Evaluate(context)); } protected abstract bool TestResult(object result); } }
28.081967
89
0.666083
[ "Apache-2.0" ]
JTOne123/ElmahCore
ElmahCore/Assertions/DataBoundAssertion.cs
1,713
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace EmpleoDotNet.WebApi.Areas.HelpPage.ModelDescriptions { public class ParameterDescription { public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); } public Collection<ParameterAnnotation> Annotations { get; private set; } public string Documentation { get; set; } public string Name { get; set; } public ModelDescription TypeDescription { get; set; } } }
26.190476
80
0.68
[ "Unlicense" ]
ArielVillalona/empleo-dot-net
EmpleoDotNet.WebApi/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
550
C#
using System; using System.Linq; using System.Text.RegularExpressions; using POETradeHelper.Common.Extensions; using POETradeHelper.ItemSearch.Contract.Models; using POETradeHelper.ItemSearch.Contract.Services.Parsers; namespace POETradeHelper.ItemSearch.Services.Parsers { public abstract class ItemParserBase : IItemParser { protected bool HasRarity(string[] itemStringLines, ItemRarity itemRarity) { return this.GetRarity(itemStringLines) == itemRarity; } protected ItemRarity? GetRarity(string[] itemStringLines) { string rarityDescriptor = POETradeHelper.ItemSearch.Contract.Properties.Resources.RarityDescriptor; string rarityLine = itemStringLines.FirstOrDefault(line => line.Contains(rarityDescriptor)); ItemRarity? rarity = rarityLine.Replace(rarityDescriptor, "").Trim().ParseToEnumByDisplayName<ItemRarity>(); return rarity.Value; } protected int GetIntegerFromFirstStringContaining(string[] itemStringLines, string containsString) { int result = 0; string matchingLine = itemStringLines.FirstOrDefault(l => l.Contains(containsString)); if (matchingLine != null) { Match match = Regex.Match(matchingLine, @"[\+\-]?\d+"); if (match.Success) { result = int.Parse(match.Value); } } return result; } protected bool IsCorrupted(string[] lines) { return lines.Any(l => l == POETradeHelper.ItemSearch.Contract.Properties.Resources.CorruptedKeyword); } protected bool IsIdentified(string[] itemStringLines) { return !itemStringLines.Any(l => l.Contains(POETradeHelper.ItemSearch.Contract.Properties.Resources.UnidentifiedKeyword)); } public Item Parse(string[] itemStringLines) { Item item = this.ParseItem(itemStringLines); item.ItemText = string.Join(Environment.NewLine, itemStringLines); return item; } protected abstract Item ParseItem(string[] itemStringLines); public abstract bool CanParse(string[] itemStringLines); } }
34.238806
134
0.645161
[ "Apache-2.0", "MIT" ]
alueck/POE-TradeHelper
Source/POETradeHelper.ItemSearch/Services/Parsers/ItemParsers/ItemParserBase.cs
2,296
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yomiage.GUI.EventMessages { class PauseDictionaryChanged { } }
15.615385
35
0.758621
[ "MIT" ]
InochiPM/YomiageLibrary
Yomiage.GUI/EventMessages/PauseDictionaryChanged.cs
205
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Vcs; using Aliyun.Acs.Vcs.Transform; using Aliyun.Acs.Vcs.Transform.V20200515; namespace Aliyun.Acs.Vcs.Model.V20200515 { public class GetBodyOptionsRequest : RpcAcsRequest<GetBodyOptionsResponse> { public GetBodyOptionsRequest() : base("Vcs", "2020-05-15", "GetBodyOptions") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string corpId; public string CorpId { get { return corpId; } set { corpId = value; DictionaryUtil.Add(BodyParameters, "CorpId", value); } } public override bool CheckShowJsonItemName() { return false; } public override GetBodyOptionsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return GetBodyOptionsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
31.7
134
0.69626
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-vcs/Vcs/Model/V20200515/GetBodyOptionsRequest.cs
2,219
C#
using HarmonyLib; using UnhollowerBaseLib; using UnityEngine; namespace Glaucus { [HarmonyPatch(typeof(GameSettingMenu), nameof(GameSettingMenu.OnEnable))] public static class GameSettingsMenuPatch { public static void Prefix(ref GameSettingMenu __instance) { __instance.HideForOnline = new Il2CppReferenceArray<Transform>(0); } } }
25.733333
78
0.712435
[ "MIT" ]
Pandraghon/BetterSabotage
BetterSabotage/GameSettingsPatch.cs
388
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft Azure Powershell - PowerBIDedicated Resource Provider")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure PowerSHell")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b1b26198-8a48-4457-a969-831b2a871a0e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")]
44.901961
93
0.684279
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/PowerBIEmbedded/Commands.PowerBI/Properties/AssemblyInfo.cs
2,240
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xunit; namespace FreeRedis.Tests.RedisClientTests { public class GeoTests : TestBase { [Fact] public void GetAdd() { cli.Del("TestGeoAdd"); Assert.Equal(3, cli.GeoAdd("TestGeoAdd", new GeoMember(10, 20, "m1"), new GeoMember(11, 21, "m2"), new GeoMember(12, 22, "m3"))); } [Fact] public void GeoDist() { cli.Del("TestGeoDist"); Assert.Equal(3, cli.GeoAdd("TestGeoDist", new GeoMember(10, 20, "m1"), new GeoMember(11, 21, "m2"), new GeoMember(12, 22, "m3"))); Assert.NotNull(cli.GeoDist("TestGeoDist", "m1", "m2")); Assert.NotNull(cli.GeoDist("TestGeoDist", "m1", "m3")); Assert.NotNull(cli.GeoDist("TestGeoDist", "m2", "m3")); Assert.Null(cli.GeoDist("TestGeoDist", "m1", "m31")); Assert.Null(cli.GeoDist("TestGeoDist", "m11", "m31")); } [Fact] public void GeoHash() { cli.Del("TestGeoHash"); Assert.Equal(3, cli.GeoAdd("TestGeoHash", new GeoMember(10, 20, "m1"), new GeoMember(11, 21, "m2"), new GeoMember(12, 22, "m3"))); Assert.False(string.IsNullOrEmpty(cli.GeoHash("TestGeoHash", "m1"))); Assert.Equal(2, cli.GeoHash("TestGeoHash", new[] { "m1", "m2" }).Select(a => string.IsNullOrEmpty(a) == false).Count()); Assert.Equal(2, cli.GeoHash("TestGeoHash", new[] { "m1", "m2", "m22" }).Where(a => string.IsNullOrEmpty(a) == false).Count()); } [Fact] public void GeoPos() { cli.Del("TestGeoPos"); Assert.Equal(3, cli.GeoAdd("TestGeoPos", new GeoMember(10, 20, "m1"), new GeoMember(11, 21, "m2"), new GeoMember(12, 22, "m3"))); Assert.Equal(4, cli.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" }).Length); //Assert.Equal((10, 20), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[0]); //Assert.Equal((11, 21), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[1]); Assert.Null(cli.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[2]); //Assert.Equal((12, 22), rds.GeoPos("TestGeoPos", new[] { "m1", "m2", "m22", "m3" })[3]); } [Fact] public void GeoRadius() { cli.Del("TestGeoRadius"); Assert.Equal(2, cli.GeoAdd("TestGeoRadius", new GeoMember(13.361389m, 38.115556m, "Palermo"), new GeoMember(15.087269m, 37.502669m, "Catania"))); var geopos = cli.GeoPos("TestGeoRadius", new[] { "m1", "Catania", "m2", "Palermo", "Catania2" }); var georadius1 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km); var georadius2 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true); var georadius3 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true); var georadius4 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true, true); var georadius5 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, true, false); var georadius6 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false); var georadius7 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false, true); var georadius8 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, true, false, false); var georadius9 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, true, false); var georadius10 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, true, true); var georadius11 = cli.GeoRadius("TestGeoRadius", 15, 37, 200, GeoUnit.km, false, false, true); } [Fact] public void GeoRadiusByMember() { cli.Del("GeoRadiusByMember"); Assert.Equal(2, cli.GeoAdd("GeoRadiusByMember", new GeoMember(13.361389m, 38.115556m, "Palermo"), new GeoMember(15.087269m, 37.502669m, "Catania"))); var geopos = cli.GeoPos("GeoRadiusByMember", new[] { "m1", "Catania", "m2", "Palermo", "Catania2" }); var georadius1 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km); var georadius2 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true); var georadius3 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true); var georadius4 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true, true); var georadius5 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, true, false); var georadius6 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false); var georadius7 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false, true); var georadius8 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, true, false, false); var georadius9 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, true, false); var georadius10 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, true, true); var georadius11 = cli.GeoRadius("GeoRadiusByMember", 15, 37, 200, GeoUnit.km, false, false, true); } } }
49.155172
138
0.561207
[ "MIT" ]
2881099/FreeRedis
test/Unit/FreeRedis.Tests/RedisClientTests/GeoTests.cs
5,704
C#
using DataProcessor.Contracts; using DataProcessor.Models; namespace DataProcessor.ProcessorDefinition { public class BypassDecoder : IFieldDecoder { public string Pattern { get; set; } public ValidationResultType FailValidationResult { get; set; } = ValidationResultType.Valid; public void Decode(Field field) { field.ValidationResult = ValidationResultType.Valid; field.Value = field.Raw; } } }
26.444444
100
0.67437
[ "MIT" ]
avalsch/intaker
DataProcessor/DataProcessor/ProcessorDefinition/BypassDecoder.cs
478
C#
using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class PlayerController : MonoBehaviour { Vector3 velocity = Vector3.zero; Vector3 rotation = Vector3.zero; Rigidbody myRigidbody; void Start() { myRigidbody = GetComponent<Rigidbody>(); } public void Move(Vector3 velocity) { this.velocity = velocity; } public void Rotate(Vector3 rotation) { this.rotation = rotation; } public void LookAt(Vector3 point) { Vector3 correctedPoint = new Vector3(point.x, transform.position.y, point.z); transform.LookAt(correctedPoint); } void FixedUpdate() { Vector3 rotation = myRigidbody.rotation.eulerAngles + this.rotation * Time.fixedDeltaTime; myRigidbody.MoveRotation(Quaternion.Euler(rotation)); if (velocity.sqrMagnitude > 0.1f) { Vector3 pos = myRigidbody.position + transform.rotation * velocity * Time.fixedDeltaTime; myRigidbody.MovePosition(pos); } else myRigidbody.velocity = Vector3.zero; } }
25.159091
101
0.642276
[ "MIT" ]
TomKauffeld/GMTK-2021
Assets/Scripts/PlayerController.cs
1,107
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Calculando_Figuras_Geometricas.Figuras._2_Dimensiones.Formas_Calculo { /// <summary> /// Lógica de interacción para Cuadrado.xaml /// </summary> public partial class Cuadrado : Window { public Cuadrado() { InitializeComponent(); } private void Btn_calcular_Click(object sender, RoutedEventArgs e) { double lado = Convert.ToDouble(txt_lado.Text); Clases.Cuadrado figura = new Clases.Cuadrado(lado); lbl_resultado.Content = figura.calcularArea().ToString(); } private void Btn_atras_Click(object sender, RoutedEventArgs e) { EleccionFigura_2D ventana = new EleccionFigura_2D(); ventana.Show(); this.Close(); } } }
27.5
78
0.670996
[ "MIT" ]
jsalmoralp/AutoDidacta-CS-CursoBasico-enVS
CS-wpf-MundoFigurasGeometricas/Calculando Figuras Geometricas/Figuras/2_Dimensiones/Formas_Calculo/Cuadrado.xaml.cs
1,159
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.Pkcs.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct Rfc3161TstInfo { private static ReadOnlySpan<byte> DefaultOrdering => new byte[] { 0x01, 0x01, 0x00 }; internal int Version; internal Oid Policy; internal System.Security.Cryptography.Pkcs.Asn1.MessageImprint MessageImprint; internal ReadOnlyMemory<byte> SerialNumber; internal DateTimeOffset GenTime; internal System.Security.Cryptography.Pkcs.Asn1.Rfc3161Accuracy? Accuracy; internal bool Ordering; internal ReadOnlyMemory<byte>? Nonce; internal System.Security.Cryptography.Asn1.GeneralNameAsn? Tsa; internal System.Security.Cryptography.Asn1.X509ExtensionAsn[]? Extensions; #if DEBUG static Rfc3161TstInfo() { Rfc3161TstInfo decoded = default; AsnValueReader reader; reader = new AsnValueReader(DefaultOrdering, AsnEncodingRules.DER); decoded.Ordering = reader.ReadBoolean(); reader.ThrowIfNotEmpty(); } #endif internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.WriteInteger(Version); writer.WriteObjectIdentifier(Policy); MessageImprint.Encode(writer); writer.WriteInteger(SerialNumber.Span); writer.WriteGeneralizedTime(GenTime); if (Accuracy.HasValue) { Accuracy.Value.Encode(writer); } // DEFAULT value handler for Ordering. { using (AsnWriter tmp = new AsnWriter(AsnEncodingRules.DER)) { tmp.WriteBoolean(Ordering); ReadOnlySpan<byte> encoded = tmp.EncodeAsSpan(); if (!encoded.SequenceEqual(DefaultOrdering)) { writer.WriteEncodedValue(encoded); } } } if (Nonce.HasValue) { writer.WriteInteger(Nonce.Value.Span); } if (Tsa.HasValue) { writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); Tsa.Value.Encode(writer); writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); } if (Extensions != null) { writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 1)); for (int i = 0; i < Extensions.Length; i++) { Extensions[i].Encode(writer); } writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 1)); } writer.PopSequence(tag); } internal static Rfc3161TstInfo Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static Rfc3161TstInfo Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); Decode(ref reader, expectedTag, encoded, out Rfc3161TstInfo decoded); reader.ThrowIfNotEmpty(); return decoded; } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out Rfc3161TstInfo decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out Rfc3161TstInfo decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); AsnValueReader explicitReader; AsnValueReader defaultReader; AsnValueReader collectionReader; ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; if (!sequenceReader.TryReadInt32(out decoded.Version)) { sequenceReader.ThrowIfNotEmpty(); } decoded.Policy = sequenceReader.ReadObjectIdentifier(); System.Security.Cryptography.Pkcs.Asn1.MessageImprint.Decode(ref sequenceReader, rebind, out decoded.MessageImprint); tmpSpan = sequenceReader.ReadIntegerBytes(); decoded.SerialNumber = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); decoded.GenTime = sequenceReader.ReadGeneralizedTime(); if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence)) { System.Security.Cryptography.Pkcs.Asn1.Rfc3161Accuracy tmpAccuracy; System.Security.Cryptography.Pkcs.Asn1.Rfc3161Accuracy.Decode(ref sequenceReader, rebind, out tmpAccuracy); decoded.Accuracy = tmpAccuracy; } if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Boolean)) { decoded.Ordering = sequenceReader.ReadBoolean(); } else { defaultReader = new AsnValueReader(DefaultOrdering, AsnEncodingRules.DER); decoded.Ordering = defaultReader.ReadBoolean(); } if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Integer)) { tmpSpan = sequenceReader.ReadIntegerBytes(); decoded.Nonce = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); } if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0))) { explicitReader = sequenceReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); System.Security.Cryptography.Asn1.GeneralNameAsn tmpTsa; System.Security.Cryptography.Asn1.GeneralNameAsn.Decode(ref explicitReader, rebind, out tmpTsa); decoded.Tsa = tmpTsa; explicitReader.ThrowIfNotEmpty(); } if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 1))) { // Decode SEQUENCE OF for Extensions { collectionReader = sequenceReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 1)); var tmpList = new List<System.Security.Cryptography.Asn1.X509ExtensionAsn>(); System.Security.Cryptography.Asn1.X509ExtensionAsn tmpItem; while (collectionReader.HasData) { System.Security.Cryptography.Asn1.X509ExtensionAsn.Decode(ref collectionReader, rebind, out tmpItem); tmpList.Add(tmpItem); } decoded.Extensions = tmpList.ToArray(); } } sequenceReader.ThrowIfNotEmpty(); } } }
37.264151
140
0.610506
[ "MIT" ]
AlFasGD/runtime
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TstInfo.xml.cs
7,902
C#
using System; using RLSKTD.General.ItemHelpers; using Sirenix.OdinInspector; using Sirenix.Serialization; namespace RLSKTD.General.ItemCategories.ArmorSubcategories{ /// <summary> This is the Neck class </summary> [System.Serializable] public class Neck : Armor { public enum SubType { Necklace, Amulet, Choker, Pendant, Locket } [OdinSerialize, UnityEngine.HideInInspector]private SubType subType; [ShowInInspector]public SubType _SubType { get => subType; set => subType = value; } public Neck(){ _ArmorType = ArmorType.Neck; } public Neck(SubType subType, Material material){ _SubType = subType; _Material = material; _ArmorType = ArmorType.Neck; GenerateQuality(); GenerateProtectionValue(); GenerateDefensiveValue(); Weight = 0.05f; _WeightClass = WeightClass.Light; GenerateName(subType.ToString()); //GenerateDescription(isArtifact); } [Button("Generate New Neck")] private void Generate(){ _SubType = (SubType)UnityEngine.Random.Range(0, Enum.GetValues(typeof(SubType)).Length); _Material = MaterialGenerator.Generate(false, true); _ArmorType = ArmorType.Neck; GenerateQuality(); GenerateProtectionValue(); GenerateDefensiveValue(); Weight = 0.05f; _WeightClass = WeightClass.Light; GenerateName(subType.ToString()); //GenerateDescription(isArtifact); } } }
32.372549
100
0.603876
[ "MIT" ]
Chizaruu/RLSKTD
Assets/Runtime/Scripts/General/Item/Categories/Armor/Subcategories/Neck.cs
1,651
C#
using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace AgileConfig.Server.Service { public class RegisterCenterService : IRegisterCenterService { private FreeSqlContext _dbContext; private ILogger<RegisterCenterService> _logger; public RegisterCenterService(FreeSqlContext freeSql, ILogger<RegisterCenterService> logger) { _dbContext = freeSql; _logger = logger; } public async Task<string> RegisterAsync(ServiceInfo serviceInfo) { if (serviceInfo == null) { throw new ArgumentNullException(nameof(serviceInfo)); } _logger.LogInformation("try to register service {0} {1}", serviceInfo.ServiceId, serviceInfo.ServiceName); //if exist var oldEntity = await _dbContext.ServiceInfo.Where(x=>x.ServiceId == serviceInfo.ServiceId).FirstAsync(); if (oldEntity != null) { oldEntity.RegisterTime = DateTime.Now; oldEntity.Alive = ServiceAlive.Online; oldEntity.LastHeartBeat = DateTime.Now; oldEntity.ServiceName = serviceInfo.ServiceName; oldEntity.Ip = serviceInfo.Ip; oldEntity.Port = serviceInfo.Port; oldEntity.MetaData = serviceInfo.MetaData; oldEntity.HeartBeatMode = serviceInfo.HeartBeatMode; oldEntity.CheckUrl = serviceInfo.CheckUrl; await _dbContext.ServiceInfo.UpdateAsync(oldEntity); var rows = await _dbContext.SaveChangesAsync(); _logger.LogInformation("registered service {0} {1} successful .", serviceInfo.ServiceId, serviceInfo.ServiceName); return oldEntity.Id; } serviceInfo.RegisterTime = DateTime.Now; serviceInfo.LastHeartBeat = DateTime.Now; serviceInfo.Alive = ServiceAlive.Online; serviceInfo.Id = Guid.NewGuid().ToString("n"); _dbContext.ServiceInfo.Add(serviceInfo); await _dbContext.SaveChangesAsync(); _logger.LogInformation("registered service {0} {1} successful .", serviceInfo.ServiceId, serviceInfo.ServiceName); return serviceInfo.Id; } public async Task<bool> UnRegisterAsync(string serviceUniqueId) { _logger.LogInformation("try to unregister service {0}", serviceUniqueId); if (string.IsNullOrEmpty(serviceUniqueId)) { throw new ArgumentNullException(nameof(serviceUniqueId)); } var oldEntity = await _dbContext.ServiceInfo.Where(x => x.Id == serviceUniqueId).FirstAsync(); if(oldEntity == null) { //if not exist _logger.LogInformation("not find the service {0} .", serviceUniqueId); return false; } _dbContext.ServiceInfo.Remove(oldEntity); await _dbContext.SaveChangesAsync(); _logger.LogInformation("unregister service {0} {1} successful .", oldEntity.ServiceId, oldEntity.ServiceName); return true; } public async Task<bool> ReceiveHeartbeatAsync(string serviceUniqueId) { var entity = await _dbContext.ServiceInfo.Where(x => x.Id == serviceUniqueId).FirstAsync(); if (entity == null) { return false; } _logger.LogInformation("receive service {0} {1} heartbeat .", entity.ServiceId, entity.ServiceName); if (entity.HeartBeatMode == "server") { //如果是server模式,则不作为服务是否在线的判断依据 } else { entity.Alive = ServiceAlive.Online; entity.LastHeartBeat = DateTime.Now; await _dbContext.UpdateAsync(entity); await _dbContext.SaveChangesAsync(); } return true; } } }
37.146552
130
0.595266
[ "MIT" ]
laolu/AgileConfig
AgileConfig.Server.Service/RegisterCenterService.cs
4,353
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Agent.AssetTransaction { public class AssetXferUploader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Upload state. /// </summary> /// <remarks> /// New -> Uploading -> Complete /// </remarks> private enum UploadState { New, Uploading, Complete } /// <summary> /// Reference to the object that holds this uploader. Used to remove ourselves from it's list if we /// are performing a delayed update. /// </summary> AgentAssetTransactions m_transactions; private UploadState m_uploadState = UploadState.New; private AssetBase m_asset; private UUID InventFolder = UUID.Zero; private sbyte invType = 0; private bool m_createItem; private uint m_createItemCallback; private bool m_updateItem; private InventoryItemBase m_updateItemData; private bool m_updateTaskItem; private TaskInventoryItem m_updateTaskItemData; private string m_description = String.Empty; private bool m_dumpAssetToFile; private string m_name = String.Empty; // private bool m_storeLocal; private uint nextPerm = 0; private IClientAPI ourClient; private UUID m_transactionID; private sbyte type = 0; private byte wearableType = 0; public ulong XferID; private Scene m_Scene; /// <summary> /// AssetXferUploader constructor /// </summary> /// <param name='transactions'>/param> /// <param name='scene'></param> /// <param name='transactionID'></param> /// <param name='dumpAssetToFile'> /// If true then when the asset is uploaded it is dumped to a file with the format /// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", /// now.Year, now.Month, now.Day, now.Hour, now.Minute, /// now.Second, m_asset.Name, m_asset.Type); /// for debugging purposes. /// </param> public AssetXferUploader( AgentAssetTransactions transactions, Scene scene, UUID transactionID, bool dumpAssetToFile) { m_asset = new AssetBase(); m_transactions = transactions; m_transactionID = transactionID; m_Scene = scene; m_dumpAssetToFile = dumpAssetToFile; } /// <summary> /// Process transfer data received from the client. /// </summary> /// <param name="xferID"></param> /// <param name="packetID"></param> /// <param name="data"></param> /// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns> public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Received packet {0} for xfer {1} (data length {2})", // packetID, xferID, data.Length); if (XferID == xferID) { if (m_asset.Data.Length > 1) { byte[] destinationArray = new byte[m_asset.Data.Length + data.Length]; Array.Copy(m_asset.Data, 0, destinationArray, 0, m_asset.Data.Length); Array.Copy(data, 0, destinationArray, m_asset.Data.Length, data.Length); m_asset.Data = destinationArray; } else { byte[] buffer2 = new byte[data.Length - 4]; Array.Copy(data, 4, buffer2, 0, data.Length - 4); m_asset.Data = buffer2; } ourClient.SendConfirmXfer(xferID, packetID); if ((packetID & 0x80000000) != 0) { SendCompleteMessage(); return true; } } return false; } /// <summary> /// Start asset transfer from the client /// </summary> /// <param name="remoteClient"></param> /// <param name="assetID"></param> /// <param name="transaction"></param> /// <param name="type"></param> /// <param name="data"> /// Optional data. If present then the asset is created immediately with this data /// rather than requesting an upload from the client. The data must be longer than 2 bytes. /// </param> /// <param name="storeLocal"></param> /// <param name="tempFile"></param> public void StartUpload( IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal, bool tempFile) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Initialised xfer from {0}, asset {1}, transaction {2}, type {3}, storeLocal {4}, tempFile {5}, already received data length {6}", // remoteClient.Name, assetID, transaction, type, storeLocal, tempFile, data.Length); lock (this) { if (m_uploadState != UploadState.New) { m_log.WarnFormat( "[ASSET XFER UPLOADER]: Tried to start upload of asset {0}, transaction {1} for {2} but this is already in state {3}. Aborting.", assetID, transaction, remoteClient.Name, m_uploadState); return; } m_uploadState = UploadState.Uploading; } ourClient = remoteClient; m_asset.FullID = assetID; m_asset.Type = type; m_asset.CreatorID = remoteClient.AgentId.ToString(); m_asset.Data = data; m_asset.Local = storeLocal; m_asset.Temporary = tempFile; // m_storeLocal = storeLocal; if (m_asset.Data.Length > 2) { SendCompleteMessage(); } else { RequestStartXfer(); } } protected void RequestStartXfer() { XferID = Util.GetNextXferID(); // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Requesting Xfer of asset {0}, type {1}, transfer id {2} from {3}", // m_asset.FullID, m_asset.Type, XferID, ourClient.Name); ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]); } protected void SendCompleteMessage() { // We must lock in order to avoid a race with a separate thread dealing with an inventory item or create // message from other client UDP. lock (this) { m_uploadState = UploadState.Complete; ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID); if (m_createItem) { CompleteCreateItem(m_createItemCallback); } else if (m_updateItem) { CompleteItemUpdate(m_updateItemData); } else if (m_updateTaskItem) { CompleteTaskItemUpdate(m_updateTaskItemData); } // else if (m_storeLocal) // { // m_Scene.AssetService.Store(m_asset); // } } m_log.DebugFormat( "[ASSET XFER UPLOADER]: Uploaded asset {0} for transaction {1}", m_asset.FullID, m_transactionID); if (m_dumpAssetToFile) { DateTime now = DateTime.Now; string filename = String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, m_asset.Name, m_asset.Type); SaveAssetToFile(filename, m_asset.Data); } } private void SaveAssetToFile(string filename, byte[] data) { string assetPath = "UserAssets"; if (!Directory.Exists(assetPath)) { Directory.CreateDirectory(assetPath); } FileStream fs = File.Create(Path.Combine(assetPath, filename)); BinaryWriter bw = new BinaryWriter(fs); bw.Write(data); bw.Close(); fs.Close(); } public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { InventFolder = folderID; m_name = name; m_description = description; this.type = type; this.invType = invType; this.wearableType = wearableType; nextPerm = nextOwnerMask; m_asset.Name = name; m_asset.Description = description; m_asset.Type = type; // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { if (m_uploadState == UploadState.Complete) { CompleteCreateItem(callbackID); } else { m_createItem = true; //set flag so the inventory item is created when upload is complete m_createItemCallback = callbackID; } } } public void RequestUpdateInventoryItem(IClientAPI remoteClient, InventoryItemBase item) { // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { m_asset.Name = item.Name; m_asset.Description = item.Description; m_asset.Type = (sbyte)item.AssetType; // We must always store the item at this point even if the asset hasn't finished uploading, in order // to avoid a race condition when the appearance module retrieves the item to set the asset id in // the AvatarAppearance structure. item.AssetID = m_asset.FullID; if (item.AssetID != UUID.Zero) m_Scene.InventoryService.UpdateItem(item); if (m_uploadState == UploadState.Complete) { CompleteItemUpdate(item); } else { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Holding update inventory item request {0} for {1} pending completion of asset xfer for transaction {2}", // item.Name, remoteClient.Name, transactionID); m_updateItem = true; m_updateItemData = item; } } } public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, TaskInventoryItem taskItem) { // We must lock to avoid a race with a separate thread uploading the asset. lock (this) { m_asset.Name = taskItem.Name; m_asset.Description = taskItem.Description; m_asset.Type = (sbyte)taskItem.Type; taskItem.AssetID = m_asset.FullID; if (m_uploadState == UploadState.Complete) { CompleteTaskItemUpdate(taskItem); } else { m_updateTaskItem = true; m_updateTaskItemData = taskItem; } } } /// <summary> /// Store the asset for the given item when it has been uploaded. /// </summary> /// <param name="item"></param> private void CompleteItemUpdate(InventoryItemBase item) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}", // m_asset.FullID, item.Name, ourClient.Name); m_Scene.AssetService.Store(m_asset); m_transactions.RemoveXferUploader(m_transactionID); m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(ourClient.AgentId, (AssetType)type, m_asset.FullID, m_asset.Name, 0); } /// <summary> /// Store the asset for the given task item when it has been uploaded. /// </summary> /// <param name="taskItem"></param> private void CompleteTaskItemUpdate(TaskInventoryItem taskItem) { // m_log.DebugFormat( // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}", // m_asset.FullID, taskItem.Name, ourClient.Name); m_Scene.AssetService.Store(m_asset); m_transactions.RemoveXferUploader(m_transactionID); } private void CompleteCreateItem(uint callbackID) { m_Scene.AssetService.Store(m_asset); InventoryItemBase item = new InventoryItemBase(); item.Owner = ourClient.AgentId; item.CreatorId = ourClient.AgentId.ToString(); item.ID = UUID.Random(); item.AssetID = m_asset.FullID; item.Description = m_description; item.Name = m_name; item.AssetType = type; item.InvType = invType; item.Folder = InventFolder; item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export); item.CurrentPermissions = item.BasePermissions; item.GroupPermissions=0; item.EveryOnePermissions=0; item.NextPermissions = nextPerm; item.Flags = (uint) wearableType; item.CreationDate = Util.UnixTimeSinceEpoch(); if (m_Scene.AddInventoryItem(item)) ourClient.SendInventoryItemCreateUpdate(item, callbackID); else ourClient.SendAlertMessage("Unable to create inventory item"); m_transactions.RemoveXferUploader(m_transactionID); } } }
38.381395
171
0.564227
[ "BSD-3-Clause" ]
BlueWall/opensim
OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
16,504
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MAVN.Common.Encryption; using MAVN.Persistence.PostgreSQL.Legacy; using MAVN.Service.CustomerProfile.Domain.Enums; using MAVN.Service.CustomerProfile.Domain.Models; using MAVN.Service.CustomerProfile.Domain.Repositories; using MAVN.Service.CustomerProfile.MsSqlRepositories.Entities; using Microsoft.EntityFrameworkCore; namespace MAVN.Service.CustomerProfile.MsSqlRepositories.Repositories { public class ReferralLeadProfileRepository : IReferralLeadProfileRepository { private readonly PostgreSQLContextFactory<CustomerProfileContext> _contextFactory; private readonly IEncryptionService _encryptionService; public ReferralLeadProfileRepository( PostgreSQLContextFactory<CustomerProfileContext> contextFactory, IEncryptionService encryptionService) { _contextFactory = contextFactory; _encryptionService = encryptionService; } public async Task<IReadOnlyList<ReferralLeadProfile>> GetAllAsync() { using (var context = _contextFactory.CreateDataContext()) { var entities = await context.ReferralLeadProfiles.ToListAsync(); return entities .Select(o => ToDomain(_encryptionService.Decrypt(o))) .ToList(); } } public async Task<ReferralLeadProfile> GetByIdAsync(Guid referralLeadId) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.ReferralLeadProfiles.FindAsync(referralLeadId); return entity != null ? ToDomain(_encryptionService.Decrypt(entity)) : null; } } public async Task<ReferralLeadProfileErrorCodes> InsertAsync(ReferralLeadProfile referralLeadProfile) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.ReferralLeadProfiles.FindAsync(referralLeadProfile.ReferralLeadId); if (entity != null) return ReferralLeadProfileErrorCodes.ReferralLeadProfileAlreadyExists; entity = new ReferralLeadProfileEntity(referralLeadProfile); entity = _encryptionService.Encrypt(entity); context.ReferralLeadProfiles.Add(entity); await context.SaveChangesAsync(); } return ReferralLeadProfileErrorCodes.None; } public async Task<ReferralLeadProfileErrorCodes> UpdateAsync(ReferralLeadProfile referralLeadProfile) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.ReferralLeadProfiles.FindAsync(referralLeadProfile.ReferralLeadId); if (entity == null) return ReferralLeadProfileErrorCodes.ReferralLeadProfileDoesNotExist; _encryptionService.Decrypt(entity); entity.Update(referralLeadProfile); _encryptionService.Encrypt(entity); await context.SaveChangesAsync(); } return ReferralLeadProfileErrorCodes.None; } public async Task DeleteAsync(Guid referralLeadId) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.ReferralLeadProfiles.FindAsync(referralLeadId); if (entity == null) return; using (var transaction = context.Database.BeginTransaction()) { var archiveEntity = new ReferralLeadProfileArchiveEntity(entity); context.ReferralLeadProfilesArchive.Add(archiveEntity); context.ReferralLeadProfiles.Remove(entity); await context.SaveChangesAsync(); transaction.Commit(); } } } private static ReferralLeadProfile ToDomain(ReferralLeadProfileEntity entity) => new ReferralLeadProfile { ReferralLeadId = entity.ReferralLeadId, FirstName = entity.FirstName, LastName = entity.LastName, PhoneNumber = entity.PhoneNumber, Email = entity.Email, Note = entity.Note }; } }
35.507813
110
0.632343
[ "MIT" ]
OpenMAVN/MAVN.Service.CustomerProfile
src/MAVN.Service.CustomerProfile.MsSqlRepositories/Repositories/ReferralLeadProfileRepository.cs
4,547
C#
using UnityEngine; using System.Collections; namespace EasyMobile { // List of all supported ad networks public enum AdNetwork { None, AdColony, AdMob, AppLovin, AudienceNetwork, Chartboost, FairBid, IronSource, MoPub, TapJoy, UnityAds, } public enum BannerAdNetwork { None = AdNetwork.None, AdColony = AdNetwork.AdColony, AdMob = AdNetwork.AdMob, AppLovin = AdNetwork.AppLovin, AudienceNetwork = AdNetwork.AudienceNetwork, FairBid = AdNetwork.FairBid, IronSource = AdNetwork.IronSource, MoPub = AdNetwork.MoPub, UnityAds = AdNetwork.UnityAds } public enum InterstitialAdNetwork { None = AdNetwork.None, AdColony = AdNetwork.AdColony, AdMob = AdNetwork.AdMob, AppLovin = AdNetwork.AppLovin, AudienceNetwork = AdNetwork.AudienceNetwork, Chartboost = AdNetwork.Chartboost, FairBid = AdNetwork.FairBid, IronSource = AdNetwork.IronSource, MoPub = AdNetwork.MoPub, TapJoy = AdNetwork.TapJoy, UnityAds = AdNetwork.UnityAds, } public enum RewardedAdNetwork { None = AdNetwork.None, AdColony = AdNetwork.AdColony, AdMob = AdNetwork.AdMob, AppLovin = AdNetwork.AppLovin, AudienceNetwork = AdNetwork.AudienceNetwork, Chartboost = AdNetwork.Chartboost, FairBid = AdNetwork.FairBid, IronSource = AdNetwork.IronSource, MoPub = AdNetwork.MoPub, TapJoy = AdNetwork.TapJoy, UnityAds = AdNetwork.UnityAds, } }
26.328125
52
0.614837
[ "MIT" ]
AndreeBurlamaqui/HyperBeatMIX
Assets/EasyMobile/Scripts/Modules/Advertising/AdNetwork.cs
1,687
C#
#pragma checksum "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "cc5af23e61cd5d6102661dfcb82e4622566cc5e2" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(ContosoUniversity.Pages.Students.Pages_Students_Create), @"mvc.1.0.razor-page", @"/Pages/Students/Create.cshtml")] namespace ContosoUniversity.Pages.Students { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\_ViewImports.cshtml" using ContosoUniversity; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cc5af23e61cd5d6102661dfcb82e4622566cc5e2", @"/Pages/Students/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c4c0473ebe7d620ab1ae06d83bc5bc87bf314407", @"/Pages/_ViewImports.cshtml")] public class Pages_Students_Create : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 4 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" ViewData["Title"] = "Create"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Create</h1>\r\n\r\n<h4>Student</h4>\r\n<hr />\r\n<div class=\"row\">\r\n <div class=\"col-md-4\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e25821", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e26091", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #nullable restore #line 15 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e27826", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 17 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.LastName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "cc5af23e61cd5d6102661dfcb82e4622566cc5e29440", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 18 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.LastName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e211048", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 19 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.LastName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e212797", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 22 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.FirstMidName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "cc5af23e61cd5d6102661dfcb82e4622566cc5e214416", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 23 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.FirstMidName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e216029", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 24 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.FirstMidName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e217782", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 27 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.EnrollmentDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "cc5af23e61cd5d6102661dfcb82e4622566cc5e219403", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 28 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.EnrollmentDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e221018", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 29 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Student.EnrollmentDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Create\" class=\"btn btn-primary\" />\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n</div>\r\n\r\n<div>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "cc5af23e61cd5d6102661dfcb82e4622566cc5e224089", async() => { WriteLiteral("Back to List"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>\r\n\r\n"); DefineSection("Scripts", async() => { WriteLiteral("\r\n"); #nullable restore #line 43 "D:\C#Projects\Algorithms\ContosoUniversity\ContosoUniversity\Pages\Students\Create.cshtml" await Html.RenderPartialAsync("_ValidationScriptsPartial"); #line default #line hidden #nullable disable } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ContosoUniversity.Pages.Students.CreateModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ContosoUniversity.Pages.Students.CreateModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ContosoUniversity.Pages.Students.CreateModel>)PageContext?.ViewData; public ContosoUniversity.Pages.Students.CreateModel Model => ViewData.Model; } } #pragma warning restore 1591
75.382436
351
0.74254
[ "MIT" ]
BaseDorp/AspRazorPagesEfCore
ContosoUniversity/ContosoUniversity/obj/Debug/netcoreapp3.0/Razor/Pages/Students/Create.cshtml.g.cs
26,610
C#
namespace OAuth.Core.Signing { public interface ISignatureGenerator { string SignatureMethod { get; } string Generate(string secret, string signatureBase); } }
23.375
61
0.684492
[ "MIT" ]
YvanSuen/oauth-mvc.net
Core/OAuth.Core/Signing/ISignatureGenerator.cs
187
C#
using System; namespace Serenity.ComponentModel { /// <summary> /// Sets filtering type as "Date" /// </summary> /// <seealso cref="Serenity.ComponentModel.CustomFilteringAttribute" /> public class DateFilteringAttribute : CustomFilteringAttribute { /// <summary>Initializes a new instance of the <see cref="DateFilteringAttribute"/> class.</summary> public DateFilteringAttribute() : base("Date") { } /// <summary> /// Gets or sets the display format. /// </summary> /// <value> /// The display format. /// </value> public String DisplayFormat { get { return GetOption<String>("displayFormat"); } set { SetOption("displayFormat", value); } } } }
29.137931
109
0.547929
[ "MIT" ]
CitysoftInfotech/Serenity
Serenity.Core/ComponentModel/Columns/Filtering/BasicFilteringTypes/DateFilteringAttribute.cs
847
C#
using System; using System.Collections.Generic; namespace RSB.Transports.RabbitMQ { public class QueueInfo { public QueueInfo(string queueName) { Name = queueName; Durable = false; Exclusive = false; AutoDelete = true; Arguments = new Dictionary<string, object>(); } public QueueInfo() : this(Environment.MachineName + "-" + Guid.NewGuid()) { } public string Name { get; set; } public bool Durable { get; set; } public bool Exclusive { get; set; } public bool AutoDelete { get; set; } public IDictionary<string, object> Arguments { get; set; } } }
26.481481
66
0.558042
[ "BSD-3-Clause" ]
tomaszkiewicz/rsb
RSB.Transports.RabbitMQ/QueueInfo.cs
717
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Xml.Linq; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; using Microsoft.AspNetCore.DataProtection.Internal; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Win32; using Xunit; namespace Microsoft.AspNetCore.DataProtection { public class RegistryPolicyResolverTests { [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_NoEntries_ResultsInNoPolicies() { // Arrange var registryEntries = new Dictionary<string, object>(); // Act var context = RunTestWithRegValues(registryEntries); // Assert Assert.Null(context.EncryptorConfiguration); Assert.Null(context.DefaultKeyLifetime); Assert.Empty(context.KeyEscrowSinks); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_KeyEscrowSinks() { // Arrange var registryEntries = new Dictionary<string, object>() { ["KeyEscrowSinks"] = String.Join( " ;; ; ", new Type[] { typeof(MyKeyEscrowSink1), typeof(MyKeyEscrowSink2) }.Select( t => t.AssemblyQualifiedName ) ) }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualKeyEscrowSinks = context.KeyEscrowSinks.ToArray(); Assert.Equal(2, actualKeyEscrowSinks.Length); Assert.IsType<MyKeyEscrowSink1>(actualKeyEscrowSinks[0]); Assert.IsType<MyKeyEscrowSink2>(actualKeyEscrowSinks[1]); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_DefaultKeyLifetime() { // Arrange var registryEntries = new Dictionary<string, object>() { ["DefaultKeyLifetime"] = 1024 // days }; // Act var context = RunTestWithRegValues(registryEntries); // Assert Assert.Equal(1024, context.DefaultKeyLifetime); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngCbcEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-cbc" }; var expectedConfiguration = new CngCbcAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngCbcAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider ); Assert.Equal(expectedConfiguration.HashAlgorithm, actualConfiguration.HashAlgorithm); Assert.Equal( expectedConfiguration.HashAlgorithmProvider, actualConfiguration.HashAlgorithmProvider ); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngCbcEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-cbc", ["EncryptionAlgorithm"] = "enc-alg", ["EncryptionAlgorithmKeySize"] = 2048, ["EncryptionAlgorithmProvider"] = "my-enc-alg-provider", ["HashAlgorithm"] = "hash-alg", ["HashAlgorithmProvider"] = "my-hash-alg-provider" }; var expectedConfiguration = new CngCbcAuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = "enc-alg", EncryptionAlgorithmKeySize = 2048, EncryptionAlgorithmProvider = "my-enc-alg-provider", HashAlgorithm = "hash-alg", HashAlgorithmProvider = "my-hash-alg-provider" }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngCbcAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider ); Assert.Equal(expectedConfiguration.HashAlgorithm, actualConfiguration.HashAlgorithm); Assert.Equal( expectedConfiguration.HashAlgorithmProvider, actualConfiguration.HashAlgorithmProvider ); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngGcmEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-gcm" }; var expectedConfiguration = new CngGcmAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngGcmAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider ); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_CngGcmEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "cng-gcm", ["EncryptionAlgorithm"] = "enc-alg", ["EncryptionAlgorithmKeySize"] = 2048, ["EncryptionAlgorithmProvider"] = "my-enc-alg-provider" }; var expectedConfiguration = new CngGcmAuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = "enc-alg", EncryptionAlgorithmKeySize = 2048, EncryptionAlgorithmProvider = "my-enc-alg-provider" }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (CngGcmAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithm, actualConfiguration.EncryptionAlgorithm ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmProvider, actualConfiguration.EncryptionAlgorithmProvider ); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_ManagedEncryption_WithoutExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "managed" }; var expectedConfiguration = new ManagedAuthenticatedEncryptorConfiguration(); // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (ManagedAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithmType, actualConfiguration.EncryptionAlgorithmType ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.ValidationAlgorithmType, actualConfiguration.ValidationAlgorithmType ); } [ConditionalFact] [ConditionalRunTestOnlyIfHkcuRegistryAvailable] public void ResolvePolicy_ManagedEncryption_WithExplicitSettings() { // Arrange var registryEntries = new Dictionary<string, object>() { ["EncryptionType"] = "managed", ["EncryptionAlgorithmType"] = typeof(TripleDES).AssemblyQualifiedName, ["EncryptionAlgorithmKeySize"] = 2048, ["ValidationAlgorithmType"] = typeof(HMACSHA1).AssemblyQualifiedName }; var expectedConfiguration = new ManagedAuthenticatedEncryptorConfiguration() { EncryptionAlgorithmType = typeof(TripleDES), EncryptionAlgorithmKeySize = 2048, ValidationAlgorithmType = typeof(HMACSHA1) }; // Act var context = RunTestWithRegValues(registryEntries); // Assert var actualConfiguration = (ManagedAuthenticatedEncryptorConfiguration)context.EncryptorConfiguration; Assert.Equal( expectedConfiguration.EncryptionAlgorithmType, actualConfiguration.EncryptionAlgorithmType ); Assert.Equal( expectedConfiguration.EncryptionAlgorithmKeySize, actualConfiguration.EncryptionAlgorithmKeySize ); Assert.Equal( expectedConfiguration.ValidationAlgorithmType, actualConfiguration.ValidationAlgorithmType ); } private static RegistryPolicy RunTestWithRegValues(Dictionary<string, object> regValues) { return WithUniqueTempRegKey( registryKey => { foreach (var entry in regValues) { registryKey.SetValue(entry.Key, entry.Value); } var policyResolver = new RegistryPolicyResolver( registryKey, activator: SimpleActivator.DefaultWithoutServices ); return policyResolver.ResolvePolicy(); } ); } /// <summary> /// Runs a test and cleans up the registry key afterward. /// </summary> private static RegistryPolicy WithUniqueTempRegKey( Func<RegistryKey, RegistryPolicy> testCode ) { string uniqueName = Guid.NewGuid().ToString(); var uniqueSubkey = LazyHkcuTempKey.Value.CreateSubKey(uniqueName); try { return testCode(uniqueSubkey); } finally { // clean up when test is done LazyHkcuTempKey.Value.DeleteSubKeyTree(uniqueName, throwOnMissingSubKey: false); } } private static readonly Lazy<RegistryKey> LazyHkcuTempKey = new Lazy<RegistryKey>( () => { try { return Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\ASP.NET\temp"); } catch { // swallow all failures return null; } } ); private class ConditionalRunTestOnlyIfHkcuRegistryAvailable : Attribute, ITestCondition { public bool IsMet => ( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && LazyHkcuTempKey.Value != null ); public string SkipReason { get; } = "HKCU registry couldn't be opened."; } private class MyKeyEscrowSink1 : IKeyEscrowSink { public void Store(Guid keyId, XElement element) { throw new NotImplementedException(); } } private class MyKeyEscrowSink2 : IKeyEscrowSink { public void Store(Guid keyId, XElement element) { throw new NotImplementedException(); } } } }
36.38539
111
0.587124
[ "Apache-2.0" ]
belav/aspnetcore
src/DataProtection/DataProtection/test/RegistryPolicyResolverTests.cs
14,445
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/oleidl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; namespace TerraFX.Interop { public static partial class Windows { [NativeTypeName("#define UPDFCACHE_NODATACACHE ( 0x1 )")] public const int UPDFCACHE_NODATACACHE = (0x1); [NativeTypeName("#define UPDFCACHE_ONSAVECACHE ( 0x2 )")] public const int UPDFCACHE_ONSAVECACHE = (0x2); [NativeTypeName("#define UPDFCACHE_ONSTOPCACHE ( 0x4 )")] public const int UPDFCACHE_ONSTOPCACHE = (0x4); [NativeTypeName("#define UPDFCACHE_NORMALCACHE ( 0x8 )")] public const int UPDFCACHE_NORMALCACHE = (0x8); [NativeTypeName("#define UPDFCACHE_IFBLANK ( 0x10 )")] public const int UPDFCACHE_IFBLANK = (0x10); [NativeTypeName("#define UPDFCACHE_ONLYIFBLANK ( 0x80000000 )")] public const uint UPDFCACHE_ONLYIFBLANK = (0x80000000); [NativeTypeName("#define UPDFCACHE_IFBLANKORONSAVECACHE ( ( UPDFCACHE_IFBLANK | UPDFCACHE_ONSAVECACHE ) )")] public const int UPDFCACHE_IFBLANKORONSAVECACHE = (((0x10) | (0x2))); [NativeTypeName("#define UPDFCACHE_ALL ( ( DWORD )~UPDFCACHE_ONLYIFBLANK )")] public const uint UPDFCACHE_ALL = ((uint)(~(0x80000000))); [NativeTypeName("#define UPDFCACHE_ALLBUTNODATACACHE ( ( UPDFCACHE_ALL & ( DWORD )~UPDFCACHE_NODATACACHE ) )")] public const uint UPDFCACHE_ALLBUTNODATACACHE = ((((uint)(~(0x80000000))) & (uint)(~(0x1u)))); [NativeTypeName("#define MK_ALT ( 0x20 )")] public const int MK_ALT = (0x20); [NativeTypeName("#define DROPEFFECT_NONE ( 0 )")] public const int DROPEFFECT_NONE = (0); [NativeTypeName("#define DROPEFFECT_COPY ( 1 )")] public const int DROPEFFECT_COPY = (1); [NativeTypeName("#define DROPEFFECT_MOVE ( 2 )")] public const int DROPEFFECT_MOVE = (2); [NativeTypeName("#define DROPEFFECT_LINK ( 4 )")] public const int DROPEFFECT_LINK = (4); [NativeTypeName("#define DROPEFFECT_SCROLL ( 0x80000000 )")] public const uint DROPEFFECT_SCROLL = (0x80000000); [NativeTypeName("#define DD_DEFSCROLLINSET ( 11 )")] public const int DD_DEFSCROLLINSET = (11); [NativeTypeName("#define DD_DEFSCROLLDELAY ( 50 )")] public const int DD_DEFSCROLLDELAY = (50); [NativeTypeName("#define DD_DEFSCROLLINTERVAL ( 50 )")] public const int DD_DEFSCROLLINTERVAL = (50); [NativeTypeName("#define DD_DEFDRAGDELAY ( 200 )")] public const int DD_DEFDRAGDELAY = (200); [NativeTypeName("#define DD_DEFDRAGMINDIST ( 2 )")] public const int DD_DEFDRAGMINDIST = (2); [NativeTypeName("#define CFSTR_ENTERPRISE_ID (TEXT(\"EnterpriseDataProtectionId\"))")] public const string CFSTR_ENTERPRISE_ID = ("EnterpriseDataProtectionId"); public static readonly Guid IID_IOleAdviseHolder = new Guid(0x00000111, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleCache = new Guid(0x0000011E, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleCache2 = new Guid(0x00000128, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleCacheControl = new Guid(0x00000129, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IParseDisplayName = new Guid(0x0000011A, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleContainer = new Guid(0x0000011B, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleClientSite = new Guid(0x00000118, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleObject = new Guid(0x00000112, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleWindow = new Guid(0x00000114, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleLink = new Guid(0x0000011D, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleItemContainer = new Guid(0x0000011C, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleInPlaceUIWindow = new Guid(0x00000115, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleInPlaceActiveObject = new Guid(0x00000117, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleInPlaceFrame = new Guid(0x00000116, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleInPlaceObject = new Guid(0x00000113, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IOleInPlaceSite = new Guid(0x00000119, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IContinue = new Guid(0x0000012A, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IViewObject = new Guid(0x0000010D, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IViewObject2 = new Guid(0x00000127, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IDropSource = new Guid(0x00000121, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IDropTarget = new Guid(0x00000122, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IDropSourceNotify = new Guid(0x0000012B, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); public static readonly Guid IID_IEnterpriseDropTarget = new Guid(0x390E3878, 0xFD55, 0x4E18, 0x81, 0x9D, 0x46, 0x82, 0x08, 0x1C, 0x0C, 0xFD); public static readonly Guid IID_IEnumOLEVERB = new Guid(0x00000104, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); } }
52.887097
151
0.693047
[ "MIT" ]
manju-summoner/terrafx.interop.windows
sources/Interop/Windows/um/oleidl/Windows.cs
6,560
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Compiler { /// <summary> /// Representa el tipo de un símbolo de la gramática. /// </summary> public abstract class GramSymType { public abstract string Name { get; } public (GramSymType, TokenType, UntType, TokenType) this[UntType expr] { get => (this, new TokenType(Token.TypeEnum.LBracket), expr, new TokenType(Token.TypeEnum.RBracket)); } public static (GramSymType, TokenType, GramSymType) operator |(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.Pipe), other); } public static (GramSymType, TokenType, GramSymType) operator +(GramSymType @this, GramSymType other) { return (@this, TokenType.Plus, other); } public static (GramSymType, TokenType, GramSymType) operator -(GramSymType @this, GramSymType other) { return (@this, TokenType.Minus, other); } public static (GramSymType, TokenType, GramSymType) operator *(GramSymType @this, GramSymType other) { return (@this, TokenType.Times, other); } public static (GramSymType, TokenType, GramSymType) operator /(GramSymType @this, GramSymType other) { return (@this, TokenType.Div, other); } public static (GramSymType, TokenType, GramSymType) operator %(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.Percent), other); } public static (GramSymType, TokenType, GramSymType) operator >(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.GreaterThan), other); } public static (GramSymType, TokenType, GramSymType) operator <(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.LowerThan), other); } public static (GramSymType, TokenType, GramSymType) operator ==(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.EqEq), other); } public static (GramSymType, TokenType, GramSymType) operator !=(GramSymType @this, GramSymType other) { return (@this, new TokenType(Token.TypeEnum.NotEq), other); } public override bool Equals(object obj) { return obj is GramSymType other && this.Name == other.Name; } public override int GetHashCode() { return this.Name.GetHashCode(); } } }
40.476923
112
0.646142
[ "MIT" ]
CSProjectsAvatar/SimCopIA
Gos/Compiler/GramSymType.cs
2,635
C#
using System; namespace EmployeeVacationCalendar.Domain.Model { /// <summary> /// Calendar day domain model. /// </summary> public class CalendarDay { /// <summary> /// Calendar day date. /// </summary> public DateTime Date { get; set; } /// <summary> /// Calendar day year. /// </summary> public int Year { get; set; } /// <summary> /// Calendar day quarter of year. /// </summary> public int Quarter { get; set; } /// <summary> /// Calendar day month of year. /// </summary> public int Month { get; set; } /// <summary> /// Calendar day week of year. /// </summary> public int Week { get; set; } /// <summary> /// Calendar day of month. /// </summary> public int Day { get; set; } /// <summary> /// Calendar day of year. /// </summary> public int DayOfYear { get; set; } /// <summary> /// Calendar day of week. /// </summary> public int DayOfWeek { get; set; } /// <summary> /// Calendar week of month. /// </summary> public int WeekOfMonth { get; set; } /// <summary> /// Is calendar day holiday. /// </summary> public bool IsHoliday { get; set; } /// <summary> /// Holiday name /// </summary> public string Description { get; set; } } }
18.893939
47
0.574178
[ "MIT" ]
Azloukyassin/EmployeeVacationCalendar-master
EmployeeVacationCalendar.Domain/Model/CalendarDay.cs
1,249
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200301 { public static class GetExpressRouteCircuitAuthorization { /// <summary> /// Authorization in an ExpressRouteCircuit resource. /// </summary> public static Task<GetExpressRouteCircuitAuthorizationResult> InvokeAsync(GetExpressRouteCircuitAuthorizationArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetExpressRouteCircuitAuthorizationResult>("azure-native:network/v20200301:getExpressRouteCircuitAuthorization", args ?? new GetExpressRouteCircuitAuthorizationArgs(), options.WithVersion()); } public sealed class GetExpressRouteCircuitAuthorizationArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the authorization. /// </summary> [Input("authorizationName", required: true)] public string AuthorizationName { get; set; } = null!; /// <summary> /// The name of the express route circuit. /// </summary> [Input("circuitName", required: true)] public string CircuitName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetExpressRouteCircuitAuthorizationArgs() { } } [OutputType] public sealed class GetExpressRouteCircuitAuthorizationResult { /// <summary> /// The authorization key. /// </summary> public readonly string? AuthorizationKey; /// <summary> /// The authorization use status. /// </summary> public readonly string? AuthorizationUseStatus; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> public readonly string? Name; /// <summary> /// The provisioning state of the authorization resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private GetExpressRouteCircuitAuthorizationResult( string? authorizationKey, string? authorizationUseStatus, string etag, string? id, string? name, string provisioningState, string type) { AuthorizationKey = authorizationKey; AuthorizationUseStatus = authorizationUseStatus; Etag = etag; Id = id; Name = name; ProvisioningState = provisioningState; Type = type; } } }
32.433962
245
0.615183
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200301/GetExpressRouteCircuitAuthorization.cs
3,438
C#
/********************************************************************************************************************** FocusOPEN Digital Asset Manager (TM) (c) Daydream Interactive Limited 1995-2011, All Rights Reserved The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. Please refer to licences/focusopen.txt or http://www.digitalassetmanager.com for licensing information about this software. **********************************************************************************************************************/ using Daydream.Data; namespace FocusOPEN.Data { public partial class BrandMetadataSettingFinder { protected void SetCustomSearchCriteria (ref SearchBuilder sb) { // Put custom search criteria here } } }
37.384615
119
0.599794
[ "MIT" ]
MatfRS2/SeminarskiRadovi
programski-projekti/Matf-RS2-FocusOpen/FocusOPEN_OS_Source_3_3_9_5/FocusOPEN.Data/Finders/BrandMetadataSettingFinder.cs
972
C#
using System; using QS.Services; using QS.DomainModel.Entity.EntityPermissions; namespace QS.Permissions { public class DefaultAllowedPermissionService : IPermissionService, ICurrentPermissionService { public IPermissionResult ValidateEntityPermission(Type entityType) { return new PermissionResult(EntityPermission.AllAllowed); } public bool ValidatePresetPermission(string permissionName) { return true; } public IPermissionResult ValidateUserPermission(Type entityType, int userId) { return new PermissionResult(EntityPermission.AllAllowed); } public bool ValidateUserPresetPermission(string permissionName, int userId) { return true; } } }
23.689655
93
0.79476
[ "Apache-2.0" ]
Art8m/QSProjects
QS.Project/Permissions/DefaultAllowedPermissionService.cs
689
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes an EC2 Fleet error. /// </summary> public partial class DeleteFleetError { private DeleteFleetErrorCode _code; private string _message; /// <summary> /// Gets and sets the property Code. /// <para> /// The error code. /// </para> /// </summary> public DeleteFleetErrorCode Code { get { return this._code; } set { this._code = value; } } // Check to see if Code property is set internal bool IsSetCode() { return this._code != null; } /// <summary> /// Gets and sets the property Message. /// <para> /// The description for the error code. /// </para> /// </summary> public string Message { get { return this._message; } set { this._message = value; } } // Check to see if Message property is set internal bool IsSetMessage() { return this._message != null; } } }
27.605263
102
0.577693
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/DeleteFleetError.cs
2,098
C#
namespace MailCheck.AggregateReport.Parser.Parser { public class ContentType { public const string TextXml = "text/xml"; public const string TextPlain = "text/plain"; public const string ApplicationGzip = "application/gzip"; public const string ApplicationZip = "application/zip"; public const string ApplicationXZipCompressed = "application/x-zip-compressed"; public const string ApplicationOctetStream = "application/octet-stream"; } }
38.384615
87
0.707415
[ "Apache-2.0" ]
ukncsc/MailCheck.Public.AggregateReport
src/MailCheck.AggregateReport.Parser/Parser/ContentType.cs
501
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Taskbar.cs" company="WildGums"> // Copyright (c) 2008 - 2014 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orchestra.Windows { using System; using System.Drawing; using System.Runtime.InteropServices; public enum TaskbarPosition { Unknown = -1, Left, Top, Right, Bottom, } /// <summary> /// Class Taskbar. This class cannot be inherited. /// </summary> /// <remarks> /// This code comes from http://winsharp93.wordpress.com/2009/06/29/find-out-size-and-position-of-the-taskbar/. /// </remarks> public sealed class Taskbar { #region Constants private const string ClassName = "Shell_TrayWnd"; #endregion #region Constructors public Taskbar() { var taskbarHandle = User32.FindWindow(Taskbar.ClassName, null); var data = APPBARDATA.NewAPPBARDATA(); data.hWnd = taskbarHandle; var result = Shell32.SHAppBarMessage(ABM.GetTaskbarPos, ref data); if (result == IntPtr.Zero) { throw new InvalidOperationException(); } Position = (TaskbarPosition) data.uEdge; Bounds = Rectangle.FromLTRB(data.rc.left, data.rc.top, data.rc.right, data.rc.bottom); result = Shell32.SHAppBarMessage(ABM.GetState, ref data); int state = result.ToInt32(); AlwaysOnTop = (state & ABS.AlwaysOnTop) == ABS.AlwaysOnTop; AutoHide = (state & ABS.Autohide) == ABS.Autohide; } #endregion #region Properties public Rectangle Bounds { get; private set; } public TaskbarPosition Position { get; private set; } public Point Location { get { return Bounds.Location; } } public Size Size { get { return Bounds.Size; } } //Always returns false under Windows 7 public bool AlwaysOnTop { get; private set; } public bool AutoHide { get; private set; } #endregion } internal enum ABM : uint { New = 0x00000000, Remove = 0x00000001, QueryPos = 0x00000002, SetPos = 0x00000003, GetState = 0x00000004, GetTaskbarPos = 0x00000005, Activate = 0x00000006, GetAutoHideBar = 0x00000007, SetAutoHideBar = 0x00000008, WindowPosChanged = 0x00000009, SetState = 0x0000000A, } internal enum ABE : uint { Left = 0, Top = 1, Right = 2, Bottom = 3 } internal static class ABS { #region Constants public const int Autohide = 0x0000001; public const int AlwaysOnTop = 0x0000002; #endregion } internal static class Shell32 { #region Methods [DllImport("shell32.dll", SetLastError = true)] internal static extern IntPtr SHAppBarMessage(ABM dwMessage, [In] ref APPBARDATA pData); #endregion } internal static class User32 { #region Methods [DllImport("user32.dll", SetLastError = true)] internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName); #endregion } [StructLayout(LayoutKind.Sequential)] internal struct APPBARDATA { public static APPBARDATA NewAPPBARDATA() { var abd = new APPBARDATA(); abd.cbSize = Marshal.SizeOf(typeof(APPBARDATA)); return abd; } #region Fields public int cbSize; public IntPtr hWnd; public uint uCallbackMessage; public ABE uEdge; public RECT rc; public int lParam; #endregion } [StructLayout(LayoutKind.Sequential)] internal struct RECT { #region Fields public int left; public int top; public int right; public int bottom; #endregion } }
27.326923
120
0.544921
[ "MIT" ]
Dmitry-VF/Orchestra
src/Orchestra.Core/Windows/Taskbar.cs
4,265
C#
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ApplicationWithRazorSdkUsed { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddLogging(loggingBuilder => loggingBuilder.AddConsole()); // Add framework services. services.AddMvc(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.UseMvcWithDefaultRoute(); } } }
26.636364
84
0.674061
[ "Apache-2.0" ]
akrisiun/AspNetCore
src/Mvc/ViewCompilation/testassets/ApplicationWithRazorSdkUsed/Startup.cs
588
C#
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalRis { /// <summary> /// Strongly-typed collection for the TupTurnosProtegido class. /// </summary> [Serializable] public partial class TupTurnosProtegidoCollection : ActiveList<TupTurnosProtegido, TupTurnosProtegidoCollection> { public TupTurnosProtegidoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>TupTurnosProtegidoCollection</returns> public TupTurnosProtegidoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { TupTurnosProtegido o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the TUP_TurnosProtegidos table. /// </summary> [Serializable] public partial class TupTurnosProtegido : ActiveRecord<TupTurnosProtegido>, IActiveRecord { #region .ctors and Default Settings public TupTurnosProtegido() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public TupTurnosProtegido(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public TupTurnosProtegido(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public TupTurnosProtegido(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("TUP_TurnosProtegidos", TableType.Table, DataService.GetInstance("RisProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTurnoSubsecretaria = new TableSchema.TableColumn(schema); colvarIdTurnoSubsecretaria.ColumnName = "idTurnoSubsecretaria"; colvarIdTurnoSubsecretaria.DataType = DbType.Int32; colvarIdTurnoSubsecretaria.MaxLength = 0; colvarIdTurnoSubsecretaria.AutoIncrement = true; colvarIdTurnoSubsecretaria.IsNullable = false; colvarIdTurnoSubsecretaria.IsPrimaryKey = true; colvarIdTurnoSubsecretaria.IsForeignKey = false; colvarIdTurnoSubsecretaria.IsReadOnly = false; colvarIdTurnoSubsecretaria.DefaultSetting = @""; colvarIdTurnoSubsecretaria.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTurnoSubsecretaria); TableSchema.TableColumn colvarIdInterconsulta = new TableSchema.TableColumn(schema); colvarIdInterconsulta.ColumnName = "idInterconsulta"; colvarIdInterconsulta.DataType = DbType.Int32; colvarIdInterconsulta.MaxLength = 0; colvarIdInterconsulta.AutoIncrement = false; colvarIdInterconsulta.IsNullable = false; colvarIdInterconsulta.IsPrimaryKey = false; colvarIdInterconsulta.IsForeignKey = false; colvarIdInterconsulta.IsReadOnly = false; colvarIdInterconsulta.DefaultSetting = @""; colvarIdInterconsulta.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdInterconsulta); TableSchema.TableColumn colvarIdTurnoEfector = new TableSchema.TableColumn(schema); colvarIdTurnoEfector.ColumnName = "idTurnoEfector"; colvarIdTurnoEfector.DataType = DbType.Int32; colvarIdTurnoEfector.MaxLength = 0; colvarIdTurnoEfector.AutoIncrement = false; colvarIdTurnoEfector.IsNullable = false; colvarIdTurnoEfector.IsPrimaryKey = false; colvarIdTurnoEfector.IsForeignKey = false; colvarIdTurnoEfector.IsReadOnly = false; colvarIdTurnoEfector.DefaultSetting = @""; colvarIdTurnoEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTurnoEfector); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdExternoEspecialidad = new TableSchema.TableColumn(schema); colvarIdExternoEspecialidad.ColumnName = "idExternoEspecialidad"; colvarIdExternoEspecialidad.DataType = DbType.Int32; colvarIdExternoEspecialidad.MaxLength = 0; colvarIdExternoEspecialidad.AutoIncrement = false; colvarIdExternoEspecialidad.IsNullable = false; colvarIdExternoEspecialidad.IsPrimaryKey = false; colvarIdExternoEspecialidad.IsForeignKey = false; colvarIdExternoEspecialidad.IsReadOnly = false; colvarIdExternoEspecialidad.DefaultSetting = @""; colvarIdExternoEspecialidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdExternoEspecialidad); TableSchema.TableColumn colvarNombreEspecialidad = new TableSchema.TableColumn(schema); colvarNombreEspecialidad.ColumnName = "nombreEspecialidad"; colvarNombreEspecialidad.DataType = DbType.AnsiString; colvarNombreEspecialidad.MaxLength = 200; colvarNombreEspecialidad.AutoIncrement = false; colvarNombreEspecialidad.IsNullable = false; colvarNombreEspecialidad.IsPrimaryKey = false; colvarNombreEspecialidad.IsForeignKey = false; colvarNombreEspecialidad.IsReadOnly = false; colvarNombreEspecialidad.DefaultSetting = @""; colvarNombreEspecialidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreEspecialidad); TableSchema.TableColumn colvarIdExternoProfesional = new TableSchema.TableColumn(schema); colvarIdExternoProfesional.ColumnName = "idExternoProfesional"; colvarIdExternoProfesional.DataType = DbType.Int32; colvarIdExternoProfesional.MaxLength = 0; colvarIdExternoProfesional.AutoIncrement = false; colvarIdExternoProfesional.IsNullable = false; colvarIdExternoProfesional.IsPrimaryKey = false; colvarIdExternoProfesional.IsForeignKey = false; colvarIdExternoProfesional.IsReadOnly = false; colvarIdExternoProfesional.DefaultSetting = @""; colvarIdExternoProfesional.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdExternoProfesional); TableSchema.TableColumn colvarNombreProfesional = new TableSchema.TableColumn(schema); colvarNombreProfesional.ColumnName = "nombreProfesional"; colvarNombreProfesional.DataType = DbType.AnsiString; colvarNombreProfesional.MaxLength = 200; colvarNombreProfesional.AutoIncrement = false; colvarNombreProfesional.IsNullable = false; colvarNombreProfesional.IsPrimaryKey = false; colvarNombreProfesional.IsForeignKey = false; colvarNombreProfesional.IsReadOnly = false; colvarNombreProfesional.DefaultSetting = @""; colvarNombreProfesional.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreProfesional); TableSchema.TableColumn colvarFechaTurno = new TableSchema.TableColumn(schema); colvarFechaTurno.ColumnName = "fechaTurno"; colvarFechaTurno.DataType = DbType.DateTime; colvarFechaTurno.MaxLength = 0; colvarFechaTurno.AutoIncrement = false; colvarFechaTurno.IsNullable = false; colvarFechaTurno.IsPrimaryKey = false; colvarFechaTurno.IsForeignKey = false; colvarFechaTurno.IsReadOnly = false; colvarFechaTurno.DefaultSetting = @""; colvarFechaTurno.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaTurno); TableSchema.TableColumn colvarHoraTurno = new TableSchema.TableColumn(schema); colvarHoraTurno.ColumnName = "horaTurno"; colvarHoraTurno.DataType = DbType.DateTime; colvarHoraTurno.MaxLength = 0; colvarHoraTurno.AutoIncrement = false; colvarHoraTurno.IsNullable = false; colvarHoraTurno.IsPrimaryKey = false; colvarHoraTurno.IsForeignKey = false; colvarHoraTurno.IsReadOnly = false; colvarHoraTurno.DefaultSetting = @""; colvarHoraTurno.ForeignKeyTableName = ""; schema.Columns.Add(colvarHoraTurno); TableSchema.TableColumn colvarIdUsuarioCarga = new TableSchema.TableColumn(schema); colvarIdUsuarioCarga.ColumnName = "idUsuarioCarga"; colvarIdUsuarioCarga.DataType = DbType.Int32; colvarIdUsuarioCarga.MaxLength = 0; colvarIdUsuarioCarga.AutoIncrement = false; colvarIdUsuarioCarga.IsNullable = false; colvarIdUsuarioCarga.IsPrimaryKey = false; colvarIdUsuarioCarga.IsForeignKey = false; colvarIdUsuarioCarga.IsReadOnly = false; colvarIdUsuarioCarga.DefaultSetting = @""; colvarIdUsuarioCarga.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioCarga); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["RisProvider"].AddSchema("TUP_TurnosProtegidos",schema); } } #endregion #region Props [XmlAttribute("IdTurnoSubsecretaria")] [Bindable(true)] public int IdTurnoSubsecretaria { get { return GetColumnValue<int>(Columns.IdTurnoSubsecretaria); } set { SetColumnValue(Columns.IdTurnoSubsecretaria, value); } } [XmlAttribute("IdInterconsulta")] [Bindable(true)] public int IdInterconsulta { get { return GetColumnValue<int>(Columns.IdInterconsulta); } set { SetColumnValue(Columns.IdInterconsulta, value); } } [XmlAttribute("IdTurnoEfector")] [Bindable(true)] public int IdTurnoEfector { get { return GetColumnValue<int>(Columns.IdTurnoEfector); } set { SetColumnValue(Columns.IdTurnoEfector, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdExternoEspecialidad")] [Bindable(true)] public int IdExternoEspecialidad { get { return GetColumnValue<int>(Columns.IdExternoEspecialidad); } set { SetColumnValue(Columns.IdExternoEspecialidad, value); } } [XmlAttribute("NombreEspecialidad")] [Bindable(true)] public string NombreEspecialidad { get { return GetColumnValue<string>(Columns.NombreEspecialidad); } set { SetColumnValue(Columns.NombreEspecialidad, value); } } [XmlAttribute("IdExternoProfesional")] [Bindable(true)] public int IdExternoProfesional { get { return GetColumnValue<int>(Columns.IdExternoProfesional); } set { SetColumnValue(Columns.IdExternoProfesional, value); } } [XmlAttribute("NombreProfesional")] [Bindable(true)] public string NombreProfesional { get { return GetColumnValue<string>(Columns.NombreProfesional); } set { SetColumnValue(Columns.NombreProfesional, value); } } [XmlAttribute("FechaTurno")] [Bindable(true)] public DateTime FechaTurno { get { return GetColumnValue<DateTime>(Columns.FechaTurno); } set { SetColumnValue(Columns.FechaTurno, value); } } [XmlAttribute("HoraTurno")] [Bindable(true)] public DateTime HoraTurno { get { return GetColumnValue<DateTime>(Columns.HoraTurno); } set { SetColumnValue(Columns.HoraTurno, value); } } [XmlAttribute("IdUsuarioCarga")] [Bindable(true)] public int IdUsuarioCarga { get { return GetColumnValue<int>(Columns.IdUsuarioCarga); } set { SetColumnValue(Columns.IdUsuarioCarga, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdInterconsulta,int varIdTurnoEfector,int varIdEfector,int varIdExternoEspecialidad,string varNombreEspecialidad,int varIdExternoProfesional,string varNombreProfesional,DateTime varFechaTurno,DateTime varHoraTurno,int varIdUsuarioCarga) { TupTurnosProtegido item = new TupTurnosProtegido(); item.IdInterconsulta = varIdInterconsulta; item.IdTurnoEfector = varIdTurnoEfector; item.IdEfector = varIdEfector; item.IdExternoEspecialidad = varIdExternoEspecialidad; item.NombreEspecialidad = varNombreEspecialidad; item.IdExternoProfesional = varIdExternoProfesional; item.NombreProfesional = varNombreProfesional; item.FechaTurno = varFechaTurno; item.HoraTurno = varHoraTurno; item.IdUsuarioCarga = varIdUsuarioCarga; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTurnoSubsecretaria,int varIdInterconsulta,int varIdTurnoEfector,int varIdEfector,int varIdExternoEspecialidad,string varNombreEspecialidad,int varIdExternoProfesional,string varNombreProfesional,DateTime varFechaTurno,DateTime varHoraTurno,int varIdUsuarioCarga) { TupTurnosProtegido item = new TupTurnosProtegido(); item.IdTurnoSubsecretaria = varIdTurnoSubsecretaria; item.IdInterconsulta = varIdInterconsulta; item.IdTurnoEfector = varIdTurnoEfector; item.IdEfector = varIdEfector; item.IdExternoEspecialidad = varIdExternoEspecialidad; item.NombreEspecialidad = varNombreEspecialidad; item.IdExternoProfesional = varIdExternoProfesional; item.NombreProfesional = varNombreProfesional; item.FechaTurno = varFechaTurno; item.HoraTurno = varHoraTurno; item.IdUsuarioCarga = varIdUsuarioCarga; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTurnoSubsecretariaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdInterconsultaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdTurnoEfectorColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IdExternoEspecialidadColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn NombreEspecialidadColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdExternoProfesionalColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn NombreProfesionalColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaTurnoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn HoraTurnoColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn IdUsuarioCargaColumn { get { return Schema.Columns[10]; } } #endregion #region Columns Struct public struct Columns { public static string IdTurnoSubsecretaria = @"idTurnoSubsecretaria"; public static string IdInterconsulta = @"idInterconsulta"; public static string IdTurnoEfector = @"idTurnoEfector"; public static string IdEfector = @"idEfector"; public static string IdExternoEspecialidad = @"idExternoEspecialidad"; public static string NombreEspecialidad = @"nombreEspecialidad"; public static string IdExternoProfesional = @"idExternoProfesional"; public static string NombreProfesional = @"nombreProfesional"; public static string FechaTurno = @"fechaTurno"; public static string HoraTurno = @"horaTurno"; public static string IdUsuarioCarga = @"idUsuarioCarga"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
32.625442
299
0.692299
[ "MIT" ]
saludnqn/prosane
RIS_Publico/RIS_Publico/generated/TupTurnosProtegido.cs
18,466
C#
using System; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; namespace SwitchDemos { public partial class MainPage : ContentPage { public ICommand NavigateCommand { get; private set; } public MainPage() { InitializeComponent(); NavigateCommand = new Command<Type>(async (Type pageType) => { Page page = (Page)Activator.CreateInstance(pageType); await Navigation.PushAsync(page); }); BindingContext = this; } } }
22.461538
72
0.587329
[ "Apache-2.0" ]
15217711253/xamarin-forms-samples
UserInterface/SwitchDemos/SwitchDemos/SwitchDemos/MainPage.xaml.cs
586
C#
using System.Data.Entity; using System.Data.SqlClient; namespace Shengtai.Web { public abstract class SqlRepository<TContext> : Repository<SqlConnection, SqlCommand, SqlParameter, TContext> where TContext : DbContext { protected SqlRepository(TContext context = null) : base(context) { } } }
25.923077
113
0.688427
[ "Apache-2.0" ]
shengtai0201/ClassLibrary
Shengtai/Web/SqlRepository.cs
339
C#
// <copyright file="IActionExecutor.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenQA.Selenium.Interactions; namespace OpenQA.Selenium.Internal { /// <summary> /// Interface allowing execution of W3C Specification-compliant actions. /// </summary> public interface IActionExecutor { /// <summary> /// Gets a value indicating whether this object is a valid action executor. /// </summary> bool IsActionExecutor { get; } /// <summary> /// Performs the specified list of actions with this action executor. /// </summary> /// <param name="actionSequenceList">The list of action sequences to perform.</param> void PerformActions(IList<ActionSequence> actionSequenceList); /// <summary> /// Resets the input state of the action executor. /// </summary> void ResetInputState(); } }
36.877551
93
0.700609
[ "Apache-2.0" ]
Acidburn0zzz/selenium
dotnet/src/webdriver/Internal/IActionExecutor.cs
1,809
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Newtonsoft.Json; using System; namespace Bicep.Decompiler.Exceptions { public class ConversionFailedException : Exception { public ConversionFailedException(string message, IJsonLineInfo jsonLineInfo, Exception? innerException = null) : base(FormatMessage(message, jsonLineInfo), innerException) { } private static string FormatMessage(string message, IJsonLineInfo jsonLineInfo) => $"[{jsonLineInfo.LineNumber}:{jsonLineInfo.LinePosition}]: {message}"; } }
30.5
118
0.711475
[ "MIT" ]
AlanFlorance/bicep
src/Bicep.Decompiler/Exceptions/ConversionFailedException.cs
610
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Citp.IO; namespace Citp.Packets.FPtc { public class FPtcSendPatch : FPtcHeader { public const string PacketType = "SPtc"; #region Setup and Initialisation public FPtcSendPatch() : base(PacketType) { } #endregion #region Packet Content private List<ushort> fixtureIdentifiers = new List<ushort>(); public List<ushort> FixtureIdentifiers { get { return fixtureIdentifiers; } } #endregion #region Read/Write public override void ReadData(CitpBinaryReader data) { base.ReadData(data); int fixtureCount = data.ReadUInt16(); for (int n = 0; n < fixtureCount; n++) FixtureIdentifiers.Add(data.ReadUInt16()); } public override void WriteData(CitpBinaryWriter data) { base.WriteData(data); data.Write((ushort)FixtureIdentifiers.Count); foreach (ushort id in FixtureIdentifiers) data.Write(id); } #endregion } }
22.107143
69
0.583199
[ "MIT" ]
HakanL/ACN
Citp/Packets/FPtc/FPtcSendPatch.cs
1,240
C#
 using DiscordMessenger; using Guna.UI2.WinForms; using KrnlAPI; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Windows.Forms; namespace Dagger { public partial class Form1 : Form { // The text labels on the starting page are purposefully shoved to the right. // Moves Button Tab private void moveImageBox(object sender) { Guna2Button b = (Guna2Button)sender; guna2PictureBox2.Location = new Point(b.Location.X + 24, b.Location.Y - 25); guna2PictureBox2.SendToBack(); } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { fucked.Dump.Initialize(); // Detects if outdated WebClient webClient = new WebClient(); if (webClient.DownloadString("https://pastebin.com/raw/gJpPaKiF").Contains("1.0.0")) { v.ForeColor = Color.Green; guna2Button5.Visible = false; } else { v.ForeColor = Color.Red; guna2Button5.Visible = true; } } // Adds ability to "cast" UC over a Panel. private void addUserControl(UserControl uc) { guna2Panel1.Controls.Clear(); uc.BringToFront(); guna2Panel1.Controls.Add(uc); } private void guna2Button1_Click(object sender, EventArgs e) { guna2PictureBox2.Visible = true; Inject uC_ = new Inject(); addUserControl(uC_); } // Moving Tab Slider private void guna2Button1_CheckedChanged(object sender, EventArgs e) { moveImageBox(sender); } private void guna2Button2_CheckedChanged(object sender, EventArgs e) { moveImageBox(sender); } private void guna2Button3_CheckedChanged(object sender, EventArgs e) { moveImageBox(sender); } private void guna2Button2_Click(object sender, EventArgs e) { guna2PictureBox2.Visible = true; options uC_ = new options(); addUserControl(uC_); } private void guna2Button3_Click(object sender, EventArgs e) { guna2PictureBox2.Visible = true; custom uC_ = new custom(); addUserControl(uC_); } private void guna2Button5_Click(object sender, EventArgs e) { Process.Start("https://discord.gg/milkshop"); } private void guna2PictureBox1_Click(object sender, EventArgs e) { } private void guna2ControlBox1_Click_1(object sender, EventArgs e) { Application.Exit(); } // Donate! private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://cash.app/$DevLovely"); } } }
25.208
96
0.568391
[ "MIT" ]
AntisocialProgramming/Dagger
Dagger/Forms/Main.cs
3,153
C#
using BitCodeGenerator.Implementations; using BitCodeGenerator.Implementations.TypeScriptClientProxyGenerator; using BitTools.Core.Contracts; using BitTools.Core.Model; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; namespace BitVSExtensionV1 { [PackageRegistration(UseManagedResourcesOnly = true)] [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] [Guid(PackageGuidString)] [ProvideAutoLoad(UIContextGuids80.SolutionExists)] public sealed class BitPacakge : Package { private const string PackageGuidString = "F5222FDA-2C19-434B-9343-B0E942816E4C"; private const string BitVSExtensionName = "Bit VS Extension V1"; protected override void Initialize() { base.Initialize(); _serviceContainer = this; _applicationObject = (DTE2)GetGlobalService(typeof(DTE)); if (_applicationObject == null) { ShowInitialLoadProblem($"{_applicationObject}-{nameof(DTE2)} not found"); return; } Window outputWindow = _applicationObject.DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); if (outputWindow == null) { ShowInitialLoadProblem($"{outputWindow}-{nameof(Window)} not found"); return; } try { _outputWindow = (OutputWindow)outputWindow.Object; _outputPane = _outputWindow.OutputWindowPanes.Cast<OutputWindowPane>().ExtendedSingleOrDefault("Finding output pane", x => x.Name == BitVSExtensionName) ?? _outputWindow.OutputWindowPanes.Add(BitVSExtensionName); } catch (Exception ex) { ShowInitialLoadProblem($"{_outputPane}-{nameof(OutputWindowPane)} not found => {ex}."); return; } try { _statusBar = (IVsStatusbar)_serviceContainer.GetService(typeof(SVsStatusbar)); if (_statusBar == null) throw new InvalidOperationException("status bar is null"); } catch (Exception ex) { ShowInitialLoadProblem($"{_statusBar}-{nameof(IVsStatusbar)} not found => {ex}"); return; } _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); if (_componentModel == null) { LogWarn($"{_componentModel}-{nameof(IComponentModel)} is null."); return; } try { GetWorkspace(); } catch (Exception ex) { LogException("Workspace not found.", ex); return; } _buildEvents = _applicationObject.Events.BuildEvents; _applicationObject.Events.BuildEvents.OnBuildProjConfigDone += _buildEvents_OnBuildProjConfigDone; _applicationObject.Events.BuildEvents.OnBuildDone += _buildEvents_OnBuildDone; _applicationObject.Events.BuildEvents.OnBuildBegin += _buildEvents_OnBuildBegin; _applicationObject.Events.SolutionEvents.Opened += SolutionEvents_Opened; } private async void SolutionEvents_Opened() { Func<bool> vsHasASavedSolutionButRoslynWorkspaceHasNoPath = () => { bool result = _applicationObject.Solution.Saved && string.IsNullOrEmpty(_visualStudioWorkspace.CurrentSolution.FilePath); if (result == false) LogWarn($"Visual studio has a saved solution, but roslyn's workspace has no file path"); return result; }; Func<bool> vsSolutionHasSomeProjectsButRoslynOneNothing = () => { bool result = _applicationObject.Solution.Projects.Cast<object>().Any() && !_visualStudioWorkspace.CurrentSolution.Projects.Any(); if (result == false) LogWarn($"Visual studio has some projects, but roslyn's workspace has no project"); return result; }; int retryCount = 30; while (vsHasASavedSolutionButRoslynWorkspaceHasNoPath() || vsSolutionHasSomeProjectsButRoslynOneNothing() || retryCount <= 0) { await System.Threading.Tasks.Task.Delay(500); retryCount--; } if (vsHasASavedSolutionButRoslynWorkspaceHasNoPath() || vsSolutionHasSomeProjectsButRoslynOneNothing()) LogWarn($"15 seconds delay wasn't enough to make Visual Studio's workspace ready."); DoOnSolutionReadyOrChange(); } private void GetWorkspace() { _visualStudioWorkspace = _componentModel.GetService<VisualStudioWorkspace>(); if (_visualStudioWorkspace == null) { throw new InvalidOperationException("Visual studio workspace is null"); } _visualStudioWorkspace.WorkspaceFailed += _workspace_WorkspaceFailed; } private void _workspace_WorkspaceFailed(object sender, WorkspaceDiagnosticEventArgs e) { LogWarn($"{sender.GetType().Name} {e.Diagnostic.Kind} {e.Diagnostic.Message}"); } private async void DoOnSolutionReadyOrChange() { if (!File.Exists(_visualStudioWorkspace.CurrentSolution.FilePath)) { LogWarn("Could not find solution."); return; } if (!WorkspaceHasBitConfigV1JsonFile()) { LogWarn("Could not find BitConfigV1.json file."); return; } _outputPane.OutputString("__________----------__________ \n"); DefaultBitConfigProvider configProvider = new DefaultBitConfigProvider(); BitConfig config; try { config = configProvider.GetConfiguration(_visualStudioWorkspace.CurrentSolution.FilePath); foreach (BitCodeGeneratorMapping mapping in config.BitCodeGeneratorConfigs.BitCodeGeneratorMappings) { if (!_visualStudioWorkspace.CurrentSolution.Projects.Any(p => p.Name == mapping.DestinationProject.Name && p.Language == LanguageNames.CSharp)) LogWarn($"No project found named {mapping.DestinationProject.Name}"); foreach (BitTools.Core.Model.ProjectInfo proj in mapping.SourceProjects) { if (!_visualStudioWorkspace.CurrentSolution.Projects.Any(p => p.Name == proj.Name && p.Language == LanguageNames.CSharp)) LogWarn($"No project found named {proj.Name}"); } } } catch (Exception ex) { LogException("Parse BitConfigV1.json failed.", ex); return; } try { bitWorkspaceIsPrepared = thereWasAnErrorInLastBuild = lastActionWasClean = false; Log("Preparing bit workspace... This includes restoring nuget packages, building your solution and generating codes."); _applicationObject.Solution.SolutionBuild.Build(WaitForBuildToFinish: true); } catch (Exception ex) { LogException("Bit workspace preparation failed", ex); } finally { bitWorkspaceIsPrepared = true; await CallGenerateCodes(); Log("Bit workspace gets prepared", activatePane: true); } } private bool WorkspaceHasBitConfigV1JsonFile() { return File.Exists(_visualStudioWorkspace.CurrentSolution.FilePath) && File.Exists(Path.Combine(Path.GetDirectoryName(_visualStudioWorkspace.CurrentSolution.FilePath) + "\\BitConfigV1.json")); } private async System.Threading.Tasks.Task CallGenerateCodes() { if (bitWorkspaceIsPrepared == false) { return; } Stopwatch sw = null; try { sw = Stopwatch.StartNew(); IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider(); IProjectDtosProvider dtosProvider = new DefaultProjectDtosProvider(controllersProvider); DefaultTypeScriptClientProxyGenerator generator = new DefaultTypeScriptClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(), new DefaultBitConfigProvider(), dtosProvider , new DefaultTypeScriptClientProxyDtoGenerator(), new DefaultTypeScriptClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider)); Workspace workspaceForCodeGeneration = await GetWorkspaceForCodeGeneration(); try { await generator.GenerateCodes(workspaceForCodeGeneration); Log($"Code Generation Completed in {sw.ElapsedMilliseconds} ms using {workspaceForCodeGeneration.GetType().Name}"); } finally { if (workspaceForCodeGeneration is MSBuildWorkspace) workspaceForCodeGeneration.Dispose(); } } catch (Exception ex) { LogException("Code Generation failed.", ex); } finally { sw?.Stop(); } } private async System.Threading.Tasks.Task<Workspace> GetWorkspaceForCodeGeneration() { bool vsWorkspaceIsValid = true; foreach (Microsoft.CodeAnalysis.Project proj in _visualStudioWorkspace.CurrentSolution.Projects.Where(p => p.Language == LanguageNames.CSharp)) { if (!(await proj.GetCompilationAsync()).ReferencedAssemblyNames.Any()) { LogWarn($"{nameof(VisualStudioWorkspace)} is not ready due project {proj.Name}"); vsWorkspaceIsValid = false; break; } } if (vsWorkspaceIsValid) return _visualStudioWorkspace; MSBuildWorkspace msBuildWorkspaace = MSBuildWorkspace.Create(new Dictionary<string, string>(), _visualStudioWorkspace.Services.HostServices); msBuildWorkspaace.LoadMetadataForReferencedProjects = msBuildWorkspaace.SkipUnrecognizedProjects = true; await msBuildWorkspaace.OpenSolutionAsync(_visualStudioWorkspace.CurrentSolution.FilePath); return msBuildWorkspaace; } private async System.Threading.Tasks.Task CallCleanCodes() { DefaultTypeScriptClientProxyCleaner cleaner = new DefaultTypeScriptClientProxyCleaner(new DefaultBitConfigProvider()); await cleaner.DeleteCodes(_visualStudioWorkspace); Log("Generated codes were deleted."); } private async void _buildEvents_OnBuildBegin(vsBuildScope scope, vsBuildAction action) { if (!WorkspaceHasBitConfigV1JsonFile() || action == vsBuildAction.vsBuildActionClean) return; if (thereWasAnErrorInLastBuild == true || lastActionWasClean == true) { lastActionWasClean = false; thereWasAnErrorInLastBuild = false; await CallGenerateCodes(); } } private void _buildEvents_OnBuildProjConfigDone(string project, string projectConfig, string platform, string solutionConfig, bool success) { if (!WorkspaceHasBitConfigV1JsonFile()) return; thereWasAnErrorInLastBuild = thereWasAnErrorInLastBuild && success; } private async void _buildEvents_OnBuildDone(vsBuildScope scope, vsBuildAction action) { if (!WorkspaceHasBitConfigV1JsonFile()) return; try { if (action == vsBuildAction.vsBuildActionClean) { await CallCleanCodes(); lastActionWasClean = true; } else { await CallGenerateCodes(); } } catch (Exception ex) { LogException("Generate|Clean codes failed.", ex); } } private void LogException(string text, Exception ex, bool activatePane = true) { _statusBar.SetText($"Bit: {text} See output pane for more info"); _outputPane.OutputString($"{text} {DateTimeOffset.Now} \n {ex} \n"); _outputPane.Activate(); if (activatePane == true) _outputPane.Activate(); } private void Log(string text, bool activatePane = false) { _statusBar.SetText($"Bit: {text}"); _outputPane.OutputString($"{text} {DateTimeOffset.Now} \n"); if (activatePane == true) _outputPane.Activate(); } private void LogWarn(string text, bool activatePane = false) { _statusBar.SetText($"Bit: {text}"); _outputPane.OutputString($"{text} {DateTimeOffset.Now} \n"); if (activatePane == true) _outputPane.Activate(); } private void ShowInitialLoadProblem(string errorMessage) { if (errorMessage == null) throw new ArgumentNullException(nameof(errorMessage)); if (string.IsNullOrEmpty(errorMessage)) throw new ArgumentException(nameof(errorMessage)); MessageBox.Show(errorMessage, BitVSExtensionName, MessageBoxButtons.OK, MessageBoxIcon.Error); } protected override void Dispose(bool disposing) { if (_visualStudioWorkspace != null) { _visualStudioWorkspace.WorkspaceFailed -= _workspace_WorkspaceFailed; } if (_applicationObject?.Events != null) { _applicationObject.Events.BuildEvents.OnBuildProjConfigDone -= _buildEvents_OnBuildProjConfigDone; _applicationObject.Events.BuildEvents.OnBuildBegin -= _buildEvents_OnBuildBegin; _applicationObject.Events.BuildEvents.OnBuildDone -= _buildEvents_OnBuildDone; _applicationObject.Events.SolutionEvents.Opened -= SolutionEvents_Opened; } base.Dispose(disposing); } private VisualStudioWorkspace _visualStudioWorkspace; private IComponentModel _componentModel; private IServiceContainer _serviceContainer; private OutputWindow _outputWindow; private OutputWindowPane _outputPane; private DTE2 _applicationObject; private BuildEvents _buildEvents; private IVsStatusbar _statusBar; private bool lastActionWasClean; private bool thereWasAnErrorInLastBuild; private bool bitWorkspaceIsPrepared; } }
37.67619
228
0.602882
[ "MIT" ]
moshtaba/bit-framework
BitTools/BitVSExtensionV1/BitPackage.cs
15,826
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace CRM.Interface { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Webpageid. /// </summary> public static partial class WebpageidExtensions { /// <summary> /// Get rra_WebPageId from rra_questions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='rraQuestionid'> /// key: rra_questionid of rra_question /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMrraWebpage Get(this IWebpageid operations, string rraQuestionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(rraQuestionid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get rra_WebPageId from rra_questions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='rraQuestionid'> /// key: rra_questionid of rra_question /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMrraWebpage> GetAsync(this IWebpageid operations, string rraQuestionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(rraQuestionid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get rra_WebPageId from rra_questions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='rraQuestionid'> /// key: rra_questionid of rra_question /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMrraWebpage> GetWithHttpMessages(this IWebpageid operations, string rraQuestionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(rraQuestionid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
42.25
298
0.571135
[ "MIT" ]
msehudi/cms-accelerator
OData.OpenAPI/odata2openapi/Client/WebpageidExtensions.cs
3,887
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.Resources.Models { /// <summary> The definition of a parameter that can be provided to the policy. </summary> public partial class ArmPolicyParameter { /// <summary> Initializes a new instance of ArmPolicyParameter. </summary> public ArmPolicyParameter() { AllowedValues = new ChangeTrackingList<BinaryData>(); } /// <summary> Initializes a new instance of ArmPolicyParameter. </summary> /// <param name="parameterType"> The data type of the parameter. </param> /// <param name="allowedValues"> The allowed values for the parameter. </param> /// <param name="defaultValue"> The default value for the parameter if no value is provided. </param> /// <param name="metadata"> General metadata for the parameter. </param> internal ArmPolicyParameter(ParameterType? parameterType, IList<BinaryData> allowedValues, BinaryData defaultValue, ParameterDefinitionsValueMetadata metadata) { ParameterType = parameterType; AllowedValues = allowedValues; DefaultValue = defaultValue; Metadata = metadata; } /// <summary> The data type of the parameter. </summary> public ParameterType? ParameterType { get; set; } /// <summary> The allowed values for the parameter. </summary> public IList<BinaryData> AllowedValues { get; } /// <summary> The default value for the parameter if no value is provided. </summary> public BinaryData DefaultValue { get; set; } /// <summary> General metadata for the parameter. </summary> public ParameterDefinitionsValueMetadata Metadata { get; set; } } }
42.304348
167
0.672662
[ "MIT" ]
Ramananaidu/dotnet-sonarqube
sdk/resourcemanager/Azure.ResourceManager/src/Resources/Generated/Models/ArmPolicyParameter.cs
1,946
C#
using System; using System.Reflection; namespace Nfantom.ABI.FunctionEncoding.Attributes { [AttributeUsage(AttributeTargets.Class)] public class ErrorAttribute : Attribute { public ErrorAttribute(string name) { this.Name = name; } public string Name { get; set; } public static ErrorAttribute GetAttribute<T>() { var type = typeof(T); return GetAttribute(type); } public static ErrorAttribute GetAttribute(Type type) { return type.GetTypeInfo().GetCustomAttribute<ErrorAttribute>(true); } public static ErrorAttribute GetAttribute(object instance) { var type = instance.GetType(); return GetAttribute(type); } public static bool IsErrorType<T>() { return GetAttribute<T>() != null; } public static bool IsErrorType(Type type) { return GetAttribute(type) != null; } public static bool IsErrorType(object type) { return GetAttribute(type) != null; } } }
24.166667
79
0.568103
[ "MIT" ]
PeaStew/Nfantom
Nfantom.ABI/FunctionEncoding/Attributes/ErrorAttribute.cs
1,162
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public sealed class DataMemberAttribute : Attribute { private string _name; private bool _isNameSetExplicitly; private int _order = -1; private bool _isRequired; private bool _emitDefaultValue = Globals.DefaultEmitDefaultValue; public DataMemberAttribute() { } public string Name { get { return _name; } set { _name = value; _isNameSetExplicitly = true; } } public bool IsNameSetExplicitly { get { return _isNameSetExplicitly; } } public int Order { get { return _order; } set { if (value < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.OrderCannotBeNegative)); _order = value; } } public bool IsRequired { get { return _isRequired; } set { _isRequired = value; } } public bool EmitDefaultValue { get { return _emitDefaultValue; } set { _emitDefaultValue = value; } } } }
28.37037
167
0.582898
[ "MIT" ]
71221-maker/runtime
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMemberAttribute.cs
1,532
C#
using System.Threading.Tasks; using DayTripper.Data.Scrapper.Scrappers; namespace DayTripper.Data.Scrapper { public class Program { public static async Task Main() { var climbingguideScrapper = new ClimbingGuideScrapper(); await climbingguideScrapper.RunAsync(); } } }
19.588235
68
0.651652
[ "MIT" ]
todor-tsankov/day-tripper
Server/Data/DayTripper.Data.Scrapper/Program.cs
335
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Shoplify.Web.Data.Migrations { public partial class ChangedNotificationTextMaxLengthConstraint : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Text", table: "Notifications", maxLength: 255, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(50)", oldMaxLength: 50); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Text", table: "Notifications", type: "nvarchar(50)", maxLength: 50, nullable: false, oldClrType: typeof(string), oldMaxLength: 255); } } }
30.46875
79
0.542564
[ "MIT" ]
KostadinovK/Shoplify
Shoplify/Shoplify.Data/Migrations/20200310113047_ChangedNotificationTextMaxLengthConstraint.cs
977
C#
// GregorianCalendarTypes.cs // // This code was automatically generated from // ECMA CLI XML Library Specification. // Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)] // Created: Wed, 5 Sep 2001 06:35:19 UTC // Source file: all.xml // URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml // // (C) 2001 Ximian, Inc. http://www.ximian.com // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(true)] [System.Serializable] public enum GregorianCalendarTypes { /// <summary> /// </summary> Localized = 1, /// <summary> /// </summary> USEnglish = 2, /// <summary> /// </summary> MiddleEastFrench = 9, /// <summary> /// </summary> Arabic = 10, /// <summary> /// </summary> TransliteratedEnglish = 11, /// <summary> /// </summary> TransliteratedFrench = 12, } // GregorianCalendarTypes } // System.Globalization
30.072464
78
0.713735
[ "Apache-2.0" ]
121468615/mono
mcs/class/corlib/System.Globalization/GregorianCalendarTypes.cs
2,075
C#
using LibraryManagement.Classes; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace LibraryManagement.Pages { /// <summary> /// Interaction logic for addEmployeePage.xaml /// </summary> public partial class addEmployeePage : Page { public event PageChanger changeToAdminPanelPage; Admin admin; string employeeImageAddress = ""; public addEmployeePage(PageChanger changeToAdminPanelPage, Admin admin) { InitializeComponent(); this.changeToAdminPanelPage = changeToAdminPanelPage; this.admin = admin; } private bool fieldIsEmpty() { if (userNameBox.Text == "" || firstNameBox.Text == "" || lastNameBox.Text == "" || emailBox.Text == "" || phoneNumberBox.Text == "" || passwordBox.Password == "" || confirmPasswordBox.Password == "") { return true; } else { return false; } } private bool userNameExists() { DataTable dataTable = PeopleTable.read(); for (int i = 0; i < dataTable.Rows.Count; i++) { if (userNameBox.Text == dataTable.Rows[i][PeopleTable.indexUserName].ToString()) { return true; } } return false; } private void signUpButton_Click(object sender, System.Windows.RoutedEventArgs e) { if (fieldIsEmpty()) { MessageBox.Show("Please fill all of the given fields!"); } else { if (userNameExists()) { MessageBox.Show("This username already exists!"); } else { //check regex bool fieldsAreValid = true; //userName if (mRegex.userNameIsValid(userNameBox.Text)) { userNameRegexWarn.Visibility = Visibility.Hidden; } else { userNameRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } //firstName if (mRegex.nameIsValid(firstNameBox.Text)) { firstNameRegexWarn.Visibility = Visibility.Hidden; } else { firstNameRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } //lastName if (mRegex.nameIsValid(lastNameBox.Text)) { lastNameRegexWarn.Visibility = Visibility.Hidden; } else { lastNameRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } //email if (mRegex.emailIsValid(emailBox.Text)) { emailRegexWarn.Visibility = Visibility.Hidden; } else { emailRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } //phoneNumber if (mRegex.phoneNumberIsValid(phoneNumberBox.Text)) { phoneNumberRegexWarn.Visibility = Visibility.Hidden; } else { phoneNumberRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } //password if (mRegex.passwordIsValid(passwordBox.Password)) { passwordRegexWarn.Visibility = Visibility.Hidden; } else { passwordRegexWarn.Visibility = Visibility.Visible; fieldsAreValid = false; } if (fieldsAreValid) { //all regexes were ok //sign up if (confirmPasswordBox.Password != passwordBox.Password) { MessageBox.Show("Please make sure your passwords match"); } else { Employee employee = new Employee (userNameBox.Text, firstNameBox.Text, lastNameBox.Text, phoneNumberBox.Text, emailBox.Text, passwordBox.Password, 0, this.employeeImageAddress); //PeopleTable.write(employee); this.admin.addEmployee(employee); MessageBox.Show("Employee added successfully! - returning to admin panel"); changeToAdminPanelPage(admin); } } else { MessageBox.Show("Please fill fields like mentioned patterns!"); } } } } private void userNameBox_TextChanged(object sender, TextChangedEventArgs e) { userNameRegexWarn.Visibility = Visibility.Hidden; } private void firstNameBox_TextChanged(object sender, TextChangedEventArgs e) { firstNameRegexWarn.Visibility = Visibility.Hidden; } private void lastNameBox_TextChanged(object sender, TextChangedEventArgs e) { lastNameRegexWarn.Visibility = Visibility.Hidden; } private void emailBox_TextChanged(object sender, TextChangedEventArgs e) { emailRegexWarn.Visibility = Visibility.Hidden; } private void phoneNumberBox_TextChanged(object sender, TextChangedEventArgs e) { phoneNumberRegexWarn.Visibility = Visibility.Hidden; } private void passwordBox_PasswordChanged(object sender, RoutedEventArgs e) { passwordRegexWarn.Visibility = Visibility.Hidden; } private void uploadButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.Title = "Select a picture"; op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" + "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + "Portable Network Graphic (*.png)|*.png"; if (op.ShowDialog() == true) { image.Source = new BitmapImage(new Uri(op.FileName)); this.employeeImageAddress = op.FileName; } } private void cancelButton_Click(object sender, RoutedEventArgs e) { changeToAdminPanelPage(admin); } } }
34.381356
103
0.459946
[ "MIT" ]
ap-class-projects/LibraryManagement
LibraryManagement/LibraryManagement/Pages/addEmployeePage.xaml.cs
8,116
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SalesMvc.Models; namespace SalesMvc.Migrations { [DbContext(typeof(SalesMvcContext))] partial class SalesMvcContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.14-servicing-32113") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("SalesMvc.Models.Department", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Department"); }); modelBuilder.Entity("SalesMvc.Models.SalesRecord", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<double>("Amount"); b.Property<DateTime>("Date"); b.Property<int?>("SellerId"); b.Property<int>("Status"); b.HasKey("Id"); b.HasIndex("SellerId"); b.ToTable("SalesRecord"); }); modelBuilder.Entity("SalesMvc.Models.Seller", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<double>("BaseSalary"); b.Property<DateTime>("BirthDate"); b.Property<int>("DepartmentId"); b.Property<string>("Email"); b.Property<string>("Name"); b.HasKey("Id"); b.HasIndex("DepartmentId"); b.ToTable("Seller"); }); modelBuilder.Entity("SalesMvc.Models.SalesRecord", b => { b.HasOne("SalesMvc.Models.Seller", "Seller") .WithMany("Sales") .HasForeignKey("SellerId"); }); modelBuilder.Entity("SalesMvc.Models.Seller", b => { b.HasOne("SalesMvc.Models.Department", "Department") .WithMany("Sellers") .HasForeignKey("DepartmentId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
29.641304
74
0.480381
[ "MIT" ]
ErickNas/WebSystem
SalesMvc/Migrations/SalesMvcContextModelSnapshot.cs
2,729
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Linq; using ShaderTools.CodeAnalysis.Symbols.Markup; using ShaderTools.Utilities; using ShaderTools.Utilities.Collections; namespace ShaderTools.CodeAnalysis.Completion { internal static class CommonCompletionItem { public static CompletionItem Create( string displayText, CompletionItemRules rules, Glyph? glyph = null, ImmutableArray<SymbolMarkupToken> description = default(ImmutableArray<SymbolMarkupToken>), string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default(ImmutableArray<string>)) { tags = tags.NullToEmpty(); //if (glyph != null) //{ // // put glyph tags first // tags = GlyphTags.GetTags(glyph.Value).AddRange(tags); //} if (showsWarningIcon) { tags = tags.Add(CompletionTags.Warning); } properties = properties ?? ImmutableDictionary<string, string>.Empty; if (!description.IsDefault && description.Length > 0) { properties = properties.Add("Description", EncodeDescription(description)); } return CompletionItem.Create( displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, glyph: glyph ?? Glyph.None, tags: tags, rules: rules); } public static bool HasDescription(CompletionItem item) { return item.Properties.ContainsKey("Description"); } public static CompletionDescription GetDescription(CompletionItem item) { if (item.Properties.TryGetValue("Description", out var encodedDescription)) { return DecodeDescription(encodedDescription); } else { return CompletionDescription.Empty; } } private static char[] s_descriptionSeparators = new char[] { '|' }; private static string EncodeDescription(ImmutableArray<SymbolMarkupToken> description) { return EncodeDescription(description.ToTaggedText()); } private static string EncodeDescription(ImmutableArray<TaggedText> description) { if (description.Length > 0) { return string.Join("|", description .SelectMany(d => new string[] { d.Tag, d.Text }) .Select(t => t.Escape('\\', s_descriptionSeparators))); } else { return null; } } private static CompletionDescription DecodeDescription(string encoded) { var parts = encoded.Split(s_descriptionSeparators).Select(t => t.Unescape('\\')).ToArray(); var builder = ImmutableArray<TaggedText>.Empty.ToBuilder(); for (int i = 0; i < parts.Length; i += 2) { builder.Add(new TaggedText(parts[i], parts[i + 1])); } return CompletionDescription.Create(builder.ToImmutable()); } } }
35.40566
162
0.550759
[ "Apache-2.0" ]
comfanter/HLSLTools-for-Source
src/ShaderTools.CodeAnalysis.Features/Completion/CommonCompletionItem.cs
3,650
C#
/* * Copyright (c) 2010-2021 Achim Friedland <code@ahzf.de> * This file is part of Pipes.NET <https://www.github.com/ahzf/Pipes.NET> * * 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. */ #if SILVERLIGHT #region Usings using System; using System.Threading; #endregion namespace de.ahzf.Silverlight { public static class SilverlightTools { /// <summary> /// Silverlight is stupid... :( /// </summary> public static T CompareExchange<T>(ref T location1, T value, T comparand) { Object _location1 = location1; Object _value = value; Object _comparand = comparand; return (T) Interlocked.CompareExchange(ref _location1, _value, _comparand); } } } #endif
24.634615
87
0.671351
[ "Apache-2.0" ]
Vanaheimr/Styx
Styx/Styx/SilverlightTools.cs
1,283
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using dotNET_Chat_Server.Data; namespace dotNET_Chat_Server.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20201018142711_removeRandom")] partial class removeRandom { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.9") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("dotNET_Chat_Server.Models.ApplicationRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("dotNET_Chat_Server.Models.ApplicationUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("dotNET_Chat_Server.Models.Message", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuthorId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<Guid?>("RecipientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Text") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("AuthorId"); b.HasIndex("RecipientId"); b.ToTable("Messages"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("dotNET_Chat_Server.Models.Message", b => { b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", "Author") .WithMany("CreatedMessages") .HasForeignKey("AuthorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("dotNET_Chat_Server.Models.ApplicationUser", "Recipient") .WithMany("ReceivedMessages") .HasForeignKey("RecipientId"); }); #pragma warning restore 612, 618 } } }
37.761006
125
0.472185
[ "MIT" ]
michaldomino/dotNET-Chat-Server
Migrations/20201018142711_removeRandom.Designer.cs
12,010
C#
using System; using System.ComponentModel; using System.Globalization; using SFML.Graphics; namespace BlackCoat.Tools { /// <summary> /// Provides conversions between <see cref="string"/> values and <see cref="Color"/> values. /// </summary> /// <seealso cref="System.ComponentModel.ExpandableObjectConverter" /> public class ColorConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="destinationType">A <see cref="T:System.Type" /> that represents the type you want to convert to.</param> /// <returns> /// <see langword="true" /> if this converter can perform the conversion; otherwise, <see langword="false" />. /// </returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(Color) || base.CanConvertTo(context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo" />. If <see langword="null" /> is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="T:System.Object" /> to convert.</param> /// <param name="destinationType">The <see cref="T:System.Type" /> to convert the <paramref name="value" /> parameter to.</param> /// <returns> /// An <see cref="T:System.Object" /> that represents the converted value. /// </returns> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if(value is Color color) return $"{color.R}{Constants.SEPERATOR}{color.G}{Constants.SEPERATOR}{color.B}{Constants.SEPERATOR}{color.A}"; return base.ConvertTo(context, culture, value, destinationType); } /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="sourceType">A <see cref="T:System.Type" /> that represents the type you want to convert from.</param> /// <returns> /// <see langword="true" /> if this converter can perform the conversion; otherwise, <see langword="false" />. /// </returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param> /// <param name="value">The <see cref="T:System.Object" /> to convert.</param> /// <returns> /// An <see cref="T:System.Object" /> that represents the converted value. /// </returns> /// <exception cref="System.ArgumentException">Can not convert '{str}' to {nameof(Color)}</exception> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string str) { try { var parts = str.Split(Constants.SEPERATOR); return new Color(byte.Parse(parts[0]), byte.Parse(parts[1]), byte.Parse(parts[2]), byte.Parse(parts[3])); } catch (Exception e) { throw new ArgumentException($"Can not convert '{str}' to {nameof(Color)}", e); } } else return base.ConvertFrom(context, culture, value); } } }
56.39759
164
0.629353
[ "Apache-2.0" ]
Neovex/BlackCoat
src/Tools/Inspector/ColorConverter.cs
4,683
C#
using JT809.Protocol.JT809Enums; using JT809.Protocol.JT809Extensions; using JT809.Protocol.JT809SubMessageBody; using System; using System.Buffers; using System.Collections.Generic; using System.Text; namespace JT809.Protocol.JT809Formatters.JT809SubMessageBodyFormatters { public class JT809_0x9200_0x9205Formatter : IJT809Formatter<JT809_0x9200_0x9205> { public JT809_0x9200_0x9205 Deserialize(ReadOnlySpan<byte> bytes, out int readSize) { int offset = 0; JT809_0x9200_0x9205 jT809_0X1200_0x9205 = new JT809_0x9200_0x9205(); jT809_0X1200_0x9205.ReasonCode = (JT809_0x9205_ReasonCode)JT809BinaryExtensions.ReadByteLittle(bytes, ref offset); readSize = offset; return jT809_0X1200_0x9205; } public int Serialize(ref byte[] bytes, int offset, JT809_0x9200_0x9205 value) { offset += JT809BinaryExtensions.WriteByteLittle(bytes, offset,(byte)value.ReasonCode); return offset; } } }
35.413793
126
0.718598
[ "MIT" ]
786744873/JT809
src/JT809.Protocol/JT809Formatters/JT809SubMessageBodyFormatters/JT809_0x9200_0x9205Formatter.cs
1,029
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Maestra_productos { public partial class About : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
18.666667
61
0.654762
[ "MIT" ]
wgcv/Ayudantias-Programacion-en-Capas
Clase 5 Dividir dos capas - Maestra_productos(dos capas)/Maestra_productos/About.aspx.cs
338
C#
namespace Xtrimmer.SqlDatabaseBuilder { internal abstract class Currency : DataType { } }
14.714286
47
0.699029
[ "Apache-2.0" ]
Xtrimmer/SqlDatabaseBuilder
src/SqlDatabaseBuilder/DataTypes/Currency/Currency.cs
105
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Calendar.Colors.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Calendar.Colors.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.708333
181
0.603516
[ "MIT" ]
ChrisDiky/MaterialDesignInXaml.Examples
Calendar/Calendar.Colors/Properties/Resources.Designer.cs
2,789
C#
using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; using static System.ServiceProcess.ServiceStartMode; using static Jobs.WindowsService.Configuration.JobsServiceConfigurationSection; using static Jobs.WindowsService.Service; namespace Jobs.WindowsService { [RunInstaller(true)] public class JobsServiceInstaller : Installer { #region constructors public JobsServiceInstaller() { var section = GetSection(ServiceSection); Installers.AddRange(new Installer[] { new ServiceProcessInstaller { Password = null, Username = null }, new ServiceInstaller { Description = section.Description, DisplayName = section.DisplayName, ServiceName = section.Name, StartType = Automatic, DelayedAutoStart = true } }); } #endregion } }
35.771429
101
0.498403
[ "MIT" ]
KatoTek/Jobs
WindowsService/JobsServiceInstaller.cs
1,254
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="D2D1_CREATION_PROPERTIES" /> struct.</summary> public static unsafe class D2D1_CREATION_PROPERTIESTests { /// <summary>Validates that the <see cref="D2D1_CREATION_PROPERTIES" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<D2D1_CREATION_PROPERTIES>(), Is.EqualTo(sizeof(D2D1_CREATION_PROPERTIES))); } /// <summary>Validates that the <see cref="D2D1_CREATION_PROPERTIES" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(D2D1_CREATION_PROPERTIES).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="D2D1_CREATION_PROPERTIES" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(D2D1_CREATION_PROPERTIES), Is.EqualTo(12)); } } }
40.305556
145
0.685045
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/d2d1_1/D2D1_CREATION_PROPERTIESTests.cs
1,453
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; [System.Serializable] public class csShurikenEffectEditor : EditorWindow { private float Scale = 1; public GameObject Effect; public Color ShurikenSystemColor = Color.white; static csShurikenEffectEditor myWindow; [MenuItem("Window/Shuriken System Effect Editor")] public static void Init() { myWindow = EditorWindow.GetWindowWithRect<csShurikenEffectEditor>(new Rect(100, 100, 300, 220)); //set Editor Position and Size //myWindow.title = "Scale Editor"; myWindow.titleContent.text = "Scale Editor"; } [System.Obsolete] void OnGUI() { GUILayout.Box("Shuriken System Effect Scale Editor", GUILayout.Width(295)); EditorGUILayout.Space(); Effect = (GameObject)EditorGUILayout.ObjectField("Shuriken System Effect", Effect, typeof(GameObject), true); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); Scale = float.Parse(EditorGUILayout.TextField("Scale Change Value", Scale.ToString())); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Scale Apply", GUILayout.Height(70))) { if (Effect.GetComponent<csShurikenEffectChanger>() != null) Effect.GetComponent<csShurikenEffectChanger>().ShurikenParticleScaleChange(Scale); else { Effect.AddComponent<csShurikenEffectChanger>(); Effect.GetComponent<csShurikenEffectChanger>().ShurikenParticleScaleChange(Scale); } DestroyImmediate(Effect.GetComponent<csShurikenEffectChanger>()); } } } #endif
29.070175
129
0.76041
[ "MIT" ]
Supetorus/GAT185
Assets/External/48 Particle Effect Pack/ShurikenEffectEditor/csShurikenEffectEditor.cs
1,659
C#
using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public void PlayGame() { SceneManager.LoadScene(1); } public void QuitGame() { Application.Quit(); } }
15
37
0.633333
[ "MIT" ]
afterglow9000/EndlessRunner
Assets/Scripts/MainMenu.cs
242
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Device.I2c; using System.Threading; using Iot.Device.Vl53L0X; namespace Vl53L0Xsample { class Program { static void Main(string[] args) { Console.WriteLine("Hello VL53L0X!"); Vl53L0X vL53L0X = new Vl53L0X(I2cDevice.Create(new I2cConnectionSettings(1, Vl53L0X.DefaultI2cAddress))); Console.WriteLine($"Rev: {vL53L0X.Information.Revision}, Prod: {vL53L0X.Information.ProductId}, Mod: {vL53L0X.Information.ModuleId}"); Console.WriteLine($"Offset in µm: {vL53L0X.Information.OffsetMicrometers}, Signal rate fixed 400 µm: {vL53L0X.Information.SignalRateMeasuementFixed400Micrometers}"); vL53L0X.MeasurementMode = MeasurementMode.Continuous; while (!Console.KeyAvailable) { try { var dist = vL53L0X.Distance; if (dist != (ushort)OperationRange.OutOfRange) { Console.WriteLine($"Distance: {dist}"); } else { Console.WriteLine("Invalid data"); } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } Thread.Sleep(500); } } } }
36.111111
177
0.553846
[ "MIT" ]
Anberm/iot
src/devices/Vl53L0X/samples/Vl53L0X.sample.cs
1,629
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.NAS.Model.V20170626; namespace Aliyun.Acs.NAS.Transform.V20170626 { public class DescribeTieringJobsResponseUnmarshaller { public static DescribeTieringJobsResponse Unmarshall(UnmarshallerContext context) { DescribeTieringJobsResponse describeTieringJobsResponse = new DescribeTieringJobsResponse(); describeTieringJobsResponse.HttpResponse = context.HttpResponse; describeTieringJobsResponse.RequestId = context.StringValue("DescribeTieringJobs.RequestId"); describeTieringJobsResponse.TotalCount = context.IntegerValue("DescribeTieringJobs.TotalCount"); describeTieringJobsResponse.PageSize = context.IntegerValue("DescribeTieringJobs.PageSize"); describeTieringJobsResponse.PageNumber = context.IntegerValue("DescribeTieringJobs.PageNumber"); List<DescribeTieringJobsResponse.DescribeTieringJobs_TieringJob> describeTieringJobsResponse_tieringJobs = new List<DescribeTieringJobsResponse.DescribeTieringJobs_TieringJob>(); for (int i = 0; i < context.Length("DescribeTieringJobs.TieringJobs.Length"); i++) { DescribeTieringJobsResponse.DescribeTieringJobs_TieringJob tieringJob = new DescribeTieringJobsResponse.DescribeTieringJobs_TieringJob(); tieringJob.Name = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Name"); tieringJob.Volume = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Volume"); tieringJob.Path = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Path"); tieringJob.Recursive = context.BooleanValue("DescribeTieringJobs.TieringJobs["+ i +"].Recursive"); tieringJob.Type = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Type"); tieringJob.Policy = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Policy"); tieringJob.Weekday = context.IntegerValue("DescribeTieringJobs.TieringJobs["+ i +"].Weekday"); tieringJob.Hour = context.IntegerValue("DescribeTieringJobs.TieringJobs["+ i +"].Hour"); tieringJob.Enabled = context.BooleanValue("DescribeTieringJobs.TieringJobs["+ i +"].Enabled"); tieringJob.Status = context.StringValue("DescribeTieringJobs.TieringJobs["+ i +"].Status"); tieringJob.LastUpdateTime = context.LongValue("DescribeTieringJobs.TieringJobs["+ i +"].LastUpdateTime"); describeTieringJobsResponse_tieringJobs.Add(tieringJob); } describeTieringJobsResponse.TieringJobs = describeTieringJobsResponse_tieringJobs; return describeTieringJobsResponse; } } }
55.806452
182
0.765607
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-nas/NAS/Transform/V20170626/DescribeTieringJobsResponseUnmarshaller.cs
3,460
C#
using System; using System.IO; using System.IO.Packaging; using System.IO.Compression; using System.Linq; using System.Text; using System.Collections.Generic; using System.Printing; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Xps; using System.Windows.Xps.Packaging; //using System.Windows.Shapes; using ICSharpCode.AvalonEdit; using ICSharpCode.AvalonEdit.Utils; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Folding; using ICSharpCode.AvalonEdit.Indentation; using ICSharpCode.AvalonEdit.Highlighting; using ICSharpCode.AvalonEdit.CodeCompletion; using ICSharpCode.AvalonEdit.Search; using Microsoft.Win32; namespace WpfTestSvgSample { /// <summary> /// Interaction logic for SvgPage.xaml /// </summary> public partial class SvgPage : Page { #region Private Fields private string _currentFileName; private FoldingManager _foldingManager; private XmlFoldingStrategy _foldingStrategy; private SearchInputHandler _searchHandler; #endregion #region Constructors and Destructor public SvgPage() { InitializeComponent(); textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("XML"); TextEditorOptions options = textEditor.Options; if (options != null) { //options.AllowScrollBelowDocument = true; options.EnableHyperlinks = true; options.EnableEmailHyperlinks = true; //options.ShowSpaces = true; //options.ShowTabs = true; //options.ShowEndOfLine = true; } textEditor.ShowLineNumbers = true; _foldingManager = FoldingManager.Install(textEditor.TextArea); _foldingStrategy = new XmlFoldingStrategy(); textEditor.CommandBindings.Add(new CommandBinding( ApplicationCommands.Print, OnPrint, OnCanExecuteTextEditorCommand)); textEditor.CommandBindings.Add(new CommandBinding( ApplicationCommands.PrintPreview, OnPrintPreview, OnCanExecuteTextEditorCommand)); _searchHandler = new SearchInputHandler(textEditor.TextArea); textEditor.TextArea.DefaultInputHandler.NestedInputHandlers.Add(_searchHandler); } #endregion #region Public Methods public void LoadDocument(string documentFileName) { if (textEditor == null || String.IsNullOrEmpty(documentFileName)) { return; } if (!String.IsNullOrEmpty(_currentFileName) && File.Exists(_currentFileName)) { // Prevent reloading the same file, just in case we are editing... if (String.Equals(documentFileName, _currentFileName, StringComparison.OrdinalIgnoreCase)) { return; } } string fileExt = Path.GetExtension(documentFileName); if (String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase)) { using (FileStream fileStream = File.OpenRead(documentFileName)) { using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress)) { // Text Editor does not work with this stream, so we read the data to memory stream... MemoryStream memoryStream = new MemoryStream(); // Use this method is used to read all bytes from a stream. int totalCount = 0; int bufferSize = 512; byte[] buffer = new byte[bufferSize]; while (true) { int bytesRead = zipStream.Read(buffer, 0, bufferSize); if (bytesRead == 0) { break; } else { memoryStream.Write(buffer, 0, bytesRead); } totalCount += bytesRead; } if (totalCount > 0) { memoryStream.Position = 0; } textEditor.Load(memoryStream); memoryStream.Close(); } } } else { textEditor.Load(documentFileName); } if (_foldingManager == null || _foldingStrategy == null) { _foldingManager = FoldingManager.Install(textEditor.TextArea); _foldingStrategy = new XmlFoldingStrategy(); } _foldingStrategy.UpdateFoldings(_foldingManager, textEditor.Document); _currentFileName = documentFileName; } public void UnloadDocument() { if (textEditor != null) { textEditor.Document.Text = String.Empty; } } public void PageSelected(bool isSelected) { if (isSelected) { if (!textEditor.TextArea.IsKeyboardFocusWithin) { Keyboard.Focus(textEditor.TextArea); } } } #endregion #region Private Methods private void OnOpenFileClick(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.CheckFileExists = true; if (dlg.ShowDialog() ?? false) { this.LoadDocument(dlg.FileName); } } private void OnSaveFileClick(object sender, EventArgs e) { if (_currentFileName == null) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "SVG Files|*.svg;*.svgz"; dlg.DefaultExt = ".svg"; if (dlg.ShowDialog() ?? false) { _currentFileName = dlg.FileName; } else { return; } } string fileExt = Path.GetExtension(_currentFileName); if (String.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase)) { textEditor.Save(_currentFileName); } else if (String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase)) { using (FileStream svgzDestFile = File.Create(_currentFileName)) { using (GZipStream zipStream = new GZipStream(svgzDestFile, CompressionMode.Compress, true)) { textEditor.Save(zipStream); } } } } private void OnSearchTextClick(object sender, RoutedEventArgs e) { string searchText = searchTextBox.Text; if (String.IsNullOrEmpty(searchText)) { return; } _searchHandler.SearchPattern = searchText; _searchHandler.FindNext(); } private void OnSearchTextBoxKeyUp(object sender, KeyEventArgs e) { if (e.Key != Key.Enter) return; // your event handler here e.Handled = true; this.OnSearchTextClick(sender, e); } private void OnHighlightingSelectionChanged(object sender, SelectionChangedEventArgs e) { //if (textEditor.SyntaxHighlighting == null) //{ // _foldingStrategy = null; //} //else //{ // switch (textEditor.SyntaxHighlighting.Name) // { // case "XML": // _foldingStrategy = new XmlFoldingStrategy(); // textEditor.TextArea.IndentationStrategy = new DefaultIndentationStrategy(); // break; // case "C#": // case "C++": // case "PHP": // case "Java": // textEditor.TextArea.IndentationStrategy = new CSharpIndentationStrategy(textEditor.Options); // _foldingStrategy = new BraceFoldingStrategy(); // break; // default: // textEditor.TextArea.IndentationStrategy = new DefaultIndentationStrategy(); // _foldingStrategy = null; // break; // } //} //if (_foldingStrategy != null) //{ // if (_foldingManager == null) // _foldingManager = FoldingManager.Install(textEditor.TextArea); // _foldingStrategy.UpdateFoldings(_foldingManager, textEditor.Document); //} //else //{ // if (_foldingManager != null) // { // FoldingManager.Uninstall(_foldingManager); // _foldingManager = null; // } //} } #region Printing Methods private Block ConvertTextDocumentToBlock() { TextDocument document = textEditor.Document; IHighlighter highlighter = textEditor.TextArea.GetService(typeof(IHighlighter)) as IHighlighter; Paragraph p = new Paragraph(); foreach (DocumentLine line in document.Lines) { int lineNumber = line.LineNumber; HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line)); if (highlighter != null) { HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber); int lineStartOffset = line.Offset; foreach (HighlightedSection section in highlightedLine.Sections) inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color); } p.Inlines.AddRange(inlineBuilder.CreateRuns()); p.Inlines.Add(new LineBreak()); } return p; } private FlowDocument CreateFlowDocumentForEditor() { FlowDocument doc = new FlowDocument(ConvertTextDocumentToBlock()); doc.FontFamily = textEditor.FontFamily; doc.FontSize = textEditor.FontSize; return doc; } // CanExecuteRoutedEventHandler that only returns true if // the source is a control. private void OnCanExecuteTextEditorCommand(object sender, CanExecuteRoutedEventArgs e) { TextEditor target = e.Source as TextEditor; if (target != null) { e.CanExecute = true; } else { e.CanExecute = false; } } private void OnPrint(object sender, ExecutedRoutedEventArgs e) { PrintDialog printDialog = new PrintDialog(); printDialog.PageRangeSelection = PageRangeSelection.AllPages; printDialog.UserPageRangeEnabled = true; bool? dialogResult = printDialog.ShowDialog(); if (dialogResult != null && dialogResult.Value == false) { return; } FlowDocument printSource = this.CreateFlowDocumentForEditor(); // Save all the existing settings. double pageHeight = printSource.PageHeight; double pageWidth = printSource.PageWidth; Thickness pagePadding = printSource.PagePadding; double columnGap = printSource.ColumnGap; double columnWidth = printSource.ColumnWidth; // Make the FlowDocument page match the printed page. printSource.PageHeight = printDialog.PrintableAreaHeight; printSource.PageWidth = printDialog.PrintableAreaWidth; printSource.PagePadding = new Thickness(20); printSource.ColumnGap = Double.NaN; printSource.ColumnWidth = printDialog.PrintableAreaWidth; Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); DocumentPaginator paginator = ((IDocumentPaginatorSource)printSource).DocumentPaginator; paginator.PageSize = pageSize; paginator.ComputePageCount(); printDialog.PrintDocument(paginator, "Svg Contents"); // Reapply the old settings. printSource.PageHeight = pageHeight; printSource.PageWidth = pageWidth; printSource.PagePadding = pagePadding; printSource.ColumnGap = columnGap; printSource.ColumnWidth = columnWidth; } private void OnPrintPreview(object sender, ExecutedRoutedEventArgs e) { PrintDialog printDialog = new PrintDialog(); printDialog.PageRangeSelection = PageRangeSelection.AllPages; printDialog.UserPageRangeEnabled = true; bool? dialogResult = printDialog.ShowDialog(); if (dialogResult != null && dialogResult.Value == false) { return; } FlowDocument printSource = this.CreateFlowDocumentForEditor(); // Save all the existing settings. double pageHeight = printSource.PageHeight; double pageWidth = printSource.PageWidth; Thickness pagePadding = printSource.PagePadding; double columnGap = printSource.ColumnGap; double columnWidth = printSource.ColumnWidth; // Make the FlowDocument page match the printed page. printSource.PageHeight = printDialog.PrintableAreaHeight; printSource.PageWidth = printDialog.PrintableAreaWidth; printSource.PagePadding = new Thickness(20); printSource.ColumnGap = Double.NaN; printSource.ColumnWidth = printDialog.PrintableAreaWidth; Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); MemoryStream xpsStream = new MemoryStream(); Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite); string packageUriString = "memorystream://data.xps"; PackageStore.AddPackage(new Uri(packageUriString), package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Normal, packageUriString); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); DocumentPaginator paginator = ((IDocumentPaginatorSource)printSource).DocumentPaginator; paginator.PageSize = pageSize; paginator.ComputePageCount(); writer.Write(paginator); // Reapply the old settings. printSource.PageHeight = pageHeight; printSource.PageWidth = pageWidth; printSource.PagePadding = pagePadding; printSource.ColumnGap = columnGap; printSource.ColumnWidth = columnWidth; PrintPreviewWindow printPreview = new PrintPreviewWindow(); printPreview.Width = this.ActualWidth; printPreview.Height = this.ActualHeight; printPreview.Owner = Application.Current.MainWindow; printPreview.LoadDocument(xpsDocument, package, packageUriString); printPreview.Show(); } #endregion #endregion } }
37.529933
120
0.539052
[ "BSD-3-Clause" ]
GuillaumeSmartLiberty/SharpVectors
Main/Samples/WpfTestSvgSample/SvgPage.xaml.cs
16,928
C#
namespace android.preference { [global::MonoJavaBridge.JavaClass()] public partial class CheckBoxPreference : android.preference.Preference { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CheckBoxPreference() { InitJNI(); } protected CheckBoxPreference(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onClick6746; protected override void onClick() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onClick6746); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onClick6746); } internal static global::MonoJavaBridge.MethodId _isChecked6747; public virtual bool isChecked() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._isChecked6747); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._isChecked6747); } internal static global::MonoJavaBridge.MethodId _setChecked6748; public virtual void setChecked(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setChecked6748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setChecked6748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onRestoreInstanceState6749; protected override void onRestoreInstanceState(android.os.Parcelable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onRestoreInstanceState6749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onRestoreInstanceState6749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSaveInstanceState6750; protected override global::android.os.Parcelable onSaveInstanceState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onSaveInstanceState6750)) as android.os.Parcelable; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onSaveInstanceState6750)) as android.os.Parcelable; } internal static global::MonoJavaBridge.MethodId _onBindView6751; protected override void onBindView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onBindView6751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onBindView6751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _shouldDisableDependents6752; public override bool shouldDisableDependents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._shouldDisableDependents6752); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._shouldDisableDependents6752); } internal static global::MonoJavaBridge.MethodId _setSummaryOn6753; public virtual void setSummaryOn(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setSummaryOn6753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setSummaryOn6753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setSummaryOn6754; public virtual void setSummaryOn(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setSummaryOn6754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setSummaryOn6754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setSummaryOn(string arg0) { setSummaryOn((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _getSummaryOn6755; public virtual global::java.lang.CharSequence getSummaryOn() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._getSummaryOn6755)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._getSummaryOn6755)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _setSummaryOff6756; public virtual void setSummaryOff(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setSummaryOff6756, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setSummaryOff6756, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setSummaryOff6757; public virtual void setSummaryOff(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setSummaryOff6757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setSummaryOff6757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setSummaryOff(string arg0) { setSummaryOff((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _getSummaryOff6758; public virtual global::java.lang.CharSequence getSummaryOff() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._getSummaryOff6758)) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._getSummaryOff6758)) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getDisableDependentsState6759; public virtual bool getDisableDependentsState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._getDisableDependentsState6759); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._getDisableDependentsState6759); } internal static global::MonoJavaBridge.MethodId _setDisableDependentsState6760; public virtual void setDisableDependentsState(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._setDisableDependentsState6760, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._setDisableDependentsState6760, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onGetDefaultValue6761; protected override global::java.lang.Object onGetDefaultValue(android.content.res.TypedArray arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onGetDefaultValue6761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onGetDefaultValue6761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _onSetInitialValue6762; protected override void onSetInitialValue(bool arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference._onSetInitialValue6762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._onSetInitialValue6762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _CheckBoxPreference6763; public CheckBoxPreference(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._CheckBoxPreference6763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _CheckBoxPreference6764; public CheckBoxPreference(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._CheckBoxPreference6764, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _CheckBoxPreference6765; public CheckBoxPreference(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.CheckBoxPreference.staticClass, global::android.preference.CheckBoxPreference._CheckBoxPreference6765, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.CheckBoxPreference.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/CheckBoxPreference")); global::android.preference.CheckBoxPreference._onClick6746 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onClick", "()V"); global::android.preference.CheckBoxPreference._isChecked6747 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "isChecked", "()Z"); global::android.preference.CheckBoxPreference._setChecked6748 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setChecked", "(Z)V"); global::android.preference.CheckBoxPreference._onRestoreInstanceState6749 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V"); global::android.preference.CheckBoxPreference._onSaveInstanceState6750 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;"); global::android.preference.CheckBoxPreference._onBindView6751 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onBindView", "(Landroid/view/View;)V"); global::android.preference.CheckBoxPreference._shouldDisableDependents6752 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "shouldDisableDependents", "()Z"); global::android.preference.CheckBoxPreference._setSummaryOn6753 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setSummaryOn", "(I)V"); global::android.preference.CheckBoxPreference._setSummaryOn6754 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setSummaryOn", "(Ljava/lang/CharSequence;)V"); global::android.preference.CheckBoxPreference._getSummaryOn6755 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "getSummaryOn", "()Ljava/lang/CharSequence;"); global::android.preference.CheckBoxPreference._setSummaryOff6756 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setSummaryOff", "(I)V"); global::android.preference.CheckBoxPreference._setSummaryOff6757 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setSummaryOff", "(Ljava/lang/CharSequence;)V"); global::android.preference.CheckBoxPreference._getSummaryOff6758 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "getSummaryOff", "()Ljava/lang/CharSequence;"); global::android.preference.CheckBoxPreference._getDisableDependentsState6759 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "getDisableDependentsState", "()Z"); global::android.preference.CheckBoxPreference._setDisableDependentsState6760 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "setDisableDependentsState", "(Z)V"); global::android.preference.CheckBoxPreference._onGetDefaultValue6761 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onGetDefaultValue", "(Landroid/content/res/TypedArray;I)Ljava/lang/Object;"); global::android.preference.CheckBoxPreference._onSetInitialValue6762 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "onSetInitialValue", "(ZLjava/lang/Object;)V"); global::android.preference.CheckBoxPreference._CheckBoxPreference6763 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.preference.CheckBoxPreference._CheckBoxPreference6764 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.preference.CheckBoxPreference._CheckBoxPreference6765 = @__env.GetMethodIDNoThrow(global::android.preference.CheckBoxPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); } } }
82.183857
372
0.82032
[ "MIT" ]
beachmiles/androidmono
jni/MonoJavaBridge/android/generated/android/preference/CheckBoxPreference.cs
18,327
C#
/* * Copyright (C) 2021 - 2021, SanteSuite Inc. and the SanteSuite Contributors (See NOTICE.md for full copyright notices) * Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors * Portions Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology * * 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. * * User: fyfej * Date: 2021-8-5 */ using System; namespace SanteDB.Core.Model.Constants { /// <summary> /// Represents a collection of container cap keys. /// </summary> public static class ContainerCapKeys { /// <summary> /// Represents a child proof cap. /// </summary> public static readonly Guid ChildProof = Guid.Parse("5A209555-FB3A-437D-B043-0190685A4284"); /// <summary> /// Represents an easy open cap. /// </summary> public static readonly Guid EasyOpen = Guid.Parse("1E630924-CE10-4A8A-A91D-E319F517A6EC"); /// <summary> /// Represents a film cap. /// </summary> public static readonly Guid Film = Guid.Parse("266A20FE-DFFB-4C8D-9EAD-FDC7CD86C552"); /// <summary> /// Represents a foil cap. /// </summary> public static readonly Guid Foil = Guid.Parse("EE2B76DB-85E9-412F-90BB-47A94F8E4C30"); /// <summary> /// Represents a medication cap. /// </summary> public static readonly Guid MedicationCap = Guid.Parse("6470A9BE-FCB4-463D-BB0C-894D0CDDD4C2"); /// <summary> /// Represents a push cap. /// </summary> public static readonly Guid PushCap = Guid.Parse("47C40DF6-3F69-47CC-A84C-33037E4BFFD9"); /// <summary> /// Represents a screw cap. /// </summary> public static readonly Guid ScrewCap = Guid.Parse("05695B7C-6BF7-4AF7-A0C9-A5C8B2E63E05"); } }
36.476923
120
0.647828
[ "Apache-2.0" ]
santedb/santedb-model
SanteDB.Core.Model/Constants/ContainerCapKeys.cs
2,373
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Camera_Follow : MonoBehaviour { public GameObject player; private Vector3 offset; // Use this for initialization void Start () { offset = transform.position - player.transform.position; GetComponent<Camera_Move_2> ().enabled = false; player.transform.position = transform.forward; } // Update is called once per frame void LateUpdate () { transform.position = player.transform.position + offset; } }
19.034483
59
0.701087
[ "BSD-3-Clause" ]
ZzupleItInc/Zzuple-It
Assets/Scripts/Camera_Follow.cs
554
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Platform.ARMv8A32.Instructions { /// <summary> /// Cmfe - Compare floating with exception compare /// </summary> /// <seealso cref="Mosa.Platform.ARMv8A32.ARMv8A32Instruction" /> public sealed class Cmfe : ARMv8A32Instruction { internal Cmfe() : base(1, 1) { } public override bool IsCommutative { get { return true; } } public override void Emit(InstructionNode node, BaseCodeEmitter emitter) { System.Diagnostics.Debug.Assert(node.ResultCount == 1); System.Diagnostics.Debug.Assert(node.OperandCount == 1); if (node.Operand1.IsCPURegister) { emitter.OpcodeEncoder.Append4Bits(GetConditionCode(node.ConditionCode)); emitter.OpcodeEncoder.Append4Bits(0b1110); emitter.OpcodeEncoder.Append3Bits(0b110); emitter.OpcodeEncoder.Append1Bit(0b1); emitter.OpcodeEncoder.Append1Bit(0b0); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append4Bits(0b1111); emitter.OpcodeEncoder.Append4Bits(0b0001); emitter.OpcodeEncoder.Append1Bit(node.Operand1.IsR4 ? 0 : 1); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append1Bit(0b1); emitter.OpcodeEncoder.Append1Bit(0b0); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); return; } throw new Compiler.Common.Exceptions.CompilerException("Invalid Opcode"); } } }
31.632653
76
0.748387
[ "BSD-3-Clause" ]
Arakis/MOSA-Project
Source/Mosa.Platform.ARMv8A32/Instructions/Cmfe.cs
1,550
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200701.Outputs { [OutputType] public sealed class ApplicationGatewayRewriteRuleActionSetResponse { /// <summary> /// Request Header Actions in the Action Set. /// </summary> public readonly ImmutableArray<Outputs.ApplicationGatewayHeaderConfigurationResponse> RequestHeaderConfigurations; /// <summary> /// Response Header Actions in the Action Set. /// </summary> public readonly ImmutableArray<Outputs.ApplicationGatewayHeaderConfigurationResponse> ResponseHeaderConfigurations; /// <summary> /// Url Configuration Action in the Action Set. /// </summary> public readonly Outputs.ApplicationGatewayUrlConfigurationResponse? UrlConfiguration; [OutputConstructor] private ApplicationGatewayRewriteRuleActionSetResponse( ImmutableArray<Outputs.ApplicationGatewayHeaderConfigurationResponse> requestHeaderConfigurations, ImmutableArray<Outputs.ApplicationGatewayHeaderConfigurationResponse> responseHeaderConfigurations, Outputs.ApplicationGatewayUrlConfigurationResponse? urlConfiguration) { RequestHeaderConfigurations = requestHeaderConfigurations; ResponseHeaderConfigurations = responseHeaderConfigurations; UrlConfiguration = urlConfiguration; } } }
39.837209
123
0.730881
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20200701/Outputs/ApplicationGatewayRewriteRuleActionSetResponse.cs
1,713
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel; using Dapper; using DapperExtensions; using DapperExtensions.Mapper; namespace WFCommon { public class WF_M_CUSTOM_CLASSMAPPER : ClassMapper<WF_M_CUSTOM> { public WF_M_CUSTOM_CLASSMAPPER() { Map(f => f.CustomId).Key(KeyType.Assigned); AutoMap(); } } public class WF_M_CUSTOM { public string CustomId { get; set; } public string FieldName { get; set; } public string FieldDisplayText { get; set; } public int? FieldType { get; set; } public string FieldAdditional { get; set; } public int? IsAllowNull { get; set; } public string DefaultValue { get; set; } public int? IsActive { get; set; } public string Extend01 { get; set; } public string Extend02 { get; set; } public string Extend03 { get; set; } public string Extend04 { get; set; } public string Extend05 { get; set; } public string CreateUser { get; set; } public DateTime? CreateTime { get; set; } public string LastModifyUser { get; set; } public DateTime? LastModifyTime { get; set; } public string Station { get; set; } } }
28.095238
64
0.711017
[ "MIT" ]
suiyanxiang/XinSiYuanKanBan
sourcecode/WFCommon/Entities/WF_M_CUSTOM.cs
1,180
C#
using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.Band.Portable; using Microsoft.Band.Portable.Sensors; using PunchingBand.Recognition; using System; using System.ComponentModel; using System.IO; using System.Threading.Tasks; namespace PunchingBand.Models { public sealed class PunchBand : IDisposable { private bool punchDetectionRunning; private readonly Func<string, Task<Stream>> getReadStream; public PunchBand(BandClient bandClient, Func<string, Task<Stream>> getReadStream, Func<string, Task<Stream>> getWriteStream) { this.getReadStream = getReadStream; BandClient = bandClient; FistSide = FistSides.Unknown; Worn = false; PunchDetector = new PunchDetector(getReadStream, getWriteStream); } public BandClient BandClient { get; private set; } public PunchDetector PunchDetector { get; private set; } public BandTileModel BandTile { get; private set; } public FistSides FistSide { get; private set; } public bool Worn { get; private set; } public PunchInfo PunchInfo { get; private set; } public event EventHandler StartFight = delegate { }; public event EventHandler FistSideSelected = delegate { }; public event EventHandler WornChanged = delegate { }; public event EventHandler PunchInfoChanged = delegate { }; public async Task Initialize() { await SetupBandTile(); BandClient.SensorManager.Contact.ReadingChanged += ContactOnReadingChanged; await BandClient.SensorManager.Contact.StartReadingsAsync(BandSensorSampleRate.Ms16); // Now wait until Band is worn to finish initialization... } private async Task SetupBandTile() { BandTile = new BandTileModel(getReadStream); BandTile.PropertyChanged += TileOnPropertyChanged; BandTile.FightButtonClick += (sender, args) => StartFight(this, EventArgs.Empty); await BandTile.Initialize(BandClient); } private async void TileOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { if (propertyChangedEventArgs.PropertyName == "FistSide") { FistSide = BandTile.FistSide; FistSideSelected(this, EventArgs.Empty); await EnsurePunchDetection(); } } private async void ContactOnReadingChanged(object sender, BandSensorReadingEventArgs<BandContactReading> bandSensorReadingEventArgs) { Worn = bandSensorReadingEventArgs.SensorReading.State == ContactState.Worn; WornChanged(this, EventArgs.Empty); await EnsurePunchDetection(); } private async void GyroscopeOnReadingChanged(object sender, BandSensorReadingEventArgs<BandGyroscopeReading> bandSensorReadingEventArgs) { var accelerometerReading = lastAccelerometerReading; lastAccelerometerReading = null; if (!punchDetectionRunning) return; PunchInfo = await PunchDetector.GetPunchInfo(new Band.GyroscopeAccelerometerReading(bandSensorReadingEventArgs.SensorReading, accelerometerReading)).ConfigureAwait(false); PunchInfoChanged(this, EventArgs.Empty); } private BandAccelerometerReading lastAccelerometerReading = null; private void AccelerometerOnReadingChanged(object sender, BandSensorReadingEventArgs<BandAccelerometerReading> bandSensorReadingEventArgs) { lastAccelerometerReading = bandSensorReadingEventArgs.SensorReading; } private async Task EnsurePunchDetection() { if (FistSide != FistSides.Unknown && Worn) { await StartPunchDetection(); } else { await StopPunchDetection(); } } private async Task StartPunchDetection() { if (punchDetectionRunning) { // If fist side changed after punch detection was running reinitialize for new fist side if (PunchDetector.FistSide != FistSide) { await PunchDetector.Initialize(FistSide); } return; } var sw = Stopwatch.StartNew(); BandClient.SensorManager.Gyroscope.ReadingChanged += GyroscopeOnReadingChanged; BandClient.SensorManager.Accelerometer.ReadingChanged += AccelerometerOnReadingChanged; await PunchDetector.Initialize(FistSide); await BandClient.SensorManager.Gyroscope.StartReadingsAsync(BandSensorSampleRate.Ms16); await BandClient.SensorManager.Accelerometer.StartReadingsAsync(BandSensorSampleRate.Ms16); Debug.WriteLine("Punch Detection Started: {0}", sw.Elapsed); punchDetectionRunning = true; } private async Task StopPunchDetection() { if (!punchDetectionRunning) { return; } BandClient.SensorManager.Gyroscope.ReadingChanged -= GyroscopeOnReadingChanged; await BandClient.SensorManager.Gyroscope.StopReadingsAsync(); punchDetectionRunning = false; } public void Dispose() { FistSide = FistSides.Unknown; Worn = false; if (BandClient != null) { BandClient.DisconnectAsync(); BandClient = null; } if (PunchDetector != null) { PunchDetector.Dispose(); PunchDetector = null; } if (BandTile != null) { BandTile = null; } } public async Task ForceFistSide(FistSides fistSide) { FistSide = fistSide; await BandTile.ForceFistSide(fistSide); await EnsurePunchDetection(); } } }
32.397906
183
0.624596
[ "Apache-2.0" ]
scottlerch/PunchingBand
PunchingBand/Models/PunchBand.cs
6,190
C#
using Microsoft.AspNetCore.Mvc; namespace WebApp.Controllers { public class ShoppingCartController : Controller { public IActionResult Index() { return View(); } } }
16.615385
52
0.601852
[ "MIT" ]
mauroservienti/microservices-done-right-demos
3-view-cart/WebApp/Controllers/ShoppingCartController.cs
218
C#
'From MIT Squeak 0.9.4 (June 1, 2003) [No updates present.] on 30 August 2016 at 6:59:49 pm'! "Change Set: RSPRover Date: 27 August 2016 Author: EiichiroIto This is change file of RSPRover(Remote Sensor Protocol Rover) program"! Object subclass: #Base64Decoder instanceVariableNames: 'out in ' classVariableNames: 'DecoderTable ' poolDictionaries: '' category: 'Decoder-Base64'! Object subclass: #Base64Encoder instanceVariableNames: 'out in count ' classVariableNames: 'DecoderTable EncoderTable ' poolDictionaries: '' category: 'Decoder-Base64'! Object subclass: #ScratchServer instanceVariableNames: 'stage userName serverSocket incomingUDPSocket peerSockets peerNames sensors lastSentValues incomingBroadcasts outgoingBroadcasts in broadcastCache imageForm ' classVariableNames: '' poolDictionaries: '' category: 'Scratch-Networking'! !Base64Decoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! decode | t1 t2 t3 t4 t5 t6 t7 t8 | [true] whileTrue: [t1 _ self next. t1 ifNil: [^ self]. t2 _ self next. t2 ifNil: [^ self]. t5 _ self class decoderTable at: t1. t6 _ self class decoderTable at: t2. self put: (t5 << 2 bitOr: t6 >> 4). t3 _ self next. t3 ifNil: [^ self]. t7 _ self class decoderTable at: t3. self put: ((t6 bitAnd: 15) << 4 bitOr: t7 >> 2). t4 _ self next. t4 ifNil: [^ self]. t8 _ self class decoderTable at: t4. self put: ((t7 bitAnd: 3) << 6 bitOr: t8)]! ! !Base64Decoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! next | t1 | in atEnd ifTrue: [^ nil]. t1 _ in next. t1 = $= ifTrue: [^ nil]. ^ t1! ! !Base64Decoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! put: t1 out nextPut: t1! ! !Base64Decoder methodsFor: 'accessing' stamp: 'EiichiroIto 8/27/2016 10:00'! decode: t1 in _ ReadStream on: t1. out _ WriteStream on: ByteArray new. self decode. ^ out contents! ! !Base64Decoder class methodsFor: 'initialization' stamp: 'EiichiroIto 8/27/2016 10:00'! initialize DecoderTable _ nil! ! !Base64Decoder class methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! defaultDecoderTable ^ Dictionary newFrom: ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' asArray withIndexCollect: [:t1 :t2 | t1 -> (t2 - 1)])! ! !Base64Decoder class methodsFor: 'accessing' stamp: 'EiichiroIto 8/27/2016 10:00'! decoderTable ^ DecoderTable ifNil: [DecoderTable _ self defaultDecoderTable]! ! !Base64Encoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! encode | t1 t2 | [true] whileTrue: [t1 _ self next. t1 ifNil: [^ self]. t2 _ t1 >> 2. self put: (self class encoderTable at: t2 + 1). t2 _ (t1 bitAnd: 3) << 4. t1 _ self next. t1 ifNil: [^ self put: (self class encoderTable at: t2 + 1)]. t2 _ t2 bitOr: t1 >> 4. self put: (self class encoderTable at: t2 + 1). t2 _ (t1 bitAnd: 15) << 2. t1 _ self next. t1 ifNil: [^ self put: (self class encoderTable at: t2 + 1)]. t2 _ t2 bitOr: t1 >> 6. self put: (self class encoderTable at: t2 + 1). t2 _ t1 bitAnd: 63. self put: (self class encoderTable at: t2 + 1)]! ! !Base64Encoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! next in atEnd ifTrue: [^ nil]. ^ in next! ! !Base64Encoder methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! put: t1 out nextPut: t1. count _ count + 1 \\ 4! ! !Base64Encoder methodsFor: 'accessing' stamp: 'EiichiroIto 8/27/2016 10:00'! encode: t1 in _ ReadStream on: t1. out _ WriteStream on: String new. count _ 0. self encode. count > 0 ifTrue: [4 - count timesRepeat: [self put: $=]]. ^ out contents! ! !Base64Encoder class methodsFor: 'initialization' stamp: 'EiichiroIto 8/27/2016 10:00'! initialize EncoderTable _ nil! ! !Base64Encoder class methodsFor: 'accessing' stamp: 'EiichiroIto 8/27/2016 10:00'! encoderTable ^ EncoderTable ifNil: [EncoderTable _ self defaultEncoderTable]! ! !Base64Encoder class methodsFor: 'private' stamp: 'EiichiroIto 8/27/2016 10:00'! defaultEncoderTable ^ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' asArray! ! !ScratchFrameMorph methodsFor: 'intialization' stamp: 'EiichiroIto 8/30/2016 18:54'! createMenuPanel "Create and add a panel containing the menus and close button." | menuSpecs m | "create panel" menuPanel _ AlignmentMorph new color: Color transparent; centering: #center; inset: 0; height: 0. "will grow as needed" self addShortcutButtonsTo: menuPanel. "menuSpecs defines the menus" menuSpecs _ #( "name selector" (File fileMenu:) (Edit editMenu:) (Share shareMenu:) (Help helpMenu:) ). menuSpecs do: [:spec | m _ ScratchMenuTitleMorph new contents: (spec at: 1) localized; target: self selector: (spec at: 2). menuPanel addMorphBack: m. #helpMenu: = (spec at: 2) ifFalse: [ menuPanel addMorphBack: (Morph new color: Color transparent; extent: 12@5)]]. topPane addMorph: menuPanel. ! ! !ScratchFrameMorph methodsFor: 'menu/button actions' stamp: 'EiichiroIto 8/30/2016 18:54'! addServerCommandsTo: menu "Add Scratch server commands to the given menu." | disable endCmd | disable _ false. "make this true to disable this feature" disable ifTrue: [^ self]. menu addLine. (workPane scratchServer notNil and: [workPane scratchServer sessionInProgress]) ifTrue: [ menu add: 'Show IP Address' action: #showNetworkAddress. endCmd _ workPane scratchServer isHosting ifTrue: ['Stop Hosting Mesh'] ifFalse: ['Leave Mesh']. menu add: endCmd action: #exitScratchSession] ifFalse: [ menu add: 'Host Mesh' action: #startHostingScratchSession. menu add: 'Join Mesh' action: #joinScratchSession]. ! ! !ScratchFrameMorph methodsFor: 'menu/button actions' stamp: 'EiichiroIto 8/27/2016 19:07'! shareMenu: aMenuTitleMorph | menu | menu _ CustomMenu new. self addServerCommandsTo: menu. menu localize. menu invokeOn: self at: aMenuTitleMorph bottomLeft + (0 @ 10)! ! !ScratchServer methodsFor: 'accessing' stamp: 'EiichiroIto 8/30/2016 18:54'! imageForm ^ imageForm! ! !ScratchServer methodsFor: 'private-incoming commands' stamp: 'EiichiroIto 8/30/2016 18:54'! dispatch: aString from: requestSock "Dispatch an incoming command from a remote Scratch." | cmd op | aString size = 0 ifTrue: [ requestSock sendMessage: 'version "ScratchServer 2.0 alpha"'. ^ self]. op _ self opcodeFrom: aString. op size = 0 ifTrue: [^ self]. (#('broadcast' 'sensor-update' 'peer-name' 'send-vars' 'jpg' 'gif' 'png') includes: op) ifFalse: [^ self]. cmd _ self parse: aString. 'broadcast' = op ifTrue: [ self doBroadcast: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. 'sensor-update' = op ifTrue: [ self doSensorUpdate: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. 'peer-name' = op ifTrue: [^ self doPeerName: cmd from: requestSock]. 'send-vars' = op ifTrue: [ self doSendVars: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. 'jpg' = op ifTrue: [ self doJpg: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. 'gif' = op ifTrue: [ self doGif: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. 'png' = op ifTrue: [ self doPng: cmd from: requestSock. ^ self resend: aString toPeersExcept: requestSock]. ! ! !ScratchServer methodsFor: 'private-incoming commands' stamp: 'EiichiroIto 8/30/2016 18:54'! doGif: cmd from: requestSocket | b64Data rawData | cmd size = 2 ifFalse: [^ self]. ((b64Data _ cmd at: 2) isKindOf: String) ifFalse: [^ self]. rawData _ Base64Decoder new decode: b64Data. imageForm _ (GIFReadWriter on: (ReadStream on: rawData)) nextImage. incomingBroadcasts removeAllSuchThat: [:each | each = 'photoReceived']. incomingBroadcasts add: 'photoReceived'! ! !ScratchServer methodsFor: 'private-incoming commands' stamp: 'EiichiroIto 8/30/2016 18:54'! doJpg: cmd from: requestSocket | b64Data rawData | cmd size = 2 ifFalse: [^ self]. ((b64Data _ cmd at: 2) isKindOf: String) ifFalse: [^ self]. rawData _ Base64Decoder new decode: b64Data. imageForm _ FastJPEG uncompress: rawData. incomingBroadcasts removeAllSuchThat: [:each | each = 'photoReceived']. incomingBroadcasts add: 'photoReceived'! ! !ScratchServer methodsFor: 'private-incoming commands' stamp: 'EiichiroIto 8/30/2016 18:54'! doPng: cmd from: requestSocket | b64Data rawData | cmd size = 2 ifFalse: [^ self]. ((b64Data _ cmd at: 2) isKindOf: String) ifFalse: [^ self]. rawData _ Base64Decoder new decode: b64Data. imageForm _ (PNGReadWriter on: (ReadStream on: rawData)) nextImage. incomingBroadcasts removeAllSuchThat: [:each | each = 'photoReceived']. incomingBroadcasts add: 'photoReceived'! ! !ScriptableScratchMorph methodsFor: 'looks ops' stamp: 'EiichiroIto 8/30/2016 18:42'! deleteCostume self deleteMedia: costume! ! !ScriptableScratchMorph methodsFor: 'looks ops' stamp: 'EiichiroIto 8/30/2016 18:42'! duplicateCostume self duplicateMedia: costume. self lookLike: media last! ! !ScriptableScratchMorph methodsFor: 'looks ops' stamp: 'EiichiroIto 8/30/2016 18:43'! numCostumes ^ (media reject: [:each | each isSound]) size! ! !ScriptableScratchMorph methodsFor: 'looks ops' stamp: 'EiichiroIto 8/30/2016 18:43'! prevCostume self costumeIndex: self costumeIndex - 1! ! !ScriptableScratchMorph methodsFor: 'looks ops' stamp: 'EiichiroIto 8/30/2016 18:54'! setReceivedPhoto | form | owner scratchServer ifNil: [^ self]. form _ owner scratchServer imageForm. form ifNil: [^ self]. costume form: form. self costumeChanged! ! !ScratchSpriteMorph class methodsFor: 'block specs' stamp: 'EiichiroIto 8/30/2016 18:54'! blockSpecs | blocks | blocks _ #( 'motion' ('move %n steps' - forward:) ('turn %n degrees' - turnRight: 15) "icon shows turn direction" ('turn %n degrees' - turnLeft: 15) "icon shows turn direction" - ('point in direction %d' - heading: 90) ('point towards %m' - pointTowards:) - ('go to x:%n y:%n' - gotoX:y: 0 0) ('go to %m' - gotoSpriteOrMouse:) ('glide %n secs to x:%n y:%n' t glideSecs:toX:y:elapsed:from: 1 50 50) - ('change x by %n' - changeXposBy: 10) ('set x to %n' - xpos: 0) ('change y by %n' - changeYposBy: 10) ('set y to %n' - ypos: 0) - ('if on edge, bounce' - bounceOffEdge) - ('x position' r xpos) ('y position' r ypos) ('direction' r heading) 'pen' ('clear' - clearPenTrails) - ('pen down' - putPenDown) ('pen up' - putPenUp) - ('set pen color to %c' - penColor:) ('change pen color by %n' - changePenHueBy:) ('set pen color to %n' - setPenHueTo: 0) - ('change pen shade by %n' - changePenShadeBy:) ('set pen shade to %n' - setPenShadeTo: 50) - ('change pen size by %n' - changePenSizeBy: 1) ('set pen size to %n' - penSize: 1) - ('stamp' - stampCostume) ). blocks _ blocks, #( 'looks' ('switch to costume %l' - lookLike:) ('next costume' - nextCostume) ('previous costume' - prevCostume) ('costume #' r costumeIndex) ('set received photo' - setReceivedPhoto) ('number of costumes' r numCostumes) ('duplicate costume' - duplicateCostume) ('delete costume' - deleteCostume) - ('say %s for %n secs' t say:duration:elapsed:from: 'Hello!!' 2) ('say %s' - say: 'Hello!!') ('think %s for %n secs' t think:duration:elapsed:from: 'Hmm...' 2) ('think %s' - think: 'Hmm...') - ('change %g effect by %n' - changeGraphicEffect:by: 'color' 25) ('set %g effect to %n' - setGraphicEffect:to: 'color' 0) ('clear graphic effects' - filterReset) - ('change size by %n' - changeSizeBy:) ('set size to %n%' - setSizeTo: 100) ('size' r scale) - ('show' - show) ('hide' - hide) - ('go to front' - comeToFront) ('go back %n layers' - goBackByLayers: 1) 'sensing' ('touching %m?' b touching:) ('touching color %C?' b touchingColor:) ('color %C is touching %C?' b color:sees:) - ('ask %s and wait' s doAsk 'What''s your name?') ('answer' r answer) - ('mouse x' r mouseX) ('mouse y' r mouseY) ('mouse down?' b mousePressed) - ('key %k pressed?' b keyPressed: 'space') - ('distance to %m' r distanceTo:) - ('reset timer' - timerReset) ('timer' r timer) - ('%a of %m' r getAttribute:of:) - ('loudness' r soundLevel) ('loud?' b isLoud) ~ ('%H sensor value' r sensor: 'slider') ('sensor %h?' b sensorPressed: 'button pressed') ). ^ blocks, super blockSpecs ! ! Base64Encoder initialize! Base64Decoder initialize!
12,867
12,867
0.670708
[ "MIT" ]
EiichiroIto/RSPRover
RSPRover.cs
12,867
C#
namespace Interface.Services { class BrazilTaxService : ITaxService { public double Tax(double amount) { if(amount <= 100.00) { return amount * 0.2; } else { return amount * 0.15; } } } }
18.277778
40
0.398176
[ "MIT" ]
MateusMacial/Udemy_CSharp
secao_14/01_Interface_Exercicio_Resolvido/Interface/Services/BrazilTaxService.cs
331
C#
using System.Collections; using System.Collections.Generic; using Unity.Entities; using Unity.Mathematics; using UnityEngine; public class LifetimeSystem : SystemBase { protected override void OnUpdate() { float deltaTime = Time.DeltaTime; Entities.ForEach((ref LifetimeComponent lifetime) => { lifetime.TimeRemaining = math.max(lifetime.TimeRemaining - 1f * deltaTime, 0f); }).Schedule(); } }
22.047619
91
0.669546
[ "MIT" ]
guidoarkesteijn/unity-hybrid-ecs
Assets/Scripts/Lifetime/LifetimeSystem.cs
465
C#
using System; using System.Collections.Immutable; using System.Data; using System.Data.SQLite; using System.IO; using System.Linq; using System.Threading.Tasks; using Wabbajack.Common; using Wabbajack.DTOs.Streams; using Wabbajack.Hashing.xxHash64; using Wabbajack.Paths; using Wabbajack.Paths.IO; namespace Wabbajack.VFS { public class VFSCache { private readonly SQLiteConnection _conn; private readonly string _connectionString; private readonly AbsolutePath _path; public VFSCache(AbsolutePath path) { _path = path; if (!_path.Parent.DirectoryExists()) _path.Parent.CreateDirectory(); _connectionString = string.Intern($"URI=file:{path};Pooling=True;Max Pool Size=100; Journal Mode=Memory;"); _conn = new SQLiteConnection(_connectionString); _conn.Open(); using var cmd = new SQLiteCommand(_conn); cmd.CommandText = @"CREATE TABLE IF NOT EXISTS VFSCache ( Hash BIGINT PRIMARY KEY, Contents BLOB) WITHOUT ROWID"; cmd.ExecuteNonQuery(); } public bool TryGetFromCache(Context context, VirtualFile parent, IPath path, IStreamFactory extractedFile, Hash hash, out VirtualFile found) { using var cmd = new SQLiteCommand(_conn); cmd.CommandText = @"SELECT Contents FROM VFSCache WHERE Hash = @hash"; cmd.Parameters.AddWithValue("@hash", (long)hash); using var rdr = cmd.ExecuteReader(); while (rdr.Read()) { var data = IndexedVirtualFile.Read(rdr.GetStream(0)); found = ConvertFromIndexedFile(context, data, path, parent, extractedFile); found.Name = path; found.Hash = hash; return true; } found = default; return false; } private static VirtualFile ConvertFromIndexedFile(Context context, IndexedVirtualFile file, IPath path, VirtualFile vparent, IStreamFactory extractedFile) { var vself = new VirtualFile { Context = context, Name = path, Parent = vparent, Size = file.Size, LastModified = extractedFile.LastModifiedUtc.AsUnixTime(), LastAnalyzed = DateTime.Now.AsUnixTime(), Hash = file.Hash, ImageState = file.ImageState }; vself.FillFullPath(); vself.Children = file.Children.Select(f => ConvertFromIndexedFile(context, f, f.Name, vself, extractedFile)) .ToImmutableList(); return vself; } public async Task WriteToCache(VirtualFile self) { await using var ms = new MemoryStream(); var ivf = self.ToIndexedVirtualFile(); // Top level path gets renamed when read, we don't want the absolute path // here else the reader will blow up when it tries to convert the value ivf.Name = (RelativePath)"not/applicable"; ivf.Write(ms); ms.Position = 0; await InsertIntoVFSCache(self.Hash, ms); } private async Task InsertIntoVFSCache(Hash hash, MemoryStream data) { await using var cmd = new SQLiteCommand(_conn); cmd.CommandText = @"INSERT INTO VFSCache (Hash, Contents) VALUES (@hash, @contents)"; cmd.Parameters.AddWithValue("@hash", (long)hash); var val = new SQLiteParameter("@contents", DbType.Binary) { Value = data.ToArray() }; cmd.Parameters.Add(val); try { await cmd.ExecuteNonQueryAsync(); } catch (SQLiteException ex) { if (ex.Message.StartsWith("constraint failed")) return; throw; } } public void VacuumDatabase() { using var cmd = new SQLiteCommand(_conn); cmd.CommandText = @"VACUUM"; cmd.PrepareAsync(); cmd.ExecuteNonQuery(); } } }
34.256
120
0.567492
[ "Unlicense" ]
wabbajack-tools/wabbajack
Wabbajack.VFS/VFSCache.cs
4,282
C#
using System; using System.Collections.Generic; using System.Reflection; namespace System.Data.Dabber { public static partial class SqlMapper { private sealed partial class DapperRow : System.Dynamic.IDynamicMetaObjectProvider { System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject( System.Linq.Expressions.Expression parameter) { return new DapperRowMetaObject(parameter, System.Dynamic.BindingRestrictions.Empty, this); } } private sealed class DapperRowMetaObject : System.Dynamic.DynamicMetaObject { private static readonly MethodInfo getValueMethod = typeof(IDictionary<string, object>).GetProperty("Item").GetGetMethod(); private static readonly MethodInfo setValueMethod = typeof(DapperRow).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) }); public DapperRowMetaObject( System.Linq.Expressions.Expression expression, System.Dynamic.BindingRestrictions restrictions ) : base(expression, restrictions) { } public DapperRowMetaObject( System.Linq.Expressions.Expression expression, System.Dynamic.BindingRestrictions restrictions, object value ) : base(expression, restrictions, value) { } private System.Dynamic.DynamicMetaObject CallMethod( MethodInfo method, System.Linq.Expressions.Expression[] parameters ) { var callMethod = new System.Dynamic.DynamicMetaObject( System.Linq.Expressions.Expression.Call( System.Linq.Expressions.Expression.Convert(Expression, LimitType), method, parameters), System.Dynamic.BindingRestrictions.GetTypeRestriction(Expression, LimitType) ); return callMethod; } public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder) { var parameters = new System.Linq.Expressions.Expression[] { System.Linq.Expressions.Expression.Constant(binder.Name) }; var callMethod = CallMethod(getValueMethod, parameters); return callMethod; } // Needed for Visual basic dynamic support public override System.Dynamic.DynamicMetaObject BindInvokeMember(System.Dynamic.InvokeMemberBinder binder, System.Dynamic.DynamicMetaObject[] args) { var parameters = new System.Linq.Expressions.Expression[] { System.Linq.Expressions.Expression.Constant(binder.Name) }; var callMethod = CallMethod(getValueMethod, parameters); return callMethod; } public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value) { var parameters = new System.Linq.Expressions.Expression[] { System.Linq.Expressions.Expression.Constant(binder.Name), value.Expression, }; var callMethod = CallMethod(setValueMethod, parameters); return callMethod; } public override IEnumerable<string> GetDynamicMemberNames() { if (HasValue && Value is IDictionary<string, object> lookup) return lookup.Keys; #if NETFrame return new string[0]; #else return Array.Empty<string>(); #endif } } } }
39.961905
160
0.558627
[ "MIT" ]
erikzhouxin/NDabber
src/Dabber/SqlMapper.DapperRowMetaObject.cs
4,198
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures { class Program { static void Main(string[] args) { Example.SUb(); //Example example = new Example(); // example.Add(); Console.Read(); } } public class Example { static Example() { Console.WriteLine("Staticc Constructor"); } public static void SUb() { } public Example() { Console.WriteLine("Regular Constructor"); } public void Add() { Console.WriteLine("Method from Example"); } } }
18.926829
53
0.514175
[ "MIT" ]
kotikavoori/Back2Basics
DataStructures/Program.cs
778
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using OfaSchlupfer.TextTemplate.Runtime; using OfaSchlupfer.TextTemplate.Syntax; namespace OfaSchlupfer.TextTemplate.Functions { /// <summary> /// A datetime object represents an instant in time, expressed as a date and time of day. /// /// | Name | Description /// |-------------- |----------------- /// | `.year` | Gets the year of a date object /// | `.month` | Gets the month of a date object /// | `.day` | Gets the day in the month of a date object /// | `.day_of_year` | Gets the day within the year /// | `.hour` | Gets the hour of the date object /// | `.minute` | Gets the minute of the date object /// | `.second` | Gets the second of the date object /// | `.millisecond` | Gets the millisecond of the date object /// /// [:top:](#builtins) /// #### Binary operations /// /// The substract operation `date1 - date2`: Substract `date2` from `date1` and return a timespan internal object (see timespan object below). /// /// Other comparison operators(`==`, `!=`, `&lt;=`, `&gt;=`, `&lt;`, `&gt;`) are also working with date objects. /// /// A `timespan` and also the added to a `datetime` object. /// </summary> /// <seealso cref="Scriban.Runtime.ScriptObject" /> public class DateTimeFunctions : ScriptObject, IScriptCustomFunction { private const string FormatKey = "format"; // This is exposed as well as default_format public const string DefaultFormat = "%d %b %Y"; [ScriptMemberIgnore] public static readonly ScriptVariable DateVariable = new ScriptVariableGlobal("date"); // Code from DotLiquid https://github.com/dotliquid/dotliquid/blob/master/src/DotLiquid/Util/StrFTime.cs // Apache License, Version 2.0 private static readonly Dictionary<char, Func<DateTime, CultureInfo, string>> Formats = new Dictionary<char, Func<DateTime, CultureInfo, string>> { { 'a', (dateTime, cultureInfo) => dateTime.ToString("ddd", cultureInfo) }, { 'A', (dateTime, cultureInfo) => dateTime.ToString("dddd", cultureInfo) }, { 'b', (dateTime, cultureInfo) => dateTime.ToString("MMM", cultureInfo) }, { 'B', (dateTime, cultureInfo) => dateTime.ToString("MMMM", cultureInfo) }, { 'c', (dateTime, cultureInfo) => dateTime.ToString("ddd MMM dd HH:mm:ss yyyy", cultureInfo) }, { 'd', (dateTime, cultureInfo) => dateTime.ToString("dd", cultureInfo) }, { 'e', (dateTime, cultureInfo) => dateTime.ToString("%d", cultureInfo).PadLeft(2, ' ') }, { 'H', (dateTime, cultureInfo) => dateTime.ToString("HH", cultureInfo) }, { 'I', (dateTime, cultureInfo) => dateTime.ToString("hh", cultureInfo) }, { 'j', (dateTime, cultureInfo) => dateTime.DayOfYear.ToString().PadLeft(3, '0') }, { 'm', (dateTime, cultureInfo) => dateTime.ToString("MM", cultureInfo) }, { 'M', (dateTime, cultureInfo) => dateTime.Minute.ToString().PadLeft(2, '0') }, { 'p', (dateTime, cultureInfo) => dateTime.ToString("tt", cultureInfo) }, { 'S', (dateTime, cultureInfo) => dateTime.ToString("ss", cultureInfo) }, { 'U', (dateTime, cultureInfo) => cultureInfo.Calendar.GetWeekOfYear(dateTime, cultureInfo.DateTimeFormat.CalendarWeekRule, DayOfWeek.Sunday).ToString().PadLeft(2, '0') }, { 'W', (dateTime, cultureInfo) => cultureInfo.Calendar.GetWeekOfYear(dateTime, cultureInfo.DateTimeFormat.CalendarWeekRule, DayOfWeek.Monday).ToString().PadLeft(2, '0') }, { 'w', (dateTime, cultureInfo) => ((int) dateTime.DayOfWeek).ToString() }, { 'x', (dateTime, cultureInfo) => dateTime.ToString("d", cultureInfo) }, { 'X', (dateTime, cultureInfo) => dateTime.ToString("T", cultureInfo) }, { 'y', (dateTime, cultureInfo) => dateTime.ToString("yy", cultureInfo) }, { 'Y', (dateTime, cultureInfo) => dateTime.ToString("yyyy", cultureInfo) }, { 'Z', (dateTime, cultureInfo) => dateTime.ToString("zzz", cultureInfo) }, { '%', (dateTime, cultureInfo) => "%" } }; /// <summary> /// Initializes a new instance of the <see cref="DateTimeFunctions"/> class. /// </summary> public DateTimeFunctions() { Format = DefaultFormat; CreateImportFunctions(); } /// <summary> /// Gets or sets the format used to format all dates /// </summary> public string Format { get => GetSafeValue<string>(FormatKey) ?? DefaultFormat; set => SetValue(FormatKey, value, false); } /// <summary> /// Returns a datetime object of the current time, including the hour, minutes, seconds and milliseconds. /// </summary> /// <remarks> /// ```scriban-html /// {{ date.now.year }} /// ``` /// ```html /// 2017 /// ``` /// </remarks> public static DateTime Now => DateTime.Now; /// <summary> /// Adds the specified number of days to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="days">The days.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_days 1 }} /// ``` /// ```html /// 06 Jan 2016 /// ``` /// </remarks> public static DateTime AddDays(DateTime date, double days) { return date.AddDays(days); } /// <summary> /// Adds the specified number of months to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="months">The months.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_months 1 }} /// ``` /// ```html /// 05 Feb 2016 /// ``` /// </remarks> public static DateTime AddMonths(DateTime date, int months) { return date.AddMonths(months); } /// <summary> /// Adds the specified number of years to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="years">The years.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_years 1 }} /// ``` /// ```html /// 05 Jan 2017 /// ``` /// </remarks> public static DateTime AddYears(DateTime date, int years) { return date.AddYears(years); } /// <summary> /// Adds the specified number of hours to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="hours">The hours.</param> /// <returns>A new date</returns> public static DateTime AddHours(DateTime date, double hours) { return date.AddHours(hours); } /// <summary> /// Adds the specified number of minutes to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="minutes">The minutes.</param> /// <returns>A new date</returns> public static DateTime AddMinutes(DateTime date, double minutes) { return date.AddMinutes(minutes); } /// <summary> /// Adds the specified number of seconds to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="seconds">The seconds.</param> /// <returns>A new date</returns> public static DateTime AddSeconds(DateTime date, double seconds) { return date.AddSeconds(seconds); } /// <summary> /// Adds the specified number of milliseconds to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="millis">The milliseconds.</param> /// <returns>A new date</returns> public static DateTime AddMilliseconds(DateTime date, double millis) { return date.AddMilliseconds(millis); } /// <summary> /// Parses the specified input string to a date object. /// </summary> /// <param name="context">The template context.</param> /// <param name="text">A text representing a date.</param> /// <returns>A date object</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' }} /// ``` /// ```html /// 05 Jan 2016 /// ``` /// </remarks> public static DateTime? Parse(TemplateContext context, string text) { if (string.IsNullOrEmpty(text)) { return null; } DateTime result; if (DateTime.TryParse(text, context.CurrentCulture, DateTimeStyles.None, out result)) { return result; } return new DateTime(); } public override IScriptObject Clone(bool deep) { var dateFunctions = (DateTimeFunctions)base.Clone(deep); // This is important to call the CreateImportFunctions as it is instance specific (using DefaultFormat from `date` object) dateFunctions.CreateImportFunctions(); return dateFunctions; } /// <summary> /// Converts a datetime object to a textual representation using the specified format string. /// /// By default, if you are using a date, it will use the format specified by `date.format` which defaults to /// `date.default_format` (readonly) which default to `%d %b %Y` /// /// You can override the format used for formatting all dates by assigning the a new format: `date.format = '%a /// %b %e %T %Y';` /// /// You can recover the default format by using `date.format = date.default_format;` /// /// By default, the to_string format is using the **current culture**, but you can switch to an invariant /// culture by using the modifier `%g` /// /// For example, using `%g %d %b %Y` will output the date using an invariant culture. /// /// If you are using `%g` alone, it will output the date with `date.format` using an invariant culture. /// /// Suppose that `date.now` would return the date `2013-09-12 22:49:27 +0530`, the following table explains the /// format modifiers: /// /// | Format | Result | Description /// |--------|---------------|-------------------------------------------- /// | `"%a"` | `"Thu"` | Name of week day in short form of the /// | `"%A"` | `"Thursday"` | Week day in full form of the time /// | `"%b"` | `"Sep"` | Month in short form of the time /// | `"%B"` | `"September"`| Month in full form of the time /// | `"%c"` | | Date and time (%a %b %e %T %Y) /// | `"%d"` | `"12"` | Day of the month of the time /// | `"%e"` | `"12"` | Day of the month, blank-padded ( 1..31) /// | `"%H"` | `"22"` | Hour of the time in 24 hour clock format /// | `"%I"` | `"10"` | Hour of the time in 12 hour clock format /// | `"%j"` | | Day of the year (001..366) (3 digits, left padded with zero) /// | `"%m"` | `"09"` | Month of the time /// | `"%M"` | `"49"` | Minutes of the time (2 digits, left padded with zero e.g 01 02) /// | `"%p"` | `"PM"` | Gives AM / PM of the time /// | `"%S"` | `"27"` | Seconds of the time /// | `"%U"` | | Week number of the current year, starting with the first Sunday as the first day /// of the first week (00..53) /// | `"%W"` | | Week number of the current year, starting with the first Monday as the first day /// of the first week (00..53) /// | `"%w"` | `"4"` | Day of week of the time /// | `"%x"` | | Preferred representation for the date alone, no time /// | `"%X"` | | Preferred representation for the time alone, no date /// | `"%y"` | `"13"` | Gives year without century of the time /// | `"%Y"` | `"2013"` | Year of the time /// | `"%Z"` | `"IST"` | Gives Time Zone of the time /// | `"%%"` | `"%"` | Output the character `%` /// /// Note that the format is using a good part of the ruby format ([source]/// (http://apidock.com/ruby/DateTime/strftime)) /// ```scriban-html /// {{ date.parse '2016/01/05' | date.to_string `%d %b %Y` }} /// ``` /// ```html /// 05 Jan 2016 /// ``` /// </summary> /// <param name="datetime">The input datetime to format</param> /// <param name="pattern">The date format pattern.</param> /// <param name="culture">The culture used to format the datetime</param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public virtual string ToString(DateTime? datetime, string pattern, CultureInfo culture) { if (pattern == null) throw new ArgumentNullException(nameof(pattern)); if (!datetime.HasValue) return null; // If pattern is %g only, use the default date if (pattern == "%g") { pattern = "%g " + Format; } var builder = new StringBuilder(); for (int i = 0; i < pattern.Length; i++) { var c = pattern[i]; if (c == '%' && (i + 1) < pattern.Length) { i++; Func<DateTime, CultureInfo, string> formatter; var format = pattern[i]; // Switch to invariant culture if (format == 'g') { culture = CultureInfo.InvariantCulture; continue; } if (Formats.TryGetValue(format, out formatter)) { builder.Append(formatter.Invoke(datetime.Value, culture)); } else { builder.Append('%'); builder.Append(format); } } else { builder.Append(c); } } return builder.ToString(); } public object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { // If we access `date` without any parameter, it calls by default the "parse" function // otherwise it is the 'date' object itself switch (arguments.Count) { case 0: return this; case 1: return Parse(context, context.ToString(callerContext.Span, arguments[0])); default: throw new ScriptRuntimeException(callerContext.Span, $"Invalid number of parameters `{arguments.Count}` for `date` object/function."); } } private void CreateImportFunctions() { // This function is very specific, as it is calling a member function of this instance // in order to retrieve the `date.format` this.Import("to_string", new Func<TemplateContext, DateTime?, string, string>((context, date, pattern) => ToString(date, pattern, context.CurrentCulture))); } } }
47.111111
183
0.530536
[ "MIT" ]
FlorianGrimm/OfaSchlupfer
OfaSchlupfer.Elementary/TextTemplate/Functions/DateTimeFunctions.cs
16,112
C#
 namespace Ink.Parsed { internal class Gather : Parsed.Object, IWeavePoint, INamedContent { public string name { get; set; } public int indentationDepth { get; protected set; } public Runtime.Container runtimeContainer { get { return (Runtime.Container) runtimeObject; } } public Gather (string name, int indentationDepth) { this.name = name; this.indentationDepth = indentationDepth; } public override Runtime.Object GenerateRuntimeObject () { var container = new Runtime.Container (); container.name = name; if (this.story.countAllVisits) { container.visitsShouldBeCounted = true; container.turnIndexShouldBeCounted = true; } container.countingAtStartOnly = true; // A gather can have null content, e.g. it's just purely a line with "-" if (content != null) { foreach (var c in content) { container.AddContent (c.runtimeObject); } } return container; } public override void ResolveReferences (Story context) { base.ResolveReferences (context); if( name != null && name.Length > 0 ) context.CheckForNamingCollisions (this, name, Story.SymbolType.SubFlowAndWeave); } } }
29.77551
103
0.561343
[ "MIT" ]
Kalus/ink
inklecate/ParsedHierarchy/Gather.cs
1,461
C#
/* Copyright 2010 MCSharp team (Modified for use with MCZall/MCSong) Licensed under the Educational Community 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.osedu.org/licenses/ECL-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; using System.IO; namespace MCSong { public class CmdBotSummon : Command { public override string name { get { return "botsummon"; } } public override string[] aliases { get { return new string[] { "" }; } } public override CommandType type { get { return CommandType.Moderation; } } public override bool consoleUsable { get { return false; } } public override bool museumUsable { get { return false; } } public override LevelPermission defaultRank { get { return LevelPermission.Admin; } } public CmdBotSummon() { } public override void Use(Player p, string message) { if (message == "") { Help(p); return; } PlayerBot who = PlayerBot.Find(message); if (who == null) { Player.SendMessage(p, "There is no bot " + message + "!"); return; } if (p.level != who.level) { Player.SendMessage(p, who.name + " is in a different level."); return; } who.SetPos(p.pos[0], p.pos[1], p.pos[2], p.rot[0], 0); //who.SendMessage("You were summoned by " + p.color + p.name + "&e."); } public override void Help(Player p) { Player.SendMessage(p, "/botsummon <name> - Summons a bot to your position."); } } }
43.613636
112
0.645649
[ "ECL-2.0" ]
727021/MCSong
MCSong/Commands/CmdBotSummon.cs
1,919
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class Metricas : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private DataTable GetData(SqlCommand cmd, SqlConnection con) { DataTable dt = new DataTable(); SqlDataAdapter sda = new SqlDataAdapter(); cmd.CommandType = CommandType.Text; cmd.Connection = con; con.Open(); sda.SelectCommand = cmd; sda.Fill(dt); return dt; } private void BindData() { SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True"); SqlCommand cmd = new SqlCommand("Select * from Metricas"); GridView1.DataSource = GetData(cmd, conexion); GridView1.DataBind(); } protected void DeleteCustomer(object sender, EventArgs e) { LinkButton lnkRemove = (LinkButton)sender; SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "delete from Metricas where " + "id_metricas=@id_metricas;" + "select * from Metricas"; cmd.Parameters.Add("@id_metricas", SqlDbType.VarChar).Value = lnkRemove.CommandArgument; GridView1.DataSource = GetData(cmd, conexion); GridView1.DataBind(); } protected void EditCustomer(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindData(); } protected void CancelEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindData(); } protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e) { int licencia = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblmetrica")).Text); string Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtnombre")).Text; string descripcion = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdescripcion")).Text; SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE Metricas Set Descripcion=@Descripcion, Nombre=@Nombre where id_metricas=@id_metricas;" + "select * from Metricas"; cmd.Parameters.Add("@id_metricas", SqlDbType.Int).Value = licencia; cmd.Parameters.Add("@Descripcion", SqlDbType.VarChar).Value = descripcion; cmd.Parameters.Add("@Nombre", SqlDbType.VarChar).Value = Name; GridView1.EditIndex = -1; GridView1.DataSource = GetData(cmd, conexion); GridView1.DataBind(); } protected void boton_guardar_Click(object sender, EventArgs e) { String nombre = nombre_me.Text; String descripcion = descripcion_guardar.Text; SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True"); conexion.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO Metricas(Nombre,Descripcion) VALUES('" + nombre + "','" + descripcion + "')", conexion); try { cmd.ExecuteNonQuery(); Response.Redirect("Metricas.aspx"); } catch (SqlException ee) { string script = "alert(\"Error al Guardar\");"; ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); conexion.Close(); } } protected void Crear_Click(object sender, EventArgs e) { div_mostrar.Visible = true; } }
37.225225
141
0.653195
[ "MIT" ]
wolfghost9898/Proyectos
IPC2/IPC FASE II/Metricas.aspx.cs
4,134
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConfigEditor { class Variable { public Variable(string typ, string nam, string val) { type = typ; name = nam; value = val; } public string type { get; } public string name { get; } public string value { get; } } class ConfigFile { public List<Variable> variableList = new List<Variable>(); public int variableCount { get { return variableList.Count; } } public void insertNewVariable(string type, string name, string value="") { variableList.Add(new Variable(type, name, value)); } public void readFile(string fileName) { variableList.Clear(); var lines = File.ReadAllLines(fileName); foreach(var l in lines) { if(l.Contains("=")) { var strlist = l.Split('='); string left = strlist[0]; var leftlist = left.Split(' '); string type = leftlist[0].Trim(); string name = leftlist[1].Trim(); string value = strlist[1].Trim(); insertNewVariable(type, name, value); } } } public void saveFile(string fileName) { StreamWriter sr = File.CreateText(fileName); foreach(var v in variableList) { string line = v.type + " " + v.name + "=" + v.value; sr.WriteLine(line); } sr.Close(); } public void ClearList() { variableList.Clear(); } } }
25.428571
80
0.463739
[ "MIT" ]
jannesavonia/UIprogramming2021_EF20SP_source
ConfigEditor/ConfigFile.cs
1,960
C#
namespace Decapent.Ledger.Api.Dtos { public sealed class LedgerEventDto { public string Id { get; set; } public string Date { get; set; } public string Type { get; set; } public string Description { get; set; } public string Author { get; set; } public string City { get; set; } public string LedgerImage { get; set; } public int LedgerPage { get; set; } } }
20.181818
47
0.572072
[ "Unlicense" ]
decapent/family-ledger
Decapent.Ledger/Decapent.Ledger.Api/Dtos/LedgerEventDto.cs
446
C#
using MinimizersCore.Models; using System; using System.Collections.Generic; namespace MinimizersCore { /// <summary> /// Extractor that implements "2.3. A mixed strategy" from article: http://www.csri.utoronto.ca/~wayne/research/papers/minimizers.pdf <para/> /// End minimizers are extracted from windows up to w-1 in size, and the rest are extracted as interior minimizers /// </summary> public static class Extractor { /// <summary> /// Static function that extracts minimizers from a given sequence /// </summary> /// <param name="sequence">Sequence from which to extract minimizers</param> /// <param name="w">Number of k-mers in one batch (window) of minimizer extraction</param> /// <param name="k">Minimizer size (character length of substrings (k-mers))</param> /// <returns>List of extracted minimizers</returns> public static List<Minimizer> Extract(GeneSequence sequence, int w, int k) { if (w < 0 || k < 0 || sequence == null || sequence.Body.Length < k) throw new ArgumentException("Given arguments not valid"); List<Minimizer> minimizers = new List<Minimizer>(); ExtractBeginningMinimizers(minimizers, sequence, w, k); ExtractInteriorMinimizers(minimizers, sequence, w, k); ExtractEndingMinimizers(minimizers, sequence, w, k); return minimizers; } private static void ExtractInteriorMinimizers(List<Minimizer> minimizers, GeneSequence sequence, int w, int k) { string minimal = sequence.Body.Substring(0, k); int posMinimal = 0; // moving a window, so last iteration has just enough space to fill w kmers for (int windowStart = 0; windowStart < (sequence.Body.Length + 2 - w - k); windowStart++) { if (posMinimal < windowStart) minimal = null; // iterate through all substrings (k-mers) inside a window for (int j = windowStart; j < windowStart + w; j++) { string kmer = sequence.Body.Substring(j, k); if (minimal == null || String.Compare(kmer, minimal) < 0) { minimal = kmer; posMinimal = j; } } if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position) minimizers.Add(new Minimizer(minimal, sequence, posMinimal)); } } private static void ExtractBeginningMinimizers(List<Minimizer> minimizers, GeneSequence sequence, int w, int k) { string minimal = sequence.Body.Substring(0, k); int posMinimal = 0; if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position) minimizers.Add(new Minimizer(minimal, sequence, posMinimal)); // since the first kmer is certainly added (it is the only kmer in a size 1 window), // we can start at position 1, rather than 0, // and since k has to be at least 1, we can set windowEnd to 2 for beginning for (int windowEnd = 2; windowEnd < Math.Min(w, sequence.Body.Length - k + 2); windowEnd++) { // iterate through all substrings (k-mers) inside a window for (int i = posMinimal + 1; i < windowEnd; i++) { string kmer = sequence.Body.Substring(i, k); if (String.Compare(kmer, minimal) < 0) { minimal = kmer; posMinimal = i; } } if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position) minimizers.Add(new Minimizer(minimal, sequence, posMinimal)); } } private static void ExtractEndingMinimizers(List<Minimizer> minimizers, GeneSequence sequence, int w, int k) { int l = sequence.Body.Length; string minimal = null; int posMinimal = l - k; for (int windowStart = Math.Max(l - k - w, 0) + 1; windowStart <= l - k; windowStart++) { if (posMinimal < windowStart) { minimal = null; } // iterate through all substrings (k-mers) inside a window for (int i = windowStart; i <= l - k; i++) { string kmer = sequence.Body.Substring(i, k); if (minimal == null || String.Compare(kmer, minimal) < 0) { minimal = kmer; posMinimal = i; } } if (minimizers.Count == 0 || posMinimal > minimizers[minimizers.Count - 1].Position) minimizers.Add(new Minimizer(minimal, sequence, posMinimal)); } } } }
39.325926
145
0.521002
[ "MIT" ]
anniekovac/minimizers
c#/Extractor.cs
5,311
C#
/* Written by Peter O. Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using NUnit.Framework; using PeterO; using PeterO.Numbers; namespace Test { [TestFixture] public class ExtensiveTest { public static string[] GetTestFiles() { try { var path = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location); var list = new List<string>( Directory.GetFiles(path)); list.Sort(); return list.ToArray(); } catch (IOException) { return new string[0]; } } [System.Diagnostics.Conditional("DEBUG")] public static void IgnoreIfDebug() { Assert.Ignore(); } [Test] public void TestParser() { var errors = new List<string>(); var dirfiles = new List<string>(); var sw = new System.Diagnostics.Stopwatch(); sw.Start(); var valueSwProcessing = new System.Diagnostics.Stopwatch(); var standardOut = Console.Out; var x = 0; dirfiles.AddRange(GetTestFiles()); foreach (var f in dirfiles) { Console.WriteLine((sw.ElapsedMilliseconds / 1000.0) + " " + f); ++x; var context = new Dictionary<string, string>(); var lowerF = DecTestUtil.ToLowerCaseAscii(f); var isinput = lowerF.Contains(".input"); if (!lowerF.Contains(".input") && !lowerF.Contains(".txt") && !lowerF.Contains(".dectest") && !lowerF.Contains(".fptest")) { continue; } using (var w = new StreamReader(f)) { while (!w.EndOfStream) { var ln = w.ReadLine(); valueSwProcessing.Start(); DecTestUtil.ParseDecTest(ln, context); valueSwProcessing.Stop(); } } } sw.Stop(); // Total running time Console.WriteLine("Time: " + (sw.ElapsedMilliseconds / 1000.0) + " s"); // Number processing time Console.WriteLine("ProcTime: " + (valueSwProcessing.ElapsedMilliseconds / 1000.0) + " s"); // Ratio of number processing time to total running time Console.WriteLine("Rate: " + (valueSwProcessing.ElapsedMilliseconds * 100.0 / sw.ElapsedMilliseconds) + "%"); } } }
31.012346
79
0.606688
[ "CC0-1.0" ]
Happypig375/Numbers
Test/ExtensiveTest.cs
2,512
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using WebApi.Helpers; namespace WebApi.Migrations.SqliteMigrations { [DbContext(typeof(SqliteDataContext))] partial class SqliteDataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.6"); modelBuilder.Entity("WebApi.Entities.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("FirstName") .HasColumnType("TEXT"); b.Property<string>("LastName") .HasColumnType("TEXT"); b.Property<string>("PasswordHash") .HasColumnType("TEXT"); b.Property<string>("Username") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("Users"); }); #pragma warning restore 612, 618 } } }
30.181818
69
0.542169
[ "MIT" ]
archi-2D/authenticationMS
Migrations/SqliteMigrations/SqliteDataContextModelSnapshot.cs
1,330
C#
using System.Linq; using System.Text; using StreamRC.Streaming.Stream; using StreamRC.Streaming.Stream.Chat; using StreamRC.Streaming.Stream.Commands; namespace StreamRC.Streaming.Polls.Commands { public class PollInfoCommandHandler : StreamCommandHandler { readonly PollModule module; public PollInfoCommandHandler(PollModule module) { this.module = module; } public override void ExecuteCommand(IChatChannel channel, StreamCommand command) { if (command.Arguments.Length != 1) throw new StreamCommandException("Invalid command syntax"); string pollname = command.Arguments[0]; Poll poll = module.GetPoll(pollname); if (poll == null) throw new StreamCommandException($"There is no active poll named '{pollname}'"); PollOption[] options = module.GetOptions(pollname); StringBuilder message = new StringBuilder(poll.Description).Append(": "); if (options.Length == 0) { message.Append("This is an unrestricted poll, so please vote for 'penis' when you're out of ideas"); } else { message.Append(string.Join(", ", options.Select(o => $"{o.Key} - {o.Description}"))); message.Append(". Usually there is more info available by typing !info <option>"); } SendMessage(channel, command.User, message.ToString()); } public override void ProvideHelp(IChatChannel channel, string user) { SendMessage(channel, user, "Returns info about an active poll. Syntax: !pollinfo <poll>"); } public override ChannelFlags RequiredFlags => ChannelFlags.None; } }
38.717391
116
0.625491
[ "Unlicense" ]
telmengedar/StreamRC
Streaming/Polls/Commands/PollInfoCommandHandler.cs
1,783
C#
using DevExpress.ExpressApp.Utils; namespace Xpand.Extensions.XAF.ObjectExtensions{ public static partial class ObjectExtensions{ public static string CompoundName(this object obj) => CaptionHelper.ConvertCompoundName($"{obj}"); } }
35.714286
106
0.764
[ "Apache-2.0" ]
mbogaerts/DevExpress.XAF
src/Extensions/Xpand.Extensions.XAF/ObjectExtensions/CompoundName.cs
252
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace Roslyn.Utilities { [ExcludeFromCodeCoverage] internal class CancellableFuture<TArg, T> { private NonReentrantLock gate; private Func<TArg, CancellationToken, T> valueFactory; private T value; [Obsolete] public CancellableFuture(Func<TArg, CancellationToken, T> valueFactory) { this.gate = new NonReentrantLock(); this.valueFactory = valueFactory; } public CancellableFuture(T value) { this.value = value; } public T GetValue(TArg arg, CancellationToken cancellationToken) { var gate = this.gate; if (gate != null) { using (gate.DisposableWait(cancellationToken)) { if (this.valueFactory != null) { this.value = this.valueFactory(arg, cancellationToken); Interlocked.Exchange(ref this.valueFactory, null); } Interlocked.Exchange(ref this.gate, null); } } return this.value; } public bool HasValue { get { return this.gate == null; } } } }
26.153846
79
0.527206
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Workspaces/Core/Utilities/CancellableFuture`2.cs
1,360
C#
using RequestSender.Properties; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using TrafficViewerSDK; using TrafficViewerSDK.Http; namespace RequestSender { /// <summary> /// Sends a series of HTTP requests /// </summary> public class RequestSender { private WebRequestClient _httpClient; private HttpRequestInfo _prevRequest; private HttpResponseInfo _prevResponse; private SessionIdHelper _sessionIdHelper = new SessionIdHelper(); private RemoteCertificateValidationCallback _certificateValidationCallback; private static string _communicationError = Resources.CommunicationError; private object _lock = new object(); public static string CommunicationError { get { return RequestSender._communicationError; } } /// <summary> /// Ctor /// </summary> /// <param name="netSettings"></param> public RequestSender() : this(null) { } /// <summary> /// Network settings /// </summary> /// <param name="netSettings"></param> public RequestSender(INetworkSettings netSettings) { _httpClient = new WebRequestClient(); if (netSettings == null) { netSettings = new DefaultNetworkSettings(); netSettings.CertificateValidationCallback = _certificateValidationCallback; } _httpClient.SetNetworkSettings(netSettings); _httpClient.ShouldHandleCookies = true; } /// <summary> /// Sends all the requests in the attached file /// </summary> /// <param name="source"></param> public void Send(ITrafficDataAccessor source) { int id = -1; TVRequestInfo info = null; PatternTracker.Instance.PatternsToTrack = source.Profile.GetTrackingPatterns(); while ((info = source.GetNext(ref id)) != null) { SendRequest(source, info); } } /// <summary> /// Sends only the requests specified by id /// </summary> /// <param name="source"></param> /// <param name="idsToSend"></param> public void Send(ITrafficDataAccessor source, IEnumerable<int> idsToSend, int numberOfThreads = 1) { PatternTracker.Instance.PatternsToTrack = source.Profile.GetTrackingPatterns(); Queue<TVRequestInfo> requestsToSend = new Queue<TVRequestInfo>(); if (numberOfThreads == 1) { foreach (int id in idsToSend) { TVRequestInfo info = source.GetRequestInfo(id); if (info != null) { requestsToSend.Enqueue(info); SendRequest(source, info); } } } else { for (int idx = 0; idx < numberOfThreads; idx++) { Thread t = new Thread(new ParameterizedThreadStart(SendAsync)); t.Start(new object[2] { source, requestsToSend }); } do { Thread.Sleep(1000); lock (_lock) { if (requestsToSend.Count == 0) return; } } while (true); } } /// <summary> /// Sends http request asynchroneusly /// </summary> /// <param name="param"></param> private void SendAsync(object param) { object[] paramArray = param as object[]; if (paramArray == null || paramArray.Length != 2) return; ITrafficDataAccessor source = paramArray[0] as ITrafficDataAccessor; Queue<TVRequestInfo> requestsToSend = paramArray[1] as Queue<TVRequestInfo>; if (source == null || requestsToSend == null) return; while (true) { TVRequestInfo info = null; lock (_lock) { if (requestsToSend.Count == 0) return; info = requestsToSend.Dequeue(); } if(info!=null) SendRequest(source, info); } } /// <summary> /// Sends the specified request info /// </summary> /// <param name="source"></param> /// <param name="info"></param> private void SendRequest(ITrafficDataAccessor source, TVRequestInfo info) { byte[] reqBytes = source.LoadRequestData(info.Id); string updatedRequest = PatternTracker.Instance.UpdateRequest(Constants.DefaultEncoding.GetString(reqBytes)); HttpRequestInfo reqInfo = new HttpRequestInfo(updatedRequest); reqInfo.IsSecure = info.IsHttps; _sessionIdHelper.UpdateSessionIds(reqInfo, _prevRequest, _prevResponse); info.RequestTime = DateTime.Now; //save the request that will be sent source.SaveRequest(info.Id, Constants.DefaultEncoding.GetBytes(updatedRequest)); try { _prevResponse = _httpClient.SendRequest(reqInfo); _prevRequest = reqInfo; //save the request and response if (_prevResponse != null) { info.ResponseTime = DateTime.Now; PatternTracker.Instance.UpdatePatternValues(_prevResponse); source.SaveResponse(info.Id, _prevResponse.ToArray()); } else { source.SaveResponse(info.Id, Constants.DefaultEncoding.GetBytes(_communicationError)); } } catch (Exception ex) { SdkSettings.Instance.Logger.Log(TraceLevel.Error, "Error playing back request {0}", ex.Message); source.SaveResponse(info.Id, Constants.DefaultEncoding.GetBytes(Resources.CommunicationError)); } } } }
30.186528
121
0.60333
[ "Apache-2.0" ]
Bhaskers-Blu-Org1/HTTP-BlackOps
RequestSender/RequestSender.cs
5,828
C#
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using StackExchange.Profiling.Helpers; namespace Benchmarks { [SimpleJob(RuntimeMoniker.Net472)] [SimpleJob(RuntimeMoniker.Net50)] [Config(typeof(Configs.Full))] public class StackTraceSnippetBenchmarks { private MiniProfilerBenchmarkOptions Options { get; } = new MiniProfilerBenchmarkOptions(); [Benchmark(Description = "System.Ben Baseline")] public void SystemDotBen() { } [Benchmark(Description = "StackTraceSnippet.Get()")] public string StackTraceSnippetGet() => StackTraceSnippet.Get(Options); } }
30.285714
99
0.721698
[ "MIT" ]
MarkZither/dotnet
benchmarks/MiniProfiler.Benchmarks/Benchmarks/StackTraceSnippetBenchmarks.cs
638
C#
using System.Web; using System.Web.Mvc; namespace WebCarManager { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19
80
0.657895
[ "MIT" ]
hossmi/beca-dotnet-2019
WebCarManager/App_Start/FilterConfig.cs
268
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotatingObstacle : MonoBehaviour { public float speed; public Vector3 rotationAxis; private void Start() { rotationAxis.Normalize(); } // Update is called once per frame void Update() { transform.Rotate(rotationAxis * speed * Time.deltaTime); } }
18.809524
64
0.673418
[ "MIT" ]
AniolAndres/FunBallRace
FunRace/Assets/Scripts/RotatingObstacle.cs
397
C#
using FIMSpace.Basics; using UnityEngine; namespace FIMSpace.FTail { /// <summary> /// FM: Using FTail_MovementSinus calculations to animate tail with simple movement in fixed update /// We disconnecting cape in demo, because it's attached to skeleton and root transform is /// moving in FixedUpdate, this making stuff problematic /// </summary> public class FTail_Demo_FixedUpdateLimit : FTail_Animator { [Header("Limitation optional variables for X rotation axis")] public bool UseXLimitation = true; public float WorldXDontGoUnder = -65f; public float PushTime = 0.25f; public float PushPower = 15f; protected Vector3 TrueTailRotationOffset = Vector3.zero; protected float pushTimer = 0f; protected override void Reset() { DisconnectTransforms = true; } protected override void Init() { base.Init(); TrueTailRotationOffset = TailRotationOffset; UpdateClock = EFUpdateClock.FixedUpdate; } internal override void Update() { if (UpdateClock == EFUpdateClock.FixedUpdate) return; CalculateOffsets(); } internal override void FixedUpdate() { if (UpdateClock != EFUpdateClock.FixedUpdate) return; CalculateOffsets(); } /// <summary> /// Adding sinus wave rotation with limiting option for first bone before other calculations /// </summary> public override void CalculateOffsets() { // Just calculating animation variables float delta; if (UpdateClock == EFUpdateClock.FixedUpdate) delta = Time.fixedDeltaTime; else delta = Time.deltaTime; if (UseWaving) { waveTime += delta * (2 * WavingSpeed); // It turned out to be problematic // When using clamp setting rotation was flipping other axes // So we push rotation in x axis (most common to this problem) if (UseXLimitation) { Vector3 worldRotation = TailTransforms[0].rotation.eulerAngles; float wrappedWorldAngle = LimitAngle360(worldRotation.x); if (wrappedWorldAngle < WorldXDontGoUnder) pushTimer = PushTime; if (pushTimer > 0f) { TrueTailRotationOffset = Vector3.Lerp(TrueTailRotationOffset, Vector3.zero, delta * PushPower); pushTimer -= delta; } else { TrueTailRotationOffset = Vector3.Lerp(TrueTailRotationOffset, TailRotationOffset, delta * PushPower * 0.7f); } } Vector3 rot = firstBoneInitialRotation + TrueTailRotationOffset; float sinVal = Mathf.Sin(waveTime) * (30f * WavingRange); rot += sinVal * WavingAxis; if (rootTransform) proceduralPoints[0].Rotation = rootTransform.rotation * Quaternion.Euler(rot); else proceduralPoints[0].Rotation = TailTransforms[0].transform.rotation * Quaternion.Euler(rot); } else { if (rootTransform) proceduralPoints[0].Rotation = rootTransform.rotation * Quaternion.Euler(firstBoneInitialRotation); else proceduralPoints[0].Rotation = TailTransforms[0].transform.rotation * Quaternion.Euler(firstBoneInitialRotation); } if (preAutoCorrect != UseAutoCorrectLookAxis) { ApplyAutoCorrection(); preAutoCorrect = UseAutoCorrectLookAxis; } proceduralPoints[0].Position = TailTransforms[0].position; // Just calculating animation variables float posDelta; float rotDelta; if (UpdateClock == EFUpdateClock.FixedUpdate) { posDelta = Time.fixedDeltaTime * PositionSpeed; rotDelta = Time.fixedDeltaTime * RotationSpeed; } else { posDelta = Time.deltaTime * PositionSpeed; rotDelta = Time.deltaTime * RotationSpeed; } for (int i = 1; i < proceduralPoints.Count; i++) { FTail_Point previousTailPoint = proceduralPoints[i - 1]; FTail_Point currentTailPoint = proceduralPoints[i]; Vector3 startLookPosition = previousTailPoint.Position; Vector3 translationVector; if (FullCorrection) translationVector = previousTailPoint.TransformDirection(tailLookDirections[i - 1]); else translationVector = previousTailPoint.TransformDirection(AxisCorrection); Vector3 targetPosition = previousTailPoint.Position + (translationVector * -1f * (distances[i] * StretchMultiplier)); proceduralPoints[i].Position = Vector3.Lerp(currentTailPoint.Position, targetPosition, posDelta); Quaternion targetLookRotation = CalculateTargetRotation(startLookPosition, currentTailPoint.Position, previousTailPoint, currentTailPoint, i - 1); proceduralPoints[i].Rotation = Quaternion.Lerp(currentTailPoint.Rotation, targetLookRotation, rotDelta); } SetTailTransformsFromPoints(); } /// <summary> /// Regulates angle values returned from rotation.eulerAngles to be same as in inspector /// </summary> private static float LimitAngle360(float angle) { angle %= 360; if (angle > 180) return angle - 360; return angle; } } }
37.17284
162
0.57539
[ "MIT" ]
Kingminje/AR_Plant-Growth-ARKit-
FImpossible Games/Tail Animator/Demo Tail Animator/Scripts/FTail_Demo_FixedUpdateLimit.cs
6,024
C#
using Volo.Abp.Application; using Volo.Abp.Modularity; using Volo.Abp.VirtualFileSystem; namespace Acme.BookStore.BookManagement { [DependsOn( typeof(BookManagementDomainSharedModule), typeof(AbpDddApplicationModule) )] public class BookManagementApplicationContractsModule : AbpModule { } }
22.266667
69
0.736527
[ "MIT" ]
271943794/abp-samples
BookStore-Modular/modules/book-management/src/Acme.BookStore.BookManagement.Application.Contracts/BookManagementApplicationContractsModule.cs
336
C#
namespace NodeCanvas.Framework { ///<summary>This is a very special dummy class for variable header separators</summary> public class VariableSeperator { public VariableSeperator() { } public bool isEditingName { get; set; } } }
29
91
0.678161
[ "Apache-2.0" ]
Grumpy-Bear-Games/Duality-Prototype
Assets/ParadoxNotion/CanvasCore/Framework/Runtime/Variables/VariableSeparator.cs
263
C#