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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3603
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Linq;
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
namespace OsmSharp.IO.Xml.Gpx.v1_1
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
[System.Xml.Serialization.XmlRootAttribute("gpx", Namespace = "http://www.topografix.com/GPX/1/1", IsNullable = false)]
public partial class gpxType
{
private metadataType metadataField;
private wptType[] wptField;
private rteType[] rteField;
private trkType[] trkField;
// private extensionsType extensionsField;
private string versionField;
private string creatorField;
/// <remarks/>
public gpxType()
{
this.versionField = "1.1";
}
/// <remarks/>
public metadataType metadata
{
get
{
return this.metadataField;
}
set
{
this.metadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("wpt")]
public wptType[] wpt
{
get
{
return this.wptField;
}
set
{
this.wptField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("rte")]
public rteType[] rte
{
get
{
return this.rteField;
}
set
{
this.rteField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trk")]
public trkType[] trk
{
get
{
return this.trkField;
}
set
{
this.trkField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string creator
{
get
{
return this.creatorField;
}
set
{
this.creatorField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class metadataType
{
private string nameField;
private string descField;
private personType authorField;
private copyrightType copyrightField;
private linkType[] linkField;
private System.DateTime timeField;
private bool timeFieldSpecified;
private string keywordsField;
private boundsType boundsField;
//private extensionsType extensionsField;
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
/// <remarks/>
public personType author
{
get
{
return this.authorField;
}
set
{
this.authorField = value;
}
}
/// <remarks/>
public copyrightType copyright
{
get
{
return this.copyrightField;
}
set
{
this.copyrightField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
/// <remarks/>
public System.DateTime time
{
get
{
return this.timeField;
}
set
{
this.timeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool timeSpecified
{
get
{
return this.timeFieldSpecified;
}
set
{
this.timeFieldSpecified = value;
}
}
/// <remarks/>
public string keywords
{
get
{
return this.keywordsField;
}
set
{
this.keywordsField = value;
}
}
/// <remarks/>
public boundsType bounds
{
get
{
return this.boundsField;
}
set
{
this.boundsField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class personType
{
private string nameField;
private emailType emailField;
private linkType linkField;
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public emailType email
{
get
{
return this.emailField;
}
set
{
this.emailField = value;
}
}
/// <remarks/>
public linkType link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class emailType
{
private string idField;
private string domainField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string domain
{
get
{
return this.domainField;
}
set
{
this.domainField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class trksegType
{
private wptType[] trkptField;
//private extensionsType extensionsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkpt")]
public wptType[] trkpt
{
get
{
return this.trkptField;
}
set
{
this.trkptField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class wptType
{
private decimal eleField;
private bool eleFieldSpecified;
private System.DateTime timeField;
private bool timeFieldSpecified;
private decimal magvarField;
private bool magvarFieldSpecified;
private decimal geoidheightField;
private bool geoidheightFieldSpecified;
private string nameField;
private string cmtField;
private string descField;
private string srcField;
private linkType[] linkField;
private string symField;
private string typeField;
private fixType fixField;
private bool fixFieldSpecified;
private string satField;
private decimal hdopField;
private bool hdopFieldSpecified;
private decimal vdopField;
private bool vdopFieldSpecified;
private decimal pdopField;
private bool pdopFieldSpecified;
private decimal ageofdgpsdataField;
private bool ageofdgpsdataFieldSpecified;
private string dgpsidField;
//private extensionsType extensionsField;
private decimal latField;
private decimal lonField;
/// <remarks/>
public decimal ele
{
get
{
return this.eleField;
}
set
{
this.eleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool eleSpecified
{
get
{
return this.eleFieldSpecified;
}
set
{
this.eleFieldSpecified = value;
}
}
/// <remarks/>
public System.DateTime time
{
get
{
return this.timeField;
}
set
{
this.timeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool timeSpecified
{
get
{
return this.timeFieldSpecified;
}
set
{
this.timeFieldSpecified = value;
}
}
/// <remarks/>
public decimal magvar
{
get
{
return this.magvarField;
}
set
{
this.magvarField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool magvarSpecified
{
get
{
return this.magvarFieldSpecified;
}
set
{
this.magvarFieldSpecified = value;
}
}
/// <remarks/>
public decimal geoidheight
{
get
{
return this.geoidheightField;
}
set
{
this.geoidheightField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool geoidheightSpecified
{
get
{
return this.geoidheightFieldSpecified;
}
set
{
this.geoidheightFieldSpecified = value;
}
}
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
/// <remarks/>
public string sym
{
get
{
return this.symField;
}
set
{
this.symField = value;
}
}
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
public fixType fix
{
get
{
return this.fixField;
}
set
{
this.fixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool fixSpecified
{
get
{
return this.fixFieldSpecified;
}
set
{
this.fixFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
public string sat
{
get
{
return this.satField;
}
set
{
this.satField = value;
}
}
/// <remarks/>
public decimal hdop
{
get
{
return this.hdopField;
}
set
{
this.hdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool hdopSpecified
{
get
{
return this.hdopFieldSpecified;
}
set
{
this.hdopFieldSpecified = value;
}
}
/// <remarks/>
public decimal vdop
{
get
{
return this.vdopField;
}
set
{
this.vdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool vdopSpecified
{
get
{
return this.vdopFieldSpecified;
}
set
{
this.vdopFieldSpecified = value;
}
}
/// <remarks/>
public decimal pdop
{
get
{
return this.pdopField;
}
set
{
this.pdopField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool pdopSpecified
{
get
{
return this.pdopFieldSpecified;
}
set
{
this.pdopFieldSpecified = value;
}
}
/// <remarks/>
public decimal ageofdgpsdata
{
get
{
return this.ageofdgpsdataField;
}
set
{
this.ageofdgpsdataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ageofdgpsdataSpecified
{
get
{
return this.ageofdgpsdataFieldSpecified;
}
set
{
this.ageofdgpsdataFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "integer")]
public string dgpsid
{
get
{
return this.dgpsidField;
}
set
{
this.dgpsidField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal lat
{
get
{
return this.latField;
}
set
{
this.latField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal lon
{
get
{
return this.lonField;
}
set
{
this.lonField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class linkType
{
private string textField;
private string typeField;
private string hrefField;
/// <remarks/>
public string text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")]
public string href
{
get
{
return this.hrefField;
}
set
{
this.hrefField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public enum fixType
{
/// <remarks/>
none,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("2d")]
Item2d,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("3d")]
Item3d,
/// <remarks/>
dgps,
/// <remarks/>
pps,
}
///// <remarks/>
//[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
//[System.Diagnostics.DebuggerStepThroughAttribute()]
//[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
//public partial class extensionsType
//{
// private XElement[] anyField;
// /// <remarks/>
// [System.Xml.Serialization.XmlAnyElementAttribute()]
// public XElement[] Any
// {
// get
// {
// return this.anyField;
// }
// set
// {
// this.anyField = value;
// }
// }
//}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class trkType
{
private string nameField;
private string cmtField;
private string descField;
private string srcField;
private linkType[] linkField;
private string numberField;
private string typeField;
//private extensionsType extensionsField;
private trksegType[] trksegField;
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
public string number
{
get
{
return this.numberField;
}
set
{
this.numberField = value;
}
}
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkseg")]
public trksegType[] trkseg
{
get
{
return this.trksegField;
}
set
{
this.trksegField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class rteType
{
private string nameField;
private string cmtField;
private string descField;
private string srcField;
private linkType[] linkField;
private string numberField;
private string typeField;
//private extensionsType extensionsField;
private wptType[] rteptField;
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public string cmt
{
get
{
return this.cmtField;
}
set
{
this.cmtField = value;
}
}
/// <remarks/>
public string desc
{
get
{
return this.descField;
}
set
{
this.descField = value;
}
}
/// <remarks/>
public string src
{
get
{
return this.srcField;
}
set
{
this.srcField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("link")]
public linkType[] link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "nonNegativeInteger")]
public string number
{
get
{
return this.numberField;
}
set
{
this.numberField = value;
}
}
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
///// <remarks/>
//public extensionsType extensions
//{
// get
// {
// return this.extensionsField;
// }
// set
// {
// this.extensionsField = value;
// }
//}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("rtept")]
public wptType[] rtept
{
get
{
return this.rteptField;
}
set
{
this.rteptField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class boundsType
{
private decimal minlatField;
private decimal minlonField;
private decimal maxlatField;
private decimal maxlonField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal minlat
{
get
{
return this.minlatField;
}
set
{
this.minlatField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal minlon
{
get
{
return this.minlonField;
}
set
{
this.minlonField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal maxlat
{
get
{
return this.maxlatField;
}
set
{
this.maxlatField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal maxlon
{
get
{
return this.maxlonField;
}
set
{
this.maxlonField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.topografix.com/GPX/1/1")]
public partial class copyrightType
{
private string yearField;
private string licenseField;
private string authorField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "gYear")]
public string year
{
get
{
return this.yearField;
}
set
{
this.yearField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI")]
public string license
{
get
{
return this.licenseField;
}
set
{
this.licenseField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string author
{
get
{
return this.authorField;
}
set
{
this.authorField = value;
}
}
}
} | 21.867133 | 123 | 0.424304 | [
"Apache-2.0"
] | fakit/OSM-AutoCAD | Mustern/core-releases-v1.3/OsmSharp/IO/Xml/Gpx/v1_1/gpx.cs | 31,272 | C# |
#region copyright
// -----------------------------------------------------------------------
// <copyright file="TypeEx.cs" company="Akka.NET Team">
// Copyright (C) 2015-2016 AsynkronIT <https://github.com/AsynkronIT>
// Copyright (C) 2016-2016 Akka.NET Team <https://github.com/akkadotnet>
// </copyright>
// -----------------------------------------------------------------------
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Hyperion.Internal;
namespace Hyperion.Extensions
{
internal static class TypeEx
{
//Why not inline typeof you ask?
//Because it actually generates calls to get the type.
//We prefetch all primitives here
public static readonly Type SystemObject = typeof(object);
public static readonly Type Int32Type = typeof(int);
public static readonly Type Int64Type = typeof(long);
public static readonly Type Int16Type = typeof(short);
public static readonly Type UInt32Type = typeof(uint);
public static readonly Type UInt64Type = typeof(ulong);
public static readonly Type UInt16Type = typeof(ushort);
public static readonly Type ByteType = typeof(byte);
public static readonly Type SByteType = typeof(sbyte);
public static readonly Type BoolType = typeof(bool);
public static readonly Type DateTimeType = typeof(DateTime);
public static readonly Type DateTimeOffsetType = typeof(DateTimeOffset);
public static readonly Type StringType = typeof(string);
public static readonly Type GuidType = typeof(Guid);
public static readonly Type FloatType = typeof(float);
public static readonly Type DoubleType = typeof(double);
public static readonly Type DecimalType = typeof(decimal);
public static readonly Type CharType = typeof(char);
public static readonly Type ByteArrayType = typeof(byte[]);
public static readonly Type TypeType = typeof(Type);
public static readonly Type RuntimeType = Type.GetType("System.RuntimeType");
public static bool IsHyperionPrimitive(this Type type)
{
return type == Int32Type ||
type == Int64Type ||
type == Int16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == UInt16Type ||
type == ByteType ||
type == SByteType ||
type == DateTimeType ||
type == DateTimeOffsetType ||
type == BoolType ||
type == StringType ||
type == GuidType ||
type == FloatType ||
type == DoubleType ||
type == DecimalType ||
type == CharType;
//add TypeSerializer with null support
}
#if NETSTANDARD16
//HACK: the GetUnitializedObject actually exists in .NET Core, its just not public
private static readonly Func<Type, object> getUninitializedObjectDelegate = (Func<Type, object>)
typeof(string)
.GetTypeInfo()
.Assembly
.GetType("System.Runtime.Serialization.FormatterServices")
?.GetTypeInfo()
?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
?.CreateDelegate(typeof(Func<Type, object>));
public static object GetEmptyObject(this Type type)
{
return getUninitializedObjectDelegate(type);
}
#else
public static object GetEmptyObject(this Type type) => System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
#endif
public static bool IsOneDimensionalArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1;
}
public static bool IsOneDimensionalPrimitiveArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1 && type.GetElementType().IsHyperionPrimitive();
}
private static readonly ConcurrentDictionary<ByteArrayKey, Type> TypeNameLookup =
new ConcurrentDictionary<ByteArrayKey, Type>(ByteArrayKeyComparer.Instance);
public static byte[] GetTypeManifest(IReadOnlyCollection<byte[]> fieldNames)
{
IEnumerable<byte> result = new[] { (byte)fieldNames.Count };
foreach (var name in fieldNames)
{
var encodedLength = BitConverter.GetBytes(name.Length);
result = result.Concat(encodedLength);
result = result.Concat(name);
}
var versionTolerantHeader = result.ToArray();
return versionTolerantHeader;
}
private static Type GetTypeFromManifestName(Stream stream, DeserializerSession session)
{
var bytes = stream.ReadLengthEncodedByteArray(session);
var byteArr = ByteArrayKey.Create(bytes);
return TypeNameLookup.GetOrAdd(byteArr, b =>
{
var shortName = StringEx.FromUtf8Bytes(b.Bytes, 0, b.Bytes.Length);
var overrides = session.Serializer.Options.CrossFrameworkPackageNameOverrides;
var oldName = shortName;
foreach (var adapter in overrides)
{
shortName = adapter(shortName);
if (!ReferenceEquals(oldName, shortName))
break;
}
return LoadTypeByName(shortName);
});
}
public static bool disallowUnsafeTypes = true;
private static ReadOnlyCollection<string> unsafeTypesDenySet =
new ReadOnlyCollection<string>(new[]
{
"System.Security.Claims.ClaimsIdentity",
"System.Windows.Forms.AxHost.State",
"System.Windows.Data.ObjectDataProvider",
"System.Management.Automation.PSObject",
"System.Web.Security.RolePrincipal",
"System.IdentityModel.Tokens.SessionSecurityToken",
"SessionViewStateHistoryItem",
"TextFormattingRunProperties",
"ToolboxItemContainer",
"System.Security.Principal.WindowsClaimsIdentity",
"System.Security.Principal.WindowsIdentity",
"System.Security.Principal.WindowsPrincipal",
"System.CodeDom.Compiler.TempFileCollection",
"System.IO.FileSystemInfo",
"System.Activities.Presentation.WorkflowDesigner",
"System.Windows.ResourceDictionary",
"System.Windows.Forms.BindingSource",
"Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider",
"System.Diagnostics.Process",
"System.Management.IWbemClassObjectFreeThreaded"
});
#if !NETSTANDARD1_6
public static bool UnsafeInheritanceCheck(Type type)
{
if (type.IsValueType)
return false;
var currentBase = type.BaseType;
while (currentBase != null)
{
if (unsafeTypesDenySet.Any(r => currentBase.FullName?.Contains(r) ?? false))
return true;
currentBase = currentBase.BaseType;
}
return false;
}
#endif
public static Type LoadTypeByName(string name)
{
if (disallowUnsafeTypes && unsafeTypesDenySet.Any(r => name.Contains(r)))
{
throw new EvilDeserializationException(
"Unsafe Type Deserialization Detected!", name);
}
try
{
// Try to load type name using strict version to avoid possible conflicts
// i.e. if there are different version available in GAC and locally
var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: false);
var type = Type.GetType(typename, true);
#if NETSTANDARD1_6
#else
if (UnsafeInheritanceCheck(type))
throw new EvilDeserializationException(
"Unsafe Type Deserialization Detected!", name);
#endif
return type;
}
catch (FileLoadException)
{
var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: true);
var type = Type.GetType(typename, true);
#if NETSTANDARD1_6
#else
if (UnsafeInheritanceCheck(type))
throw new EvilDeserializationException(
"Unsafe Type Deserialization Detected!", name);
#endif
return type;
}
}
public static Type GetTypeFromManifestFull(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
session.TrackDeserializedType(type);
return type;
}
public static Type GetTypeFromManifestVersion(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
var fieldCount = stream.ReadByte();
for (var i = 0; i < fieldCount; i++)
{
var fieldName = stream.ReadLengthEncodedByteArray(session);
}
session.TrackDeserializedTypeWithVersion(type, null);
return type;
}
public static Type GetTypeFromManifestIndex(int typeId, DeserializerSession session)
{
var type = session.GetTypeFromTypeId(typeId);
return type;
}
public static bool IsNullable(this Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static Type GetNullableElement(this Type type)
{
return type.GetTypeInfo().GetGenericArguments()[0];
}
public static bool IsFixedSizeType(this Type type)
{
return type == Int16Type ||
type == Int32Type ||
type == Int64Type ||
type == BoolType ||
type == UInt16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == CharType;
}
public static int GetTypeSize(this Type type)
{
if (type == Int16Type)
return sizeof(short);
if (type == Int32Type)
return sizeof (int);
if (type == Int64Type)
return sizeof (long);
if (type == BoolType)
return sizeof (bool);
if (type == UInt16Type)
return sizeof (ushort);
if (type == UInt32Type)
return sizeof (uint);
if (type == UInt64Type)
return sizeof (ulong);
if (type == CharType)
return sizeof(char);
throw new NotSupportedException();
}
private static readonly string CoreAssemblyQualifiedName = 1.GetType().AssemblyQualifiedName;
private static readonly string CoreAssemblyName = GetCoreAssemblyName();
private static readonly Regex cleanAssemblyVersionRegex = new Regex(
"(, Version=([\\d\\.]+))?(, Culture=[^,\\] \\t]+)?(, PublicKeyToken=(null|[\\da-f]+))?",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static string GetCoreAssemblyName()
{
var part = CoreAssemblyQualifiedName.Substring(CoreAssemblyQualifiedName.IndexOf(", Version", StringComparison.Ordinal));
return part;
}
public static string GetShortAssemblyQualifiedName(this Type self)
{
var name = self.AssemblyQualifiedName;
name = name.Replace(CoreAssemblyName, ",%core%");
name = cleanAssemblyVersionRegex.Replace(name, string.Empty);
return name;
}
public static string ToQualifiedAssemblyName(string shortName, bool ignoreAssemblyVersion)
{
// Strip out assembly version, if specified
if (ignoreAssemblyVersion)
{
shortName = cleanAssemblyVersionRegex.Replace(shortName, string.Empty);
}
var res = shortName.Replace(",%core%", CoreAssemblyName);
return res;
}
/// <summary>
/// Search for a method by name, parameter types, and binding flags.
/// Unlike GetMethod(), does 'loose' matching on generic
/// parameter types, and searches base interfaces.
/// </summary>
/// <exception cref="AmbiguousMatchException"/>
public static MethodInfo GetMethodExt(this Type thisType,
string name,
BindingFlags bindingFlags,
params Type[] parameterTypes)
{
MethodInfo matchingMethod = null;
// Check all methods with the specified name, including in base classes
GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, parameterTypes);
// If we're searching an interface, we have to manually search base interfaces
if (matchingMethod == null && thisType.GetTypeInfo().IsInterface)
{
foreach (Type interfaceType in thisType.GetInterfaces())
GetMethodExt(ref matchingMethod,
interfaceType,
name,
bindingFlags,
parameterTypes);
}
return matchingMethod;
}
private static void GetMethodExt(ref MethodInfo matchingMethod,
Type type,
string name,
BindingFlags bindingFlags,
params Type[] parameterTypes)
{
// Check all methods with the specified name, including in base classes
foreach (MethodInfo methodInfo in type.GetTypeInfo().GetMember(name,
MemberTypes.Method,
bindingFlags))
{
// Check that the parameter counts and types match,
// with 'loose' matching on generic parameters
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length == parameterTypes.Length)
{
int i = 0;
for (; i < parameterInfos.Length; ++i)
{
if (!parameterInfos[i].ParameterType
.IsSimilarType(parameterTypes[i]))
break;
}
if (i == parameterInfos.Length)
{
if (matchingMethod == null)
matchingMethod = methodInfo;
else
throw new AmbiguousMatchException(
"More than one matching method found!");
}
}
}
}
/// <summary>
/// Special type used to match any generic parameter type in GetMethodExt().
/// </summary>
public class T
{ }
/// <summary>
/// Determines if the two types are either identical, or are both generic
/// parameters or generic types with generic parameters in the same
/// locations (generic parameters match any other generic paramter,
/// and concrete types).
/// </summary>
private static bool IsSimilarType(this Type thisType, Type type)
{
// Ignore any 'ref' types
if (thisType.IsByRef)
thisType = thisType.GetElementType();
if (type.IsByRef)
type = type.GetElementType();
// Handle array types
if (thisType.IsArray && type.IsArray)
return thisType.GetElementType().IsSimilarType(type.GetElementType());
// If the types are identical, or they're both generic parameters
// or the special 'T' type, treat as a match
if (thisType == type || thisType.IsGenericParameter || thisType == typeof(T) || type.IsGenericParameter || type == typeof(T))
return true;
// Handle any generic arguments
if (thisType.GetTypeInfo().IsGenericType && type.GetTypeInfo().IsGenericType)
{
Type[] thisArguments = thisType.GetGenericArguments();
Type[] arguments = type.GetGenericArguments();
if (thisArguments.Length == arguments.Length)
{
for (int i = 0; i < thisArguments.Length; ++i)
{
if (!thisArguments[i].IsSimilarType(arguments[i]))
return false;
}
return true;
}
}
return false;
}
}
} | 40.905747 | 139 | 0.55367 | [
"Apache-2.0"
] | Aaronontheweb/Hyperion | src/Hyperion/Extensions/TypeEx.cs | 17,794 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VRGIN.Helpers;
namespace VRGIN.Core
{
public class InitializeCameraEventArgs : EventArgs
{
public readonly Camera Camera;
public readonly Camera Blueprint;
public InitializeCameraEventArgs(Camera camera, Camera blueprint)
{
Camera = camera;
Blueprint = blueprint;
}
}
public class CopiedCameraEventArgs : EventArgs
{
public readonly Camera Camera;
public CopiedCameraEventArgs(Camera camera)
{
Camera = camera;
}
}
public class CameraKiller : ProtectedBehaviour
{
MonoBehaviour[] _CameraEffects = new MonoBehaviour[0];
Camera _Camera;
protected override void OnStart()
{
base.OnStart();
_CameraEffects = gameObject.GetCameraEffects().ToArray();
_Camera = GetComponent<Camera>();
_Camera.cullingMask = 0;
_Camera.depth = -9999;
_Camera.useOcclusionCulling = false;
_Camera.clearFlags = CameraClearFlags.Nothing;
}
public void OnPreCull()
{
_Camera.enabled = false;
//VRLog.Info("Disable");
}
public void OnGUI()
{
if (Event.current.type == EventType.Repaint)
{
//VRLog.Info("Enable");
_Camera.enabled = true;
}
}
//protected override void OnUpdate()
//{
// base.OnUpdate();
// foreach(var fx in _CameraEffects.Where(fx => fx.enabled))
// {
// fx.enabled = false;
// VRLog.Info("Disabled camera effect: {0}", fx.GetType().Name);
// }
//}
}
public class CameraSlave : ProtectedBehaviour
{
protected override void OnAwake()
{
base.OnAwake();
var camera = Camera;
if(!camera)
{
VRLog.Error("No camera found! {0}", name);
Destroy(this);
return;
}
nearClipPlane = camera.nearClipPlane;
farClipPlane = camera.farClipPlane;
clearFlags = camera.clearFlags;
renderingPath = camera.renderingPath;
clearStencilAfterLightingPass = camera.clearStencilAfterLightingPass;
depthTextureMode = camera.depthTextureMode;
layerCullDistances = camera.layerCullDistances;
layerCullSpherical = camera.layerCullSpherical;
useOcclusionCulling = camera.useOcclusionCulling;
backgroundColor = camera.backgroundColor;
cullingMask = camera.cullingMask;
}
public void OnEnable()
{
try
{
VR.Camera.RegisterSlave(this);
} catch(Exception e)
{
VRLog.Error(e);
}
}
public void OnDisable()
{
try
{
VR.Camera.UnregisterSlave(this);
} catch(Exception e)
{
VRLog.Error(e);
}
}
public Camera Camera
{
get
{
return GetComponent<Camera>();
}
}
public float nearClipPlane { get; private set; }
public float farClipPlane { get; private set; }
public CameraClearFlags clearFlags { get; private set; }
public RenderingPath renderingPath { get; private set; }
public bool clearStencilAfterLightingPass { get; private set; }
public DepthTextureMode depthTextureMode { get; private set; }
public float[] layerCullDistances { get; private set; }
public bool layerCullSpherical { get; private set; }
public bool useOcclusionCulling { get; private set; }
public Color backgroundColor { get; private set; }
public int cullingMask { get; private set; }
}
/// <summary>
/// Handles the insertion of a OpenVR camera into an existing scene. The camera is controlled by a ControlMode.
/// </summary>
public class VRCamera : ProtectedBehaviour
{
private delegate void CameraOperation(Camera camera);
private static VRCamera _Instance;
private bool m_bFxEnabled = false;
public SteamVR_Camera SteamCam { get; private set; }
public Camera Blueprint
{
get
{
return _Blueprint && _Blueprint.isActiveAndEnabled ? _Blueprint : Slaves.Select(s => s.Camera).FirstOrDefault(c => !VR.GUI.Owns(c));
}
}
private Camera _Blueprint { get; set; }
private IList<CameraSlave> Slaves = new List<CameraSlave>();
private const float MIN_FAR_CLIP_PLANE = 10f;
public bool HasValidBlueprint { get { return Slaves.Count > 0; } }
public Transform Origin
{
get
{
return SteamCam.origin;
}
}
public Transform Head
{
get
{
return SteamCam.head;
}
}
private Camera _Camera;
/// <summary>
/// Called when the main camera has been initialized.
/// </summary>
public event EventHandler<InitializeCameraEventArgs> InitializeCamera = delegate { };
/// <summary>
/// Called when a camera is copied.
/// </summary>
public event EventHandler<CopiedCameraEventArgs> CopiedCamera = delegate { };
/// <summary>
/// Gets the current instance of VRCamera or creates one if need be.
/// </summary>
public static VRCamera Instance
{
get
{
if (_Instance == null)
{
_Instance = new GameObject("VRGIN_Camera").AddComponent<AudioListener>().gameObject.AddComponent<VRCamera>();
}
return _Instance;
}
}
protected override void OnAwake()
{
VRLog.Info("Creating VR Camera");
_Camera = gameObject.AddComponent<Camera>();
gameObject.AddComponent<SteamVR_Camera>();
SteamCam = GetComponent<SteamVR_Camera>();
SteamCam.Expand(); // Expand immediately!
if (!VR.Settings.MirrorScreen)
{
Destroy(SteamCam.head.GetComponent<SteamVR_GameView>());
Destroy(SteamCam.head.GetComponent<Camera>()); // Save GPU power
}
// Set render scale to the value defined by the user
SteamVR_Camera.sceneResolutionScale = VR.Settings.RenderScale;
// Needed for the Camera Modifications mod to work. It's an artifact from DK2 days
var legacyAnchor = new GameObject("CenterEyeAnchor");
legacyAnchor.transform.SetParent(SteamCam.head);
DontDestroyOnLoad(SteamCam.origin.gameObject);
}
/// <summary>
/// Copies the values of a in-game camera to the VR camera.
/// </summary>
/// <param name="blueprint">The camera to copy.</param>
public void Copy(Camera blueprint, bool master = false, bool hasOtherConsumers = false)
{
VRLog.Info("Copying camera: {0}", blueprint ? blueprint.name : "NULL");
if (blueprint && blueprint.GetComponent<CameraSlave>())
{
VRLog.Warn("Is already slave -- NOOP");
return;
}
if (master && UseNewCamera(blueprint))
{
_Blueprint = blueprint ?? _Camera;
// Apply to both the head camera and the VR camera
ApplyToCameras(targetCamera =>
{
targetCamera.nearClipPlane = VR.Context.NearClipPlane;
targetCamera.farClipPlane = Mathf.Max(Blueprint.farClipPlane, MIN_FAR_CLIP_PLANE);
targetCamera.clearFlags = Blueprint.clearFlags == CameraClearFlags.Skybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
targetCamera.renderingPath = Blueprint.renderingPath;
targetCamera.clearStencilAfterLightingPass = Blueprint.clearStencilAfterLightingPass;
targetCamera.depthTextureMode = Blueprint.depthTextureMode;
targetCamera.layerCullDistances = Blueprint.layerCullDistances;
targetCamera.layerCullSpherical = Blueprint.layerCullSpherical;
targetCamera.useOcclusionCulling = Blueprint.useOcclusionCulling;
targetCamera.hdr = false;
targetCamera.backgroundColor = Blueprint.backgroundColor;
var skybox = Blueprint.GetComponent<Skybox>();
if (skybox != null)
{
var vrSkybox = targetCamera.gameObject.GetComponent<Skybox>();
if (vrSkybox == null) vrSkybox = targetCamera.gameObject.AddComponent<Skybox>();
vrSkybox.material = skybox.material;
}
foreach (var comp in blueprint.GetComponents<MonoBehaviour>())
{
if (targetCamera.gameObject.GetComponent(comp.GetType()) == null)
{
if (VR.Interpreter.IsAllowedEffect(comp))
{
VRLog.Debug("Copy FX " + comp.GetType().Name);
var cp = targetCamera.gameObject.CopyComponentFrom(comp);
cp.enabled = comp.enabled;
m_bFxEnabled = true;
FixEffectOrder();
}
}
}
});
}
if(blueprint)
{
blueprint.gameObject.AddComponent<CameraSlave>();
// Highlander principle
var listener = blueprint.GetComponent<AudioListener>();
if (listener)
{
Destroy(listener);
}
if (!hasOtherConsumers && blueprint.targetTexture == null && VR.Interpreter.IsIrrelevantCamera(blueprint))
{
//StartCoroutine(ExecuteDelayed(delegate { CopyFX(Blueprint); }));
//CopyFX(Blueprint);
blueprint.gameObject.AddComponent<CameraKiller>();
//blueprint.enabled = false;
//blueprint.nearClipPlane = Blueprint.farClipPlane = 0;
//Blueprint.targetTexture = _MiniTexture;
//Blueprint.gameObject.AddComponent<BlacklistThrottler>();
}
}
if(master)
{
// Hook
InitializeCamera(this, new InitializeCameraEventArgs(GetComponent<Camera>(), Blueprint));
}
CopiedCamera(this, new CopiedCameraEventArgs(blueprint));
}
private bool UseNewCamera(Camera blueprint)
{
if(_Blueprint && _Blueprint != _Camera && _Blueprint != blueprint)
{
// We already have a main camera
if(_Blueprint.name == "Main Camera")
{
VRLog.Info("Using {0} over {1} as main camera", _Blueprint.name, blueprint.name);
return false;
}
}
return true;
}
private void UpdateCameraConfig()
{
int cullingMask = Slaves.Aggregate(0, (cull, cam) => cull | cam.cullingMask);
// Remove layers that are captured by other cameras (see VRGUI)
cullingMask |= VR.Interpreter.DefaultCullingMask;
cullingMask &= ~(LayerMask.GetMask(VR.Context.UILayer, VR.Context.InvisibleLayer));
cullingMask &= ~(VR.Context.IgnoreMask);
VRLog.Info("The camera sees {0} ({1})", string.Join(", ", UnityHelper.GetLayerNames(cullingMask)), string.Join(", ", Slaves.Select(s => s.name).ToArray()));
GetComponent<Camera>().cullingMask = cullingMask;
}
/*/// <summary>
/// Doesn't really work yet.
/// </summary>
/// <param name="blueprint"></param>
public void CopyFX(Camera blueprint)
{
CopyFX(blueprint.gameObject, gameObject, true);
FixEffectOrder();
}*/
public void FixEffectOrder()
{
if (!SteamCam)
{
SteamCam = GetComponent<SteamVR_Camera>();
}
SteamCam.ForceLast();
SteamCam = GetComponent<SteamVR_Camera>();
}
/*private void CopyFX(GameObject source, GameObject target, bool disabledSourceFx = false)
{
// Clean
foreach (var fx in target.GetCameraEffects())
{
DestroyImmediate(fx);
}
int comps = target.GetComponents<Component>().Length;
VRLog.Info("Copying FX to {0}...", target.name);
// Rebuild
foreach (var fx in source.GetCameraEffects())
{
if (VR.Interpreter.IsAllowedEffect(fx))
{
VRLog.Info("Copy FX: {0} (enabled={1})", fx.GetType().Name, fx.enabled);
var attachedFx = target.CopyComponentFrom(fx);
if (attachedFx)
{
VRLog.Info("Attached!");
}
attachedFx.enabled = fx.enabled;
} else
{
VRLog.Info("Skipping image effect {0}", fx.GetType().Name);
}
if (disabledSourceFx)
{
fx.enabled = false;
}
}
VRLog.Info("{0} components before the additions, {1} after", comps, target.GetComponents<Component>().Length);
}*/
private void ApplyToCameras(CameraOperation operation)
{
operation(SteamCam.GetComponent<Camera>());
//operation(SteamCam.head.GetComponent<Camera>());
}
protected override void OnUpdate()
{
base.OnUpdate();
if (SteamCam.origin)
{
// Make sure the scale is right
SteamCam.origin.localScale = Vector3.one * VR.Settings.IPDScale;
}
}
public void Refresh()
{
//CopyFX(Blueprint);
}
internal Camera Clone(bool copyEffects = true)
{
var clone = new GameObject("VRGIN_Camera_Clone").CopyComponentFrom(SteamCam.GetComponent<Camera>());
if (copyEffects)
{
// FIXME lateron
//CopyFX(SteamCam.gameObject, clone.gameObject);
}
clone.transform.position = transform.position;
clone.transform.rotation = transform.rotation;
clone.nearClipPlane = 0.01f;
return clone;
}
internal void RegisterSlave(CameraSlave slave)
{
VRLog.Info("Camera went online: {0}", slave.name);
Slaves.Add(slave);
UpdateCameraConfig();
}
internal void UnregisterSlave(CameraSlave slave)
{
VRLog.Info("Camera went offline: {0}", slave.name);
Slaves.Remove(slave);
UpdateCameraConfig();
}
public void ToggleFX()
{
m_bFxEnabled = !m_bFxEnabled;
foreach (var comp in SteamCam.GetComponents<MonoBehaviour>())
{
if (VR.Interpreter.IsAllowedEffect(comp))
{
comp.enabled = m_bFxEnabled;
VRLog.Debug("Toggling FX : {0}, Enabled: {1}", comp.GetType().Name, comp.enabled);
}
else if (comp.GetType().Name.Equals("PostProcessingBehaviour"))
{
comp.enabled = m_bFxEnabled;
}
}
}
}
}
| 33.778689 | 168 | 0.524448 | [
"MIT"
] | Riqorm/PlayHomeVR | VRGIN/VRGIN/Core/VRCamera.cs | 16,486 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Dingtalkattendance_1_0.Models
{
public class CheckWritePermissionRequest : TeaModel {
/// <summary>
/// corpId
/// </summary>
[NameInMap("corpId")]
[Validation(Required=false)]
public string CorpId { get; set; }
/// <summary>
/// opUserId
/// </summary>
[NameInMap("opUserId")]
[Validation(Required=false)]
public string OpUserId { get; set; }
/// <summary>
/// category
/// </summary>
[NameInMap("category")]
[Validation(Required=false)]
public string Category { get; set; }
/// <summary>
/// resourceKey
/// </summary>
[NameInMap("resourceKey")]
[Validation(Required=false)]
public string ResourceKey { get; set; }
/// <summary>
/// entityIds
/// </summary>
[NameInMap("entityIds")]
[Validation(Required=false)]
public List<long?> EntityIds { get; set; }
}
}
| 23.52 | 57 | 0.54932 | [
"Apache-2.0"
] | yndu13/dingtalk-sdk | dingtalk/csharp/core/attendance_1_0/Models/CheckWritePermissionRequest.cs | 1,176 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Cdn.V20200415.Inputs
{
/// <summary>
/// Defines the RequestBody condition for the delivery rule.
/// </summary>
public sealed class DeliveryRuleRequestBodyConditionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the condition for the delivery rule.
/// Expected value is 'RequestBody'.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// Defines the parameters for the condition.
/// </summary>
[Input("parameters", required: true)]
public Input<Inputs.RequestBodyMatchConditionParametersArgs> Parameters { get; set; } = null!;
public DeliveryRuleRequestBodyConditionArgs()
{
}
}
}
| 31.222222 | 102 | 0.647687 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Cdn/V20200415/Inputs/DeliveryRuleRequestBodyConditionArgs.cs | 1,124 | 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.EventGrid.V20201015Preview.Outputs
{
[OutputType]
public sealed class StorageBlobDeadLetterDestinationResponse
{
/// <summary>
/// The name of the Storage blob container that is the destination of the deadletter events
/// </summary>
public readonly string? BlobContainerName;
/// <summary>
/// Type of the endpoint for the dead letter destination
/// Expected value is 'StorageBlob'.
/// </summary>
public readonly string EndpointType;
/// <summary>
/// The Azure Resource ID of the storage account that is the destination of the deadletter events
/// </summary>
public readonly string? ResourceId;
[OutputConstructor]
private StorageBlobDeadLetterDestinationResponse(
string? blobContainerName,
string endpointType,
string? resourceId)
{
BlobContainerName = blobContainerName;
EndpointType = endpointType;
ResourceId = resourceId;
}
}
}
| 31.704545 | 105 | 0.653047 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/EventGrid/V20201015Preview/Outputs/StorageBlobDeadLetterDestinationResponse.cs | 1,395 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
#if !DEBUG
using NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol;
using FieldSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol;
using MethodSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol;
using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol;
using PropertySymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol;
#endif
namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia
{
internal sealed class EmbeddedType : EmbeddedTypesManager.CommonEmbeddedType
{
private bool _embeddedAllMembersOfImplementedInterface;
public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbolAdapter underlyingNamedType) :
base(typeManager, underlyingNamedType)
{
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsDefinition);
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsTopLevelType());
Debug.Assert(!underlyingNamedType.AdaptedNamedTypeSymbol.IsGenericType);
}
public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType());
if (_embeddedAllMembersOfImplementedInterface)
{
return;
}
_embeddedAllMembersOfImplementedInterface = true;
// Embed all members
foreach (MethodSymbol m in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit())
{
if ((object)m != null)
{
TypeManager.EmbedMethod(this, m.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
}
// We also should embed properties and events, but we don't need to do this explicitly here
// because accessors embed them automatically.
// Do the same for implemented interfaces.
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true);
}
}
protected override int GetAssemblyRefIndex()
{
ImmutableArray<AssemblySymbol> refs = TypeManager.ModuleBeingBuilt.SourceModule.GetReferencedAssemblySymbols();
return refs.IndexOf(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, ReferenceEqualityComparer.Instance);
}
protected override bool IsPublic
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == Accessibility.Public;
}
}
protected override Cci.ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
NamedTypeSymbol baseType = UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
return (object)baseType != null ? moduleBuilder.Translate(baseType, syntaxNodeOpt, diagnostics) : null;
}
protected override IEnumerable<FieldSymbolAdapter> GetFieldsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<MethodSymbolAdapter> GetMethodsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()
#if DEBUG
.Select(s => s?.GetCciAdapter())
#endif
;
}
protected override IEnumerable<EventSymbolAdapter> GetEventsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<PropertySymbolAdapter> GetPropertiesToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context)
{
Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module);
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
var typeRef = moduleBeingBuilt.Translate(
@interface,
(CSharpSyntaxNode)context.SyntaxNodeOpt,
context.Diagnostics);
var type = TypeWithAnnotations.Create(@interface);
yield return type.GetTypeRefWithAttributes(
moduleBeingBuilt,
declaringSymbol: UnderlyingNamedType.AdaptedNamedTypeSymbol,
typeRef);
}
}
protected override bool IsAbstract
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract;
}
}
protected override bool IsBeforeFieldInit
{
get
{
switch (UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind)
{
case TypeKind.Enum:
case TypeKind.Delegate:
//C# interfaces don't have fields so the flag doesn't really matter, but Dev10 omits it
case TypeKind.Interface:
return false;
}
// We shouldn't embed static constructor.
return true;
}
}
protected override bool IsComImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport;
}
}
protected override bool IsInterface
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType();
}
}
protected override bool IsDelegate
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType();
}
}
protected override bool IsSerializable
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable;
}
}
protected override bool IsSpecialName
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName;
}
}
protected override bool IsWindowsRuntimeImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport;
}
}
protected override bool IsSealed
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed;
}
}
protected override TypeLayout? GetTypeLayoutIfStruct()
{
if (UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType())
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout;
}
return null;
}
protected override System.Runtime.InteropServices.CharSet StringFormat
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet;
}
}
protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder);
}
protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var member = hasGuid ?
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctor :
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString;
var ctor = TypeManager.GetWellKnownMethod(member, syntaxNodeOpt, diagnostics);
if ((object)ctor == null)
{
return null;
}
if (hasGuid)
{
// This is an interface with a GuidAttribute, so we will generate the no-parameter TypeIdentifier.
return new SynthesizedAttributeData(ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
else
{
// This is an interface with no GuidAttribute, or some other type, so we will generate the
// TypeIdentifier with name and scope parameters.
// Look for a GUID attribute attached to type's containing assembly. If we find one, we'll use it;
// otherwise, we expect that we will have reported an error (ERRID_PIAHasNoAssemblyGuid1) about this assembly, since
// you can't /link against an assembly which lacks a GuidAttribute.
var stringType = TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics);
if ((object)stringType != null)
{
string guidString = TypeManager.GetAssemblyGuidString(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly);
return new SynthesizedAttributeData(ctor,
ImmutableArray.Create(new TypedConstant(stringType, TypedConstantKind.Primitive, guidString),
new TypedConstant(stringType, TypedConstantKind.Primitive,
UnderlyingNamedType.AdaptedNamedTypeSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))),
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
}
return null;
}
protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, UnderlyingNamedType.AdaptedNamedTypeSymbol, description.FullName);
}
protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
foreach (Symbol s in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember))
{
switch (s.Kind)
{
case SymbolKind.Field:
TypeManager.EmbedField(this, ((FieldSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Method:
TypeManager.EmbedMethod(this, ((MethodSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Property:
TypeManager.EmbedProperty(this, ((PropertySymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Event:
TypeManager.EmbedEvent(this, ((EventSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false);
break;
}
}
}
}
}
| 39.205047 | 182 | 0.6215 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Compilers/CSharp/Portable/Emitter/NoPia/EmbeddedType.cs | 12,430 | C# |
/// OSVR-Config
///
/// <copyright>
/// Copyright 2016 Sensics, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </copyright>
///
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace OSVR.Config.Models
{
public class OSVRInclude
{
public string RelativePath { get; set; }
public JObject Body { get; set; }
public static OSVRInclude Parse(JObject json, string fieldName, string serverRoot)
{
OSVRInclude ret = null;
JToken token = null;
if (json.TryGetValue(fieldName, out token) && token.Type == JTokenType.String)
{
string relativePath = token.Value<string>();
ret = new OSVRInclude();
ret.RelativePath = relativePath;
try {
using (var includeReader = File.OpenText(Path.Combine(serverRoot, relativePath)))
{
ret.Body = (JObject)JObject.ReadFrom(new JsonTextReader(includeReader));
}
}
catch (System.IO.FileNotFoundException)
{
ret = null;
}
}
return ret;
}
}
}
| 32.925926 | 101 | 0.584927 | [
"Apache-2.0"
] | JeroMiya/OSVR-Config | src/OSVR.Config/Models/OSVRInclude.cs | 1,780 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
namespace MappingEdu.Service.Model.SystemItemCustomDetail
{
public class SystemItemCustomDetailEditModel : SystemItemCustomDetailCreateModel
{
public Guid SystemItemCustomDetailId { get; set; }
}
} | 35.928571 | 86 | 0.765408 | [
"Apache-2.0"
] | Ed-Fi-Exchange-OSS/MappingEDU | src/MappingEdu.Service.Model/SystemItemCustomDetail/SystemItemCustomDetailEditModel.cs | 505 | C# |
#pragma checksum "..\..\..\..\Views\SettingsView.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "CAE44CBFC038EF4BF34784E0D55AE29C"
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
using MahApps.Metro.Controls;
using MahApps.Metro.IconPacks;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace WpfApplication1.Views {
/// <summary>
/// SettingsView
/// </summary>
public partial class SettingsView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 13 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button remember;
#line default
#line hidden
#line 16 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal MahApps.Metro.IconPacks.PackIconOcticons remember1;
#line default
#line hidden
#line 18 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button quick;
#line default
#line hidden
#line 20 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal MahApps.Metro.IconPacks.PackIconOcticons quick1;
#line default
#line hidden
#line 24 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label remember_label;
#line default
#line hidden
#line 25 "..\..\..\..\Views\SettingsView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label quick_label;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/WpfApplication1;component/views/settingsview.xaml", System.UriKind.Relative);
#line 1 "..\..\..\..\Views\SettingsView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.remember = ((System.Windows.Controls.Button)(target));
#line 15 "..\..\..\..\Views\SettingsView.xaml"
this.remember.Click += new System.Windows.RoutedEventHandler(this.remember_Click_1);
#line default
#line hidden
return;
case 2:
this.remember1 = ((MahApps.Metro.IconPacks.PackIconOcticons)(target));
return;
case 3:
this.quick = ((System.Windows.Controls.Button)(target));
#line 19 "..\..\..\..\Views\SettingsView.xaml"
this.quick.Click += new System.Windows.RoutedEventHandler(this.quick_Click);
#line default
#line hidden
return;
case 4:
this.quick1 = ((MahApps.Metro.IconPacks.PackIconOcticons)(target));
return;
case 5:
this.remember_label = ((System.Windows.Controls.Label)(target));
return;
case 6:
this.quick_label = ((System.Windows.Controls.Label)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 38.924051 | 141 | 0.624878 | [
"MIT"
] | Nymini/Vlive-Streamers | Vlive Stream Machine 3/obj/x64/Debug/Views/SettingsView.g.i.cs | 6,152 | C# |
/*
* Copyright 2010-2013 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.
*/
using System.Collections.Generic;
using Amazon.EC2.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// ImportVolumeTaskDetails Unmarshaller
/// </summary>
internal class ImportVolumeTaskDetailsUnmarshaller : IUnmarshaller<ImportVolumeTaskDetails, XmlUnmarshallerContext>, IUnmarshaller<ImportVolumeTaskDetails, JsonUnmarshallerContext>
{
public ImportVolumeTaskDetails Unmarshall(XmlUnmarshallerContext context)
{
ImportVolumeTaskDetails importVolumeTaskDetails = new ImportVolumeTaskDetails();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 1;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("bytesConverted", targetDepth))
{
importVolumeTaskDetails.BytesConverted = LongUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("availabilityZone", targetDepth))
{
importVolumeTaskDetails.AvailabilityZone = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("description", targetDepth))
{
importVolumeTaskDetails.Description = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("image", targetDepth))
{
importVolumeTaskDetails.Image = DiskImageDescriptionUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("volume", targetDepth))
{
importVolumeTaskDetails.Volume = DiskImageVolumeDescriptionUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return importVolumeTaskDetails;
}
}
return importVolumeTaskDetails;
}
public ImportVolumeTaskDetails Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static ImportVolumeTaskDetailsUnmarshaller instance;
public static ImportVolumeTaskDetailsUnmarshaller GetInstance()
{
if (instance == null)
instance = new ImportVolumeTaskDetailsUnmarshaller();
return instance;
}
}
}
| 38.444444 | 185 | 0.56516 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.EC2/Model/Internal/MarshallTransformations/ImportVolumeTaskDetailsUnmarshaller.cs | 3,806 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using ProtoBuf;
using ProtoBuf.Meta;
using NUnit.Framework;
namespace Examples.Issues
{
// note that some additional changes were needed beyond what is shown on SO
// in order to fully test standalone compilation / PEVerify; mainly due to
// public readonly fields, which protobuf-net will still try and mutate
[TestFixture]
public class SO11705351
{
[ProtoContract]
public class Whole
{
private readonly PartCollection parts;
public Whole() { parts = new PartCollection { Whole = this }; }
[ProtoMember(1)]
public PartCollection Parts { get { return parts; } }
}
[ProtoContract]
public class Part
{
[ProtoMember(1, AsReference = true)]
public Whole Whole { get; set; }
}
[ProtoContract(IgnoreListHandling = true)]
public class PartCollection : List<Part>
{
public Whole Whole { get; set; }
}
[ProtoContract]
public class Assemblage
{
private readonly PartCollection parts = new PartCollection();
[ProtoMember(1)]
public PartCollection Parts { get { return parts; }}
}
[ProtoContract]
public class PartCollectionSurrogate
{
[ProtoMember(1, AsReference = true)]
public List<Part> Collection { get; set; }
[ProtoMember(2, AsReference = true)]
public Whole Whole { get; set; }
public static implicit operator PartCollectionSurrogate(PartCollection value)
{
if (value == null) return null;
return new PartCollectionSurrogate { Collection = value, Whole = value.Whole };
}
public static implicit operator PartCollection(PartCollectionSurrogate value)
{
if (value == null) return null;
PartCollection result = new PartCollection {Whole = value.Whole};
if(value.Collection != null)
{ // add the data we colated
result.AddRange(value.Collection);
}
return result;
}
}
static RuntimeTypeModel GetModel()
{
var model = TypeModel.Create();
model.AutoCompile = false;
model.Add(typeof(PartCollection), true).SetSurrogate(typeof(PartCollectionSurrogate));
return model;
}
static Assemblage GetData()
{
var whole = new Whole();
var part = new Part { Whole = whole };
whole.Parts.Add(part);
var assemblage = new Assemblage();
assemblage.Parts.Add(part);
return assemblage;
}
[Test]
public void Execute()
{
var model = GetModel();
Execute(model, "Runtime");
model.CompileInPlace();
Execute(model, "CompileInPlace");
Execute(model.Compile(), "Compile");
model.Compile("SO11705351", "SO11705351.dll");
PEVerify.AssertValid("SO11705351.dll");
}
private static void Execute(TypeModel model, string caption)
{
try
{
using (var stream = new MemoryStream())
{
{
var assemblage = GetData();
model.Serialize(stream, assemblage);
}
stream.Position = 0;
var obj = (Assemblage) model.Deserialize(stream, null, typeof (Assemblage));
{
var assemblage = obj;
var whole = assemblage.Parts[0].Whole;
Assert.AreSame(assemblage.Parts[0].Whole, whole.Parts[0].Whole, "Whole:" + caption);
Assert.AreSame(assemblage.Parts[0], whole.Parts[0], "Part:" + caption);
}
}
} catch(Exception ex)
{
Assert.Fail(ex.Message + ":" + caption);
}
}
[Test]
public void CheckSchema()
{
var model = GetModel();
model.Serialize(Stream.Null, GetData()); // to bring the other types into play
string schema = model.GetSchema(null);
Assert.AreEqual(@"package Examples.Issues;
import ""bcl.proto""; // schema for protobuf-net's handling of core .NET types
message Assemblage {
optional PartCollectionSurrogate Parts = 1;
}
message Part {
optional bcl.NetObjectProxy Whole = 1; // reference-tracked Whole
}
message PartCollectionSurrogate {
repeated bcl.NetObjectProxy Collection = 1; // reference-tracked Part
optional bcl.NetObjectProxy Whole = 2; // reference-tracked Whole
}
message Whole {
optional PartCollectionSurrogate Parts = 1;
}
", schema);
}
}
}
| 32.955696 | 109 | 0.529095 | [
"Apache-2.0"
] | 0xec/protobuf-net | Examples/Issues/SO11705351.cs | 5,209 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Asakuma
{
public class RedirectToLevel : MonoBehaviour
{
public static int redirectToLevel = 3;
public static int nextLevel;
void Update()
{
if (redirectToLevel == 3)
{
SceneManager.LoadScene(redirectToLevel);
}
}
}
} | 20.363636 | 56 | 0.607143 | [
"MIT"
] | asakuma3/SwordWolf | Assets/Scripts/UI/StartMenu/RedirectToLevel.cs | 448 | C# |
//using System;
//using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using HarmonyLib;
namespace LSTMMod
{
public class LSTMNavi : NaviLineDelegate
{
//ガス惑星手動採集ボタンをコピーして横にずらす
public static GameObject MakeNaviPop(LSTMNavi navi)
{
UIFunctionPanel functionPanel = UIRoot.instance.uiGame.functionPanel;
UIButton extractButton = functionPanel.extractButton;
UIButton btn = GameObject.Instantiate<UIButton>(extractButton, extractButton.transform.parent);
btn.gameObject.name = "lstm-clear-navi-btn";
Vector3 pos = btn.transform.localPosition;
pos.x -= 200f;
btn.transform.localPosition = pos;
btn.gameObject.SetActive(false);
//元の onClick は m_PersistentCalls にあるっぽいので作り直す
Util.RemovePersistentCalls(btn.gameObject);
btn.button?.onClick.AddListener(navi.NaviLineTipClicked);
Text txt = btn.transform.Find("text")?.GetComponent<Text>();
if (txt)
{
GameObject.Destroy(txt.gameObject.GetComponent<Localizer>());
txt.fontSize += 2;
txt.text = "Click here to clear navi".Translate();
}
Image img = btn.transform.Find("icon")?.GetComponent<Image>();
if(img != null) img.sprite = LSTM.astroIndicator;
return btn.gameObject;
}
//右側に出てくるチップにボタンを付けてクリックできるようにする 不採用
public static UIKeyTipNode MakeNaviTip(LSTMNavi navi)
{
UIKeyTipNode naviTip = UIRoot.instance.uiGame.keyTips.RegisterTip("Navi", "Click here to erase");
GameObject go = new GameObject("button");
Image image = go.AddComponent<Image>();
image.color = new Color(1f, 0.25f, 0f, 0.27f);
var button = go.AddComponent<Button>();
button.targetGraphic = image;
button.onClick.AddListener(new UnityAction(navi.NaviLineTipClicked));
go.transform.SetParent(naviTip.transform, false);
Vector2 size = ((RectTransform)naviTip.transform).sizeDelta;
RectTransform rect = Util.NormalizeRectC(go, size.x, size.y);
rect.anchoredPosition = Vector2.zero;
return naviTip;
}
public void NaviLineTipClicked()
{
naviLine.Disable(true);
//naviTip.desired = false;
naviPop?.SetActive(false);
}
public NaviLine naviLine;
//public UIKeyTipNode naviTip;
public GameObject naviPop;
internal bool _initialized = false;
public LSTMNavi()
{
naviLine = new NaviLine();
naviLine.autoDisappear = true;
naviLine._delegate = this;
}
public void NaviLineWillAppear(NaviLine naviLine)
{
if (!_initialized)
{
_initialized = true;
//naviTip = MakeNaviTip(this);
naviPop = MakeNaviPop(this);
}
//if (naviTip != null) naviTip.desired = true;
naviPop?.SetActive(true);
}
public void NaviLineWillDisappear(NaviLine naviLine)
{
//if (naviTip != null) naviTip.desired = false;
naviPop?.SetActive(false);
}
public void NaviLineDidGameTick(NaviLine naviLine)
{
if (naviPop == null)
{
return;
}
if (UIGame.viewMode >= EViewMode.Globe)
{
//naviTip.desired = false;
naviPop.SetActive(false);
}
else
{
if (LSTM.dropSorterKeyEracesNavi.Value && VFInput._cancelTemplateInserter.onDown && !VFInput.inputing)
{
Disable();
}
//naviTip.desired = (naviLine.lineGizmo != null);
naviPop.SetActive(naviLine.lineGizmo != null);
}
}
public void SetStationNavi(StationComponent station, int planetId)
{
EntityData[] pool = GameMain.galaxy.PlanetById(planetId)?.factory?.entityPool;
if (pool == null || pool[station.entityId].stationId != station.id)
{
return;
}
Vector3 pos = pool[station.entityId].pos;
naviLine.planetId = planetId;
naviLine.entityId = station.entityId;
naviLine.endPoint = pos + (pos.normalized * 8);
}
public void SetPointNavi(Vector3 pos, int planetId)
{
naviLine.planetId = planetId;
naviLine.entityId = 0;
naviLine.endPoint = pos;
}
public void Disable()
{
naviLine.Disable(true);
}
}
}
| 33.384106 | 119 | 0.539179 | [
"Unlicense"
] | hetima/DSP_LSTM | LSTM/LSTMNavi.cs | 5,183 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace MisturTee.Config.Claims
{
public class ClaimValidationConfig
{
public bool IsRequired { get; set; }
public string ClaimName { get; set; }
public bool AllowNullOrEmpty { get; set; }
public bool ValueMustBeExactMatch { get; set; }
/// <summary>
/// Delegate that takes in <see cref="HttpContext"/> and evaluates if all is good with the request
/// </summary>
/// <param name="context">current http context</param>
/// <returns>
/// true if claims are valid and all is good with the request.
/// false if errors were found with the request, and the request will be cut short and the response returned
/// </returns>
public delegate Task<bool> ClaimValidatorDelegate(HttpContext context);
}
}
| 36.75 | 116 | 0.647392 | [
"MIT"
] | abdulbeard/aspnet-core-webapi-auth-middleware | MisturTee/Config/Claims/ClaimValidationConfig.cs | 884 | 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/winioctl.h in the Windows SDK for Windows 10.0.19041.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="FAT_STATISTICS" /> struct.</summary>
public static unsafe class FAT_STATISTICSTests
{
/// <summary>Validates that the <see cref="FAT_STATISTICS" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<FAT_STATISTICS>(), Is.EqualTo(sizeof(FAT_STATISTICS)));
}
/// <summary>Validates that the <see cref="FAT_STATISTICS" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(FAT_STATISTICS).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="FAT_STATISTICS" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(FAT_STATISTICS), Is.EqualTo(36));
}
}
}
| 37.861111 | 145 | 0.66471 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/winioctl/FAT_STATISTICSTests.cs | 1,365 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Outputs.Org.V1
{
[OutputType]
public sealed class CheClusterSpecServerDevfileRegistryIngress
{
/// <summary>
/// Comma separated list of labels that can be used to organize and categorize (scope and select) objects.
/// </summary>
public readonly string Labels;
[OutputConstructor]
private CheClusterSpecServerDevfileRegistryIngress(string labels)
{
Labels = labels;
}
}
}
| 28.071429 | 114 | 0.684478 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/eclipse-che/dotnet/Kubernetes/Crds/Operators/EclipseChe/Org/V1/Outputs/CheClusterSpecServerDevfileRegistryIngress.cs | 786 | C# |
namespace FabianPizzas.Migrations
{
using FabianPizzas.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<FabianPizzas.Data.FabianPizzasContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(FabianPizzas.Data.FabianPizzasContext context)
{
context.Menus.AddOrUpdate(new Menu
{
MenuID = 1,
Name = "Fabian Pizzas",
Pizzas = new List<Pizza>()
{
new Pizza
{
PizzaID = 1,
Name = "Supreme",
Toppings = new List<Topping>()
{
new Topping
{
ToppingID = 1,
Name = "Mozzarella"
},
new Topping
{
ToppingID = 2,
Name = "Bacon"
}
}
},
new Pizza
{
PizzaID = 2,
Name = "Hawaiian ",
Toppings = new List<Topping>()
{
new Topping
{
ToppingID = 3,
Name = "Ham"
},
new Topping
{
ToppingID = 4,
Name = "pineapple"
}
}
}
}
});
}
}
}
| 31.439394 | 106 | 0.319518 | [
"MIT"
] | Fabho/FabianPizzas | Migrations/Configuration.cs | 2,075 | C# |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2016 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using Hotcakes.CommerceDTO.v1.Catalog;
namespace Hotcakes.Commerce.Catalog
{
/// <summary>
/// This is the primary object that is used to manage all aspects of Reviews in the main application.
/// </summary>
/// <remarks>The REST API equivalent is ProductReviewDTO.</remarks>
[Serializable]
public class ProductReview
{
public ProductReview()
{
Bvin = string.Empty;
StoreId = 0;
LastUpdated = DateTime.UtcNow;
UserID = string.Empty;
ProductBvin = string.Empty;
ReviewDateUtc = DateTime.UtcNow;
Rating = ProductReviewRating.ThreeStars;
Karma = 0;
Description = string.Empty;
Approved = false;
ProductName = string.Empty;
}
/// <summary>
/// This is the ID of the review.
/// </summary>
public string Bvin { get; set; }
/// <summary>
/// This is the ID of the Hotcakes store. Typically, this is 1, except in multi-tenant environments.
/// </summary>
public long StoreId { get; set; }
/// <summary>
/// The last updated date is used for auditing purposes to know when the review was last updated.
/// </summary>
public DateTime LastUpdated { get; set; }
/// <summary>
/// The unique ID of the user account that created the review.
/// </summary>
public string UserID { get; set; }
/// <summary>
/// The unique ID of the product that this review is written for.
/// </summary>
public string ProductBvin { get; set; }
/// <summary>
/// The date/time stamp reflecting when the review was submitted. This value is shown to customers.
/// </summary>
[Obsolete("Obsolete in 1.8.0. Use DateHelper.ConvertUtcToStoreTime method instead")]
public DateTime ReviewDate
{
get { return ReviewDateUtc.ToLocalTime(); }
set { ReviewDateUtc = value.ToUniversalTime(); }
}
/// <summary>
/// The UTC version of the date/time stamp reflecting when the review was submitted.
/// </summary>
public DateTime ReviewDateUtc { get; set; }
/// <summary>
/// A star rating from 1-5 to reflect how good or bad the purchased product and/or service was.
/// </summary>
public ProductReviewRating Rating { get; set; }
/// <summary>
/// A conversion of Rating to a numeric value, used for mathematical functions.
/// </summary>
public int RatingAsInteger
{
get { return (int) Rating; }
}
/// <summary>
/// Karma is used by merchants to adjust the overall rating of a review.
/// </summary>
/// <remarks>This property is currently not being used by the application.</remarks>
public int Karma { get; set; }
/// <summary>
/// Gets or sets the comments from the reviewer that describe their feelings/experience with the product and/or
/// service.
/// </summary>
public string Description { get; set; }
/// <summary>
/// When moderation is enabled, this value will determine if the review will be shown to site visitors.
/// </summary>
public bool Approved { get; set; }
/// <summary>
/// Gets or sets the name of the product that this review was created for.
/// </summary>
/// <remarks>This property is currently not saved in the data source.</remarks>
public string ProductName { get; set; }
/// <summary>
/// A time zone adjusted date/time stamp of the review date in the local time of the current user.
/// </summary>
/// <param name="tz">TimeZoneInfo - an object describing the timezone of the user.</param>
/// <returns>DateTime - an adjusted date/time stamp for the current user in their time zone.</returns>
public DateTime ReviewDateForTimeZone(TimeZoneInfo tz)
{
return TimeZoneInfo.ConvertTimeFromUtc(ReviewDateUtc, tz);
}
#region DTO
/// <summary>
/// Allows you to convert the current product review object to the DTO equivalent for use with the REST API
/// </summary>
/// <returns>A new instance of ProductReviewDTO</returns>
public ProductReviewDTO ToDto()
{
var dto = new ProductReviewDTO();
dto.Approved = Approved;
dto.Bvin = Bvin;
dto.Description = Description;
dto.Karma = Karma;
dto.ProductBvin = ProductBvin;
dto.ProductName = ProductName;
dto.Rating = (ProductReviewRatingDTO) (int) Rating;
dto.ReviewDateUtc = ReviewDateUtc;
dto.UserID = UserID;
return dto;
}
/// <summary>
/// Allows you to populate the current product review object using a ProductReviewDTO instance
/// </summary>
/// <param name="dto">An instance of the product review from the REST API</param>
public void FromDto(ProductReviewDTO dto)
{
if (dto == null) return;
Approved = dto.Approved;
Bvin = dto.Bvin;
Description = dto.Description;
Karma = dto.Karma;
ProductBvin = dto.ProductBvin;
ProductName = dto.ProductName;
Rating = (ProductReviewRating) (int) dto.Rating;
ReviewDateUtc = dto.ReviewDateUtc;
UserID = dto.UserID;
}
#endregion
}
} | 38.393443 | 123 | 0.598207 | [
"MIT"
] | ketangarala/core | Libraries/Hotcakes.Commerce/Catalog/ProductReview.cs | 7,026 | C# |
using FortBlast.Extras;
using FortBlast.ProceduralTerrain.Generators;
using FortBlast.ProceduralTerrain.ProceduralTerrainCreators;
using FortBlast.ProceduralTerrain.Settings;
using UnityEngine;
namespace FortBlast.ProceduralTerrain.DataHolders.TerrainChunkData
{
public class Trees
{
private readonly ClearingSettings _clearingSettings;
private readonly Vector3 _meshCenter;
private readonly TreeSettings _treeSettings;
public bool hasPlacedTrees;
public bool hasReceivedTreePoints;
public bool hasRequestedTreePoints;
private Vector3[] _treePoints;
private GameObject[] _trees;
public Trees(Vector2 meshCenter, TreeSettings treeSettings, ClearingSettings clearingSettings)
{
_meshCenter = new Vector3(meshCenter.x, 0, meshCenter.y);
_treeSettings = treeSettings;
_clearingSettings = clearingSettings;
_trees = new GameObject[0];
_treePoints = new Vector3[0];
}
public void RequestTreePoints(Vector3[] meshVertices, int chunkSizeIndex)
{
hasRequestedTreePoints = true;
ThreadedDataRequester.RequestData(
() =>
TreePointsGenerator.SelectTreePoints(meshVertices, chunkSizeIndex,
_meshCenter, _treeSettings, _clearingSettings),
OnTreePointsReceived
);
}
public void PlaceTreesOnPoints()
{
hasPlacedTrees = true;
var maxValue = float.MinValue;
for (var i = 0; i < _treePoints.Length; i++)
if (_treePoints[i].y > maxValue)
maxValue = _treePoints[i].y;
for (var i = 0; i < _treePoints.Length; i++)
{
if (_treePoints[i] == Vector3.zero)
Debug.Log("Tree At Zero");
var normalizedPoint = ExtensionFunctions.Map(_treePoints[i].y, 0, maxValue,
0, 1);
_trees[i] = TreesManager.instance.RequestTree(normalizedPoint);
if (_trees[i] != null)
{
_trees[i].transform.position = _treePoints[i] + _meshCenter;
if (_treeSettings.useRandomTreeRotation)
_trees[i].transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
_trees[i].SetActive(true);
}
}
}
public void ClearTrees()
{
for (var i = 0; i < _trees.Length; i++)
{
_trees[i]?.SetActive(false);
_trees[i] = null;
}
hasPlacedTrees = false;
}
private void OnTreePointsReceived(object treePointsObject)
{
hasReceivedTreePoints = true;
_treePoints = (Vector3[]) treePointsObject;
_trees = new GameObject[_treePoints.Length];
PlaceTreesOnPoints();
}
}
} | 33.844444 | 102 | 0.569599 | [
"MIT"
] | Rud156/FortBlast | Assets/Scripts/Procedular Terrain/Data Holders/Terrain Chunk Data/Trees.cs | 3,046 | C# |
//
// DO NOT MODIFY! THIS IS AUTOGENERATED FILE!
//
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
// Role: PROXY
public sealed unsafe partial class CefDomNode : IDisposable
{
internal static CefDomNode FromNative(cef_domnode_t* ptr)
{
return new CefDomNode(ptr);
}
internal static CefDomNode FromNativeOrNull(cef_domnode_t* ptr)
{
if (ptr == null) return null;
return new CefDomNode(ptr);
}
private cef_domnode_t* _self;
private CefDomNode(cef_domnode_t* ptr)
{
if (ptr == null) throw new ArgumentNullException("ptr");
_self = ptr;
}
~CefDomNode()
{
if (_self != null)
{
Release();
_self = null;
}
}
public void Dispose()
{
if (_self != null)
{
Release();
_self = null;
}
GC.SuppressFinalize(this);
}
internal void AddRef()
{
cef_domnode_t.add_ref(_self);
}
internal bool Release()
{
return cef_domnode_t.release(_self) != 0;
}
internal bool HasOneRef
{
get { return cef_domnode_t.has_one_ref(_self) != 0; }
}
internal cef_domnode_t* ToNative()
{
AddRef();
return _self;
}
}
}
| 22.853333 | 71 | 0.475496 | [
"MIT"
] | git-thinh/Xilium.CefGlue-lvcef-39.0 | xilium.cefglue/CefGlue/Classes.g/CefDomNode.g.cs | 1,714 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using MyCompany.EntityFrameworkCore;
namespace MyCompany.Migrations
{
[DbContext(typeof(MyCompanyDbContext))]
[Migration("20170608053244_Upgraded_To_Abp_2_1_0")]
partial class Upgraded_To_Abp_2_1_0
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(255)")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsDisabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("MyCompany.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("MyCompany.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("MyCompany.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId")
.HasColumnType("int");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("MyCompany.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("MyCompany.Authorization.Roles.Role", b =>
{
b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("MyCompany.Authorization.Users.User", b =>
{
b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("MyCompany.MultiTenancy.Tenant", b =>
{
b.HasOne("MyCompany.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("MyCompany.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("MyCompany.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("MyCompany.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("MyCompany.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 35.39631 | 117 | 0.429924 | [
"MIT"
] | StefanKoenen/aspnetboilerplate-5844 | aspnet-core/src/MyCompany.EntityFrameworkCore/Migrations/20170608053244_Upgraded_To_Abp_2_1_0.Designer.cs | 47,962 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace Automatonymous
{
using System;
using Activities;
using Binders;
using Events;
using MassTransit.Context;
public static class RequestExtensions
{
static RequestExtensions()
{
ScheduleTokenId.UseTokenId<RequestTimeoutExpired>(x => x.RequestId);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> Request<TInstance, TData, TRequest, TResponse>(
this EventActivityBinder<TInstance, TData> binder, Request<TInstance, TRequest, TResponse> request,
EventMessageFactory<TInstance, TData, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TRequest : class
where TResponse : class
{
var activity = new RequestActivity<TInstance, TData, TRequest, TResponse>(request, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="serviceAddressProvider">A provider for the address used for the request</param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> Request<TInstance, TData, TRequest, TResponse>(
this EventActivityBinder<TInstance, TData> binder, Request<TInstance, TRequest, TResponse> request,
ServiceAddressProvider<TInstance, TData> serviceAddressProvider, EventMessageFactory<TInstance, TData, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TRequest : class
where TResponse : class
{
var activity = new RequestActivity<TInstance, TData, TRequest, TResponse>(request, serviceAddressProvider, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <typeparam name="TException"></typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static ExceptionActivityBinder<TInstance, TData, TException> Request<TInstance, TData, TException, TRequest, TResponse>(
this ExceptionActivityBinder<TInstance, TData, TException> binder, Request<TInstance, TRequest, TResponse> request,
EventExceptionMessageFactory<TInstance, TData, TException, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TRequest : class
where TResponse : class
where TException : Exception
{
var activity = new FaultedRequestActivity<TInstance, TData, TException, TRequest, TResponse>(request, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TData">The event data type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <typeparam name="TException"></typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="serviceAddressProvider"></param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static ExceptionActivityBinder<TInstance, TData, TException> Request<TInstance, TData, TException, TRequest, TResponse>(
this ExceptionActivityBinder<TInstance, TData, TException> binder, Request<TInstance, TRequest, TResponse> request,
ServiceAddressProvider<TInstance, TData, TException> serviceAddressProvider,
EventExceptionMessageFactory<TInstance, TData, TException, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TRequest : class
where TResponse : class
where TException : Exception
{
var activity = new FaultedRequestActivity<TInstance, TData, TException, TRequest, TResponse>(request, serviceAddressProvider, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static EventActivityBinder<TInstance> Request<TInstance, TRequest, TResponse>(
this EventActivityBinder<TInstance> binder, Request<TInstance, TRequest, TResponse> request,
EventMessageFactory<TInstance, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TRequest : class
where TResponse : class
{
var activity = new RequestActivity<TInstance, TRequest, TResponse>(request, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Send a request to the configured service endpoint, and setup the state machine to accept the response.
/// </summary>
/// <typeparam name="TInstance">The state instance type</typeparam>
/// <typeparam name="TRequest">The request message type</typeparam>
/// <typeparam name="TResponse">The response message type</typeparam>
/// <param name="binder">The event binder</param>
/// <param name="request">The configured request to use</param>
/// <param name="serviceAddressProvider"></param>
/// <param name="messageFactory">The request message factory</param>
/// <returns></returns>
public static EventActivityBinder<TInstance> Request<TInstance, TRequest, TResponse>(
this EventActivityBinder<TInstance> binder, Request<TInstance, TRequest, TResponse> request,
ServiceAddressProvider<TInstance> serviceAddressProvider, EventMessageFactory<TInstance, TRequest> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TRequest : class
where TResponse : class
{
var activity = new RequestActivity<TInstance, TRequest, TResponse>(request, serviceAddressProvider, messageFactory);
return binder.Add(activity);
}
/// <summary>
/// Cancels the request timeout, and clears the request data from the state instance
/// </summary>
/// <typeparam name="TInstance"></typeparam>
/// <typeparam name="TData"></typeparam>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="binder"></param>
/// <param name="request"></param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> CancelRequestTimeout<TInstance, TData, TRequest, TResponse>(
this EventActivityBinder<TInstance, TData> binder, Request<TInstance, TRequest, TResponse> request)
where TInstance : class, SagaStateMachineInstance
where TRequest : class
where TResponse : class
{
var activity = new CancelRequestTimeoutActivity<TInstance, TData, TRequest, TResponse>(request);
return binder.Add(activity);
}
/// <summary>
/// Clears the requestId on the state
/// </summary>
/// <typeparam name="TInstance"></typeparam>
/// <typeparam name="TData"></typeparam>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <param name="binder"></param>
/// <param name="request"></param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> ClearRequest<TInstance, TData, TRequest, TResponse>(
this EventActivityBinder<TInstance, TData> binder, Request<TInstance, TRequest, TResponse> request)
where TInstance : class, SagaStateMachineInstance
where TRequest : class
where TResponse : class
{
var activity = new ClearRequestActivity<TInstance, TData, TRequest, TResponse>(request);
return binder.Add(activity);
}
}
} | 53.488584 | 155 | 0.641796 | [
"Apache-2.0"
] | zengdl/MassTransit | src/MassTransit.AutomatonymousIntegration/RequestExtensions.cs | 11,716 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/number-of-paths-with-max-score
/// Submission: https://leetcode.com/submissions/detail/435597901/
/// </summary>
internal class P1301
{
public class Solution
{
public int[] PathsWithMaxScore(IList<string> board)
{
var mod = (int)1e9 + 7;
var length = board.Count;
var dpSum = new int[length, length];
var dpCount = new int[length, length];
dpCount[0, 0] = 1;
// impossible paths
if (board[0][0] == 'X' || board[length - 1][length - 1] == 'X')
return new int[] { 0, 0 };
for (var i = 1; i < 2 * length - 1; i++)
{
var row = i;
var col = 0;
if (i >= length)
{
row = length - 1;
col = i - length + 1;
}
// go diagonal incrementally
while (row >= 0 && col < length)
{
if (board[row][col] == 'X')
{
row--;
col++;
continue;
}
// prev cells
var prev = new List<(int r, int c)>
{
(row - 1, col),
(row - 1, col - 1),
(row, col - 1)
};
var cell = board[row][col] == 'S'
? 0
: int.Parse(board[row][col].ToString());
var max = 0;
// find max sum from prev cells + current
foreach (var p in prev)
if (p.r >= 0 && p.c >= 0 && p.r < length && p.c < length)
max = Math.Max(max, dpSum[p.r, p.c] + cell);
var count = 0;
// find count of ways for that max sum
foreach (var p in prev)
{
if (p.r >= 0 && p.c >= 0 && p.r < length && p.c < length)
{
if (dpSum[p.r, p.c] + cell == max)
{
count += dpCount[p.r, p.c];
count %= mod;
}
}
}
dpSum[row, col] = max;
dpCount[row, col] = count;
row--;
col++;
}
}
var maxP = dpSum[length - 1, length - 1];
var maxC = dpCount[length - 1, length - 1];
if (maxC == 0)
maxP = 0;
return new int[] { maxP, maxC };
}
}
}
}
| 25.398058 | 79 | 0.389908 | [
"MIT"
] | viacheslave/leetcode-naive | c#/Problems/P1301.cs | 2,616 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace FashionStore.App_Code
{
public class MD5
{
#region Mã hoá
private static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes("d3c8eshop06e57cc1afthanh7ebdba0142dory7e62bc2"));
}
else keyArray = Encoding.UTF8.GetBytes("d3c8eshop06e57cc1afthanh7ebdba0142dory7e62bc2");
var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
private static string Decrypt(string toDecrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes("d3c8eshop06e57cc1afthanh7ebdba0142dory7e62bc2"));
}
else keyArray = Encoding.UTF8.GetBytes("d3c8eshop06e57cc1afthanh7ebdba0142dory7e62bc2");
var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
public static string md5(string data, bool hash)
{
if (hash)
return Encrypt(data, true);
else
return Decrypt(data, true);
}
#endregion
}
} | 38.269841 | 120 | 0.604728 | [
"MIT"
] | nguyenthienthanh/FashionStore | FashionStore/App_Code/MD5.cs | 2,415 | C# |
using Content.Server.Doors.Components;
using Content.Shared.Doors;
using Content.Shared.Notification.Managers;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
namespace Content.Server.Doors.Systems
{
public class FirelockSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<FirelockComponent, BeforeDoorOpenedEvent>(OnBeforeDoorOpened);
SubscribeLocalEvent<FirelockComponent, BeforeDoorDeniedEvent>(OnBeforeDoorDenied);
SubscribeLocalEvent<FirelockComponent, DoorGetPryTimeModifierEvent>(OnDoorGetPryTimeModifier);
SubscribeLocalEvent<FirelockComponent, DoorClickShouldActivateEvent>(OnDoorClickShouldActivate);
SubscribeLocalEvent<FirelockComponent, BeforeDoorPryEvent>(OnBeforeDoorPry);
SubscribeLocalEvent<FirelockComponent, BeforeDoorAutoCloseEvent>(OnBeforeDoorAutoclose);
}
private void OnBeforeDoorOpened(EntityUid uid, FirelockComponent component, BeforeDoorOpenedEvent args)
{
if (component.IsHoldingFire() || component.IsHoldingPressure())
args.Cancel();
}
private void OnBeforeDoorDenied(EntityUid uid, FirelockComponent component, BeforeDoorDeniedEvent args)
{
args.Cancel();
}
private void OnDoorGetPryTimeModifier(EntityUid uid, FirelockComponent component, DoorGetPryTimeModifierEvent args)
{
if (component.IsHoldingFire() || component.IsHoldingPressure())
args.PryTimeModifier *= component.LockedPryTimeModifier;
}
private void OnDoorClickShouldActivate(EntityUid uid, FirelockComponent component, DoorClickShouldActivateEvent args)
{
// We're a firelock, you can't click to open it
args.Handled = true;
}
private void OnBeforeDoorPry(EntityUid uid, FirelockComponent component, BeforeDoorPryEvent args)
{
if (component.DoorComponent == null || component.DoorComponent.State != SharedDoorComponent.DoorState.Closed)
{
return;
}
if (component.IsHoldingPressure())
{
component.Owner.PopupMessage(args.Args.User, Loc.GetString("firelock-component-is-holding-pressure-message"));
}
else if (component.IsHoldingFire())
{
component.Owner.PopupMessage(args.Args.User, Loc.GetString("firelock-component-is-holding-fire-message"));
}
}
private void OnBeforeDoorAutoclose(EntityUid uid, FirelockComponent component, BeforeDoorAutoCloseEvent args)
{
// Firelocks can't autoclose, they must be manually closed
args.Cancel();
}
}
}
| 40.657143 | 126 | 0.674631 | [
"MIT"
] | Ccw2007/space-station-14 | Content.Server/Doors/Systems/FirelockSystem.cs | 2,848 | C# |
using Tibia.Addresses;
namespace Tibia
{
public partial class Version
{
public static void SetVersion842()
{
BattleList.Start = 0x631DF0;
BattleList.End = 0x631DF0 + 0xA0 * 250;
BattleList.StepCreatures = 0xA0;
BattleList.MaxCreatures = 250;
Client.StartTime = 0x7902B8;
Client.XTeaKey = 0x78ADF4;
Client.SocketStruct = 0x78ADC8;
Client.RecvPointer = 0x5AF5DC;
Client.SendPointer = 0x5AF608;
Client.FrameRatePointer = 0x78EF9C;
Client.FrameRateCurrentOffset = 0x60;
Client.FrameRateLimitOffset = 0x58;
Client.MultiClient = 0x505EF4;//not verified
Client.Status = 0x78E458;
Client.SafeMode = 0x78B21C;
Client.FollowMode = Client.SafeMode + 4;
Client.AttackMode = Client.FollowMode + 4;
Client.ActionState = 0x78E4B8;
Client.LastMSGAuthor = Client.LastMSGText - 0x28;
Client.LastMSGText = 0x790520;
Client.StatusbarText = 0x7902D0;
Client.StatusbarTime = Client.StatusbarText - 4;
Client.ClickId = 0x78E4F4;
Client.ClickCount = Client.ClickId + 4;
Client.ClickZ = Client.ClickId - 0x68;
Client.SeeId = Client.ClickId + 12;
Client.SeeCount = Client.SeeId + 4;
Client.SeeZ = Client.SeeId - 0x68;
Client.ClickContextMenuItemId = 0x78E500;
Client.ClickContextMenuItemGroundId = 0x78E50C;
Client.ClickContextMenuCreatureId = 0x78E45C;
Client.SeeText = 0x7904F8;
Client.LoginServerStart = 0x785D30;
Client.StepLoginServer = 112;
Client.DistancePort = 100;
Client.MaxLoginServers = 10;
Client.RSA = 0x5AF610;
Client.LoginCharList = 0x78E40C;
Client.LoginCharListLength = Client.LoginCharList + 4;
Client.LoginSelectedChar = 0x78E408;
Client.GameWindowRectPointer = 0x63D794;
Client.GameWindowBar = 0x640B00;
Client.DatPointer = 0x78AE14;
Client.EventTriggerPointer = 0x518E40;
Client.DialogPointer = 0x640AFC;
Client.DialogLeft = 0x14;
Client.DialogTop = 0x18;
Client.DialogWidth = 0x1C;
Client.DialogHeight = 0x20;
Client.DialogCaption = 0x50;
Client.LastRcvPacket = 0x7865A8;
Client.DecryptCall = 0x45B145;
Client.LoginAccountNum = 0;
Client.LoginPassword = 0x78E414;
Client.LoginAccount = Client.LoginPassword + 32;
Client.LoginPatch = 0;
Client.LoginPatch2 = 0;
Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 };
Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 };
Container.Start = 0x63E248;
Container.StepContainer = 492;
Container.StepSlot = 12;
Container.MaxContainers = 16;
Container.MaxStack = 100;
Container.DistanceIsOpen = 0;
Container.DistanceId = 4;
Container.DistanceName = 16;
Container.DistanceVolume = 48;
Container.DistanceAmount = 56;
Container.DistanceItemId = 60;
Container.DistanceItemCount = 64;
Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer);
ContextMenus.AddContextMenuPtr = 0x451160;
ContextMenus.OnClickContextMenuPtr = 0x44D920;
ContextMenus.OnClickContextMenuVf = 0x5B4AA0;
ContextMenus.AddSetOutfitContextMenu = 0x452092;
ContextMenus.AddPartyActionContextMenu = 0x4520E3;
ContextMenus.AddCopyNameContextMenu = 0x4520FA;
ContextMenus.AddTradeWithContextMenu = 0x451D09;
Creature.DistanceId = 0;
Creature.DistanceType = 3;
Creature.DistanceName = 4;
Creature.DistanceX = 36;
Creature.DistanceY = 40;
Creature.DistanceZ = 44;
Creature.DistanceScreenOffsetHoriz = 48;
Creature.DistanceScreenOffsetVert = 52;
Creature.DistanceIsWalking = 76;
Creature.DistanceWalkSpeed = 140;
Creature.DistanceDirection = 80;
Creature.DistanceIsVisible = 144;
Creature.DistanceBlackSquare = 132;
Creature.DistanceLight = 120;
Creature.DistanceLightColor = 124;
Creature.DistanceHPBar = 136;
Creature.DistanceSkull = 148;
Creature.DistanceParty = 152;
Creature.DistanceOutfit = 96;
Creature.DistanceColorHead = 100;
Creature.DistanceColorBody = 104;
Creature.DistanceColorLegs = 108;
Creature.DistanceColorFeet = 112;
Creature.DistanceAddon = 116;
DatItem.StepItems = 0x4C;
DatItem.Width = 0;
DatItem.Height = 4;
DatItem.MaxSizeInPixels = 8;
DatItem.Layers = 12;
DatItem.PatternX = 16;
DatItem.PatternY = 20;
DatItem.PatternDepth = 24;
DatItem.Phase = 28;
DatItem.Sprite = 32;
DatItem.Flags = 36;
DatItem.CanLookAt = 0;
DatItem.WalkSpeed = 40;
DatItem.TextLimit = 44;
DatItem.LightRadius = 48;
DatItem.LightColor = 52;
DatItem.ShiftX = 56;
DatItem.ShiftY = 60;
DatItem.WalkHeight = 64;
DatItem.Automap = 68;
DatItem.LensHelp = 72;
Hotkey.SendAutomaticallyStart = 0x78B418;
Hotkey.SendAutomaticallyStep = 0x01;
Hotkey.TextStart = 0x78B440;
Hotkey.TextStep = 0x100;
Hotkey.ObjectStart = 0x78B388;
Hotkey.ObjectStep = 0x04;
Hotkey.ObjectUseTypeStart = 0x78B268;
Hotkey.ObjectUseTypeStep = 0x04;
Hotkey.MaxHotkeys = 36;
Map.MapPointer = 0x645650;
Map.StepTile = 168;
Map.StepTileObject = 12;
Map.DistanceTileObjectCount = 0;
Map.DistanceTileObjects = 4;
Map.DistanceObjectId = 0;
Map.DistanceObjectData = 4;
Map.DistanceObjectDataEx = 8;
Map.MaxTileObjects = 10;
Map.MaxX = 18;
Map.MaxY = 14;
Map.MaxZ = 8;
Map.MaxTiles = 2016;
Map.ZAxisDefault = 7;
Map.NameSpy1 = 0x4ECA89;
Map.NameSpy2 = 0x4ECA93;
Map.NameSpy1Default = 19061;
Map.NameSpy2Default = 16501;
Map.LevelSpy1 = 0x4EE93A;
Map.LevelSpy2 = 0x4EEA3F;
Map.LevelSpy3 = 0x4EEAC0;
Map.LevelSpyPtr = 0x63D794;
Map.LevelSpyAdd1 = 28;
Map.LevelSpyAdd2 = 0x2A88;
Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 };
Map.RevealInvisible1 = 0x45EFE3;
Map.RevealInvisible2 = 0x4EBD55;
Map.FullLightNop = 0x4E5239;
Map.FullLightAdr = 0x4E523C;
Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 };
Map.FullLightNopEdited = new byte[] { 0x90, 0x90 };
Map.FullLightAdrDefault = 0x80;
Map.FullLightAdrEdited = 0xFF;
Player.Experience = 0x631D84;
Player.Flags = Player.Experience - 108;
Player.Id = Player.Experience + 12;
Player.Health = Player.Experience + 8;
Player.HealthMax = Player.Experience + 4;
Player.Level = Player.Experience - 4;
Player.MagicLevel = Player.Experience - 8;
Player.LevelPercent = Player.Experience - 12;
Player.MagicLevelPercent = Player.Experience - 16;
Player.Mana = Player.Experience - 20;
Player.ManaMax = Player.Experience - 24;
Player.Soul = Player.Experience - 28;
Player.Stamina = Player.Experience - 32;
Player.Capacity = Player.Experience - 36;
Player.FistPercent = 0x62CCBC;
Player.ClubPercent = Player.FistPercent + 4;
Player.SwordPercent = Player.FistPercent + 8;
Player.AxePercent = Player.FistPercent + 12;
Player.DistancePercent = Player.FistPercent + 16;
Player.ShieldingPercent = Player.FistPercent + 20;
Player.FishingPercent = Player.FistPercent + 24;
Player.Fist = Player.FistPercent + 28;
Player.Club = Player.FistPercent + 32;
Player.Sword = Player.FistPercent + 36;
Player.Axe = Player.FistPercent + 40;
Player.Distance = Player.FistPercent + 44;
Player.Shielding = Player.FistPercent + 48;
Player.Fishing = Player.FistPercent + 52;
Player.SlotHead = 0x63E1D0;
Player.SlotNeck = Player.SlotHead + 12;
Player.SlotBackpack = Player.SlotHead + 24;
Player.SlotArmor = Player.SlotHead + 36;
Player.SlotRight = Player.SlotHead + 48;
Player.SlotLeft = Player.SlotHead + 60;
Player.SlotLegs = Player.SlotHead + 72;
Player.SlotFeet = Player.SlotHead + 84;
Player.SlotRing = Player.SlotHead + 96;
Player.SlotAmmo = Player.SlotHead + 108;
Player.MaxSlots = 10;
Player.DistanceSlotCount = 4;
Player.CurrentTileToGo = 0x631D98;
Player.TilesToGo = 0x631D9C;
Player.GoToX = Player.Experience + 80;
Player.GoToY = Player.GoToX - 4;
Player.GoToZ = Player.GoToX - 8;
Player.RedSquare = 0x631D5C;
Player.GreenSquare = Player.RedSquare - 4;
Player.WhiteSquare = Player.GreenSquare - 8;
Player.AccessN = 0;
Player.AccessS = 0;
Player.TargetId = Player.RedSquare;
Player.TargetBattlelistId = Player.TargetId - 8;
Player.TargetBattlelistType = Player.TargetId - 5;
Player.TargetType = Player.TargetId + 3;
Player.Z = 0x640B38;
TextDisplay.PrintName = 0x4EFA71;
TextDisplay.PrintFPS = 0x459048;
TextDisplay.ShowFPS = 0x62FA34;
TextDisplay.PrintTextFunc = 0x4AF8D0;
TextDisplay.NopFPS = 0x458F84;
Vip.Start = 0x62FAB0;
Vip.StepPlayers = 0x2C;
Vip.MaxPlayers = 200;
Vip.DistanceId = 0;
Vip.DistanceName = 4;
Vip.DistanceStatus = 34;
Vip.DistanceIcon = 40;
Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers);
}
}
}
| 43.316406 | 99 | 0.561728 | [
"MIT"
] | BeldenGit/tibiaapi | tibiaapi/Addresses/Versions/Version842.cs | 11,089 | C# |
using Autofac;
using Microsoft.Build.Locator;
using NuGet.Credentials;
using Serilog;
using System;
using System.Linq;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using LSP = OmniSharp.Extensions.LanguageServer;
using NuGetNullLogger = NuGet.Common.NullLogger;
namespace MSBuildProjectTools.LanguageServer
{
using Utilities;
/// <summary>
/// The MSBuild language server.
/// </summary>
static class Program
{
/// <summary>
/// The minimum version of the .NET Core SDK supported by the language server.
/// </summary>
static readonly Version TargetSdkMinVersion = new Version("5.0.102");
/// <summary>
/// The maximum version of the .NET Core SDK supported by the language server.
/// </summary>
static readonly Version TargetSdkMaxVersion = new Version("5.0.999");
/// <summary>
/// The main program entry-point.
/// </summary>
/// <returns>
/// The process exit code.
/// </returns>
static int Main()
{
SynchronizationContext.SetSynchronizationContext(
new SynchronizationContext()
);
try
{
AutoDetectExtensionDirectory();
MSBuildHelper.DiscoverMSBuildEngine();
ConfigureNuGetCredentialProviders();
return AsyncMain().GetAwaiter().GetResult();
}
catch (AggregateException aggregateError)
{
foreach (Exception unexpectedError in aggregateError.Flatten().InnerExceptions)
Console.Error.WriteLine(unexpectedError);
return 1;
}
catch (Exception unexpectedError)
{
Console.Error.WriteLine(unexpectedError);
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
/// <summary>
/// The asynchronous program entry-point.
/// </summary>
/// <returns>
/// The process exit code.
/// </returns>
static async Task<int> AsyncMain()
{
using (ActivityCorrelationManager.BeginActivityScope())
using (Terminator terminator = new Terminator())
using (IContainer container = BuildContainer())
{
// Force initialisation of logging.
ILogger log = container.Resolve<ILogger>().ForContext(typeof(Program));
log.Debug("Creating language server...");
var server = container.Resolve<LSP.Server.LanguageServer>();
log.Debug("Waiting for client to initialise language server...");
Task initializeTask = server.Initialize();
// Special case for probing whether language server is startable given current runtime environment.
string[] commandLineArguments = Environment.GetCommandLineArgs();
if (commandLineArguments.Length == 2 && commandLineArguments[1] == "--probe")
{
// Give the language server a chance to start.
await Task.Yield();
// Show any exception encountered while starting the language server.
if (initializeTask.IsFaulted || initializeTask.IsCanceled)
await initializeTask;
Console.Error.WriteLine("PROBE: Yes, the language server can start.");
return 0;
}
await initializeTask;
log.Debug("Language server initialised by client.");
if (server.Client.ProcessId != null)
{
terminator.Initialize(
(int)server.Client.ProcessId.Value
);
}
await server.WasShutDown;
log.Debug("Language server is shutting down...");
await server.WaitForExit;
log.Debug("Server has shut down. Preparing to terminate server process...");
log.Debug("Server process is ready to terminate.");
return 0;
}
}
/// <summary>
/// Build a container for language server components.
/// </summary>
/// <returns>
/// The container.
/// </returns>
static IContainer BuildContainer()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule<LoggingModule>();
builder.RegisterModule<LanguageServerModule>();
return builder.Build();
}
/// <summary>
/// Auto-detect the directory containing the extension's files.
/// </summary>
static void AutoDetectExtensionDirectory()
{
string extensionDir = Environment.GetEnvironmentVariable("MSBUILD_PROJECT_TOOLS_DIR");
if (String.IsNullOrWhiteSpace(extensionDir))
{
extensionDir = Path.Combine(
AppContext.BaseDirectory, "..", ".."
);
}
extensionDir = Path.GetFullPath(extensionDir);
Environment.SetEnvironmentVariable("MSBUILD_PROJECT_TOOLS_DIR", extensionDir);
}
/// <summary>
/// Configure NuGet's credential providers (i.e. support for authenticated package feeds).
/// </summary>
static void ConfigureNuGetCredentialProviders()
{
DefaultCredentialServiceUtility.SetupDefaultCredentialService(
logger: NuGetNullLogger.Instance,
nonInteractive: true
);
}
}
}
| 32.563536 | 115 | 0.54547 | [
"MIT"
] | tintoy/msbuild-project-tools-server | src/LanguageServer/Program.cs | 5,896 | C# |
//
// RegisteredDisposeScript.cs
//
// Author:
// Igor Zelmanovich <igorz@mainsoft.com>
//
// (C) 2008 Mainsoft, Inc. http://www.mainsoft.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.
//
using System;
namespace System.Web.UI
{
public sealed class RegisteredDisposeScript
{
readonly Control _control;
readonly UpdatePanel _updatePanel;
readonly string _script;
internal RegisteredDisposeScript (Control control, string script, UpdatePanel updatePanel) {
_control = control;
_script = script;
_updatePanel = updatePanel;
}
public Control Control {
get { return _control; }
}
public string Script {
get { return _script; }
}
internal UpdatePanel UpdatePanel {
get { return _updatePanel; }
}
}
}
| 30.254237 | 94 | 0.739496 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web.Extensions/System.Web.UI/RegisteredDisposeScript.cs | 1,785 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
SceneManager.LoadScene("City");
}
}
| 17.733333 | 46 | 0.733083 | [
"MIT"
] | AcquaWh/oculus_spaceapps | Assets/Scripts/ChangeScene/ChangeScene.cs | 268 | C# |
using Microsoft.EntityFrameworkCore;
using Nssol.Platypus.Infrastructure;
using Nssol.Platypus.Models.TenantModels;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Nssol.Platypus.DataAccess.Core
{
/// <summary>
/// テナント向けテーブルにアクセスするための基本リポジトリクラス
/// </summary>
public abstract class RepositoryForTenantBase<TModel> : IRepositoryForTenant<TModel>
where TModel : TenantModelBase
{
/// <summary>
/// 現在選択中のテナントID
/// 新規作成時、TModel.Tenant に TenantオブジェクトそのものをAddするとTenantも新規作成をしようとするので、IDだけを保持させる。
/// </summary>
protected long CurrentTenantId { get; private set; }
/// <summary>
/// 接続先のデータソースを表すDBコンテキスト
/// </summary>
private CommonDbContext DataContext;
/// <summary>
/// TModelに対応するテーブルにアクセスするためのアクセッサ
/// </summary>
private readonly DbSet<TModel> dbset;
/// <summary>
/// サブクラスから他のテナント用テーブルにアクセスするためのアクセッサ。
/// この結果を用いたDBアクセスは、テナントIDの制約が入らない(そのままだと他のテナント情報にアクセスできる)ので、取り扱いには注意。
/// </summary>
protected DbSet<T> GetDbSet<T>() where T : TenantModelBase
{
return DataContext.Set<T>();
}
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="context">DBコンテキスト</param>
/// <param name="accessor">HTTPコンテキストアクセサ</param>
protected RepositoryForTenantBase(CommonDbContext context, Microsoft.AspNetCore.Http.IHttpContextAccessor accessor)
{
DataContext = context;
dbset = DataContext.Set<TModel>();
CurrentTenantId = accessor.HttpContext.GetClaims().GetTenantId();
}
/// <summary>
/// 新規エントリを追加
/// </summary>
/// <param name="entity">追加するエントリ</param>
public virtual void Add(TModel entity)
{
AddModel(entity, false);
}
/// <summary>
/// 新規エントリを追加
/// </summary>
/// <param name="entity">追加するエントリ</param>
/// <param name="force">他テナントに対する追加を許可するか</param>
public void Add(TModel entity, bool force)
{
AddModel(entity, force);
}
/// <summary>
/// 新規エントリを追加
/// </summary>
/// <param name="entity">追加するエントリ</param>
/// <param name="force">他テナントに対する追加を許可するか</param>
protected void AddModel<T>(T entity, bool force = false) where T : TenantModelBase
{
if (force == false)
{
if (entity.TenantId <= 0)
{
entity.TenantId = CurrentTenantId;
}
else if (force == false && entity.TenantId != CurrentTenantId)
{
throw new UnauthorizedAccessException("異なるテナントのデータを追加しようとしています。");
}
}
DataContext.Set<T>().Add(entity);
}
/// <summary>
/// 新規エントリを一括追加
/// </summary>
/// <param name="entities">追加するエントリ</param>
public virtual void AddRange(IQueryable<TModel> entities)
{
AddModelRange(entities);
}
/// <summary>
/// 新規エントリを一括追加
/// </summary>
/// <param name="entities">追加するエントリ</param>
protected void AddModelRange<T>(IQueryable<T> entities) where T : TenantModelBase
{
if (entities == null)
{
return;
}
foreach (T entity in entities)
{
AddModel(entity);
}
}
/// <summary>
/// 既存エントリを更新
/// </summary>
/// <param name="entity">更新するエントリ</param>
public virtual void Update(TModel entity)
{
UpdateModel(entity, false);
}
/// <summary>
/// 既存エントリを更新
/// </summary>
/// <param name="entity">更新するエントリ</param>
/// <param name="force">他テナントに対する変更を許可するか</param>
public void Update(TModel entity, bool force)
{
UpdateModel(entity, force);
}
/// <summary>
/// 既存エントリを更新
/// </summary>
/// <param name="entity">更新するエントリ</param>
/// <param name="force">他テナントに対する変更を許可するか</param>
protected void UpdateModel<T>(T entity, bool force = false) where T : TenantModelBase
{
if (!force && entity.TenantId != CurrentTenantId)
{
throw new UnauthorizedAccessException("異なるテナントのデータを更新しようとしています。");
}
DataContext.Set<T>().Attach(entity);
DataContext.Entry(entity).State = EntityState.Modified;
}
/// <summary>
/// 既存エントリを削除
/// </summary>
/// <param name="entity">削除するエントリ</param>
public virtual void Delete(TModel entity)
{
this.DeleteModel(entity, false);
}
/// <summary>
/// 既存エントリを削除
/// </summary>
/// <param name="id">削除対象のID</param>
public async virtual Task DeleteByIdAsync(long id)
{
var entity = await GetByIdAsync(id);
this.DeleteModel(entity, false);
}
/// <summary>
/// 既存エントリを削除
/// </summary>
/// <param name="entity">削除するエントリ</param>
/// <param name="force">他テナントに対する削除を許可するか</param>
public void Delete(TModel entity, bool force)
{
this.DeleteModel(entity, force);
}
/// <summary>
/// 既存エントリを削除
/// </summary>
/// <param name="id">削除対象のID</param>
/// <param name="force">他テナントに対する削除を許可するか</param>
public async Task DeleteByIdAsync(long id, bool force)
{
var entity = await GetByIdAsync(id);
this.DeleteModel(entity, force);
}
/// <summary>
/// 既存エントリを削除
/// </summary>
/// <param name="entity">削除するエントリ</param>
/// <param name="force">他テナントに対する削除を許可するか</param>
protected void DeleteModel<T>(T entity, bool force = false) where T : TenantModelBase
{
if (!force && entity.TenantId != CurrentTenantId)
{
throw new UnauthorizedAccessException("異なるテナントのデータを削除しようとしています。");
}
DataContext.Set<T>().Remove(entity);
}
/// <summary>
/// 条件を満たす既存エントリを一括削除
/// </summary>
/// <param name="where">削除条件</param>
public virtual void DeleteAll(Expression<Func<TModel, bool>> where)
{
this.DeleteModelAll(where, false);
}
/// <summary>
/// 条件を満たす既存エントリを一括削除
/// </summary>
/// <param name="where">削除条件</param>
/// <param name="force">他テナントに対する削除を許可するか</param>
public void DeleteAll(Expression<Func<TModel, bool>> where, bool force)
{
this.DeleteModelAll(where, force);
}
/// <summary>
/// 条件を満たす既存エントリを一括削除
/// </summary>
/// <param name="where">削除条件</param>
/// <param name="force">他テナントに対する削除を許可するか</param>
protected void DeleteModelAll<T>(Expression<Func<T, bool>> where, bool force = false) where T : TenantModelBase
{
IQueryable<T> entries = GetModelAll<T>(force).Where(where);
DataContext.Set<T>().RemoveRange(entries);
}
/// <summary>
/// 既存エントリを一括削除
/// </summary>
/// <param name="entities">削除するエントリ</param>
public virtual void DeleteRange(IQueryable<TModel> entities)
{
DeleteModelRange(entities);
}
/// <summary>
/// 既存エントリを一括削除
/// </summary>
/// <param name="entities">削除するエントリ</param>
protected void DeleteModelRange<T>(IQueryable<T> entities) where T : TenantModelBase
{
if (entities == null)
{
return;
}
foreach (T entity in entities)
{
DeleteModel(entity);
}
}
/// <summary>
/// エントリの数を取得する。
/// </summary>
public async Task<long> Count()
{
return await GetAll().LongCountAsync();
}
/// <summary>
/// 条件を満たすエントリの数を取得する。
/// </summary>
/// <param name="where">取得条件</param>
public async Task<long> Count(Expression<Func<TModel, bool>> where)
{
return await FindAll(where).LongCountAsync();
}
/// <summary>
/// 条件を満たすエントリが存在するか確認する。
/// </summary>
/// <param name="where">取得条件</param>
public async virtual Task<bool> ExistsAsync(Expression<Func<TModel, bool>> where)
{
return await GetAll().AnyAsync(where);
}
/// <summary>
/// 条件を満たすエントリが存在するか確認する。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected async Task<bool> ExistsModelAsync<T>(Expression<Func<T, bool>> where, bool force = false) where T : TenantModelBase
{
return await GetModelAll<T>(force).AnyAsync(where);
}
/// <summary>
/// PKから既存エントリを取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// </summary>
/// <param name="id">取得対象のID</param>
public virtual async Task<TModel> GetByIdAsync(long id)
{
return await GetModelByIdAsync<TModel>(id);
}
/// <summary>
/// PKから既存エントリを取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// </summary>
/// <param name="id">取得対象のID</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
public async Task<TModel> GetByIdAsync(long id, bool force)
{
return await GetModelByIdAsync<TModel>(id, force);
}
/// <summary>
/// PKから既存エントリを取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// </summary>
/// <param name="id">取得対象のID</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected async Task<T> GetModelByIdAsync<T>(long id, bool force = false) where T : TenantModelBase
{
T model = await DataContext.Set<T>().FindAsync(id);
if (model == null)
{
return null;
}
if (!force && model != null && model.TenantId != CurrentTenantId)
{
throw new UnauthorizedAccessException("異なるテナントのデータを取得しようとしています。");
}
return model;
}
/// <summary>
/// 現在のテナントに属する、既存エントリをすべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
public virtual IQueryable<TModel> GetAll()
{
return this.GetModelAll<TModel>(false);
}
/// <summary>
/// 現在のテナントに属する、既存エントリをすべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected IQueryable<T> GetModelAll<T>(bool force = false) where T : TenantModelBase
{
if (force)
{
return DataContext.Set<T>();
}
else
{
return DataContext.Set<T>().Where(model => model.Tenant.Id == CurrentTenantId);
}
}
/// <summary>
/// 既存エントリを指定した順番ですべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="asc">昇順の場合はtrue, 降順ならfalse</param>
/// <param name="keySelector">並び順を表す式</param>
public virtual IQueryable<TModel> GetAllWithOrderby<TKey>(Expression<Func<TModel, TKey>> keySelector, bool asc)
{
return this.GetModelAllWithOrderby(keySelector, asc, false);
}
/// <summary>
/// 既存エントリを指定した順番ですべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="asc">昇順の場合はtrue, 降順ならfalse</param>
/// <param name="keySelector">並び順を表す式</param>
/// <param name="force">ログイン中のテナント以外も含めるか</param>
protected IQueryable<T> GetModelAllWithOrderby<T, TKey>(Expression<Func<T, TKey>> keySelector, bool asc, bool force) where T : TenantModelBase
{
IQueryable<T> result = GetModelAll<T>(force);
if (asc)
{
return result.OrderBy(keySelector);
}
else
{
return result.OrderByDescending(keySelector);
}
}
/// <summary>
/// 条件を満たす既存エントリを一つ取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// </summary>
/// <param name="where">取得条件</param>
public virtual TModel Find(Expression<Func<TModel, bool>> where)
{
return FindModel<TModel>(where);
}
/// <summary>
/// 条件を満たす既存エントリを一つ取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected T FindModel<T>(Expression<Func<T, bool>> where, bool force = false) where T : TenantModelBase
{
return FindModelAll(where, force).FirstOrDefault<T>();
}
/// <summary>
/// 条件を満たす既存エントリをすべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
public virtual IQueryable<TModel> FindAll(Expression<Func<TModel, bool>> where)
{
return FindModelAll<TModel>(where);
}
/// <summary>
/// 条件を満たす既存エントリをすべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
public IQueryable<TModel> FindAll(Expression<Func<TModel, bool>> where, bool force)
{
return FindModelAll<TModel>(where, force);
}
/// <summary>
/// 条件を満たす既存エントリをすべて取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected IQueryable<T> FindModelAll<T>(Expression<Func<T, bool>> where, bool force = false) where T : TenantModelBase
{
return GetModelAll<T>(force).Where(where);
}
/// <summary>
/// 条件を満たす既存エントリを指定した順番で取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="keySelector">並び順を表す式</param>
/// <param name="asc">昇順の場合はtrue, 降順ならfalse</param>
public virtual IQueryable<TModel> FindAllWithOrderby<TKey>(Expression<Func<TModel, bool>> where, Expression<Func<TModel, TKey>> keySelector, bool asc)
{
return FindModelAllWithOrderby<TModel, TKey>(where, keySelector, asc);
}
/// <summary>
/// 条件を満たす既存エントリを指定した順番で取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="keySelector">並び順を表す式</param>
/// <param name="asc">昇順の場合はtrue, 降順ならfalse</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
public IQueryable<TModel> FindAllWithOrderby<TKey>(Expression<Func<TModel, bool>> where, Expression<Func<TModel, TKey>> keySelector, bool asc, bool force)
{
return FindModelAllWithOrderby<TModel, TKey>(where, keySelector, asc, force);
}
/// <summary>
/// 条件を満たす既存エントリを指定した順番で取得する。
/// 外部参照がある場合、そのインスタンスは含まれない。
/// エントリが存在しない場合、nullではなく空のコレクションが返る。
/// </summary>
/// <param name="where">取得条件</param>
/// <param name="keySelector">並び順を表す式</param>
/// <param name="asc">昇順の場合はtrue, 降順ならfalse</param>
/// <param name="force">他テナントに対する取得を許可するか</param>
protected IQueryable<T> FindModelAllWithOrderby<T, TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> keySelector, bool asc, bool force = false) where T : TenantModelBase
{
var set = FindModelAll(where, force);
if (asc)
{
return set.OrderBy(keySelector);
}
else
{
return set.OrderByDescending(keySelector);
}
}
}
}
| 33.39604 | 192 | 0.542484 | [
"Apache-2.0"
] | yonetatuu/kamonohashi | web-api/platypus/platypus/DataAccess/Core/RepositoryForTenantBase.cs | 21,237 | C# |
/// File Name: EnemyControl.cs
/// File Author(s): Lincoln Schroeder
/// File Purpose: Every GameObject that is representing an enemy has this script attached. This script is used
/// for monitoring and changing enemy behavior. It also stores necessary data for the enemy, such as health and
/// damage.
///
/// Date Last Updated: November 26, 2019
using UnityEngine;
public class OverdriveControl : MonoBehaviour
{
[SerializeField]
private int lifetime;
private PlayerControl playerController;
private float timer;
/// <summary>
/// Awake is called on the first frame of instantation.
/// </summary>
private void Awake()
{
playerController = GameObject.Find("PlayerController").GetComponent<PlayerControl>();
playerController.OverdriveActive = true;
timer = 0;
}
/// <summary>
/// Update is called once per frame.
/// </summary>
private void Update()
{
timer += Time.deltaTime;
if (timer >= lifetime)
{
playerController.OverdriveActive = false;
Destroy(this.gameObject);
}
else
playerController.OverdriveActive = true;
}
}
| 27.159091 | 111 | 0.645188 | [
"MIT"
] | lincolnsch99/GameOff2019SourceCode | Assets/Scripts/Powerups/OverdriveControl.cs | 1,197 | C# |
using System;
namespace WireMock.Admin.Mappings
{
/// <summary>
/// MappingModel
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class MappingModel
{
/// <summary>
/// Gets or sets the unique identifier.
/// </summary>
public Guid? Guid { get; set; }
/// <summary>
/// The unique title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// The priority.
/// </summary>
public int? Priority { get; set; }
/// <summary>
/// The Scenario.
/// </summary>
public string Scenario { get; set; }
/// <summary>
/// Execution state condition for the current mapping.
/// </summary>
public string WhenStateIs { get; set; }
/// <summary>
/// The next state which will be signaled after the current mapping execution.
/// In case the value is null state will not be changed.
/// </summary>
public string SetStateTo { get; set; }
/// <summary>
/// The request model.
/// </summary>
public RequestModel Request { get; set; }
/// <summary>
/// The response model.
/// </summary>
public ResponseModel Response { get; set; }
/// <summary>
/// Saves this mapping as a static mapping file.
/// </summary>
public bool? SaveToFile { get; set; }
/// <summary>
/// The Webhook.
/// </summary>
public WebhookModel Webhook { get; set; }
/// <summary>
/// The Webhooks.
/// </summary>
public WebhookModel[] Webhooks { get; set; }
}
} | 25.820896 | 86 | 0.506936 | [
"Apache-2.0"
] | qq362220083/WireMock.Net | src/WireMock.Net.Abstractions/Admin/Mappings/MappingModel.cs | 1,732 | 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.Reflection;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace RemoteExecutorConsoleApp
{
/// <summary>
/// Provides an entry point in a new process that will load a specified method and invoke it.
/// </summary>
internal static class Program
{
private static int Main(string[] args)
{
// The program expects to be passed the target assembly name to load, the type
// from that assembly to find, and the method from that assembly to invoke.
// Any additional arguments are passed as strings to the method.
if (args.Length < 3)
{
Console.Error.WriteLine("Usage: {0} assemblyName typeName methodName", typeof(Program).GetTypeInfo().Assembly.GetName().Name);
Environment.Exit(-1);
return -1;
}
string assemblyName = args[0];
string typeName = args[1];
string methodName = args[2];
string[] additionalArgs = args.Length > 3 ?
args.Subarray(3, args.Length - 3) :
Array.Empty<string>();
// Load the specified assembly, type, and method, then invoke the method.
// The program's exit code is the return value of the invoked method.
Assembly a = null;
Type t = null;
MethodInfo mi = null;
object instance = null;
int exitCode;
try
{
// Create the test class if necessary
a = Assembly.Load(new AssemblyName(assemblyName));
t = a.GetType(typeName);
mi = t.GetTypeInfo().GetDeclaredMethod(methodName);
if (!mi.IsStatic)
{
instance = Activator.CreateInstance(t);
}
// Invoke the test
object result = mi.Invoke(instance, additionalArgs);
exitCode = result is Task<int> task ?
task.GetAwaiter().GetResult() :
(int)result;
}
catch (Exception exc)
{
Console.Error.WriteLine("Exception from RemoteExecutorConsoleApp({0}):", string.Join(", ", args));
Console.Error.WriteLine("Assembly: {0}", a);
Console.Error.WriteLine("Type: {0}", t);
Console.Error.WriteLine("Method: {0}", mi);
Console.Error.WriteLine("Exception: {0}", exc);
throw exc;
}
finally
{
(instance as IDisposable)?.Dispose();
}
// Environment.Exit not supported on .Net Native - don't even call it to avoid the nuisance exception.
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase))
{
// Use Exit rather than simply returning the exit code so that we forcibly shut down
// the process even if there are foreground threads created by the operation that would
// end up keeping the process alive potentially indefinitely.
try
{
Environment.Exit(exitCode);
}
catch (PlatformNotSupportedException)
{
}
}
return exitCode;
}
private static MethodInfo GetMethod(this Type type, string methodName)
{
Type t = type;
while (t != null)
{
TypeInfo ti = t.GetTypeInfo();
MethodInfo mi = ti.GetDeclaredMethod(methodName);
if (mi != null)
{
return mi;
}
t = ti.BaseType;
}
return null;
}
private static T[] Subarray<T>(this T[] arr, int offset, int count)
{
var newArr = new T[count];
Array.Copy(arr, offset, newArr, 0, count);
return newArr;
}
}
}
| 37.904348 | 142 | 0.527644 | [
"MIT"
] | Acidburn0zzz/corefx | src/Common/tests/System/Diagnostics/RemoteExecutorConsoleApp/RemoteExecutorConsoleApp.cs | 4,359 | C# |
using Alba.CsConsoleFormat.Fluent;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Data
{
public static class PrintDataExtensions
{
#region Print Columns
public static void PrintColumns(this DataTable dataTable, params string[] columnNames)
{
PrintColumns(dataTable.TableName, GetColumns(dataTable, columnNames));
}
public static string AddDoubleQuotes(this string value)
{
return "\"" + value + "\"";
}
public static string AddSingleQuotes(this string value)
{
return "\'" + value + "\'";
}
public static void PrintColumns(this DataView dataView, params string[] columnNames)
{
PrintColumns(dataView.Table.TableName, GetColumns(dataView.Table, columnNames));
}
public static void PrintColumns(this DataSet dataSet, params string[] columnNames)
{
foreach (DataTable dataTable in dataSet.Tables)
PrintColumns(dataTable, columnNames);
}
private static void PrintColumns(string name, DataColumn[] columns)
{
string columnName = "Column Name";
string dataType = "Data Type";
string nullable = "Nullable";
string dataMember = "Data Member";
int length0 = 0;
int length1 = columnName.Length;
int length2 = dataType.Length;
int length3 = nullable.Length;
int length4 = dataMember.Length;
if (columns.Length > 0)
{
int maxLength = columns.Select(c => c.Ordinal).Max().ToString().Length;
if (length0 < maxLength)
length0 = maxLength;
maxLength = columns.Select(c => c.ColumnName.Length).Max();
if (length1 < maxLength)
length1 = maxLength;
maxLength = columns.Select(c => c.DataType.ToString().Length).Max();
if (length2 < maxLength)
length2 = maxLength;
maxLength = columns.Select(c => GetDataMemberType(c).Length + 1 + c.ColumnName.Length).Max();
if (length4 < maxLength)
length4 = maxLength;
}
string horizontal0 = new(Horizontal_Bar, length0 + 2);
string horizontal1 = new String(Horizontal_Bar, length1 + 2);
string horizontal2 = new String(Horizontal_Bar, length2 + 2);
string horizontal3 = new String(Horizontal_Bar, length3 + 2);
string horizontal4 = new String(Horizontal_Bar, length4 + 2);
if (string.IsNullOrEmpty(name) == false)
WriteLine("{0}:", name);
WriteLine("{5}{0}{6}{1}{6}{2}{6}{3}{6}{4}{7}", horizontal0, horizontal1, horizontal2, horizontal3, horizontal4, Top_Left, Top_Center, Top_Right);
string format1 = string.Format("{{5}} {{0,-{0}}} {{5}} {{1,-{1}}} {{5}} {{2,-{2}}} {{5}} {{3,-{3}}} {{5}} {{4,-{4}}} {{5}}", length0, length1, length2, length3, length4);
WriteLine(format1, string.Empty, columnName, dataType, nullable, dataMember, Verticl_Bar);
WriteLine("{5}{0}{6}{1}{6}{2}{6}{3}{6}{4}{7}", horizontal0, horizontal1, horizontal2, horizontal3, horizontal4, Middle_Left, Middle_Center, Middle_Right);
foreach (DataColumn column in columns)
{
string dataMemberType = GetDataMemberType(column);
string format2 = string.Format("{{5}} {{0,{0}}} {{5}} {{1,-{1}}} {{5}} {{2,-{2}}} {{5}} {{3,-{3}}} {{5}} {{4}} {{1}} {{5,{4}}}", length0, length1, length2, length3, length4 - dataMemberType.Length - column.ColumnName.Length);
WriteLine(format2, column.Ordinal, column.ColumnName, column.DataType, column.AllowDBNull, dataMemberType, Verticl_Bar);
}
WriteLine("{5}{0}{6}{1}{6}{2}{6}{3}{6}{4}{7}", horizontal0, horizontal1, horizontal2, horizontal3, horizontal4, Bottom_Left, Bottom_Center, Bottom_Right);
WriteLine();
}
private static string GetDataMemberType(DataColumn column)
{
if (column.DataType == typeof(string))
return "string";
else if (column.DataType == typeof(int))
return "int" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(short))
return "short" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(long))
return "long" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(double))
return "double" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(decimal))
return "decimal" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(float))
return "float" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(char))
return "char" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(bool))
return "bool" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(uint))
return "uint" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(ushort))
return "ushort" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(ulong))
return "ulong" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(byte))
return "byte" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(sbyte))
return "sbyte" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(DateTime))
return "DateTime" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(TimeSpan))
return "TimeSpan" + (column.AllowDBNull ? "?" : string.Empty);
else if (column.DataType == typeof(Type))
return "Type";
else if (column.DataType == typeof(byte[]))
return "byte[]";
else
return column.DataType.ToString() + (column.AllowDBNull && column.DataType.IsClass == false ? "?" : string.Empty);
}
#endregion
#region Print DataTable
public static void Print(this DataTable dataTable, params string[] columnNames)
{
Print(dataTable, false, 0, null, columnNames);
}
public static void Print(this DataTable dataTable, bool rowOrdinals, params string[] columnNames)
{
Print(dataTable, rowOrdinals, 0, null, columnNames);
}
public static void Print(this DataTable dataTable, int top, params string[] columnNames)
{
Print(dataTable, false, top, null, columnNames);
}
public static void Print(this DataTable dataTable, bool rowOrdinals, int top, params string[] columnNames)
{
Print(dataTable, rowOrdinals, top, null, columnNames);
}
public static void Print(this DataTable dataTable, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataTable, false, 0, toString, columnNames);
}
public static void Print(this DataTable dataTable, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataTable, rowOrdinals, 0, toString, columnNames);
}
public static void Print(this DataTable dataTable, int top, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataTable, false, top, toString, columnNames);
}
public static void Print(this DataTable dataTable, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, params string[] columnNames)
{
PrintRows(dataTable, dataTable.AsEnumerable(), rowOrdinals, top, toString, columnNames);
}
#endregion
#region Print DataView
public static void Print(this DataView dataView, params string[] columnNames)
{
Print(dataView, false, 0, null, columnNames);
}
public static void Print(this DataView dataView, bool rowOrdinals, params string[] columnNames)
{
Print(dataView, rowOrdinals, 0, null, columnNames);
}
public static void Print(this DataView dataView, int top, params string[] columnNames)
{
Print(dataView, false, top, null, columnNames);
}
public static void Print(this DataView dataView, bool rowOrdinals, int top, params string[] columnNames)
{
Print(dataView, rowOrdinals, top, null, columnNames);
}
public static void Print(this DataView dataView, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataView, false, 0, toString, columnNames);
}
public static void Print(this DataView dataView, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataView, rowOrdinals, 0, toString, columnNames);
}
public static void Print(this DataView dataView, int top, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataView, false, top, toString, columnNames);
}
public static void Print(this DataView dataView, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, params string[] columnNames)
{
PrintRows(dataView, rowOrdinals, top, toString, columnNames);
}
#endregion
#region Print DataSet
public static void Print(this DataSet dataSet, params string[] columnNames)
{
Print(dataSet, false, 0, null, columnNames);
}
public static void Print(this DataSet dataSet, bool rowOrdinals, params string[] columnNames)
{
Print(dataSet, rowOrdinals, 0, null, columnNames);
}
public static void Print(this DataSet dataSet, int top, params string[] columnNames)
{
Print(dataSet, false, top, null, columnNames);
}
public static void Print(this DataSet dataSet, bool rowOrdinals, int top, params string[] columnNames)
{
Print(dataSet, rowOrdinals, top, null, columnNames);
}
public static void Print(this DataSet dataSet, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataSet, false, 0, toString, columnNames);
}
public static void Print(this DataSet dataSet, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataSet, rowOrdinals, 0, toString, columnNames);
}
public static void Print(this DataSet dataSet, int top, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataSet, false, top, toString, columnNames);
}
public static void Print(this DataSet dataSet, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, params string[] columnNames)
{
foreach (DataTable dataTable in dataSet.Tables)
Print(dataTable, rowOrdinals, top, toString, columnNames);
}
#endregion
#region Print DataRow[]
public static void Print(this DataRow[] dataRows, params string[] columnNames)
{
Print(dataRows, false, 0, null, columnNames);
}
public static void Print(this DataRow[] dataRows, bool rowOrdinals, params string[] columnNames)
{
Print(dataRows, rowOrdinals, 0, null, columnNames);
}
public static void Print(this DataRow[] dataRows, int top, params string[] columnNames)
{
Print(dataRows, false, top, null, columnNames);
}
public static void Print(this DataRow[] dataRows, bool rowOrdinals, int top, params string[] columnNames)
{
Print(dataRows, rowOrdinals, top, null, columnNames);
}
public static void Print(this DataRow[] dataRows, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataRows, false, 0, toString, columnNames);
}
public static void Print(this DataRow[] dataRows, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataRows, rowOrdinals, 0, toString, columnNames);
}
public static void Print(this DataRow[] dataRows, int top, ValueToStringHandler toString, params string[] columnNames)
{
Print(dataRows, false, top, toString, columnNames);
}
public static void Print(this DataRow[] dataRows, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, params string[] columnNames)
{
PrintRows((dataRows.Length != 0 ? dataRows[0].Table : null), dataRows, rowOrdinals, top, toString, columnNames);
}
#endregion
#region Print Helper Methods
public delegate string ValueToStringHandler(object obj, DataRow row, DataColumn column);
private static void PrintRows(DataTable dataTable, IEnumerable<DataRow> dataRows, bool rowOrdinals, int top, ValueToStringHandler toString, string[] columnNames, string ordinalColumnName = null)
{
if (dataTable == null && !dataRows.Any())
{
WriteLine("No rows were selected");
WriteLine();
return;
}
if (dataTable != null && string.IsNullOrEmpty(dataTable.TableName) == false)
WriteLine("{0}:{1}", dataTable.TableName, "Top 50 Columns Preview");
DataColumn[] columns = GetColumns(dataTable, columnNames, ordinalColumnName);
if (columns.Length == 0)
{
WriteLine("No columns were selected");
WriteLine();
return;
}
if (top > 0)
dataRows = dataRows.Take(top);
int[] lengths = columns.Select(c => c.ColumnName.Length).ToArray();
foreach (DataRow row in dataRows)
CalculateLengths(row, columns, lengths, toString);
int rowOrdinalsLength = 0;
if (rowOrdinals)
{
if (dataRows.Any())
{
int maxRowOrdinal = 0;
if (string.IsNullOrEmpty(ordinalColumnName))
maxRowOrdinal = dataRows.Select(row => row.Table.Rows.IndexOf(row)).Max();
else
maxRowOrdinal = dataRows.Select(row => (int)row[ordinalColumnName]).Max();
if (maxRowOrdinal > -1)
rowOrdinalsLength = maxRowOrdinal.ToString().Length;
}
}
string header = Top_Left.ToString();
string separator = Middle_Left.ToString();
string footer = Bottom_Left.ToString();
string formatHeaders = Verticl_Bar.ToString();
string format = Verticl_Bar.ToString();
if (rowOrdinals)
{
string horizontal = new String(Horizontal_Bar, rowOrdinalsLength + 2);
header += horizontal + Top_Center;
separator += horizontal + Middle_Center;
footer += horizontal + Bottom_Center;
formatHeaders += string.Format(" {{0,-{0}}} {1}", rowOrdinalsLength, Verticl_Bar);
format += string.Format(" {{0,{0}}} {1}", rowOrdinalsLength, Verticl_Bar);
}
int k = 0;
for (; k < columns.Length - 1; k++)
{
string horizontal = new String(Horizontal_Bar, lengths[k] + 2);
header += horizontal + Top_Center;
separator += horizontal + Middle_Center;
footer += horizontal + Bottom_Center;
string cellFormat = string.Format(" {{{0},-{1}}} {2}", k + 1, lengths[k], Verticl_Bar);
formatHeaders += cellFormat;
format += cellFormat;
}
k = columns.Length - 1;
if (k >= 0)
{
string horizontal = new String(Horizontal_Bar, lengths[k] + 2);
header += horizontal + Top_Right;
separator += horizontal + Middle_Right;
footer += horizontal + Bottom_Right;
string cellFormat = string.Format(" {{{0},-{1}}} {2}", k + 1, lengths[k], Verticl_Bar);
formatHeaders += cellFormat;
format += cellFormat;
}
object[] objects = new object[columns.Length + 1];
WriteLine(header);
objects[0] = string.Empty;
for (int i = 0; i < columns.Length; i++)
objects[i + 1] = columns[i];
WriteLine(formatHeaders, objects);
WriteLine(separator);
foreach (DataRow row in dataRows)
{
if (rowOrdinals)
{
int ordinal = 0;
if (string.IsNullOrEmpty(ordinalColumnName))
ordinal = row.Table.Rows.IndexOf(row);
else
ordinal = (int)row[ordinalColumnName];
objects[0] = (ordinal > -1 ? ordinal : (int?)null);
}
for (int i = 0; i < columns.Length; i++)
{
object obj = row[columns[i]];
string str = null;
if (toString != null)
{
str = toString(obj, row, columns[i]);
if (str == null)
str = "null";
}
else
{
str = string.Format("{0}", (obj == DBNull.Value || obj == null ? "null" : obj));
}
objects[i + 1] = str;
}
WriteLine(format, objects);
}
WriteLine(footer);
WriteLine();
}
private static void PrintRows(DataView dataView, bool rowOrdinals, int top, ValueToStringHandler toString, string[] columnNames)
{
string ordinalColumnName = null;
DataTable dataTable = GetTableFromView(dataView, rowOrdinals, top, ref ordinalColumnName);
PrintRows(dataTable, dataTable.AsEnumerable(), rowOrdinals, top, toString, columnNames, ordinalColumnName);
}
private static DataTable GetTableFromView(DataView dataView, bool rowOrdinals, int top, ref string ordinalColumnName)
{
DataTable dataTable = dataView.ToTable();
if (rowOrdinals)
{
ordinalColumnName = "_ordinal";
while (dataTable.Columns.Contains(ordinalColumnName))
ordinalColumnName = "_" + ordinalColumnName;
dataTable.Columns.Add(ordinalColumnName, typeof(int));
var it = dataView.GetEnumerator();
int rowCounter = -1;
while (it.MoveNext())
{
rowCounter++;
if (top > 0 && rowCounter >= top)
break;
DataRow dataRow = ((DataRowView)it.Current).Row;
dataTable.Rows[rowCounter][ordinalColumnName] = dataRow.Table.Rows.IndexOf(dataRow);
}
}
return dataTable;
}
private static DataColumn[] GetColumns(DataTable dataTable, string[] columnNames, string ordinalColumnName = null)
{
if (columnNames != null && columnNames.Length > 0)
return columnNames.Join(dataTable.Columns.Cast<DataColumn>(), n => n, c => c.ColumnName, (n, c) => c, StringComparer.CurrentCultureIgnoreCase).Where(c => string.IsNullOrEmpty(ordinalColumnName) || c.ColumnName != ordinalColumnName).ToArray();
else
return dataTable.Columns.Cast<DataColumn>().Where(c => string.IsNullOrEmpty(ordinalColumnName) || c.ColumnName != ordinalColumnName).ToArray();
}
private static void CalculateLengths(DataRow row, DataColumn[] columns, int[] lengths, ValueToStringHandler toString)
{
for (int i = 0; i < columns.Length; i++)
{
object obj = row[columns[i]];
string str = null;
if (toString != null)
{
str = toString(obj, row, columns[i]);
if (str == null)
str = "null";
}
else
{
str = string.Format("{0}", (obj == DBNull.Value || obj == null ? "null" : obj));
}
if (lengths[i] < str.Length)
lengths[i] = str.Length;
}
}
#endregion
#region PrintList DataTable
public static void PrintList(this DataTable dataTable, params string[] columnNames)
{
PrintList(dataTable, false, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, bool rowOrdinals, string Dbserver, params string[] columnNames)
{
PrintList(dataTable, rowOrdinals, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, int top, params string[] columnNames)
{
PrintList(dataTable, false, top, null, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, bool rowOrdinals, int top, params string[] columnNames)
{
PrintList(dataTable, rowOrdinals, top, null, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataTable, false, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataTable, rowOrdinals, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, int top, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataTable, false, top, toString, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, int repeatColumns, RepeatDirection repeatDirection, params string[] columnNames)
{
PrintList(dataTable, false, 0, null, repeatColumns: repeatColumns, repeatDirection: repeatDirection, columnNames: columnNames);
}
public static void PrintList(this DataTable dataTable, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, int repeatColumns = 2, RepeatDirection repeatDirection = RepeatDirection.Vertical, string delimiter = ": ", params string[] columnNames)
{
PrintListRows(dataTable, dataTable.AsEnumerable(), rowOrdinals, top, toString, repeatColumns, repeatDirection, delimiter, columnNames);
}
#endregion
#region PrintList DataView
public static void PrintList(this DataView dataView, params string[] columnNames)
{
PrintList(dataView, false, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, bool rowOrdinals, params string[] columnNames)
{
PrintList(dataView, rowOrdinals, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, int top, params string[] columnNames)
{
PrintList(dataView, false, top, null, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, bool rowOrdinals, int top, params string[] columnNames)
{
PrintList(dataView, rowOrdinals, top, null, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataView, false, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataView, rowOrdinals, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, int top, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataView, false, top, toString, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, int repeatColumns, RepeatDirection repeatDirection, params string[] columnNames)
{
PrintList(dataView, false, 0, null, repeatColumns: repeatColumns, repeatDirection: repeatDirection, columnNames: columnNames);
}
public static void PrintList(this DataView dataView, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, int repeatColumns = 2, RepeatDirection repeatDirection = RepeatDirection.Vertical, string delimiter = ": ", params string[] columnNames)
{
PrintListRows(dataView, rowOrdinals, top, toString, repeatColumns, repeatDirection, delimiter, columnNames);
}
#endregion
#region PrintList DataSet
public static void PrintList(this DataSet dataSet, params string[] columnNames)
{
PrintList(dataSet, false, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, bool rowOrdinals, params string[] columnNames)
{
PrintList(dataSet, rowOrdinals, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, int top, params string[] columnNames)
{
PrintList(dataSet, false, top, null, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, bool rowOrdinals, int top, params string[] columnNames)
{
PrintList(dataSet, rowOrdinals, top, null, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataSet, false, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataSet, rowOrdinals, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, int top, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataSet, false, top, toString, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, int repeatColumns, RepeatDirection repeatDirection, params string[] columnNames)
{
PrintList(dataSet, false, 0, null, repeatColumns: repeatColumns, repeatDirection: repeatDirection, columnNames: columnNames);
}
public static void PrintList(this DataSet dataSet, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, int repeatColumns = 2, RepeatDirection repeatDirection = RepeatDirection.Vertical, string delimiter = ": ", params string[] columnNames)
{
foreach (DataTable dataTable in dataSet.Tables)
PrintList(dataTable, rowOrdinals, top, toString, repeatColumns, repeatDirection, delimiter, columnNames);
}
#endregion
#region PrintList DataRow[]
public static void PrintList(this DataRow[] dataRows, params string[] columnNames)
{
PrintList(dataRows, false, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, bool rowOrdinals, params string[] columnNames)
{
PrintList(dataRows, rowOrdinals, 0, null, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, int top, params string[] columnNames)
{
PrintList(dataRows, false, top, null, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, bool rowOrdinals, int top, params string[] columnNames)
{
PrintList(dataRows, rowOrdinals, top, null, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataRows, false, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, bool rowOrdinals, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataRows, rowOrdinals, 0, toString, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, int top, ValueToStringHandler toString, params string[] columnNames)
{
PrintList(dataRows, false, top, toString, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, int repeatColumns, RepeatDirection repeatDirection, params string[] columnNames)
{
PrintList(dataRows, false, 0, null, repeatColumns: repeatColumns, repeatDirection: repeatDirection, columnNames: columnNames);
}
public static void PrintList(this DataRow[] dataRows, bool rowOrdinals = false, int top = 0, ValueToStringHandler toString = null, int repeatColumns = 2, RepeatDirection repeatDirection = RepeatDirection.Vertical, string delimiter = ": ", params string[] columnNames)
{
PrintListRows((dataRows.Length != 0 ? dataRows[0].Table : null), dataRows, rowOrdinals, top, toString, repeatColumns, repeatDirection, delimiter, columnNames);
}
#endregion
#region PrintList Helper Methods
public enum RepeatDirection
{
Horizontal = 0,
Vertical = 1,
}
private static void PrintListRows(DataTable dataTable, IEnumerable<DataRow> dataRows, bool rowOrdinals, int top, ValueToStringHandler toString, int repeatColumns, RepeatDirection repeatDirection, string delimiter, string[] columnNames, string ordinalColumnName = null)
{
if (dataTable != null && string.IsNullOrEmpty(dataTable.TableName) == false)
{
if (dataTable.Rows.Count > 50)
{
var t = new DataView(dataTable).ToTable(false, new string[] { "SCHEMA"}).AsEnumerable().Select(n => n[0]).ToList().Distinct();
WriteLine("{0}: Top 50 Schema Information Preview", dataTable.TableName);
WriteLine("{0}: {1}", "DataSourceType", ConfigurationManager.AppSettings["DataSourceType"]);
WriteLine("{0}: {1}", "Schema", string.Join(",", t.ToArray()));
}
else
{
var t = new DataView(dataTable).ToTable(false, new string[] { "SCHEMA" }).AsEnumerable().Select(n => n[0]).ToList().Distinct();
WriteLine("{0}: Schema Information Preview", dataTable.TableName);
WriteLine("{0}: {1}", "DataSourceType", ConfigurationManager.AppSettings["DataSourceType"]);
WriteLine("{0}: {1}", "Schema", string.Join(", ", t.ToArray()));
//Colors.WriteLine(ConfigurationManager.AppSettings["DataSourceType"].Red(), "", Environment.NewLine);
}
}
if (dataRows.Count() == 0)
{
WriteLine("No rows were selected");
WriteLine();
return;
}
DataColumn[] columns = GetColumns(dataTable, columnNames, ordinalColumnName);
if (columns.Length == 0)
{
WriteLine("No columns were selected");
WriteLine();
return;
}
if (top > 0)
dataRows = dataRows.Take(top);
int columnsLength = columns.Select(c => c.ColumnName.Length).Max();
int[] lengths = new int[columns.Length];
foreach (DataRow row in dataRows)
CalculateLengths(row, columns, lengths, toString);
int rowsLength = lengths.Max();
if (rowOrdinals)
{
if (dataRows.Count() > 0)
{
if (columnsLength < 7) // "Ordinal".Length
columnsLength = 7;
int maxRowOrdinal = 0;
if (string.IsNullOrEmpty(ordinalColumnName))
maxRowOrdinal = dataRows.Select(row => row.Table.Rows.IndexOf(row)).Max();
else
maxRowOrdinal = dataRows.Select(row => (int)row[ordinalColumnName]).Max();
if (maxRowOrdinal > -1)
{
int rowOrdinalsLength = maxRowOrdinal.ToString().Length;
if (rowsLength < rowOrdinalsLength)
rowsLength = rowOrdinalsLength;
}
}
}
if (repeatColumns < 1)
repeatColumns = 1;
if (repeatColumns > dataRows.Count())
repeatColumns = dataRows.Count();
int lastRowFilledCellsCount = dataRows.Count() % repeatColumns;
if (lastRowFilledCellsCount == 0)
lastRowFilledCellsCount = repeatColumns;
int lastRowEmptyCellsCount = repeatColumns - lastRowFilledCellsCount;
int rowsCount = (dataRows.Count() / repeatColumns) + (dataRows.Count() % repeatColumns > 0 ? 1 : 0);
if (delimiter == null)
delimiter = string.Empty;
string cellFormat = string.Format(" {{{{0,-{0}}}}}{1}{{{{{{0}},-{2}}}}} {3}", columnsLength, delimiter, rowsLength, Verticl_Bar);
string horizontal = new String(Horizontal_Bar, columnsLength + delimiter.Length + rowsLength + 2);
string header = Top_Left.ToString();
string separator = Middle_Left.ToString();
string footer = Bottom_Left.ToString();
string format = Verticl_Bar.ToString();
int k = 0;
for (; k < repeatColumns - 1; k++)
{
header += horizontal + Top_Center;
separator += horizontal + Middle_Center;
footer += horizontal + Bottom_Center;
format += string.Format(cellFormat, k + 1);
}
k = repeatColumns - 1;
if (k >= 0)
{
header += horizontal + Top_Right;
separator += horizontal + Middle_Right;
footer += horizontal + Bottom_Right;
format += string.Format(cellFormat, k + 1);
}
string formatPartial = format;
if (lastRowEmptyCellsCount > 0)
{
formatPartial = Verticl_Bar.ToString();
for (int i = 0; i < lastRowFilledCellsCount; i++)
formatPartial += string.Format(cellFormat, i + 1);
for (int i = 0; i < lastRowEmptyCellsCount; i++)
formatPartial += new String(' ', columnsLength + delimiter.Length + rowsLength + 2) + Verticl_Bar;
}
object[] objects = new object[repeatColumns + 1];
if (repeatDirection == RepeatDirection.Horizontal)
{
for (int i = 0; i < rowsCount; i++)
{
WriteLine(i == 0 ? header : separator);
var rows = dataRows.Skip(i * repeatColumns).Take(repeatColumns);
PrintListRow(rows, columns, objects, (i < rowsCount - 1 ? format : formatPartial), rowOrdinals, toString, ordinalColumnName);
}
}
else if (repeatDirection == RepeatDirection.Vertical && lastRowEmptyCellsCount == 0)
{
for (int i = 0; i < rowsCount; i++)
{
WriteLine(i == 0 ? header : separator);
var rows = dataRows.Where((r, n) => n % rowsCount == i);
PrintListRow(rows, columns, objects, (i < rowsCount - 1 ? format : formatPartial), rowOrdinals, toString, ordinalColumnName);
}
}
else if (repeatDirection == RepeatDirection.Vertical && lastRowEmptyCellsCount > 0)
{
for (int i = 0; i < rowsCount; i++)
{
WriteLine(i == 0 ? header : separator);
var rows = dataRows.Where((r, n) =>
(n < lastRowFilledCellsCount * rowsCount && n % rowsCount == i) ||
(n >= lastRowFilledCellsCount * rowsCount && (n - (lastRowFilledCellsCount * rowsCount)) % (rowsCount - 1) == i)
);
PrintListRow(rows, columns, objects, (i < rowsCount - 1 ? format : formatPartial), rowOrdinals, toString, ordinalColumnName);
}
}
WriteLine(footer);
WriteLine();
}
private static void PrintListRows(DataView dataView, bool rowOrdinals, int top, ValueToStringHandler toString, int repeatColumns, RepeatDirection repeatDirection, string delimiter, string[] columnNames)
{
string ordinalColumnName = null;
DataTable dataTable = GetTableFromView(dataView, rowOrdinals, top, ref ordinalColumnName);
PrintListRows(dataTable, dataTable.AsEnumerable(), rowOrdinals, top, toString, repeatColumns, repeatDirection, delimiter, columnNames, ordinalColumnName);
}
private static void PrintListRow(IEnumerable<DataRow> rows, DataColumn[] columns, object[] objects, string format, bool rowOrdinals, ValueToStringHandler toString, string ordinalColumnName)
{
if (rowOrdinals)
{
IEnumerable<int> ordinals = null;
if (string.IsNullOrEmpty(ordinalColumnName))
ordinals = rows.Select(row => row.Table.Rows.IndexOf(row));
else
ordinals = rows.Select(row => (int)row[ordinalColumnName]);
objects[0] = "Ordinal";
int k = 1;
foreach (int ordinal in ordinals)
objects[k++] = (ordinal > -1 ? ordinal : (int?)null);
WriteLine(format, objects);
}
for (int i = 0; i < columns.Length; i++)
{
objects[0] = columns[i].ColumnName;
int k = 1;
foreach (DataRow row in rows)
{
object obj = row[columns[i]];
string str = null;
if (toString != null)
{
str = toString(obj, row, columns[i]);
if (str == null)
str = "null";
}
else
{
str = string.Format("{0}", (obj == DBNull.Value || obj == null ? "null" : obj));
}
objects[k++] = str;
}
WriteLine(format, objects);
}
}
#endregion
#region Write, WriteLine
public delegate void WriteHandler(string value = null, params object[] args);
public delegate void WriteLineHandler(string value = null, params object[] args);
public static event WriteHandler Write = ConsoleWrite;
public static event WriteLineHandler WriteLine = ConsoleWriteLine;
public static void SetOutput(WriteHandler writeHandler, WriteLineHandler writeLineHandler)
{
Write = null;
WriteLine = null;
Write += writeHandler;
WriteLine += writeLineHandler;
}
public static void SetOutputConsole()
{
SetOutput(ConsoleWrite, ConsoleWriteLine);
}
public static void SetOutputStringBuilder(StringBuilder builder)
{
SetOutput(
(value, args) => StringBuilderWrite(builder, value, args),
(value, args) => StringBuilderWriteLine(builder, value, args)
);
}
public static void SetOutputStream(Stream stream)
{
SetOutputStream(stream, Encoding.UTF8);
}
public static void SetOutputStream(Stream stream, Encoding encoding)
{
SetOutput(
(value, args) => StreamWrite(stream, encoding ?? Encoding.UTF8, value, args),
(value, args) => StreamWriteLine(stream, encoding ?? Encoding.UTF8, value, args)
);
}
#region Console
private static void ConsoleWrite(string value = null, params object[] args)
{
if (string.IsNullOrEmpty(value))
return;
if (args == null)
Console.Write(value);
else
Console.Write(value, args);
}
private static void ConsoleWriteLine(string value = null, params object[] args)
{
if (string.IsNullOrEmpty(value))
Console.WriteLine();
else if (args == null)
Console.WriteLine(value);
else
Console.WriteLine(value, args);
}
#endregion
#region StringBuilder
private static void StringBuilderWrite(StringBuilder builder, string value = null, params object[] args)
{
if (string.IsNullOrEmpty(value))
return;
if (args == null)
builder.Append(value);
else
builder.AppendFormat(value, args);
}
private static void StringBuilderWriteLine(StringBuilder builder, string value = null, params object[] args)
{
if (string.IsNullOrEmpty(value))
{
builder.AppendLine();
}
else if (args == null)
{
builder.AppendLine(value);
}
else
{
builder.AppendFormat(value, args);
builder.AppendLine();
}
}
#endregion
#region Stream
private static void StreamWrite(Stream stream, Encoding encoding, string value = null, params object[] args)
{
if (string.IsNullOrEmpty(value))
return;
byte[] buffer = null;
if (args == null)
buffer = encoding.GetBytes(value);
else
buffer = encoding.GetBytes(string.Format(value, args));
stream.Write(buffer, 0, buffer.Length);
}
private static void StreamWriteLine(Stream stream, Encoding encoding, string value = null, params object[] args)
{
byte[] buffer = null;
if (string.IsNullOrEmpty(value) == false)
{
if (args == null)
buffer = encoding.GetBytes(value);
else
buffer = encoding.GetBytes(string.Format(value, args));
stream.Write(buffer, 0, buffer.Length);
}
buffer = encoding.GetBytes(Environment.NewLine);
stream.Write(buffer, 0, buffer.Length);
}
#endregion
#endregion
#region Border
private const char ASCII_MINUS = '-';
private const char ASCII_VERTICL_BAR = '|';
private const char ASCII_PLUS = '+';
private const char EXTENDED_ASCII_HORIZONTAL_BAR = '─';
private const char EXTENDED_ASCII_VERTICL_BAR = '│';
private const char EXTENDED_ASCII_TOP_LEFT = '┌';
private const char EXTENDED_ASCII_TOP_CENTER = '┬';
private const char EXTENDED_ASCII_TOP_RIGHT = '┐';
private const char EXTENDED_ASCII_MIDDLE_LEFT = '├';
private const char EXTENDED_ASCII_MIDDLE_CENTER = '┼';
private const char EXTENDED_ASCII_MIDDLE_RIGHT = '┤';
private const char EXTENDED_ASCII_BOTTOM_LEFT = '└';
private const char EXTENDED_ASCII_BOTTOM_CENTER = '┴';
private const char EXTENDED_ASCII_BOTTOM_RIGHT = '┘';
private static char Horizontal_Bar;
private static char Verticl_Bar;
private static char Top_Left;
private static char Top_Center;
private static char Top_Right;
private static char Middle_Left;
private static char Middle_Center;
private static char Middle_Right;
private static char Bottom_Left;
private static char Bottom_Center;
private static char Bottom_Right;
public static void ClearBorder()
{
Horizontal_Bar = ' ';
Verticl_Bar = ' ';
Top_Left = ' ';
Top_Center = ' ';
Top_Right = ' ';
Middle_Left = ' ';
Middle_Center = ' ';
Middle_Right = ' ';
Bottom_Left = ' ';
Bottom_Center = ' ';
Bottom_Right = ' ';
}
public static void ASCIIBorder()
{
Horizontal_Bar = ASCII_MINUS;
Verticl_Bar = ASCII_VERTICL_BAR;
Top_Left = ASCII_PLUS;
Top_Center = ASCII_PLUS;
Top_Right = ASCII_PLUS;
Middle_Left = ASCII_PLUS;
Middle_Center = ASCII_PLUS;
Middle_Right = ASCII_PLUS;
Bottom_Left = ASCII_PLUS;
Bottom_Center = ASCII_PLUS;
Bottom_Right = ASCII_PLUS;
}
public static void ExtendedASCIIBorder()
{
Horizontal_Bar = EXTENDED_ASCII_HORIZONTAL_BAR;
Verticl_Bar = EXTENDED_ASCII_VERTICL_BAR;
Top_Left = EXTENDED_ASCII_TOP_LEFT;
Top_Center = EXTENDED_ASCII_TOP_CENTER;
Top_Right = EXTENDED_ASCII_TOP_RIGHT;
Middle_Left = EXTENDED_ASCII_MIDDLE_LEFT;
Middle_Center = EXTENDED_ASCII_MIDDLE_CENTER;
Middle_Right = EXTENDED_ASCII_MIDDLE_RIGHT;
Bottom_Left = EXTENDED_ASCII_BOTTOM_LEFT;
Bottom_Center = EXTENDED_ASCII_BOTTOM_CENTER;
Bottom_Right = EXTENDED_ASCII_BOTTOM_RIGHT;
}
static PrintDataExtensions()
{
ExtendedASCIIBorder();
}
#endregion
}
}
| 41.00172 | 276 | 0.572947 | [
"Apache-2.0"
] | sookeke/DataMasker.Net5 | DataClassification/DataClassification/PrintDataExtensions.cs | 47,709 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.Azure.WebJobs.Extensions.DurableTask.Tests
{
public class HttpApiHandlerTests
{
private const string EmptyEntityKeySymbol = "$";
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void CreateCheckStatusResponse_Throws_Exception_When_NotificationUrl_Missing()
{
var options = new DurableTaskOptions()
{
Notifications = new NotificationOptions(),
};
// With a null override, and the production code path returning null webhook path,
// this simulates a non-configured webhook url.
options.WebhookUriProviderOverride = null;
options.HubName = "DurableTaskHub";
var httpApiHandler = new HttpApiHandler(GetTestExtension(options), null);
var ex = Assert.Throws<InvalidOperationException>(() => httpApiHandler.CreateCheckStatusResponse(new HttpRequestMessage(), string.Empty, null));
Assert.Equal("Webhooks are not configured", ex.Message);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Throws_Exception_When_Bad_Timeout_Request()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var ex = await Assert.ThrowsAsync<ArgumentException>(() => httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.InstanceId,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(0),
TimeSpan.FromSeconds(100)));
Assert.Equal($"Total timeout 0 should be bigger than retry timeout 100", ex.Message);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void OutOfProcEndpoints_UpdateWithNewWebhookUri()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var webhookProvider = new ChangingWebhookProvider() { WebhookUri = new Uri(TestConstants.NotificationUrl) };
httpApiHandler.RegisterWebhookProvider(() => webhookProvider.WebhookUri);
AssertApisUsingCorrectWebhookUri(httpApiHandler, TestConstants.NotificationUrlBase);
string newWebhookUri = TestConstants.NotificationUrl.Replace("localhost:7071", "localhost:5050");
string newBaseUri = TestConstants.NotificationUrlBase.Replace("localhost:7071", "localhost:5050");
webhookProvider.WebhookUri = new Uri(newWebhookUri);
AssertApisUsingCorrectWebhookUri(httpApiHandler, newBaseUri);
}
// Validate the expected uris are used for CreateHttpManagementPayload(), GetBaseUrl(), and GetInstanceCreationLinks()
private static void AssertApisUsingCorrectWebhookUri(HttpApiHandler httpApiHandler, string expectedBaseUri)
{
HttpManagementPayload managementPayload = httpApiHandler.CreateHttpManagementPayload(
TestConstants.InstanceId,
null,
null);
Assert.StartsWith(expectedBaseUri, managementPayload.StatusQueryGetUri);
Assert.StartsWith(expectedBaseUri, managementPayload.SendEventPostUri);
Assert.StartsWith(expectedBaseUri, managementPayload.PurgeHistoryDeleteUri);
Assert.StartsWith(expectedBaseUri, managementPayload.RestartPostUri);
Assert.StartsWith(expectedBaseUri, managementPayload.TerminatePostUri);
string baseUri = httpApiHandler.GetBaseUrl();
Assert.Equal(expectedBaseUri, baseUri);
HttpCreationPayload creationPayload = httpApiHandler.GetInstanceCreationLinks();
Assert.StartsWith(expectedBaseUri, creationPayload.CreateNewInstancePostUri);
Assert.StartsWith(expectedBaseUri, creationPayload.CreateAndWaitOnNewInstancePostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task CreateCheckStatusResponse_Returns_Correct_HTTP_202_Response()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var httpResponseMessage = httpApiHandler.CreateCheckStatusResponse(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.InstanceId,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
});
Assert.Equal(HttpStatusCode.Accepted, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal((string)status["id"], TestConstants.InstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["statusQueryGetUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["sendEventPostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["terminatePostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["purgeHistoryDeleteUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/restart?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["restartPostUri"]);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void CreateCheckStatus_Returns_Correct_HttpManagementPayload_based_on_default_values()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
HttpManagementPayload httpManagementPayload = httpApiHandler.CreateHttpManagementPayload(TestConstants.InstanceId, null, null);
Assert.NotNull(httpManagementPayload);
Assert.Equal(httpManagementPayload.Id, TestConstants.InstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=DurableFunctionsHub&connection=Storage&code=mykey",
httpManagementPayload.StatusQueryGetUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/raiseEvent/{{eventName}}?taskHub=DurableFunctionsHub&connection=Storage&code=mykey",
httpManagementPayload.SendEventPostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/terminate?reason={{text}}&taskHub=DurableFunctionsHub&connection=Storage&code=mykey",
httpManagementPayload.TerminatePostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=DurableFunctionsHub&connection=Storage&code=mykey",
httpManagementPayload.PurgeHistoryDeleteUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/restart?taskHub=DurableFunctionsHub&connection=Storage&code=mykey",
httpManagementPayload.RestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void CreateCheckStatus_Returns_Correct_HttpManagementPayload_based_on_custom_taskhub_value()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
HttpManagementPayload httpManagementPayload = httpApiHandler.CreateHttpManagementPayload(TestConstants.InstanceId, TestConstants.TaskHub, null);
Assert.NotNull(httpManagementPayload);
Assert.Equal(httpManagementPayload.Id, TestConstants.InstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=Storage&code=mykey",
httpManagementPayload.StatusQueryGetUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey",
httpManagementPayload.SendEventPostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey",
httpManagementPayload.TerminatePostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=Storage&code=mykey",
httpManagementPayload.PurgeHistoryDeleteUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/restart?taskHub=SampleHubVS&connection=Storage&code=mykey",
httpManagementPayload.RestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void CreateCheckStatus_Returns_Correct_HttpManagementPayload_based_on_custom_connection_value()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
HttpManagementPayload httpManagementPayload = httpApiHandler.CreateHttpManagementPayload(TestConstants.InstanceId, null, TestConstants.CustomConnectionName);
Assert.NotNull(httpManagementPayload);
Assert.Equal(httpManagementPayload.Id, TestConstants.InstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=DurableFunctionsHub&connection=TestConnection&code=mykey",
httpManagementPayload.StatusQueryGetUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/raiseEvent/{{eventName}}?taskHub=DurableFunctionsHub&connection=TestConnection&code=mykey",
httpManagementPayload.SendEventPostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/terminate?reason={{text}}&taskHub=DurableFunctionsHub&connection=TestConnection&code=mykey",
httpManagementPayload.TerminatePostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=DurableFunctionsHub&connection=TestConnection&code=mykey",
httpManagementPayload.PurgeHistoryDeleteUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/restart?taskHub=DurableFunctionsHub&connection=TestConnection&code=mykey",
httpManagementPayload.RestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public void CreateCheckStatus_Returns_Correct_HttpManagementPayload_based_on_custom_values()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
HttpManagementPayload httpManagementPayload = httpApiHandler.CreateHttpManagementPayload(TestConstants.InstanceId, TestConstants.TaskHub, TestConstants.CustomConnectionName, returnInternalServerErrorOnFailure: true);
Assert.NotNull(httpManagementPayload);
Assert.Equal(httpManagementPayload.Id, TestConstants.InstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=TestConnection&code=mykey&returnInternalServerErrorOnFailure=true",
httpManagementPayload.StatusQueryGetUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=TestConnection&code=mykey",
httpManagementPayload.SendEventPostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/terminate?reason={{text}}&taskHub=SampleHubVS&connection=TestConnection&code=mykey",
httpManagementPayload.TerminatePostUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742?taskHub=SampleHubVS&connection=TestConnection&code=mykey",
httpManagementPayload.PurgeHistoryDeleteUri);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/7b59154ae666471993659902ed0ba742/restart?taskHub=SampleHubVS&connection=TestConnection&code=mykey",
httpManagementPayload.RestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_Custom_HttpManagementPayload_After_Timeout()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var stopWatch = Stopwatch.StartNew();
var httpResponseMessage = await httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.RandomInstanceId,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(3),
true);
stopWatch.Stop();
Assert.Equal(HttpStatusCode.Accepted, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], TestConstants.RandomInstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749?taskHub=SampleHubVS&connection=Storage&code=mykey&returnInternalServerErrorOnFailure=true",
(string)status["statusQueryGetUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["sendEventPostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["terminatePostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["purgeHistoryDeleteUri"]);
Assert.True(stopWatch.Elapsed > TimeSpan.FromSeconds(10));
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_HTTP_202_Response_After_Timeout()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var stopWatch = Stopwatch.StartNew();
var httpResponseMessage = await httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.RandomInstanceId,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(3));
stopWatch.Stop();
Assert.Equal(HttpStatusCode.Accepted, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], TestConstants.RandomInstanceId);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["statusQueryGetUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["sendEventPostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["terminatePostUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["purgeHistoryDeleteUri"]);
Assert.Equal(
$"{TestConstants.NotificationUrlBase}/instances/9b59154ae666471993659902ed0ba749/restart?taskHub=SampleHubVS&connection=Storage&code=mykey",
(string)status["restartPostUri"]);
Assert.True(stopWatch.Elapsed > TimeSpan.FromSeconds(10));
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_HTTP_200_Response()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var httpResponseMessage = await httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.IntanceIdFactComplete,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(100),
TimeSpan.FromSeconds(10));
Assert.Equal(HttpStatusCode.OK, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var value = JsonConvert.DeserializeObject<string>(content);
Assert.Equal("Hello Tokyo!", value);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_HTTP_200_Response_After_Few_Iterations()
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var stopwatch = Stopwatch.StartNew();
var httpResponseMessage = await httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
TestConstants.InstanceIdIterations,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(3));
stopwatch.Stop();
Assert.Equal(HttpStatusCode.OK, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var value = JsonConvert.DeserializeObject<string>(content);
Assert.Equal("Hello Tokyo!", value);
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(10));
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_Defaults_When_Runtime_Status_is_Terminated()
{
await this.CheckRuntimeStatus(TestConstants.InstanceIdTerminated, OrchestrationRuntimeStatus.Terminated);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task WaitForCompletionOrCreateCheckStatusResponseAsync_Returns_Defaults_When_Runtime_Status_is_Canceled()
{
await this.CheckRuntimeStatus(TestConstants.InstanceIdCanceled, OrchestrationRuntimeStatus.Canceled);
}
private async Task CheckRuntimeStatus(string instanceId, OrchestrationRuntimeStatus expectedRuntimeStatus, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
{
var httpApiHandler = new HttpApiHandler(GetTestExtension(), null);
var httpResponseMessage = await httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync(
new HttpRequestMessage
{
RequestUri = new Uri(TestConstants.RequestUri),
},
instanceId,
new DurableClientAttribute
{
TaskHub = TestConstants.TaskHub,
ConnectionName = TestConstants.ConnectionName,
},
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(8));
Assert.Equal(expectedStatusCode, httpResponseMessage.StatusCode);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(expectedRuntimeStatus.ToString(), (string)response["runtimeStatus"]);
}
[Theory]
[InlineData(true, HttpStatusCode.InternalServerError)]
[InlineData(false, HttpStatusCode.OK)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task HandleGetStatusRequestAsync_Failed_Orchestration_Config_Response_Code(bool returnInternalServerErrorOnFailure, HttpStatusCode statusCode)
{
var list = (IList<DurableOrchestrationStatus>)new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Failed,
},
};
var instanceId = Guid.NewGuid().ToString();
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.GetStatusAsync(instanceId, false, false, true))
.Returns(Task.FromResult(list.First()));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/" + instanceId;
getStatusRequestUriBuilder.Query = $"returnInternalServerErrorOnFailure={returnInternalServerErrorOnFailure}";
var responseMessage = await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
});
Assert.Equal(statusCode, responseMessage.StatusCode);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetAllStatus_is_Success()
{
var result = new OrchestrationStatusQueryResult
{
DurableOrchestrationState = new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
new DurableOrchestrationStatus
{
Name = "DoThat",
InstanceId = "02",
RuntimeStatus = OrchestrationRuntimeStatus.Completed,
},
},
};
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(result));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/";
var responseMessage = await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
});
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
Assert.Equal(string.Empty, responseMessage.Headers.GetValues("x-ms-continuation-token").FirstOrDefault());
var actual = JsonConvert.DeserializeObject<IList<StatusResponsePayload>>(await responseMessage.Content.ReadAsStringAsync());
Assert.Equal("DoThis", actual[0].Name);
Assert.Equal("01", actual[0].InstanceId);
Assert.Equal("Running", actual[0].RuntimeStatus);
Assert.Equal("DoThat", actual[1].Name);
Assert.Equal("02", actual[1].InstanceId);
Assert.Equal("Completed", actual[1].RuntimeStatus);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetQueryStatus_is_Success()
{
// Build mock
var result = new OrchestrationStatusQueryResult
{
DurableOrchestrationState = new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
new DurableOrchestrationStatus
{
Name = "DoThat",
InstanceId = "02",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
},
ContinuationToken = "YYYY-YYYYYYYY-YYYYYYYYYYYY",
};
var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0);
var createdTimeTo = new DateTime(2018, 3, 10, 10, 23, 59);
var runtimeStatus = new List<OrchestrationRuntimeStatus>();
runtimeStatus.Add(OrchestrationRuntimeStatus.Running);
var runtimeStatusString = OrchestrationRuntimeStatus.Running.ToString();
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(result));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
// Build uri
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/";
getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}&createdTimeTo={WebUtility.UrlEncode(createdTimeTo.ToString())}&runtimeStatus={runtimeStatusString}";
// Test HttpApiHandler response
var responseMessage = await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
});
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
var actual = JsonConvert.DeserializeObject<IList<StatusResponsePayload>>(await responseMessage.Content.ReadAsStringAsync());
clientMock.Verify(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()));
Assert.Equal("DoThis", actual[0].Name);
Assert.Equal("01", actual[0].InstanceId);
Assert.Equal("Running", actual[0].RuntimeStatus);
Assert.Equal("DoThat", actual[1].Name);
Assert.Equal("02", actual[1].InstanceId);
Assert.Equal("Running", actual[1].RuntimeStatus);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetQueryStatusWithPaging_is_Success()
{
// Build mock
var result = new OrchestrationStatusQueryResult
{
DurableOrchestrationState = new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
new DurableOrchestrationStatus
{
Name = "DoThat",
InstanceId = "02",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
},
ContinuationToken = "YYYY-YYYYYYYY-YYYYYYYYYYYY",
};
var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0, DateTimeKind.Utc);
var createdTimeTo = new DateTime(2018, 3, 10, 10, 23, 59, DateTimeKind.Utc);
var runtimeStatus = new List<OrchestrationRuntimeStatus>();
runtimeStatus.Add(OrchestrationRuntimeStatus.Running);
var runtimeStatusString = OrchestrationRuntimeStatus.Running.ToString();
var pageSize = 100;
var continuationToken = "XXXX-XXXXXXXX-XXXXXXXXXXXX";
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(result))
.Callback<OrchestrationStatusQueryCondition, CancellationToken>((condition, cancellationToken) =>
{
Assert.Equal(createdTimeFrom, condition.CreatedTimeFrom);
Assert.Equal(createdTimeTo, condition.CreatedTimeTo);
Assert.Equal(OrchestrationRuntimeStatus.Running, condition.RuntimeStatus.FirstOrDefault());
Assert.Equal(pageSize, condition.PageSize);
Assert.Equal(continuationToken, condition.ContinuationToken);
});
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
// Build uri
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/";
getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}&createdTimeTo={WebUtility.UrlEncode(createdTimeTo.ToString())}&runtimeStatus={runtimeStatusString}&top=100";
// Test HttpApiHandler response
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
};
requestMessage.Headers.Add("x-ms-continuation-token", "XXXX-XXXXXXXX-XXXXXXXXXXXX");
var responseMessage = await httpApiHandler.HandleRequestAsync(requestMessage);
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
Assert.Equal("YYYY-YYYYYYYY-YYYYYYYYYYYY", responseMessage.Headers.GetValues("x-ms-continuation-token").FirstOrDefault());
var actual = JsonConvert.DeserializeObject<IList<StatusResponsePayload>>(await responseMessage.Content.ReadAsStringAsync());
clientMock.Verify(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()));
Assert.Equal("DoThis", actual[0].Name);
Assert.Equal("01", actual[0].InstanceId);
Assert.Equal("Running", actual[0].RuntimeStatus);
Assert.Equal("DoThat", actual[1].Name);
Assert.Equal("02", actual[1].InstanceId);
Assert.Equal("Running", actual[1].RuntimeStatus);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetQueryMultipleRuntimeStatus_is_Success()
{
// Build Mock
var result = new OrchestrationStatusQueryResult
{
DurableOrchestrationState = new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
new DurableOrchestrationStatus
{
Name = "DoThat",
InstanceId = "02",
RuntimeStatus = OrchestrationRuntimeStatus.Completed,
},
},
ContinuationToken = "YYYY-YYYYYYYY-YYYYYYYYYYYY",
};
var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0);
var createdTimeTo = new DateTime(2018, 3, 10, 10, 23, 59);
var runtimeStatus = new List<OrchestrationRuntimeStatus>();
runtimeStatus.Add(OrchestrationRuntimeStatus.Running);
runtimeStatus.Add(OrchestrationRuntimeStatus.Completed);
var runtimeStatusRunningString = OrchestrationRuntimeStatus.Running.ToString();
var runtimeStatusCompletedString = OrchestrationRuntimeStatus.Completed.ToString();
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(result));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
// Build uri
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/";
getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}&createdTimeTo={WebUtility.UrlEncode(createdTimeTo.ToString())}&runtimeStatus={runtimeStatusRunningString},{runtimeStatusCompletedString}";
// Test HttpApiHandler response
var responseMessage = await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
});
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
var actual = JsonConvert.DeserializeObject<IList<StatusResponsePayload>>(await responseMessage.Content.ReadAsStringAsync());
clientMock.Verify(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()));
Assert.Equal("DoThis", actual[0].Name);
Assert.Equal("01", actual[0].InstanceId);
Assert.Equal("Running", actual[0].RuntimeStatus);
Assert.Equal("DoThat", actual[1].Name);
Assert.Equal("02", actual[1].InstanceId);
Assert.Equal("Completed", actual[1].RuntimeStatus);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetQueryWithoutRuntimeStatus_is_Success()
{
// Build mock
var result = new OrchestrationStatusQueryResult
{
DurableOrchestrationState = new List<DurableOrchestrationStatus>
{
new DurableOrchestrationStatus
{
Name = "DoThis",
InstanceId = "01",
RuntimeStatus = OrchestrationRuntimeStatus.Running,
},
new DurableOrchestrationStatus
{
Name = "DoThat",
InstanceId = "02",
RuntimeStatus = OrchestrationRuntimeStatus.Completed,
},
},
ContinuationToken = "YYYY-YYYYYYYY-YYYYYYYYYYYY",
};
var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0);
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(result));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
// Build uri
var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
getStatusRequestUriBuilder.Path += $"/Instances/";
getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}";
// Test HttpApiHandler response
var responseMessage = await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = getStatusRequestUriBuilder.Uri,
});
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
var actual = JsonConvert.DeserializeObject<IList<StatusResponsePayload>>(await responseMessage.Content.ReadAsStringAsync());
clientMock.Verify(x => x.ListInstancesAsync(It.IsAny<OrchestrationStatusQueryCondition>(), It.IsAny<CancellationToken>()));
Assert.Equal("DoThis", actual[0].Name);
Assert.Equal("01", actual[0].InstanceId);
Assert.Equal("Running", actual[0].RuntimeStatus);
Assert.Equal("DoThat", actual[1].Name);
Assert.Equal("02", actual[1].InstanceId);
Assert.Equal("Completed", actual[1].RuntimeStatus);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task TerminateInstanceWebhook()
{
string testInstanceId = Guid.NewGuid().ToString("N");
string testReason = "TerminationReason" + Guid.NewGuid();
string actualInstanceId = null;
string actualReason = null;
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.TerminateAsync(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask)
.Callback((string instanceId, string reason) =>
{
actualInstanceId = instanceId;
actualReason = reason;
});
clientMock
.Setup(x => x.GetStatusAsync(It.IsAny<string>(), false, false, true))
.Returns(Task.FromResult(
new DurableOrchestrationStatus
{
InstanceId = testInstanceId,
RuntimeStatus = OrchestrationRuntimeStatus.Running,
}));
var terminateRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
terminateRequestUriBuilder.Path += $"/Instances/{testInstanceId}/terminate";
terminateRequestUriBuilder.Query = $"reason={testReason}&{terminateRequestUriBuilder.Query.TrimStart('?')}";
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
await httpApiHandler.HandleRequestAsync(
new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = terminateRequestUriBuilder.Uri,
});
Assert.Equal(testInstanceId, actualInstanceId);
Assert.Equal(testReason, actualReason);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task RestartInstance_Is_Success(bool restartWithNewInstanceId)
{
string testInstanceId = Guid.NewGuid().ToString();
string restartedInstanceId = restartWithNewInstanceId ? Guid.NewGuid().ToString() : testInstanceId;
var restartUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
restartUriBuilder.Path += $"/Instances/{testInstanceId}/restart";
restartUriBuilder.Query = $"restartWithNewInstanceId={restartWithNewInstanceId}&{restartUriBuilder.Query.TrimStart('?')}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = restartUriBuilder.Uri,
};
var testStatusQueryGetUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}?taskhub=SampleHubVS&connection=Storage&code=mykey";
var testSendEventPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testTerminatePostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRewindPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/rewind?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRestartPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/restart?taskHub=SampleHubVS&connection=Storage&code=mykey&restartWithNewInstanceId={restartWithNewInstanceId}";
var testResponse = testRequest.CreateResponse(
HttpStatusCode.Accepted,
new
{
id = restartedInstanceId,
statusQueryGetUri = testStatusQueryGetUri,
sendEventPostUri = testSendEventPostUri,
terminatePostUri = testTerminatePostUri,
rewindPostUri = testRewindPostUri,
restartPostUri = testRestartPostUri,
});
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.RestartAsync(testInstanceId, restartWithNewInstanceId))
.Returns(Task.FromResult(restartedInstanceId));
clientMock
.Setup(x => x.CreateCheckStatusResponse(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns(testResponse);
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], restartedInstanceId);
Assert.Equal(status["statusQueryGetUri"], testStatusQueryGetUri);
Assert.Equal(status["sendEventPostUri"], testSendEventPostUri);
Assert.Equal(status["terminatePostUri"], testTerminatePostUri);
Assert.Equal(status["rewindPostUri"], testRewindPostUri);
Assert.Equal(status["restartPostUri"], testRestartPostUri);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task RestartInstanceAndWaitToComplete_Is_Success(bool restartWithNewInstanceId)
{
string testInstanceId = Guid.NewGuid().ToString();
string restartedInstanceId = restartWithNewInstanceId ? Guid.NewGuid().ToString() : testInstanceId;
var restartUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
restartUriBuilder.Path += $"/Instances/{testInstanceId}/restart";
restartUriBuilder.Query = $"timeout=90&pollingInterval=10&restartWithNewInstanceId={restartWithNewInstanceId}&{restartUriBuilder.Query.TrimStart('?')}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = restartUriBuilder.Uri,
};
var testStatusQueryGetUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}?taskhub=SampleHubVS&connection=Storage&code=mykey";
var testSendEventPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testTerminatePostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRewindPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/rewind?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRestartPostUri = $"{TestConstants.NotificationUrlBase}/instances/{restartedInstanceId}/restart?taskHub=SampleHubVS&connection=Storage&code=mykey&restartWithNewInstanceId={restartWithNewInstanceId}";
var testResponse = testRequest.CreateResponse(
HttpStatusCode.Accepted,
new
{
id = restartedInstanceId,
statusQueryGetUri = testStatusQueryGetUri,
sendEventPostUri = testSendEventPostUri,
terminatePostUri = testTerminatePostUri,
rewindPostUri = testRewindPostUri,
restartPostUri = testRestartPostUri,
});
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.RestartAsync(testInstanceId, restartWithNewInstanceId))
.Returns(Task.FromResult(restartedInstanceId));
clientMock
.Setup(x => x.WaitForCompletionOrCreateCheckStatusResponseAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>(), It.IsAny<bool>()))
.Returns(Task.FromResult(testResponse));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], restartedInstanceId);
Assert.Equal(status["statusQueryGetUri"], testStatusQueryGetUri);
Assert.Equal(status["sendEventPostUri"], testSendEventPostUri);
Assert.Equal(status["terminatePostUri"], testTerminatePostUri);
Assert.Equal(status["rewindPostUri"], testRewindPostUri);
Assert.Equal(status["restartPostUri"], testRestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task RestartInstance_Returns_HTTP_400_On_Invalid_InstanceId()
{
string testBadInstanceId = Guid.NewGuid().ToString("N");
var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
startRequestUriBuilder.Path += $"/Instances/{testBadInstanceId}/restart";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = startRequestUriBuilder.Uri,
};
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.RestartAsync(It.IsAny<string>(), It.IsAny<bool>()))
.Throws(new ArgumentException());
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.BadRequest, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal("InstanceId does not match a valid orchestration instance.", error["Message"].ToString());
}
[Theory]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(TestConstants.RandomInstanceId, false)]
[InlineData(TestConstants.RandomInstanceId, true)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task StartNewInstance_Is_Success(string instanceId, bool hasContentHeader)
{
string testInstanceId = string.IsNullOrEmpty(instanceId) ? Guid.NewGuid().ToString("N") : instanceId;
string testFunctionName = "TestOrchestrator";
var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = startRequestUriBuilder.Uri,
Content = hasContentHeader
? new StringContent("\"TestContent\"", Encoding.UTF8, "application/json")
: new StringContent("\"TestContent\""),
};
var testStatusQueryGetUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}?taskhub=SampleHubVS&connection=Storage&code=mykey";
var testSendEventPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testTerminatePostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRewindPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/rewind?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRestartPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/restart?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testResponse = testRequest.CreateResponse(
HttpStatusCode.Accepted,
new
{
id = testInstanceId,
statusQueryGetUri = testStatusQueryGetUri,
sendEventPostUri = testSendEventPostUri,
terminatePostUri = testTerminatePostUri,
rewindPostUri = testRewindPostUri,
restartPostUri = testRestartPostUri,
});
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.StartNewAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.FromResult(testInstanceId));
clientMock
.Setup(x => x.CreateCheckStatusResponse(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), false))
.Returns(testResponse);
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], testInstanceId);
Assert.Equal(status["statusQueryGetUri"], testStatusQueryGetUri);
Assert.Equal(status["sendEventPostUri"], testSendEventPostUri);
Assert.Equal(status["terminatePostUri"], testTerminatePostUri);
Assert.Equal(status["rewindPostUri"], testRewindPostUri);
Assert.Equal(status["restartPostUri"], testRestartPostUri);
}
[Theory]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(TestConstants.RandomInstanceId, false)]
[InlineData(TestConstants.RandomInstanceId, true)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task StartNewInstanceAndWaitToComplete_Is_Success(string instanceId, bool hasContentHeader)
{
string testInstanceId = string.IsNullOrEmpty(instanceId) ? Guid.NewGuid().ToString("N") : instanceId;
string testFunctionName = "TestOrchestrator";
var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";
startRequestUriBuilder.Query = $"timeout=90&pollingInterval=10&{startRequestUriBuilder.Query.TrimStart('?')}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = startRequestUriBuilder.Uri,
Content = hasContentHeader
? new StringContent("\"TestContent\"", Encoding.UTF8, "application/json")
: new StringContent("\"TestContent\""),
};
var testStatusQueryGetUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}?taskhub=SampleHubVS&connection=Storage&code=mykey";
var testSendEventPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testTerminatePostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRewindPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/rewind?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
var testRestartPostUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/restart?taskHub=SampleHubVS&connection=Storage&code=mykey";
var testResponse = testRequest.CreateResponse(
HttpStatusCode.Accepted,
new
{
id = testInstanceId,
statusQueryGetUri = testStatusQueryGetUri,
sendEventPostUri = testSendEventPostUri,
terminatePostUri = testTerminatePostUri,
rewindPostUri = testRewindPostUri,
restartPostUri = testRestartPostUri,
});
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.StartNewAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.FromResult(testInstanceId));
clientMock
.Setup(x => x.WaitForCompletionOrCreateCheckStatusResponseAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>(), It.IsAny<bool>()))
.Returns(Task.FromResult(testResponse));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal(status["id"], testInstanceId);
Assert.Equal(status["statusQueryGetUri"], testStatusQueryGetUri);
Assert.Equal(status["sendEventPostUri"], testSendEventPostUri);
Assert.Equal(status["terminatePostUri"], testTerminatePostUri);
Assert.Equal(status["rewindPostUri"], testRewindPostUri);
Assert.Equal(status["restartPostUri"], testRestartPostUri);
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task StartNewInstance_Returns_HTTP_400_On_Bad_JSON()
{
string testInstanceId = Guid.NewGuid().ToString("N");
string testFunctionName = "TestOrchestrator";
var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = startRequestUriBuilder.Uri,
Content = new StringContent("badly formatted JSON string", Encoding.UTF8, "application/json"),
};
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.StartNewAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.FromResult(testInstanceId));
clientMock
.Setup(x => x.CreateCheckStatusResponse(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), false))
.Throws(new JsonReaderException());
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.BadRequest, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal("Invalid JSON content", error["Message"].ToString());
}
[Fact]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task StartNewInstance_Returns_HTTP_400_On_Missing_Function()
{
string testInstanceId = Guid.NewGuid().ToString("N");
string testFunctionName = "NonexistentFunction";
string exceptionMessage = $"The function '{testFunctionName}' doesn't exist, is disabled, or is not an orchestrator function. Additional info: ";
var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);
startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = startRequestUriBuilder.Uri,
Content = new StringContent("\"TestContent\"", Encoding.UTF8, "application/json"),
};
var clientMock = new Mock<IDurableClient>();
clientMock
.Setup(x => x.StartNewAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>()))
.Throws(new ArgumentException(exceptionMessage));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.BadRequest, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<JObject>(content);
Assert.Equal("One or more of the arguments submitted is incorrect", error["Message"].ToString());
Assert.Equal(exceptionMessage, error["ExceptionMessage"].ToString());
}
[Theory]
[InlineData(false, true)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(true, false)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task GetEntity_Returns_State_Or_HTTP_404(bool hasKey, bool exists)
{
string entity = "SomeEntity";
string key = hasKey ? Guid.NewGuid().ToString("N") : "$";
var uriBuilder = new UriBuilder(TestConstants.NotificationUrl);
uriBuilder.Path += $"/entities/{entity}/{key}";
if (key.Equals(EmptyEntityKeySymbol))
{
key = "";
}
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = uriBuilder.Uri,
};
var entityId = new EntityId(entity, key);
var result = new EntityStateResponse<JToken>() { EntityExists = exists, EntityState = exists ? new JObject() : null };
var clientMock = new Mock<IDurableClient>(MockBehavior.Strict);
clientMock
.Setup(x => x.ReadEntityStateAsync<JToken>(entityId, null, null))
.Returns(Task.FromResult(result));
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
if (exists)
{
Assert.Equal(HttpStatusCode.OK, actualResponse.StatusCode);
var content = await actualResponse.Content.ReadAsStringAsync();
Assert.Equal("{}", content);
}
else
{
Assert.Equal(HttpStatusCode.NotFound, actualResponse.StatusCode);
}
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
[InlineData(true, true, true)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task Entities_Query_Calls_ListEntitiesAsync(bool useNameFilter, bool fetchState, bool useContinuationToken)
{
// Build mock
string entityName = Guid.NewGuid().ToString("N");
var mockList = new List<DurableEntityStatus>
{
new DurableEntityStatus
{
EntityId = new EntityId(entityName, "one"),
LastOperationTime = new DateTime(2018, 3, 10, 10, 10, 10, DateTimeKind.Utc),
State = 1,
},
new DurableEntityStatus
{
EntityId = new EntityId(entityName, "two"),
LastOperationTime = new DateTime(2018, 3, 10, 10, 6, 10, DateTimeKind.Utc),
State = 2,
},
};
if (!fetchState)
{
mockList.ForEach(status => status.State = null);
}
var lastOperationTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0, DateTimeKind.Utc);
var lastOperationTimeTo = new DateTime(2018, 3, 10, 10, 23, 59, DateTimeKind.Utc);
var continuationToken = useContinuationToken ? Guid.NewGuid().ToString("N") : null;
var pageSize = 2;
var mockResult = new EntityQueryResult() { Entities = mockList, ContinuationToken = continuationToken };
var clientMock = new Mock<IDurableClient>(MockBehavior.Strict);
clientMock
.Setup(x => x.ListEntitiesAsync(It.IsAny<EntityQuery>(), It.IsAny<CancellationToken>()))
.Callback<EntityQuery, CancellationToken>((query, cancellationToken) =>
{
// Ensure all query string parameters were correctly parsed
Assert.Equal(lastOperationTimeFrom, query.LastOperationFrom);
Assert.Equal(lastOperationTimeTo, query.LastOperationTo);
Assert.Equal(useNameFilter ? entityName : null, query.EntityName);
Assert.Equal(fetchState, query.FetchState);
Assert.Equal(continuationToken, query.ContinuationToken);
Assert.Equal(useContinuationToken ? continuationToken : null, query.ContinuationToken);
Assert.Equal(pageSize, query.PageSize);
})
.Returns(Task.FromResult(mockResult));
// Build Uri
var uriBuilder = new UriBuilder(TestConstants.NotificationUrl);
if (useNameFilter)
{
uriBuilder.Path += $"/entities/{entityName}";
}
else
{
uriBuilder.Path += $"/entities/";
}
uriBuilder.Query += $"&lastOperationTimeFrom={WebUtility.UrlEncode(lastOperationTimeFrom.ToString("s"))}";
uriBuilder.Query += $"&lastOperationTimeTo={WebUtility.UrlEncode(lastOperationTimeTo.ToString("s"))}";
uriBuilder.Query += $"&fetchState={fetchState}";
uriBuilder.Query += $"&top={pageSize}";
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = uriBuilder.Uri,
};
if (useContinuationToken)
{
requestMessage.Headers.Add("x-ms-continuation-token", continuationToken);
}
// Test HttpApiHandler response
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
HttpResponseMessage responseMessage = await httpApiHandler.HandleRequestAsync(requestMessage);
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
clientMock.Verify(x => x.ListEntitiesAsync(It.IsAny<EntityQuery>(), It.IsAny<CancellationToken>()));
var actual = JsonConvert.DeserializeObject<IList<DurableEntityStatus>>(await responseMessage.Content.ReadAsStringAsync());
Assert.Equal(mockList.Count, actual.Count);
Assert.Equal(entityName, actual[0].EntityId.EntityName);
Assert.Equal("one", actual[0].EntityId.EntityKey);
Assert.Equal(entityName, actual[1].EntityId.EntityName);
Assert.Equal("two", actual[1].EntityId.EntityKey);
if (fetchState)
{
Assert.Equal(1, (int)actual[0].State);
Assert.Equal(2, (int)actual[1].State);
}
else
{
Assert.Equal(JTokenType.Null, actual[0].State.Type);
Assert.Equal(JTokenType.Null, actual[1].State.Type);
}
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true, true)]
[InlineData(false, false, true, false)]
[InlineData(false, true, false)]
[InlineData(false, true, true, true)]
[InlineData(false, true, true, false)]
[InlineData(true, false, false)]
[InlineData(true, false, true, true)]
[InlineData(true, false, true, false)]
[InlineData(true, true, false)]
[InlineData(true, true, true, true)]
[InlineData(true, true, true, false)]
[Trait("Category", PlatformSpecificHelpers.TestCategory)]
public async Task SignalEntity_Is_Success(bool hasKey, bool hasOp, bool hasContent, bool hasJsonContent = false)
{
string entity = "SomeEntity";
string key = hasKey ? Guid.NewGuid().ToString("N") : "";
string operation = hasOp ? (hasJsonContent ? "jsonOp" : "stringOp") : "";
string content = hasContent ? (hasJsonContent ? "{ \"someProperty\" : \"someValue\" }" : "text content") : "";
var uriBuilder = new UriBuilder(TestConstants.NotificationUrl);
uriBuilder.Path += $"/entities/{entity}";
if (!string.IsNullOrEmpty(key))
{
uriBuilder.Path += $"/{key}";
}
if (!string.IsNullOrEmpty(operation))
{
uriBuilder.Query = $"op={operation}";
}
var testRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uriBuilder.Uri,
};
if (hasContent)
{
if (hasJsonContent)
{
testRequest.Content = new StringContent(content, Encoding.UTF8, "application/json");
}
else
{
testRequest.Content = new StringContent(content);
}
}
var entityId = new EntityId(entity, key);
var clientMock = new Mock<IDurableClient>(MockBehavior.Strict);
if (hasContent)
{
if (hasJsonContent)
{
clientMock
.Setup(x => x.SignalEntityAsync(entityId, operation, It.IsAny<JToken>(), null, null))
.Returns(Task.CompletedTask);
}
else
{
clientMock
.Setup(x => x.SignalEntityAsync(entityId, operation, content, null, null))
.Returns(Task.CompletedTask);
}
}
else
{
clientMock
.Setup(x => x.SignalEntityAsync(entityId, operation, null, null, null))
.Returns(Task.CompletedTask);
}
var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);
Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
}
private static DurableTaskExtension GetTestExtension()
{
var options = new DurableTaskOptions();
options.WebhookUriProviderOverride = () => new Uri(TestConstants.NotificationUrl);
options.HubName = "DurableFunctionsHub";
return GetTestExtension(options);
}
private static DurableTaskExtension GetTestExtension(DurableTaskOptions options)
{
return new MockDurableTaskExtension(options);
}
// Same as regular HTTP Api handler except you can specify a custom client object.
internal class ExtendedHttpApiHandler : HttpApiHandler
{
public ExtendedHttpApiHandler(IDurableClient client)
: base(GetTestExtension(), null /* traceWriter */)
{
this.InnerClient = client;
}
internal IDurableClient InnerClient { get; set; }
protected override IDurableClient GetClient(DurableClientAttribute attribute)
{
return this.InnerClient;
}
}
private class ChangingWebhookProvider
{
public Uri WebhookUri { get; set; }
}
private class MockDurableTaskExtension : DurableTaskExtension
{
public MockDurableTaskExtension(DurableTaskOptions options)
: base(
new OptionsWrapper<DurableTaskOptions>(options),
new LoggerFactory(),
TestHelpers.GetTestNameResolver(),
new[]
{
new AzureStorageDurabilityProviderFactory(
new OptionsWrapper<DurableTaskOptions>(options),
new TestStorageAccountProvider(),
TestHelpers.GetTestNameResolver(),
NullLoggerFactory.Instance,
TestHelpers.GetMockPlatformInformationService()),
},
new TestHostShutdownNotificationService(),
new DurableHttpMessageHandlerFactory(),
platformInformationService: TestHelpers.GetMockPlatformInformationService())
{
}
protected internal override IDurableClient GetClient(DurableClientAttribute attribute)
{
var orchestrationServiceClientMock = new Mock<IOrchestrationServiceClient>();
var orchestrationServiceMock = new Mock<IOrchestrationService>();
var storageProvider = new DurabilityProvider("Mock", orchestrationServiceMock.Object, orchestrationServiceClientMock.Object, "mock");
Assert.Equal(TestConstants.TaskHub, attribute.TaskHub);
Assert.Equal(TestConstants.ConnectionName, attribute.ConnectionName);
return new DurableClientMock(storageProvider, this, attribute);
}
}
}
}
| 52.491479 | 255 | 0.61896 | [
"MIT"
] | wsugarman/azure-functions-durable-extension | test/Common/HttpApiHandlerTests.cs | 77,007 | C# |
using Bussiness;
using log4net;
using SqlDataProvider.Data;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace Game.Server.Managers
{
public class ConsortiaLevelMgr
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Dictionary<int, ConsortiaLevelInfo> _consortiaLevel;
private static ReaderWriterLock m_lock;
private static ThreadSafeRandom rand;
public static bool ReLoad()
{
try
{
Dictionary<int, ConsortiaLevelInfo> tempConsortiaLevel = new Dictionary<int, ConsortiaLevelInfo>();
if (Load(tempConsortiaLevel))
{
m_lock.AcquireWriterLock(-1);
try
{
_consortiaLevel = tempConsortiaLevel;
return true;
}
catch
{
}
finally
{
m_lock.ReleaseWriterLock();
}
}
}
catch (Exception e)
{
if (log.IsErrorEnabled)
{
log.Error("ConsortiaLevelMgr", e);
}
}
return false;
}
public static bool Init()
{
try
{
m_lock = new ReaderWriterLock();
_consortiaLevel = new Dictionary<int, ConsortiaLevelInfo>();
rand = new ThreadSafeRandom();
return Load(_consortiaLevel);
}
catch (Exception e)
{
if (log.IsErrorEnabled)
{
log.Error("ConsortiaLevelMgr", e);
}
return false;
}
}
private static bool Load(Dictionary<int, ConsortiaLevelInfo> consortiaLevel)
{
using (ConsortiaBussiness db = new ConsortiaBussiness())
{
ConsortiaLevelInfo[] array = db.GetAllConsortiaLevel();
foreach (ConsortiaLevelInfo info in array)
{
if (!consortiaLevel.ContainsKey(info.Level))
{
consortiaLevel.Add(info.Level, info);
}
}
}
return true;
}
public static ConsortiaLevelInfo FindConsortiaLevelInfo(int level)
{
m_lock.AcquireReaderLock(-1);
try
{
if (_consortiaLevel.ContainsKey(level))
{
return _consortiaLevel[level];
}
}
catch
{
}
finally
{
m_lock.ReleaseReaderLock();
}
return null;
}
}
}
| 19.247706 | 103 | 0.659199 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/SourceQuest4.5/Bussiness/Game.Server.Managers/ConsortiaLevelMgr.cs | 2,098 | C# |
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Infrastructure.Persistence.Configurations;
public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.Property(p => p.Username).IsRequired();
builder.Property(p => p.Hash).IsRequired();
}
} | 30.142857 | 69 | 0.767773 | [
"MIT"
] | lnans/personal.budget | src/Infrastructure/Persistence/Configurations/UserEntityConfiguration.cs | 422 | C# |
// AccountStatus
public enum AccountStatus
{
Active,
AwaitingParentalConsent,
DeleteRequested,
Unknown,
Deleted
}
| 11.9 | 25 | 0.789916 | [
"MIT"
] | smdx24/CPI-Source-Code | Disney.Mix.SDK/AccountStatus.cs | 119 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AmbientSoundsTuner2.SoundPack;
using AmbientSoundsTuner2.SoundPack.Migration;
using UnityEngine;
namespace AmbientSoundsTuner2.Sounds
{
/// <summary>
/// A static class that contains various methods related to sounds patching.
/// </summary>
public static class SoundPatchUtils
{
/// <summary>
/// Gets the volume of a sound.
/// </summary>
/// <param name="sound">The sound.</param>
/// <returns>The volume of the sound if it has one; otherwise null.</returns>
public static float? GetVolume(SoundContainer sound)
{
if (sound.HasSound)
{
return GetVolume(sound.AudioInfo);
}
return null;
}
/// <summary>
/// Gets the volume of a sound effect.
/// </summary>
/// <param name="effect">The sound effect.</param>
/// <returns>The volume of the sound effect if it has one; otherwise null.</returns>
public static float? GetVolume(SoundEffect effect)
{
if (effect != null)
{
return GetVolume(effect.m_audioInfo);
}
return null;
}
/// <summary>
/// Gets the volume of an audio info.
/// </summary>
/// <param name="info">The audio info.</param>
/// <returns>The volume of the audio info if it's not null; otherwise null.</returns>
public static float? GetVolume(AudioInfo info)
{
if (info != null)
{
return info.m_volume;
}
return null;
}
/// <summary>
/// Sets the volume of a sound.
/// </summary>
/// <param name="sound">The sound.</param>
/// <param name="volume">The new volume.</param>
/// <returns>True if successful; false otherwise.</returns>
public static bool SetVolume(SoundContainer sound, float volume)
{
if (sound.HasSound)
{
return SetVolume(sound.AudioInfo, volume);
}
return false;
}
/// <summary>
/// Sets the volume of a sound effect.
/// </summary>
/// <param name="effect">The sound effect.</param>
/// <param name="volume">The new volume.</param>
/// <returns>True if successful; false otherwise.</returns>
public static bool SetVolume(SoundEffect effect, float volume)
{
if (effect != null)
{
return SetVolume(effect.m_audioInfo, volume);
}
return false;
}
/// <summary>
/// Sets the volume of an audio info and its variations.
/// </summary>
/// <param name="info">The audio info.</param>
/// <param name="volume">The new volume.</param>
/// <returns>True if successful; false otherwise.</returns>
public static bool SetVolume(AudioInfo info, float volume)
{
if (info != null)
{
info.m_volume = volume;
for (int i = 0; i < info.m_variations.Length; i++)
{
info.m_variations[i].m_sound.m_volume = volume;
}
return true;
}
return false;
}
/// <summary>
/// Gets the sound pack file audio from an audio info.
/// </summary>
/// <param name="sound">The sound.</param>
/// <returns>The sound pack file audio.</returns>
public static SoundPacksFileV1.Audio GetAudioInfo(SoundContainer sound)
{
if (sound.HasSound)
{
return GetAudioInfo(sound.AudioInfo);
}
return null;
}
/// <summary>
/// Gets the sound pack file audio from an audio info.
/// </summary>
/// <param name="audioInfo">The original audio info.</param>
/// <returns>The sound pack file audio.</returns>
public static SoundPacksFileV1.Audio GetAudioInfo(AudioInfo audioInfo)
{
if (audioInfo != null)
{
var spfAudio = new SoundPacksFileV1.Audio()
{
Name = audioInfo.name,
AudioInfo = new SoundPacksFileV1.AudioInfo()
};
Action<AudioInfo, SoundPacksFileV1.AudioInfo> backupAudioInfo = null;
backupAudioInfo = new Action<AudioInfo, SoundPacksFileV1.AudioInfo>((ai, spf) =>
{
spf.AudioClip = ai.m_clip;
spf.Volume = ai.m_volume;
spf.MaxVolume = Mathf.Max(ai.m_volume, 1);
spf.Pitch = ai.m_pitch;
spf.FadeLength = ai.m_fadeLength;
spf.IsLoop = ai.m_loop;
spf.Is3D = ai.m_is3D;
spf.IsRandomTime = ai.m_randomTime;
if (ai.m_variations != null)
{
spf.Variations = new SoundPacksFileV1.Variation[ai.m_variations.Length];
for (int i = 0; i < ai.m_variations.Length; i++)
{
spf.Variations[i] = new SoundPacksFileV1.Variation()
{
Probability = ai.m_variations[i].m_probability,
AudioInfo = new SoundPacksFileV1.AudioInfo()
};
backupAudioInfo(ai.m_variations[i].m_sound, spf.Variations[i].AudioInfo);
}
}
});
backupAudioInfo(audioInfo, spfAudio.AudioInfo);
return spfAudio;
}
return null;
}
/// <summary>
/// Sets the audio info to the data of a sound pack file audio.
/// </summary>
/// <param name="sound">The sound.</param>
/// <param name="spfAudio">The sound pack file audio.</param>
/// <returns>True if successful; false otherwise.</returns>
public static bool SetAudioInfo(SoundContainer sound, SoundPacksFileV1.Audio spfAudio)
{
if (sound.HasSound)
{
return SetAudioInfo(sound.AudioInfo, spfAudio);
}
return false;
}
/// <summary>
/// Sets the audio info to the data of a sound pack file audio.
/// </summary>
/// <param name="audioInfo">The audio info to set.</param>
/// <param name="spfAudio">The sound pack file audio.</param>
/// <returns>True if successful; false otherwise.</returns>
public static bool SetAudioInfo(AudioInfo audioInfo, SoundPacksFileV1.Audio spfAudio)
{
if (audioInfo != null && spfAudio != null)
{
Action<AudioInfo, SoundPacksFileV1.AudioInfo> patchAudioInfo = null;
int variation = 0;
patchAudioInfo = new Action<AudioInfo, SoundPacksFileV1.AudioInfo>((ai, spf) =>
{
if (spf.AudioClip != null)
ai.m_clip = spf.AudioClip;
else
{
WWW www = new WWW(new Uri(spf.Clip).AbsoluteUri);
ai.m_clip = www.GetAudioClip(true, false);
}
ai.m_volume = spf.Volume;
ai.m_pitch = spf.Pitch;
ai.m_fadeLength = spf.FadeLength;
ai.m_loop = spf.IsLoop;
ai.m_is3D = spf.Is3D;
ai.m_randomTime = spf.IsRandomTime;
variation++;
if (spf.Variations != null)
{
ai.m_variations = new AudioInfo.Variation[spf.Variations.Length];
for (int i = 0; i < spf.Variations.Length; i++)
{
ai.m_variations[i] = new AudioInfo.Variation()
{
m_probability = spf.Variations[i].Probability,
m_sound = ScriptableObject.CreateInstance<AudioInfo>()
};
patchAudioInfo(ai.m_variations[i].m_sound, spf.Variations[i].AudioInfo);
}
}
else
{
ai.m_variations = null;
}
});
patchAudioInfo(audioInfo, spfAudio.AudioInfo);
return true;
}
return false;
}
}
}
| 37.217573 | 101 | 0.488252 | [
"MIT"
] | bloodypenguin/csl-ambient-sounds-tuner | CSL Ambient Sounds Tuner/Sounds/Utils/SoundPatchUtils.cs | 8,897 | C# |
using System;
namespace TheRectangles
{
class Program
{
static void Main(string[] args)
{
Grid grid = new Grid();
Rectangle rectangle01 = new Rectangle("Rectangle 01",
"Red",
new Point(2, 1),
new Point(4, 6));
Console.WriteLine(rectangle01.ToString());
Rectangle rectangle02 = new Rectangle("Rectangle 02",
"Black",
new Point(3, 3),
new Point(7, 8));
Console.WriteLine(rectangle02.ToString());
Console.WriteLine("Overlapped area: " + OverlappedArea(rectangle01, rectangle02));
}
public static int OverlappedArea(Rectangle rectangleOne, Rectangle rectangleTwo)
{
//var rectangleOneArea = rectangleOne.Area();
//var rectangleTwoArea = rectangleTwo.Area();
int areaOverlapped = (Math.Min(rectangleOne.vertexTwo.x, rectangleTwo.vertexTwo.x) -
Math.Max(rectangleOne.vertexOne.x, rectangleTwo.vertexOne.x)) *
(Math.Min(rectangleOne.vertexTwo.y, rectangleTwo.vertexTwo.y) -
Math.Max(rectangleOne.vertexOne.y, rectangleTwo.vertexOne.y));
//return (rectangleOneArea + rectangleTwoArea - areaOverlapped);
return areaOverlapped;
}
}
}
| 36.244444 | 96 | 0.483139 | [
"MIT"
] | matheusmorcinek/TheRectangles | TheRectangles/TheRectangles/Program.cs | 1,633 | 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.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents expression and deconstruction variables declared in a global statement.
/// </summary>
internal class GlobalExpressionVariable : SourceMemberFieldSymbol
{
private TypeWithAnnotations.Boxed _lazyType;
/// <summary>
/// The type syntax, if any, from source. Optional for patterns that can omit an explicit type.
/// </summary>
private SyntaxReference _typeSyntaxOpt;
internal GlobalExpressionVariable(
SourceMemberContainerTypeSymbol containingType,
DeclarationModifiers modifiers,
TypeSyntax typeSyntax,
string name,
SyntaxReference syntax,
Location location)
: base(containingType, modifiers, name, syntax, location)
{
Debug.Assert(DeclaredAccessibility == Accessibility.Private);
_typeSyntaxOpt = typeSyntax?.GetReference();
}
internal static GlobalExpressionVariable Create(
SourceMemberContainerTypeSymbol containingType,
DeclarationModifiers modifiers,
TypeSyntax typeSyntax,
string name,
SyntaxNode syntax,
Location location,
FieldSymbol containingFieldOpt,
SyntaxNode nodeToBind)
{
Debug.Assert(nodeToBind.Kind() == SyntaxKind.VariableDeclarator || nodeToBind is ExpressionSyntax);
var syntaxReference = syntax.GetReference();
return (typeSyntax == null || typeSyntax.IsVar)
? new InferrableGlobalExpressionVariable(containingType, modifiers, typeSyntax, name, syntaxReference, location, containingFieldOpt, nodeToBind)
: new GlobalExpressionVariable(containingType, modifiers, typeSyntax, name, syntaxReference, location);
}
protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList => default(SyntaxList<AttributeListSyntax>);
protected override TypeSyntax TypeSyntax => (TypeSyntax)_typeSyntaxOpt?.GetSyntax();
protected override SyntaxTokenList ModifiersTokenList => default(SyntaxTokenList);
public override bool HasInitializer => false;
protected override ConstantValue MakeConstantValue(
HashSet<SourceFieldSymbolWithSyntaxReference> dependencies,
bool earlyDecodingWellKnownAttributes,
DiagnosticBag diagnostics) => null;
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
Debug.Assert(fieldsBeingBound != null);
if (_lazyType != null)
{
return _lazyType.Value;
}
var typeSyntax = TypeSyntax;
var compilation = this.DeclaringCompilation;
var diagnostics = DiagnosticBag.GetInstance();
TypeWithAnnotations type;
bool isVar;
var binderFactory = compilation.GetBinderFactory(SyntaxTree);
var binder = binderFactory.GetBinder(typeSyntax ?? SyntaxNode);
if (typeSyntax != null)
{
type = binder.BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar);
}
else
{
// Recursive patterns may omit the type syntax
isVar = true;
type = default;
}
Debug.Assert(type.HasType || isVar);
if (isVar && !fieldsBeingBound.ContainsReference(this))
{
InferFieldType(fieldsBeingBound, binder);
Debug.Assert(_lazyType != null);
}
else
{
if (isVar)
{
diagnostics.Add(ErrorCode.ERR_RecursivelyTypedVariable, this.ErrorLocation, this);
type = TypeWithAnnotations.Create(binder.CreateErrorType("var"));
}
SetType(compilation, diagnostics, type);
}
diagnostics.Free();
return _lazyType.Value;
}
/// <summary>
/// Can add some diagnostics into <paramref name="diagnostics"/>.
/// Returns the type that it actually locks onto (it's possible that it had already locked onto ErrorType).
/// </summary>
private TypeWithAnnotations SetType(CSharpCompilation compilation, DiagnosticBag diagnostics, TypeWithAnnotations type)
{
var originalType = _lazyType?.Value.DefaultType;
// In the event that we race to set the type of a field, we should
// always deduce the same type, unless the cached type is an error.
Debug.Assert((object)originalType == null ||
originalType.IsErrorType() ||
TypeSymbol.Equals(originalType, type.Type, TypeCompareKind.ConsiderEverything2));
if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null) == null)
{
TypeChecks(type.Type, diagnostics);
compilation.DeclarationDiagnostics.AddRange(diagnostics);
state.NotePartComplete(CompletionPart.Type);
}
return _lazyType.Value;
}
/// <summary>
/// Can add some diagnostics into <paramref name="diagnostics"/>.
/// Returns the type that it actually locks onto (it's possible that it had already locked onto ErrorType).
/// </summary>
internal TypeWithAnnotations SetTypeWithAnnotations(TypeWithAnnotations type, DiagnosticBag diagnostics)
{
return SetType(DeclaringCompilation, diagnostics, type);
}
protected virtual void InferFieldType(ConsList<FieldSymbol> fieldsBeingBound, Binder binder)
{
throw ExceptionUtilities.Unreachable;
}
private class InferrableGlobalExpressionVariable : GlobalExpressionVariable
{
private readonly FieldSymbol _containingFieldOpt;
private readonly SyntaxReference _nodeToBind;
internal InferrableGlobalExpressionVariable(
SourceMemberContainerTypeSymbol containingType,
DeclarationModifiers modifiers,
TypeSyntax typeSyntax,
string name,
SyntaxReference syntax,
Location location,
FieldSymbol containingFieldOpt,
SyntaxNode nodeToBind)
: base(containingType, modifiers, typeSyntax, name, syntax, location)
{
Debug.Assert(nodeToBind.Kind() == SyntaxKind.VariableDeclarator || nodeToBind is ExpressionSyntax);
_containingFieldOpt = containingFieldOpt;
_nodeToBind = nodeToBind.GetReference();
}
protected override void InferFieldType(ConsList<FieldSymbol> fieldsBeingBound, Binder binder)
{
var nodeToBind = _nodeToBind.GetSyntax();
if ((object)_containingFieldOpt != null && nodeToBind.Kind() != SyntaxKind.VariableDeclarator)
{
binder = binder.WithContainingMemberOrLambda(_containingFieldOpt).WithAdditionalFlags(BinderFlags.FieldInitializer);
}
fieldsBeingBound = new ConsList<FieldSymbol>(this, fieldsBeingBound);
binder = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound);
var diagnostics = DiagnosticBag.GetInstance();
switch (nodeToBind.Kind())
{
case SyntaxKind.VariableDeclarator:
// This occurs, for example, in
// int x, y[out var Z, 1 is int I];
// for (int x, y[out var Z, 1 is int I]; ;) {}
binder.BindDeclaratorArguments((VariableDeclaratorSyntax)nodeToBind, diagnostics);
break;
default:
binder.BindExpression((ExpressionSyntax)nodeToBind, diagnostics);
break;
}
diagnostics.Free();
}
}
}
}
| 40.85782 | 161 | 0.611646 | [
"Apache-2.0"
] | 20chan/roslyn | src/Compilers/CSharp/Portable/Symbols/Source/GlobalExpressionVariable.cs | 8,623 | C# |
// If using dropbox remember to add the &dl=1 to trigger a download
var file = Download("https://www.dropbox.com?....&dl=1");
| 42 | 67 | 0.690476 | [
"Apache-2.0"
] | Jay-Jay-D/Documentation | 02 Algorithm Reference/04 Importing Custom Data/04 Loading Reference Data/01 code.cs | 126 | C# |
namespace Wirehome.Core
{
public static class WirehomeCoreVersion
{
public static string Version => "1.1.0";
}
}
| 16.75 | 48 | 0.634328 | [
"Apache-2.0"
] | SeppPenner/Wirehome.Core | Wirehome.Core/WirehomeCoreVersion.cs | 136 | C# |
#nullable enable
using System;
using Robust.Shared.Serialization;
namespace Content.Shared.Cabinet
{
[Serializable, NetSerializable]
public enum ItemCabinetVisuals : byte
{
IsOpen,
ContainsItem
}
}
| 16.571429 | 41 | 0.693966 | [
"MIT"
] | Bright0/space-station-14 | Content.Shared/Cabinet/ItemCabinetVisuals.cs | 234 | C# |
/****************************************************************************
*项目名称:SAEA.MVCTest.Controllers
*CLR 版本:4.0.30319.42000
*机器名称:WALLE-PC
*命名空间:SAEA.MVCTest.Controllers
*类 名 称:OrmController
*版 本 号:V1.0.0.0
*创建人: yswenli
*电子邮箱:yswenli@outlook.com
*创建时间:2021/3/12 13:52:34
*描述:
*=====================================================================
*修改时间:2021/3/12 13:52:34
*修 改 人: yswenli
*版 本 号: V1.0.0.0
*描 述:
*****************************************************************************/
using SAEA.MVC;
using SAEA.MVCTest.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SAEA.MVCTest.Controllers
{
public class OrmController:Controller
{
/// <summary>
/// 新增服务器配置
/// </summary>
/// <param name="serverConfigLog">服务器配置</param>
/// <returns></returns>
public ActionResult ServerConfigLogAdd(ServerConfigLog serverConfigLog)
{
return Json(serverConfigLog);
}
/// <summary>
/// 更新服务器配置
/// </summary>
/// <param name="serverConfigLog">服务器配置</param>
/// <returns></returns>
public ActionResult ServerConfigLogUpdate(ServerConfigLog serverConfigLog)
{
return Json(serverConfigLog);
}
}
}
| 26.529412 | 82 | 0.52476 | [
"Apache-2.0"
] | dsfop/SAEA | Src/SAEA.MVCTest/Controllers/OrmController.cs | 1,521 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("WebRTCBindings")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WebRTCBindings")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 34.935484 | 84 | 0.746999 | [
"Apache-2.0"
] | akonsand/Peer.Net | WebRTCBindings/Properties/AssemblyInfo.cs | 1,086 | C# |
/*
* This file is part of WotoGUI Project (https://github.com/RudoRonuma/SibylClient).
* Copyright (c) 2021 WotoGUI Authors.
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code of library.
* If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Reflection;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.Versioning;
using osu.Framework;
using osu.Framework.Platform;
using osu.Framework.Graphics.Colour;
using osu.Framework.Configuration;
using osu.Framework.Development;
using osu.Framework.Logging;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Transforms;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Framework.Platform.SDL2;
using osu.Framework.Platform.Linux;
using WotoGUI.Client;
using SibylClient.Screens;
using SibylClient.Configuration;
using WHost = osu.Framework.Host;
namespace SibylClient.Client
{
public sealed partial class AppHostProvider : IDisposable
{
//-------------------------------------------------
#region Constant's Region
#endregion
//-------------------------------------------------
#region static Properties Region
#endregion
//-------------------------------------------------
#region Properties Region
public DesktopGameHost Host { get; }
public string Name { get; set; }
public bool IsDebugBuild => DebugUtils.IsDebugBuild;
public bool IsPrimaryInstance => Host.IsPrimaryInstance;
#endregion
//-------------------------------------------------
#region static field's Region
// some members here
#endregion
//-------------------------------------------------
#region field's Region
#endregion
//-------------------------------------------------
#region static event field's Region
// some members here
#endregion
//-------------------------------------------------
#region event field's Region
//public virtual
#endregion
//-------------------------------------------------
#region Constructor's Region
public AppHostProvider(string appName)
{
Host = WHost.GetSuitableHost(appName);
Name = appName;
}
#endregion
//-------------------------------------------------
#region Ordinary Method's Region
public void Dispose() => Host.Dispose();
#endregion
//-------------------------------------------------
}
} | 31.130841 | 84 | 0.648454 | [
"MIT"
] | MinistryOfWelfare/SibylClient | SibylClient/Client/AppHostProvider.cs | 3,331 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Microsoft.VisualStudioTools {
internal static class CommonUtils {
private static readonly char[] InvalidPathChars = GetInvalidPathChars();
private static readonly char[] DirectorySeparators = new[] {
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
};
private static char[] GetInvalidPathChars() {
return Path.GetInvalidPathChars().Concat(new[] { '*', '?' }).ToArray();
}
internal static bool TryMakeUri(string path, bool isDirectory, UriKind kind, out Uri uri) {
if (isDirectory && !string.IsNullOrEmpty(path) && !HasEndSeparator(path)) {
path += Path.DirectorySeparatorChar;
}
return Uri.TryCreate(path, kind, out uri);
}
internal static Uri MakeUri(string path, bool isDirectory, UriKind kind, string throwParameterName = "path") {
try {
if (isDirectory && !string.IsNullOrEmpty(path) && !HasEndSeparator(path)) {
path += Path.DirectorySeparatorChar;
}
return new Uri(path, kind);
} catch (UriFormatException ex) {
throw new ArgumentException("Path was invalid", throwParameterName, ex);
} catch (ArgumentException ex) {
throw new ArgumentException("Path was invalid", throwParameterName, ex);
}
}
/// <summary>
/// Normalizes and returns the provided path.
/// </summary>
public static string NormalizePath(string path) {
if (string.IsNullOrEmpty(path)) {
return null;
}
var uri = MakeUri(path, false, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri) {
if (uri.IsFile) {
return uri.LocalPath;
} else {
return uri.AbsoluteUri.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
} else {
return Uri.UnescapeDataString(uri.ToString()).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
}
/// <summary>
/// Normalizes and returns the provided directory path, always
/// ending with '/'.
/// </summary>
public static string NormalizeDirectoryPath(string path) {
if (string.IsNullOrEmpty(path)) {
return null;
}
var uri = MakeUri(path, true, UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri) {
if (uri.IsFile) {
return uri.LocalPath;
} else {
return uri.AbsoluteUri.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
} else {
return Uri.UnescapeDataString(uri.ToString()).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
}
/// <summary>
/// Return true if both paths represent the same directory.
/// </summary>
public static bool IsSameDirectory(string path1, string path2) {
if (string.IsNullOrEmpty(path1)) {
return string.IsNullOrEmpty(path2);
} else if (string.IsNullOrEmpty(path2)) {
return false;
}
if (String.Equals(path1, path2, StringComparison.Ordinal)) {
// Quick return, but will only work where the paths are already normalized and
// have matching case.
return true;
}
Uri uri1, uri2;
return
TryMakeUri(path1, true, UriKind.Absolute, out uri1) &&
TryMakeUri(path2, true, UriKind.Absolute, out uri2) &&
uri1 == uri2;
}
/// <summary>
/// Return true if both paths represent the same location.
/// </summary>
public static bool IsSamePath(string file1, string file2) {
if (string.IsNullOrEmpty(file1)) {
return string.IsNullOrEmpty(file2);
} else if (string.IsNullOrEmpty(file2)) {
return false;
}
if (String.Equals(file1, file2, StringComparison.Ordinal)) {
// Quick return, but will only work where the paths are already normalized and
// have matching case.
return true;
}
Uri uri1, uri2;
return
TryMakeUri(file1, false, UriKind.Absolute, out uri1) &&
TryMakeUri(file2, false, UriKind.Absolute, out uri2) &&
uri1 == uri2;
}
/// <summary>
/// Return true if the path represents a file or directory contained in
/// root or a subdirectory of root.
/// </summary>
public static bool IsSubpathOf(string root, string path) {
if (HasEndSeparator(root) && !path.Contains("..") && path.StartsWith(root, StringComparison.Ordinal)) {
// Quick return, but only where the paths are already normalized and
// have matching case.
return true;
}
var uriRoot = MakeUri(root, true, UriKind.Absolute, "root");
var uriPath = MakeUri(path, false, UriKind.Absolute, "path");
if (uriRoot.Equals(uriPath) || uriRoot.IsBaseOf(uriPath)) {
return true;
}
// Special case where root and path are the same, but path was provided
// without a terminating separator.
var uriDirectoryPath = MakeUri(path, true, UriKind.Absolute, "path");
if (uriRoot.Equals(uriDirectoryPath)) {
return true;
}
return false;
}
/// <summary>
/// Returns a normalized directory path created by joining relativePath to root.
/// The result is guaranteed to end with a backslash.
/// </summary>
/// <exception cref="ArgumentException">root is not an absolute path, or
/// either path is invalid.</exception>
/// <exception cref="InvalidOperationException">An absolute path cannot be
/// created.</exception>
public static string GetAbsoluteDirectoryPath(string root, string relativePath) {
string absPath;
if (string.IsNullOrEmpty(relativePath)) {
return NormalizeDirectoryPath(root);
}
var relUri = MakeUri(relativePath, true, UriKind.RelativeOrAbsolute, "relativePath");
Uri absUri;
if (relUri.IsAbsoluteUri) {
absUri = relUri;
} else {
var rootUri = MakeUri(root, true, UriKind.Absolute, "root");
try {
absUri = new Uri(rootUri, relUri);
} catch (UriFormatException ex) {
throw new InvalidOperationException("Cannot create absolute path", ex);
}
}
absPath = absUri.IsFile ? absUri.LocalPath : absUri.AbsoluteUri;
if (!string.IsNullOrEmpty(absPath) && !HasEndSeparator(absPath)) {
absPath += absUri.IsFile ? Path.DirectorySeparatorChar : Path.AltDirectorySeparatorChar;
}
return absPath;
}
/// <summary>
/// Returns a normalized file path created by joining relativePath to root.
/// The result is not guaranteed to end with a backslash.
/// </summary>
/// <exception cref="ArgumentException">root is not an absolute path, or
/// either path is invalid.</exception>
public static string GetAbsoluteFilePath(string root, string relativePath) {
var rootUri = MakeUri(root, true, UriKind.Absolute, "root");
var relUri = MakeUri(relativePath, false, UriKind.RelativeOrAbsolute, "relativePath");
Uri absUri;
if (relUri.IsAbsoluteUri) {
absUri = relUri;
} else {
try {
absUri = new Uri(rootUri, relUri);
} catch (UriFormatException ex) {
throw new InvalidOperationException("Cannot create absolute path", ex);
}
}
return absUri.IsFile ? absUri.LocalPath : absUri.AbsoluteUri;
}
/// <summary>
/// Returns a relative path from the base path to the other path. This is
/// intended for serialization rather than UI. See CreateFriendlyDirectoryPath
/// for UI strings.
/// </summary>
/// <exception cref="ArgumentException">Either parameter was an invalid or a
/// relative path.</exception>
public static string GetRelativeDirectoryPath(string fromDirectory, string toDirectory) {
var fromUri = MakeUri(fromDirectory, true, UriKind.Absolute, "fromDirectory");
var toUri = MakeUri(toDirectory, true, UriKind.Absolute, "toDirectory");
string relPath;
var sep = toUri.IsFile ? Path.DirectorySeparatorChar : Path.AltDirectorySeparatorChar;
try {
var relUri = fromUri.MakeRelativeUri(toUri);
if (relUri.IsAbsoluteUri) {
relPath = relUri.IsFile ? relUri.LocalPath : relUri.AbsoluteUri;
} else {
relPath = Uri.UnescapeDataString(relUri.ToString());
}
} catch (InvalidOperationException ex) {
Trace.WriteLine(string.Format("Error finding path from {0} to {1}", fromUri, toUri));
Trace.WriteLine(ex);
relPath = toUri.IsFile ? toUri.LocalPath : toUri.AbsoluteUri;
}
if (!string.IsNullOrEmpty(relPath) && !HasEndSeparator(relPath)) {
relPath += Path.DirectorySeparatorChar;
}
if (toUri.IsFile) {
return relPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
} else {
return relPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
}
/// <summary>
/// Returns a relative path from the base path to the file. This is
/// intended for serialization rather than UI. See CreateFriendlyFilePath
/// for UI strings.
/// </summary>
public static string GetRelativeFilePath(string fromDirectory, string toFile) {
var fromUri = MakeUri(fromDirectory, true, UriKind.Absolute, "fromDirectory");
var toUri = MakeUri(toFile, false, UriKind.Absolute, "toFile");
string relPath;
var sep = toUri.IsFile ? Path.DirectorySeparatorChar : Path.AltDirectorySeparatorChar;
try {
var relUri = fromUri.MakeRelativeUri(toUri);
if (relUri.IsAbsoluteUri) {
relPath = relUri.IsFile ? relUri.LocalPath : relUri.AbsoluteUri;
} else {
relPath = Uri.UnescapeDataString(relUri.ToString());
}
} catch (InvalidOperationException ex) {
Trace.WriteLine(string.Format("Error finding path from {0} to {1}", fromUri, toUri));
Trace.WriteLine(ex);
relPath = toUri.IsFile ? toUri.LocalPath : toUri.AbsoluteUri;
}
if (toUri.IsFile) {
return relPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
} else {
return relPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
}
/// <summary>
/// Tries to create a friendly directory path: '.' if the same as base path,
/// relative path if short, absolute path otherwise.
/// </summary>
public static string CreateFriendlyDirectoryPath(string basePath, string path) {
var relativePath = GetRelativeDirectoryPath(basePath, path);
if (relativePath.Length > 1) {
relativePath = TrimEndSeparator(relativePath);
}
if (string.IsNullOrEmpty(relativePath)) {
relativePath = ".";
}
return relativePath;
}
/// <summary>
/// Tries to create a friendly file path.
/// </summary>
public static string CreateFriendlyFilePath(string basePath, string path) {
return GetRelativeFilePath(basePath, path);
}
/// <summary>
/// Returns the last directory segment of a path. The last segment is
/// assumed to be the string between the second-last and last directory
/// separator characters in the path. If there is no suitable substring,
/// the empty string is returned.
///
/// The first segment of the path is only returned if it does not
/// contain a colon. Segments equal to "." are ignored and the preceding
/// segment is used.
/// </summary>
/// <remarks>
/// This should be used in place of:
/// <c>Path.GetFileName(CommonUtils.TrimEndSeparator(Path.GetDirectoryName(path)))</c>
/// </remarks>
public static string GetLastDirectoryName(string path) {
if (string.IsNullOrEmpty(path)) {
return string.Empty;
}
int last = path.LastIndexOfAny(DirectorySeparators);
string result = string.Empty;
while (last > 1) {
int first = path.LastIndexOfAny(DirectorySeparators, last - 1);
if (first < 0) {
if (path.IndexOf(':') < last) {
// Don't want to return scheme/drive as a directory
return string.Empty;
}
first = -1;
}
if (first == 1 && path[0] == path[1]) {
// Don't return computer name in UNC path
return string.Empty;
}
result = path.Substring(first + 1, last - (first + 1));
if (!string.IsNullOrEmpty(result) && result != ".") {
// Result is valid
break;
}
last = first;
}
return result;
}
/// <summary>
/// Returns the path to the parent directory segment of a path. If the
/// last character of the path is a directory separator, the segment
/// prior to that character is removed. Otherwise, the segment following
/// the last directory separator is removed.
/// </summary>
/// <remarks>
/// This should be used in place of:
/// <c>Path.GetDirectoryName(CommonUtils.TrimEndSeparator(path)) + Path.DirectorySeparatorChar</c>
/// </remarks>
public static string GetParent(string path) {
if (string.IsNullOrEmpty(path)) {
return string.Empty;
}
int last = path.Length - 1;
if (DirectorySeparators.Contains(path[last])) {
last -= 1;
}
if (last <= 0) {
return string.Empty;
}
last = path.LastIndexOfAny(DirectorySeparators, last);
if (last < 0) {
return string.Empty;
}
return path.Remove(last + 1);
}
/// <summary>
/// Returns the last segment of the path. If the last character is a
/// directory separator, this will be the segment preceding the
/// separator. Otherwise, it will be the segment following the last
/// separator.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetFileOrDirectoryName(string path) {
if (string.IsNullOrEmpty(path)) {
return string.Empty;
}
int last = path.Length - 1;
if (DirectorySeparators.Contains(path[last])) {
last -= 1;
}
if (last < 0) {
return string.Empty;
}
int start = path.LastIndexOfAny(DirectorySeparators, last);
return path.Substring(start + 1, last - start);
}
/// <summary>
/// Returns true if the path has a directory separator character at the end.
/// </summary>
public static bool HasEndSeparator(string path) {
return !string.IsNullOrEmpty(path) && DirectorySeparators.Contains(path[path.Length - 1]);
}
/// <summary>
/// Removes up to one directory separator character from the end of path.
/// </summary>
public static string TrimEndSeparator(string path) {
if (HasEndSeparator(path)) {
if (path.Length > 2 && path[path.Length - 2] == ':') {
// The slash at the end of a drive specifier is not actually
// a separator.
return path;
} else if (path.Length > 3 && path[path.Length - 2] == path[path.Length - 1] && path[path.Length - 3] == ':') {
// The double slash at the end of a schema is not actually a
// separator.
return path;
}
return path.Remove(path.Length - 1);
} else {
return path;
}
}
/// <summary>
/// Adds a directory separator character to the end of path if required.
/// </summary>
public static string EnsureEndSeparator(string path) {
if (string.IsNullOrEmpty(path)) {
return string.Empty;
} else if (!HasEndSeparator(path)) {
return path + Path.DirectorySeparatorChar;
} else {
return path;
}
}
/// <summary>
/// Removes leading @"..\" segments from a path.
/// </summary>
private static string TrimUpPaths(string path) {
int actualStart = 0;
while (actualStart + 2 < path.Length) {
if (path[actualStart] == '.' && path[actualStart + 1] == '.' &&
(path[actualStart + 2] == Path.DirectorySeparatorChar || path[actualStart + 2] == Path.AltDirectorySeparatorChar)) {
actualStart += 3;
} else {
break;
}
}
return (actualStart > 0) ? path.Substring(actualStart) : path;
}
/// <summary>
/// Returns true if the path is a valid path, regardless of whether the
/// file exists or not.
/// </summary>
public static bool IsValidPath(string path) {
return !string.IsNullOrEmpty(path) &&
path.IndexOfAny(InvalidPathChars) < 0;
}
/// <summary>
/// Recursively searches for a file using breadth-first-search. This
/// ensures that the result closest to <paramref name="root"/> is
/// returned first.
/// </summary>
/// <param name="root">
/// Directory to start searching.
/// </param>
/// <param name="file">
/// Filename to find. Wildcards are not supported.
/// </param>
/// <param name="depthLimit">
/// The number of subdirectories to search in.
/// </param>
/// <param name="firstCheck">
/// A sequence of subdirectories to prioritize.
/// </param>
/// <returns>
/// The path to the file if found, including <paramref name="root"/>;
/// otherwise, null.
/// </returns>
public static string FindFile(
string root,
string file,
int depthLimit = 2,
IEnumerable<string> firstCheck = null
) {
var candidate = Path.Combine(root, file);
if (File.Exists(candidate)) {
return candidate;
}
if (firstCheck != null) {
foreach (var subPath in firstCheck) {
candidate = Path.Combine(root, subPath, file);
if (File.Exists(candidate)) {
return candidate;
}
}
}
// Do a BFS of the filesystem to ensure we find the match closest to
// the root directory.
var dirQueue = new Queue<string>();
dirQueue.Enqueue(root);
dirQueue.Enqueue("<EOD>");
while (dirQueue.Any()) {
var dir = dirQueue.Dequeue();
if (dir == "<EOD>") {
depthLimit -= 1;
if (depthLimit <= 0) {
return null;
}
continue;
}
var result = Directory.EnumerateFiles(dir, file, SearchOption.TopDirectoryOnly).FirstOrDefault();
if (result != null) {
return result;
}
foreach (var subDir in Directory.EnumerateDirectories(dir)) {
dirQueue.Enqueue(subDir);
}
dirQueue.Enqueue("<EOD>");
}
return null;
}
/// <summary>
/// Gets a filename in the specified location with the specified name and extension.
/// If the file already exist it will calculate a name with a number in it.
/// </summary>
public static string GetAvailableFilename(string location, string basename, string extension) {
var newPath = Path.Combine(location, basename);
int index = 0;
if (File.Exists(newPath + extension)) {
string candidateNewPath;
do {
candidateNewPath = string.Format("{0}{1}", newPath, ++index);
} while (File.Exists(candidateNewPath + extension));
newPath = candidateNewPath;
}
string final = newPath + extension;
return final;
}
}
}
| 40.410866 | 137 | 0.524704 | [
"Apache-2.0"
] | mousetraps/xtvs-common | Product/SharedProject/CommonUtils.cs | 23,804 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace LumiSoft.Net.UPnP.Client
{
/// <summary>
/// This class implements UPnP client.
/// </summary>
public class UPnP_Client
{
/// <summary>
/// Defaultc onstructor.
/// </summary>
public UPnP_Client()
{
}
#region method Search
/// <summary>
/// Searches the network for UPnP root devices.
/// </summary>
/// <param name="timeout">Search wait timeout in milliseconds.</param>
/// <returns>Returns matched UPnP devices.</returns>
public UPnP_Device[] Search(int timeout)
{
return Search("upnp:rootdevice",timeout);
}
/// <summary>
/// Searches the network for UPnP devices.
/// </summary>
/// <param name="deviceType">UPnP device type. For example: "urn:schemas-upnp-org:device:InternetGatewayDevice:1".</param>
/// <param name="timeout">Search wait timeout in milliseconds.</param>
/// <returns>Returns matched UPnP devices.</returns>
public UPnP_Device[] Search(string deviceType,int timeout)
{
if(timeout < 1){
timeout = 1;
}
/* www.unpnp.org. Search request with M-SEARCH.
When a control point desires to search the network for devices, it MUST send a multicast request with method M-SEARCH in the
following format. Control points that know the address of a specific device MAY also use a similar format to send unicast requests
with method M-SEARCH.
For multicast M-SEARCH, the message format is defined below. Values in italics are placeholders for actual values.
M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1900
MAN: "ssdp:discover"
MX: seconds to delay response
ST: search target
USER-AGENT: OS/version UPnP/1.1 product/version
Note: No body is present in requests with method M-SEARCH, but note that the message MUST have a blank line following the
last header field.
Note: The TTL for the IP packet SHOULD default to 2 and SHOULD be configurable.
Listed below are details for the request line and header fields appearing in the listing above. Field names are not case sensitive.
All field values are case sensitive except where noted.
Request line
Must be “M-SEARCH * HTTP/1.1”
M-SEARCH
Method for search requests.
*
Request applies generally and not to a specific resource. MUST be *.
HTTP/1.1
HTTP version.
Header fields
HOST
REQUIRED. Field value contains the multicast address and port reserved for SSDP by Internet Assigned Numbers Authority
(IANA). MUST be 239.255.255.250:1900.
MAN
REQUIRED by HTTP Extension Framework. Unlike the NTS and ST field values, the field value of the MAN header field is
enclosed in double quotes; it defines the scope (namespace) of the extension. MUST be "ssdp:discover".
MX
REQUIRED. Field value contains maximum wait time in seconds. MUST be greater than or equal to 1 and SHOULD be less than
5 inclusive. Device responses SHOULD be delayed a random duration between 0 and this many seconds to balance load for
the control point when it processes responses. This value MAY be increased if a large number of devices are expected to
respond. The MX field value SHOULD NOT be increased to accommodate network characteristics such as latency or
propagation delay (for more details, see the explanation below). Specified by UPnP vendor. Integer.
ST
REQUIRED. Field value contains Search Target. MUST be one of the following. (See NT header field in NOTIFY with ssdp:alive
above.) Single URI.
ssdp:all
Search for all devices and services.
upnp:rootdevice
Search for root devices only.
uuid:device-UUID
Search for a particular device. device-UUID specified by UPnP vendor. See section 1.1.4, “UUID format and
RECOMMENDED generation algorithms” for the MANDATORY UUID format.
urn:schemas-upnp-org:device:deviceType:ver
Search for any device of this type where deviceType and ver are defined by the UPnP Forum working committee.
urn:schemas-upnp-org:service:serviceType:ver
Search for any service of this type where serviceType and ver are defined by the UPnP Forum working committee.
urn:domain-name:device:deviceType:ver
Search for any device of this typewhere domain-name (a Vendor Domain Name), deviceType and ver are defined
by the UPnP vendor and ver specifies the highest specifies the highest supported version of the device type.
Period characters in the Vendor Domain Name MUST be replaced with hyphens in accordance with RFC 2141.
urn:domain-name:service:serviceType:ver
Search for any service of this type. Where domain-name (a Vendor Domain Name), serviceType and ver are
defined by the UPnP vendor and ver specifies the highest specifies the highest supported version of the service
type. Period characters in the Vendor Domain Name MUST be replaced with hyphens in accordance with RFC 2141.
USER-AGENT
OPTIONAL. Specified by UPnP vendor. String. Field value MUST begin with the following “product tokens” (defined by
HTTP/1.1). The first product token identifes the operating system in the form OS name/OS version, the second token
represents the UPnP version and MUST be UPnP/1.1, and the third token identifes the product using the form
product name/product version. For example, “USER-AGENT: unix/5.1 UPnP/1.1 MyProduct/1.0”. Control points MUST be
prepared to accept a higher minor version number of the UPnP version than the control point itself implements. For
example, control points implementing UDA version 1.0 will be able to interoperate with devices implementing
UDA version 1.1.
*/
StringBuilder query = new StringBuilder();
query.Append("M-SEARCH * HTTP/1.1\r\n");
query.Append("HOST: 239.255.255.250:1900\r\n");
query.Append("MAN: \"ssdp:discover\"\r\n");
query.Append("MX: 1\r\n");
query.Append("ST: " + deviceType + "\r\n");
query.Append("\r\n");
using(Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp)){
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast,1);
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.IpTimeToLive,2);
socket.SendTo(Encoding.UTF8.GetBytes(query.ToString()),new IPEndPoint(IPAddress.Broadcast,1900));
List<string> deviceLocations = new List<string>();
byte[] buffer = new byte[32000];
DateTime startTime = DateTime.Now;
// Receive responses while timeout reached.
while(startTime.AddMilliseconds(timeout) > DateTime.Now){
// We have response, read it.
if(socket.Poll(1,SelectMode.SelectRead)){
int countReceived = socket.Receive(buffer);
string[] responseLines = Encoding.UTF8.GetString(buffer,0,countReceived).Split('\n');
foreach(string responseLine in responseLines){
string[] name_value = responseLine.Split(new char[]{':'},2);
if(string.Equals(name_value[0],"location",StringComparison.InvariantCultureIgnoreCase)){
deviceLocations.Add(name_value[1].Trim());
}
}
}
}
// Create devices.
List<UPnP_Device> devices = new List<UPnP_Device>();
foreach(string location in deviceLocations){
try{
devices.Add(new UPnP_Device(location));
}
catch{
}
}
return devices.ToArray();
}
}
/// <summary>
/// Searches the network for UPnP devices.
/// </summary>
/// <param name="ip">IP address of UPnP device.</param>
/// <param name="deviceType">UPnP device type. For example: "urn:schemas-upnp-org:device:InternetGatewayDevice:1".</param>
/// <param name="timeout">Search wait timeout in milliseconds.</param>
/// <returns>Returns matched UPnP devices.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception>
public UPnP_Device[] Search(IPAddress ip,string deviceType,int timeout)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
if(timeout < 1){
timeout = 1;
}
using(Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp)){
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.IpTimeToLive,2);
StringBuilder query = new StringBuilder();
query.Append("M-SEARCH * HTTP/1.1\r\n");
query.Append("MAN: \"ssdp:discover\"\r\n");
query.Append("MX: 1\r\n");
query.Append("ST: " + deviceType + "\r\n");
query.Append("\r\n");
socket.SendTo(Encoding.UTF8.GetBytes(query.ToString()),new IPEndPoint(ip,1900));
List<string> deviceLocations = new List<string>();
byte[] buffer = new byte[32000];
DateTime startTime = DateTime.Now;
// Receive responses while timeout reached.
while(startTime.AddMilliseconds(timeout) > DateTime.Now){
// We have response, read it.
if(socket.Poll(1,SelectMode.SelectRead)){
int countReceived = socket.Receive(buffer);
string[] responseLines = Encoding.UTF8.GetString(buffer,0,countReceived).Split('\n');
foreach(string responseLine in responseLines){
string[] name_value = responseLine.Split(new char[]{':'},2);
if(string.Equals(name_value[0],"location",StringComparison.InvariantCultureIgnoreCase)){
deviceLocations.Add(name_value[1].Trim());
}
}
}
}
// Create devices.
List<UPnP_Device> devices = new List<UPnP_Device>();
foreach(string location in deviceLocations){
try{
devices.Add(new UPnP_Device(location));
}
catch{
}
}
return devices.ToArray();
}
}
#endregion
}
}
| 51.299595 | 151 | 0.54163 | [
"MIT"
] | bhuebschen/feuerwehrcloud-deiva | Mail/Net/UPnP/Client/UPnP_Client.cs | 12,689 | C# |
/*
Copyright (C) 2018-2019 de4dot@gmail.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.
*/
using System.IO;
using Generator.Enums;
using Generator.IO;
namespace Generator.Tables.CSharp {
[Generator(TargetLanguage.CSharp, GeneratorNames.Dictionaries)]
sealed class CSharpDictGenerator {
readonly IdentifierConverter idConverter;
readonly GeneratorOptions generatorOptions;
public CSharpDictGenerator(GeneratorOptions generatorOptions) {
idConverter = CSharpIdentifierConverter.Create();
this.generatorOptions = generatorOptions;
}
public void Generate() {
new FileUpdater(TargetLanguage.CSharp, "Dicts", Path.Combine(generatorOptions.CSharpTestsDir, "Intel", "InstructionInfoTests", "InstructionInfoConstants.cs")).Generate(writer => {
WriteDict(writer, InstrInfoDictConstants.OpAccessConstants, "ToAccess");
WriteDict(writer, InstrInfoDictConstants.MemorySizeFlagsTable, "MemorySizeFlagsTable");
WriteDict(writer, InstrInfoDictConstants.RegisterFlagsTable, "RegisterFlagsTable");
});
new FileUpdater(TargetLanguage.CSharp, "Dicts", Path.Combine(generatorOptions.CSharpTestsDir, "Intel", "EncoderTests", "OpCodeInfoConstants.cs")).Generate(writer => {
WriteDict(writer, EncoderConstants.EncodingKindTable, "ToEncodingKind");
WriteDict(writer, EncoderConstants.MandatoryPrefixTable, "ToMandatoryPrefix");
WriteDict(writer, EncoderConstants.OpCodeTableKindTable, "ToOpCodeTableKind");
});
new FileUpdater(TargetLanguage.CSharp, "Dicts", Path.Combine(generatorOptions.CSharpTestsDir, "Intel", "FormatterTests", "Masm", "SymbolOptionsTests.cs")).Generate(writer => {
WriteDict(writer, MasmSymbolOptionsConstants.SymbolTestFlagsTable, "ToSymbolTestFlags");
});
new FileUpdater(TargetLanguage.CSharp, "Dicts", Path.Combine(generatorOptions.CSharpTestsDir, "Intel", "FormatterTests", "MnemonicOptionsTestsReader.cs")).Generate(writer => {
WriteDict(writer, FormatMnemonicOptionsConstants.FormatMnemonicOptionsTable, "ToFormatMnemonicOptions");
});
new FileUpdater(TargetLanguage.CSharp, "Dicts", Path.Combine(generatorOptions.CSharpTestsDir, "Intel", "FormatterTests", "SymbolResolverTestsReader.cs")).Generate(writer => {
WriteDict(writer, SymbolFlagsConstants.SymbolFlagsTable, "ToSymbolFlags");
});
}
void WriteDict(FileWriter writer, (string name, EnumValue value)[] constants, string fieldName) {
var declTypeStr = constants[0].value.DeclaringType.Name(idConverter);
writer.WriteLine($"internal static readonly Dictionary<string, {declTypeStr}> {fieldName} = new Dictionary<string, {declTypeStr}>(StringComparer.Ordinal) {{");
using (writer.Indent()) {
foreach (var constant in constants)
writer.WriteLine($"{{ \"{constant.name}\", {declTypeStr}.{constant.value.Name(idConverter)} }},");
}
writer.WriteLine("};");
}
}
}
| 53.013889 | 182 | 0.780194 | [
"MIT"
] | NIKJOO/iced | src/csharp/Intel/Generator/Tables/CSharp/CSharpDictGenerator.cs | 3,817 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StructuredXmlEditor.Definition;
using StructuredXmlEditor.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;
namespace StructuredXmlEditor.Data
{
public class XmlDataModel : NotifyPropertyChanged
{
//-----------------------------------------------------------------------
public Workspace Workspace { get; set; }
//-----------------------------------------------------------------------
public Document Document { get; set; }
//-----------------------------------------------------------------------
public UndoRedoManager UndoRedo { get; set; }
//-----------------------------------------------------------------------
public XmlDataModel(Workspace workspace, Document document, UndoRedoManager undoRedo)
{
this.Document = document;
this.Workspace = workspace;
this.UndoRedo = undoRedo;
m_proxyRootItem = new DummyItem(" ⌂ ", this);
GraphNodeItems = new ObservableCollection<GraphNodeItem>();
RootItems = new ObservableCollection<DataItem>();
GraphCommentItems.CollectionChanged += (obj, args) =>
{
RaisePropertyChangedEvent("GraphComments");
};
}
//-----------------------------------------------------------------------
public bool IsJson { get { return RootItems[0].Definition.DataType == "json"; } }
public bool IsYaml { get { return RootItems[0].Definition.DataType == "yaml"; } }
//-----------------------------------------------------------------------
public string Extension { get { return RootItems[0].Definition.Extension; } }
//-----------------------------------------------------------------------
public Command<object> FocusCMD { get { return new Command<object>((e) => FocusItem((DataItem)e)); } }
//-----------------------------------------------------------------------
public Command<object> ClearFilterCMD { get { return new Command<object>((e) => ClearFilter(null, null)); } }
//-----------------------------------------------------------------------
public bool IsFocusing
{
get
{
return m_isFocusing;
}
set
{
m_isFocusing = value;
RaisePropertyChangedEvent("IsFocusing");
RaisePropertyChangedEvent("FocusedItemPath");
RaisePropertyChangedEvent("DisplayAsTabs");
}
}
//-----------------------------------------------------------------------
public ObservableCollection<DataItem> FocusedItemPath
{
get { return m_focusedItemsPath; }
}
//-----------------------------------------------------------------------
public ObservableCollection<GraphNodeItem> GraphNodeItems
{
get { return m_graphNodeItems; }
private set
{
m_graphNodeItems = value;
value.CollectionChanged += (e, args) => { RaisePropertyChangedEvent("GraphNodes"); };
}
}
private ObservableCollection<GraphNodeItem> m_graphNodeItems;
//-----------------------------------------------------------------------
private GraphNodeDefinition GraphNodeDefinition
{
get
{
return m_storedRootItems.FirstOrDefault(e => e is GraphNodeItem)?.Definition as GraphNodeDefinition;
}
}
//-----------------------------------------------------------------------
public bool AllowCircularLinks { get { return GraphNodeDefinition?.AllowCircularLinks ?? false; } }
public bool AllowReferenceLinks { get { return GraphNodeDefinition?.AllowReferenceLinks ?? false; } }
public bool FlattenData { get { return GraphNodeDefinition?.FlattenData ?? false; } }
public bool ShowLinkTypeMenu { get { return AllowReferenceLinks && !FlattenData; } }
//-----------------------------------------------------------------------
public ObservableCollection<DataItem> RootItems
{
get { return m_rootItems; }
set
{
if (m_rootItems != null)
{
m_rootItems.CollectionChanged -= RootItemCollectionChanged;
}
m_rootItems = value;
RaisePropertyChangedEvent("RootItems");
if (m_rootItems != null)
{
m_rootItems.CollectionChanged += RootItemCollectionChanged;
}
UpdateEditorType();
}
}
//-----------------------------------------------------------------------
private void RootItemCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
UpdateEditorType();
}
//-----------------------------------------------------------------------
private void UpdateEditorType()
{
ShowAsGraph = false;
ShowAsDataModel = false;
ShowAsSkeletalEditor = false;
if (RootItems.All(e => e is GraphNodeItem))
{
ShowAsGraph = true;
}
else if (RootItems.All(e => e is SkeletalAnimationItem))
{
ShowAsSkeletalEditor = true;
Selected = RootItems[0];
}
else
{
ShowAsDataModel = true;
}
RaisePropertyChangedEvent("ShowAsGraph");
RaisePropertyChangedEvent("ShowAsDataModel");
RaisePropertyChangedEvent("ShowAsSkeletalEditor");
}
//-----------------------------------------------------------------------
public object Selected
{
get { return m_selected; }
set
{
if (m_selected != value)
{
if (m_selected is List<DataItem>)
{
var list = m_selected as List<DataItem>;
var item = list[0];
if (item.IsMultiediting)
{
item.ClearMultiEdit();
}
}
if (value == null)
{
m_selectedDataItems.Clear();
}
m_selected = value;
if (m_selected is List<DataItem>)
{
var list = m_selected as List<DataItem>;
if (list.Count > 1)
{
var firstCopy = list[0].DuplicateData(new UndoRedoManager());
firstCopy.IsExpanded = true;
var otherChildren = new List<DataItem>();
for (int i = 0; i < list.Count; i++)
{
otherChildren.Add(list[i]);
}
firstCopy.MultiEdit(otherChildren, otherChildren.Count);
m_selected = new List<DataItem>() { firstCopy };
}
else
{
list[0].IsExpanded = true;
m_selected = new List<DataItem>() { list[0] };
}
}
RaisePropertyChangedEvent();
RaisePropertyChangedEvent("SelectedItems");
RaisePropertyChangedEvent("IsSelectedDataItem");
RaisePropertyChangedEvent("IsSelectedAsciiGrid");
RaisePropertyChangedEvent("IsSelectedSkeletalAnimation");
}
}
}
private object m_selected;
private List<DataItem> m_selectedDataItems = new List<DataItem>();
//-----------------------------------------------------------------------
public void AddSelected(DataItem item)
{
if (!m_selectedDataItems.Contains(item))
{
m_selectedDataItems.Add(item);
}
foreach (var i in m_selectedDataItems.ToList())
{
if (i.GetType() != item.GetType())
{
i.IsSelected = false;
}
}
Selected = m_selectedDataItems;
}
//-----------------------------------------------------------------------
public void RemoveSelected(DataItem item)
{
m_selectedDataItems.Remove(item);
if (m_selectedDataItems.Count > 0)
{
Selected = m_selectedDataItems;
}
else
{
Selected = null;
}
}
//-----------------------------------------------------------------------
public List<DataItem> SelectedItems
{
get { return Selected as List<DataItem>; }
}
//-----------------------------------------------------------------------
public bool IsSelectedDataItem { get { return SelectedItems != null; } }
public bool IsSelectedAsciiGrid { get { return Selected is MultilineStringItem; } }
public bool IsSelectedSkeletalAnimation { get { return Selected is SkeletalAnimationItem; } }
//-----------------------------------------------------------------------
public IEnumerable<GraphNode> GraphNodes
{
get
{
foreach (var item in GraphNodeItems.ToList())
{
if (item.DataModel != this)
{
foreach (var i in item.Descendants)
{
i.DataModel = this;
}
}
yield return item.GraphNode;
}
}
}
//-----------------------------------------------------------------------
public IEnumerable<GraphComment> GraphComments
{
get
{
foreach (var item in GraphCommentItems.ToList())
{
yield return item.GraphComment;
}
}
}
//-----------------------------------------------------------------------
public DeferableObservableCollection<GraphCommentItem> GraphCommentItems { get; set; } = new DeferableObservableCollection<GraphCommentItem>();
//-----------------------------------------------------------------------
public IEnumerable<DataItem> Descendants
{
get
{
foreach (var child in RootItems)
{
yield return child;
foreach (var item in child.Descendants)
{
yield return item;
}
}
}
}
//-----------------------------------------------------------------------
public bool ShowAsDataModel { get; set; } = true;
public bool ShowAsGraph { get; set; }
public bool ShowAsSkeletalEditor { get; set; }
//##############################################################################################################
#region Filter
//-----------------------------------------------------------------------
public bool CaseSensitiveFilter
{
get { return m_caseSensitive; }
set
{
m_caseSensitive = value;
ApplyFilter();
RaisePropertyChangedEvent();
}
}
//-----------------------------------------------------------------------
public bool ShowMatchElementsOnly
{
get { return m_showMatchesOnly; }
set
{
m_showMatchesOnly = value;
ApplyFilter();
RaisePropertyChangedEvent();
}
}
//-----------------------------------------------------------------------
public bool UseRegex
{
get { return m_useRegex; }
set
{
m_useRegex = value;
ApplyFilter();
RaisePropertyChangedEvent();
}
}
//-----------------------------------------------------------------------
public string Filter
{
get { return m_filter; }
set
{
OnFilterChanged(m_filter, value);
RaisePropertyChangedEvent();
}
}
//-----------------------------------------------------------------------
void OnFilterChanged(string oldValue, string newValue)
{
m_filter = newValue;
if (string.IsNullOrEmpty(oldValue))
{
m_lastNullFilterState.Clear();
foreach (var i in RootItems)
{
foreach (var j in i.ActiveDescendants())
{
m_lastNullFilterState[j] = j.IsExpanded;
}
}
}
ApplyFilter();
}
//-----------------------------------------------------------------------
private void ApplyFilter()
{
try
{
if (!string.IsNullOrEmpty(Filter))
{
string filter = CaseSensitiveFilter ? Filter : Filter.ToLower();
Regex regex = UseRegex ? new Regex(filter) : null;
foreach (DataItem item in RootItems)
{
item.Filter(filter, regex, CaseSensitiveFilter, ShowMatchElementsOnly);
}
foreach (var node in GraphNodeItems)
{
node.Filter(filter, regex, CaseSensitiveFilter, ShowMatchElementsOnly);
}
}
else
{
foreach (DataItem item in RootItems)
{
item.Filter(null, null, false, false);
}
foreach (var node in GraphNodeItems)
{
node.Filter(null, null, false, false);
}
}
if (string.IsNullOrEmpty(Filter))
{
foreach (var i in m_lastNullFilterState)
{
i.Key.IsExpanded = i.Value;
}
}
}
catch (Exception) { }
}
#endregion Filter
//##############################################################################################################
//-----------------------------------------------------------------------
public void FocusItem(DataItem item)
{
if (item == m_proxyRootItem)
{
m_focusedItemsPath.Clear();
RootItems.Clear();
foreach (var child in m_storedRootItems)
{
RootItems.Add(child);
}
}
else if (RootItems.Contains(item))
{
return;
}
else
{
item.Focus();
m_focusedItemsPath.Clear();
DataItem current = null;
if (item is GraphNodeItem)
{
current = (item as GraphNodeItem).LinkParents.FirstOrDefault();
}
else
{
current = item.Parent;
}
while (current != null)
{
if (current is CollectionChildItem || current is GraphNodeItem || !(current.Parent is CollectionChildItem)) m_focusedItemsPath.Add(current);
if (current is GraphNodeItem)
{
current = (current as GraphNodeItem).LinkParents.FirstOrDefault();
}
else
{
current = current.Parent;
}
}
m_focusedItemsPath.Remove(m_focusedItemsPath.Last());
m_focusedItemsPath.Add(m_proxyRootItem);
for (int i = 0; i < m_focusedItemsPath.Count; i++)
{
m_focusedItemsPath[i].ZIndex = i;
m_focusedItemsPath[i].FirstItem = Visibility.Visible;
}
for (int i = 0; i < m_focusedItemsPath.Count; i++)
{
m_focusedItemsPath.Move(m_focusedItemsPath.Count - 1, i);
}
m_focusedItemsPath[0].FirstItem = Visibility.Hidden;
RootItems.Clear();
RootItems.Add(item);
item.IsExpanded = true;
if (m_lastFocusedItem != null)
{
if (m_lastFocusedItem is CollectionItem)
{
CollectionItem collectionItem = m_lastFocusedItem as CollectionItem;
//collectionItem.IsFocused = false;
}
}
m_lastFocusedItem = item;
if (m_lastFocusedItem != null)
{
if (m_lastFocusedItem is CollectionItem)
{
CollectionItem collectionItem = m_lastFocusedItem as CollectionItem;
//collectionItem.IsFocused = true;
}
}
}
IsFocusing = m_focusedItemsPath.Count > 0;
RaisePropertyChangedEvent("RootItems");
}
//-----------------------------------------------------------------------
private void ClearFilter(object sender, ExecutedRoutedEventArgs e)
{
Filter = null;
}
//-----------------------------------------------------------------------
public void SetRootItem(DataItem item)
{
RootItems.Clear();
RootItems.Add(item);
m_storedRootItems.Add(item);
GraphNodeItems.Clear();
foreach (var i in Descendants)
{
i.DataModel = this;
if (item is GraphNodeItem && !GraphNodeItems.Contains(item))
{
if (!GraphNodeItems.Contains(item as GraphNodeItem)) GraphNodeItems.Add(item as GraphNodeItem);
}
}
UpdateEditorType();
}
//-----------------------------------------------------------------------
public void Save(string path)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
XDocument doc = new XDocument();
XElement fakeRoot = new XElement("FAKE_ROOT");
foreach (var item in m_storedRootItems)
{
item.Definition.SaveData(fakeRoot, item, true);
}
foreach (var el in fakeRoot.Elements())
{
doc.Add(el);
}
if (doc.Elements().Count() == 0) return;
doc.Elements().First().SetAttributeValue(XNamespace.Xmlns + "meta", DataDefinition.MetaNS);
var saveableComments = GraphCommentItems.Where(e => e.Nodes.Count > 0).ToList();
if (saveableComments.Count > 0)
{
var commentStr = string.Join("%", saveableComments.Select(e => e.GUID + "$" + e.Title + "$" + e.ToolTip + "$" + e.Colour.ToCSV()));
doc.Elements().First().SetAttributeValue(DataDefinition.MetaNS + "GraphCommentData", commentStr);
}
if (FlattenData)
{
var nodeEl = new XElement(GraphNodeDefinition.NodeStoreName);
if (IsJson || IsYaml)
{
nodeEl.SetAttributeValue(XNamespace.Xmlns + "json", DataDefinition.JsonNS);
nodeEl.SetAttributeValue(DataDefinition.JsonNS + "Array", "true");
}
foreach (var node in GraphNodeItems)
{
if (m_storedRootItems.Contains(node) || node.LinkParents.Count == 0) continue;
node.Definition.SaveData(nodeEl, node);
}
doc.Elements().First().Add(nodeEl);
}
if (IsYaml)
{
string json = JsonConvert.SerializeXNode(doc, Newtonsoft.Json.Formatting.Indented);
var data = ConvertJTokenToObject(JsonConvert.DeserializeObject<JToken>(json)); ;
var serializer = new YamlDotNet.Serialization.Serializer();
using (var writer = new StringWriter())
{
serializer.Serialize(writer, data);
var yaml = writer.ToString();
File.WriteAllText(path, yaml);
}
}
else if (IsJson)
{
string json = JsonConvert.SerializeXNode(doc, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(path, json);
}
else
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = "\t",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace,
OmitXmlDeclaration = true,
Encoding = new UTF8Encoding(false)
};
using (XmlWriter writer = XmlTextWriter.Create(path, settings))
{
doc.Save(writer);
}
}
}
//-----------------------------------------------------------------------
static object ConvertJTokenToObject(JToken token)
{
if (token is JValue)
return ((JValue)token).Value;
if (token is JArray)
return token.AsEnumerable().Select(ConvertJTokenToObject).ToList();
if (token is JObject)
return token.AsEnumerable().Cast<JProperty>().ToDictionary(x => x.Name, x => ConvertJTokenToObject(x.Value));
throw new InvalidOperationException("Unexpected token: " + token);
}
bool m_caseSensitive = false;
bool m_useRegex = false;
bool m_showMatchesOnly = true;
string m_filter;
bool m_isFocusing = true;
DataItem m_lastFocusedItem;
DataItem m_proxyRootItem;
List<DataItem> m_storedRootItems = new List<DataItem>();
ObservableCollection<DataItem> m_rootItems;
ObservableCollection<DataItem> m_focusedItemsPath = new ObservableCollection<DataItem>();
Dictionary<DataItem, bool> m_lastNullFilterState = new Dictionary<DataItem, bool>();
}
//-----------------------------------------------------------------------
public class GraphCommentItem : NotifyPropertyChanged
{
//-----------------------------------------------------------------------
public string GUID { get; set; }
//-----------------------------------------------------------------------
public string Title
{
get
{
return ((StringItem)Item.Children[0]).Value;
}
set
{
((StringItem)Item.Children[0]).Value = value;
}
}
//-----------------------------------------------------------------------
public string ToolTip { get; set; }
//-----------------------------------------------------------------------
public Color Colour
{
get
{
var col = ((ColourItem)Item.Children[1]).Value;
if (col.HasValue) return col.Value;
else return Colors.White;
}
set
{
((ColourItem)Item.Children[1]).Value = value;
}
}
//-----------------------------------------------------------------------
public SolidColorBrush ColourBrush
{
get
{
if (brush != null && Colour == brush.Color)
{
return brush;
}
brush = new SolidColorBrush(Colour);
brush.Freeze();
return brush;
}
}
private SolidColorBrush brush;
//-----------------------------------------------------------------------
public DeferableObservableCollection<GraphNodeItem> Nodes { get; set; } = new DeferableObservableCollection<GraphNodeItem>();
//-----------------------------------------------------------------------
public GraphComment GraphComment
{
get
{
if (m_comment == null)
{
m_comment = new GraphComment(this);
}
return m_comment;
}
}
private GraphComment m_comment;
//-----------------------------------------------------------------------
public DataItem Item { get; set; }
public XmlDataModel Model { get; set; }
//-----------------------------------------------------------------------
public GraphCommentItem(XmlDataModel dataModel, UndoRedoManager undoRedo, string title, Color colour)
{
this.Model = dataModel;
var def = dataModel.Workspace.RootDataTypes["graphcomment"];
using (undoRedo.DisableUndoScope())
{
Item = def.CreateData(undoRedo);
}
Item.ChildPropertyChangedEvent += (e, args) =>
{
RaisePropertyChangedEvent("Title");
RaisePropertyChangedEvent("Colour");
RaisePropertyChangedEvent("ColourBrush");
};
using (undoRedo.DisableUndoScope())
{
Title = title;
Colour = colour;
}
}
//-----------------------------------------------------------------------
public static List<GraphCommentItem> ParseGraphComments(XmlDataModel model, UndoRedoManager undoRedo, string commentChain)
{
var output = new List<GraphCommentItem>();
var comments = commentChain.Split('%');
foreach (var commentString in comments)
{
var split = commentString.Split('$');
var comment = new GraphCommentItem(model, undoRedo, split[1], split[3].ToColour().Value);
comment.GUID = split[0];
output.Add(comment);
}
return output;
}
}
}
| 26.342466 | 145 | 0.542334 | [
"Apache-2.0"
] | moggabor/StructuredXmlEditor | StructuredXmlEditor/Data/XmlDataModel.cs | 21,157 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicRepeater : MonoBehaviour {
/* A very gnarly, hard-coded way to loop a piece after a certain intro period
* Could be expanded by doing calculations based on BPM of intro (as long as it was constant),
* # of beats in intro.
*
* Although this is actually inferior to just recording the intro and the looping section separately,
* then just delaying the play of the looping section until after the intro. I already have this
* started so I'm going to finish it, but lesson learned...
*/
AudioSource audioSource;
int lastTimeSample = 0;
int thisTimeSample = 0;
// Use this for initialization
void Start () {
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
lastTimeSample = thisTimeSample;
thisTimeSample = audioSource.timeSamples;
// Using this and last sample count to create a very small buffer to help avoid a single-frame gap in audio
if (audioSource.timeSamples >= 2944000 - (thisTimeSample -lastTimeSample))
{
audioSource.timeSamples = 384000;
audioSource.Play();
thisTimeSample = 384000;
}
}
}
| 30.674419 | 115 | 0.66793 | [
"Unlicense"
] | GamesByMoonlight/HeartHome | Assets/Scripts/MusicRepeater.cs | 1,321 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace RubiksCube
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} | 22.904762 | 65 | 0.600832 | [
"MIT"
] | davedissian/archive | comp4-rubikscube/RubiksCube/Program.cs | 483 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Permissions;
namespace System.Diagnostics
{
#if NET5_0_OR_GREATER
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
public sealed class EventLogPermission : ResourcePermissionBase
{
public EventLogPermission() { }
public EventLogPermission(EventLogPermissionAccess permissionAccess, string machineName) { }
public EventLogPermission(EventLogPermissionEntry[] permissionAccessEntries) { }
public EventLogPermission(PermissionState state) { }
public EventLogPermissionEntryCollection PermissionEntries { get; }
}
}
| 41.55 | 147 | 0.777377 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Security.Permissions/src/System/Diagnostics/EventLogPermission.cs | 831 | C# |
using Stl.RegisterAttributes;
namespace Stl.Tests.CommandR.Services;
[RegisterService, RegisterCommandHandlers]
public class LogCommandHandler : ServiceBase, ICommandHandler<LogCommand>
{
public LogCommandHandler(IServiceProvider services) : base(services) { }
public Task OnCommand(
LogCommand command, CommandContext context,
CancellationToken cancellationToken)
{
var handler = context.ExecutionState.Handlers[^1];
handler.GetType().Should().Be(typeof(InterfaceCommandHandler<LogCommand>));
handler.Priority.Should().Be(0);
Log.LogInformation("{Message}", command.Message);
return Task.CompletedTask;
}
}
| 31.090909 | 83 | 0.726608 | [
"MIT"
] | ScriptBox21/Stl.Fusion | tests/Stl.Tests/CommandR/Services/LogCommandHandler.cs | 684 | C# |
/*
* Copyright 2019 faddenSoft
*
* 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;
using System.Windows;
namespace SourceGen.Res {
/// <summary>
/// This is a bridge between the XAML definitions and the C# code that uses the strings.
/// FindResource() throws an exception if the resource isn't found, so typos and missing
/// resources will cause the app to fail the first time any string is referenced.
/// </summary>
public static class Strings {
public static string ABBREV_ADDRESS =
(string)Application.Current.FindResource("str_AbbrevAddress");
public static string ABBREV_CONSTANT =
(string)Application.Current.FindResource("str_AbbrevConstant");
public static string ABBREV_STACK_RELATIVE =
(string)Application.Current.FindResource("str_AbbrevStackRelative");
public static string ANALYZER_TAG_MULTI_CHK =
(string)Application.Current.FindResource("str_AnalyzerTagMultiChk");
public static string ASM_LATEST_VERSION =
(string)Application.Current.FindResource("str_AsmLatestVersion");
public static string ASM_MATCH_FAILURE =
(string)Application.Current.FindResource("str_AsmMatchFailure");
public static string ASM_MATCH_SUCCESS =
(string)Application.Current.FindResource("str_AsmMatchSuccess");
public static string ASM_MISMATCH_CAPTION =
(string)Application.Current.FindResource("str_AsmMismatchCaption");
public static string ASM_MISMATCH_DATA_FMT =
(string)Application.Current.FindResource("str_AsmMismatchDataFmt");
public static string ASM_MISMATCH_LENGTH_FMT =
(string)Application.Current.FindResource("str_AsmMismatchLengthFmt");
public static string ASM_OUTPUT_NOT_FOUND =
(string)Application.Current.FindResource("str_AsmOutputNotFound");
public static string CONFIRMATION_NEEDED =
(string)Application.Current.FindResource("str_ConfirmationNeeded");
public static string DATA_BANK_AUTO_FMT =
(string)Application.Current.FindResource("str_DataBankAutoFmt");
public static string DATA_BANK_USER_FMT =
(string)Application.Current.FindResource("str_DataBankUserFmt");
public static string DATA_BANK_K =
(string)Application.Current.FindResource("str_DataBankK");
public static string DEFAULT_HEADER_COMMENT_FMT =
(string)Application.Current.FindResource("str_DefaultHeaderCommentFmt");
public static string DEFAULT_ASCII_DELIM_PAT =
(string)Application.Current.FindResource("str_DefaultAsciiDelimPat");
public static string DEFAULT_HIGH_ASCII_DELIM_PAT =
(string)Application.Current.FindResource("str_DefaultHighAsciiDelimPat");
public static string DEFAULT_C64_PETSCII_DELIM_PAT =
(string)Application.Current.FindResource("str_DefaultC64PetsciiDelimPat");
public static string DEFAULT_C64_SCREEN_CODE_DELIM_PAT =
(string)Application.Current.FindResource("str_DefaultC64ScreenCodeDelimPat");
public static string CLIPFORMAT_ALL_COLUMNS =
(string)Application.Current.FindResource("str_ClipformatAllColumns");
public static string CLIPFORMAT_ASSEMBLER_SOURCE =
(string)Application.Current.FindResource("str_ClipformatAssemblerSource");
public static string CLIPFORMAT_DISASSEMBLY =
(string)Application.Current.FindResource("str_ClipformatDisassembly");
public static string EQU_ADDRESS =
(string)Application.Current.FindResource("str_EquAddress");
public static string EQU_CONSTANT =
(string)Application.Current.FindResource("str_EquConstant");
public static string EQU_STACK_RELATIVE =
(string)Application.Current.FindResource("str_EquStackRelative");
public static string ERR_BAD_DEF_SYMBOL_DIR =
(string)Application.Current.FindResource("str_ErrBadDefSymbolDir");
public static string ERR_BAD_FD_FMT =
(string)Application.Current.FindResource("str_ErrBadFdFmt");
public static string ERR_BAD_FD_FORMAT =
(string)Application.Current.FindResource("str_ErrBadFdFormat");
public static string ERR_BAD_FILE_LENGTH =
(string)Application.Current.FindResource("str_ErrBadFileLength");
public static string ERR_BAD_IDENT =
(string)Application.Current.FindResource("str_ErrBadIdent");
public static string ERR_BAD_LOCAL_VARIABLE_FMT =
(string)Application.Current.FindResource("str_ErrBadLocalVariableFmt");
public static string ERR_BAD_LV_TABLE_FMT =
(string)Application.Current.FindResource("str_ErrBadLvTableFmt");
public static string ERR_BAD_RANGE =
(string)Application.Current.FindResource("str_ErrBadRange");
public static string ERR_BAD_SYMBOL_LABEL =
(string)Application.Current.FindResource("str_ErrBadSymbolLabel");
public static string ERR_BAD_SYMBOL_ST =
(string)Application.Current.FindResource("str_ErrBadSymbolSt");
public static string ERR_BAD_SYMREF_PART =
(string)Application.Current.FindResource("str_ErrBadSymrefPart");
public static string ERR_BAD_ANALYZER_TAG =
(string)Application.Current.FindResource("str_ErrBadAnalyzerTag");
public static string ERR_BAD_VISUALIZATION_FMT =
(string)Application.Current.FindResource("str_ErrBadVisualizationFmt");
public static string ERR_BAD_VISUALIZATION_SET_FMT =
(string)Application.Current.FindResource("str_ErrBadVisualizationSetFmt");
public static string ERR_DIR_CREATE_FAILED_FMT =
(string)Application.Current.FindResource("str_ErrDirCreateFailedFmt");
public static string ERR_DUPLICATE_LABEL_FMT =
(string)Application.Current.FindResource("str_ErrDuplicateLabelFmt");
public static string ERR_FILE_COPY_FAILED_FMT =
(string)Application.Current.FindResource("str_ErrFileCopyFailedFmt");
public static string ERR_FILE_EXISTS_NOT_DIR_FMT =
(string)Application.Current.FindResource("str_ErrFileExistsNotDirFmt");
public static string ERR_FILE_GENERIC_CAPTION =
(string)Application.Current.FindResource("str_ErrFileGenericCaption");
public static string ERR_FILE_NOT_FOUND_FMT =
(string)Application.Current.FindResource("str_ErrFileNotFoundFmt");
public static string ERR_FILE_READ_FAILED_FMT =
(string)Application.Current.FindResource("str_ErrFileReadFailedFmt");
public static string ERR_FILE_READ_ONLY_FMT =
(string)Application.Current.FindResource("str_ErrFileReadOnlyFmt");
public static string ERR_INVALID_ADDRESS_MASK =
(string)Application.Current.FindResource("str_ErrInvalidAddressMask");
public static string ERR_INVALID_CMP_ADDR_OVERLAP =
(string)Application.Current.FindResource("str_ErrInvalidCmpAddrOverlap");
public static string ERR_INVALID_CMP_EXTRA_BITS =
(string)Application.Current.FindResource("str_ErrInvalidCmpExtraBits");
public static string ERR_INVALID_COMPARE_MASK =
(string)Application.Current.FindResource("str_ErrInvalidCompareMask");
public static string ERR_INVALID_COMPARE_VALUE =
(string)Application.Current.FindResource("str_ErrInvalidCompareValue");
public static string ERR_INVALID_INT_VALUE =
(string)Application.Current.FindResource("str_ErrInvalidIntValue");
public static string ERR_INVALID_KEY_VALUE =
(string)Application.Current.FindResource("str_ErrInvalidKeyValue");
public static string ERR_INVALID_MULTI_MASK =
(string)Application.Current.FindResource("str_ErrInvalidMultiMask");
public static string ERR_INVALID_WIDTH =
(string)Application.Current.FindResource("str_ErrInvalidWidth");
public static string ERR_INVALID_SYSDEF =
(string)Application.Current.FindResource("str_ErrInvalidSysdef");
public static string ERR_LOAD_CONFIG_FILE =
(string)Application.Current.FindResource("str_ErrLoadConfigFile");
public static string ERR_NOT_PROJECT_FILE =
(string)Application.Current.FindResource("str_ErrNotProjectFile");
public static string ERR_PROJECT_FILE_CORRUPT =
(string)Application.Current.FindResource("str_ErrProjectFileCorrupt");
public static string ERR_PROJECT_LOAD_FAIL =
(string)Application.Current.FindResource("str_ErrProjectLoadFail");
public static string ERR_PROJECT_SAVE_FAIL =
(string)Application.Current.FindResource("str_ErrProjectSaveFail");
public static string ERR_TOO_LARGE_FOR_PREVIEW =
(string)Application.Current.FindResource("str_ErrTooLargeForPreview");
public static string ERR_VALUE_INCOMPATIBLE_WITH_MASK =
(string)Application.Current.FindResource("str_ErrValueIncompatibleWithMask");
public static string EXPORTING_HTML =
(string)Application.Current.FindResource("str_ExportingHtml");
public static string EXPORTING_HTML_AND_IMAGES =
(string)Application.Current.FindResource("str_ExportingHtmlAndImages");
public static string EXTERNAL_FILE_BAD_DIR_FMT =
(string)Application.Current.FindResource("str_ExternalFileBadDirFmt");
public static string EXTERNAL_FILE_BAD_DIR_CAPTION =
(string)Application.Current.FindResource("str_ExternalFileBadDirCaption");
public static string FILE_FILTER_ALL =
(string)Application.Current.FindResource("str_FileFilterAll");
public static string FILE_FILTER_CS =
(string)Application.Current.FindResource("str_FileFilterCs");
public static string FILE_FILTER_CSV =
(string)Application.Current.FindResource("str_FileFilterCsv");
public static string FILE_FILTER_DIS65 =
(string)Application.Current.FindResource("str_FileFilterDis65");
public static string FILE_FILTER_GIF =
(string)Application.Current.FindResource("str_FileFilterGif");
public static string FILE_FILTER_HTML =
(string)Application.Current.FindResource("str_FileFilterHtml");
public static string FILE_FILTER_SGEC =
(string)Application.Current.FindResource("str_FileFilterSgec");
public static string FILE_FILTER_SYM65 =
(string)Application.Current.FindResource("str_FileFilterSym65");
public static string FILE_FILTER_TEXT =
(string)Application.Current.FindResource("str_FileFilterText");
public static string FILE_INFO_FMT =
(string)Application.Current.FindResource("str_FileInfoFmt");
public static string FIND_REACHED_START =
(string)Application.Current.FindResource("str_FindReachedStart");
public static string FIND_REACHED_START_CAPTION =
(string)Application.Current.FindResource("str_FindReachedStartCaption");
public static string FONT_DESCRIPTOR_FMT =
(string)Application.Current.FindResource("str_FontDescriptorFmt");
public static string GENERATED_FOR_VERSION_FMT =
(string)Application.Current.FindResource("str_GeneratedForVersion");
public static string HIDE_COL =
(string)Application.Current.FindResource("str_HideCol");
public static string INFO_AUTO_FORMAT =
(string)Application.Current.FindResource("str_InfoAutoFormat");
public static string INFO_CUSTOM_FORMAT =
(string)Application.Current.FindResource("str_InfoCustomFormat");
public static string INFO_DEFAULT_FORMAT =
(string)Application.Current.FindResource("str_InfoDefaultFormat");
public static string INFO_LABEL_DESCR_FMT =
(string)Application.Current.FindResource("str_InfoLabelDescrFmt");
public static string INFO_LINE_SUM_NON_FMT =
(string)Application.Current.FindResource("str_InfoLineSumNonFmt");
public static string INFO_LINE_SUM_PLURAL_FMT =
(string)Application.Current.FindResource("str_InfoLineSumPluralFmt");
public static string INFO_LINE_SUM_SINGULAR_FMT =
(string)Application.Current.FindResource("str_InfoLineSumSingularFmt");
public static string INITIAL_EXTENSION_SCRIPTS =
(string)Application.Current.FindResource("str_InitialExtensionScripts");
public static string INITIAL_PARAMETERS =
(string)Application.Current.FindResource("str_InitialParameters");
public static string INITIAL_SYMBOL_FILES =
(string)Application.Current.FindResource("str_InitialSymbolFiles");
public static string INVALID_ADDRESS =
(string)Application.Current.FindResource("str_InvalidAddress");
public static string INVALID_FORMAT_WORD_SEL_CAPTION =
(string)Application.Current.FindResource("str_InvalidFormatWordSelCaption");
public static string INVALID_FORMAT_WORD_SEL_NON1 =
(string)Application.Current.FindResource("str_InvalidFormatWordSelNon1");
public static string INVALID_FORMAT_WORD_SEL_UNEVEN_FMT =
(string)Application.Current.FindResource("str_InvalidFormatWordSelUnevenFmt");
public static string LOAD_ADDRESS =
(string)Application.Current.FindResource("str_LoadAddress");
public static string LOCAL_VARIABLE_TABLE_CLEAR =
(string)Application.Current.FindResource("str_LocalVariableTableClear");
public static string LOCAL_VARIABLE_TABLE_EMPTY =
(string)Application.Current.FindResource("str_LocalVariableTableEmpty");
public static string MSG_BANK_OVERRUN =
(string)Application.Current.FindResource("str_MsgBankOverrun");
public static string MSG_BANK_OVERRUN_DETAIL_FMT =
(string)Application.Current.FindResource("str_MsgBankOverrunDetailFmt");
public static string MSG_FORMAT_DESCRIPTOR_IGNORED =
(string)Application.Current.FindResource("str_MsgFormatDescriptorIgnored");
public static string MSG_HIDDEN_LABEL =
(string)Application.Current.FindResource("str_MsgHiddenLabel");
public static string MSG_HIDDEN_LOCAL_VARIABLE_TABLE =
(string)Application.Current.FindResource("str_MsgHiddenLocalVariableTable");
public static string MSG_HIDDEN_VISUALIZATION =
(string)Application.Current.FindResource("str_MsgHiddenVisualization");
public static string MSG_INVALID_DESCRIPTOR =
(string)Application.Current.FindResource("str_MsgInvalidDescriptor");
public static string MSG_INVALID_OFFSET_OR_LENGTH =
(string)Application.Current.FindResource("str_MsgInvalidOffsetOrLength");
public static string MSG_LABEL_IGNORED =
(string)Application.Current.FindResource("str_MsgLabelIgnored");
public static string MSG_LOCAL_VARIABLE_TABLE_IGNORED =
(string)Application.Current.FindResource("str_MsgLocalVariableTableIgnored");
public static string MSG_UNRESOLVED_WEAK_REF =
(string)Application.Current.FindResource("str_MsgUnresolvedWeakRef");
public static string MSG_VISUALIZATION_IGNORED =
(string)Application.Current.FindResource("str_MsgVisualizationIgnored");
public static string NO_FILES_AVAILABLE =
(string)Application.Current.FindResource("str_NoFilesAvailable");
public static string NO_EXPORTED_SYMBOLS_FOUND =
(string)Application.Current.FindResource("str_NoExportedSymbolsFound");
public static string OMF_SEG_COMMENT_FMT =
(string)Application.Current.FindResource("str_OmfSegCommentFmt");
public static string OMF_SEG_HDR_COMMENT_FMT =
(string)Application.Current.FindResource("str_OmfSegHdrCommentFmt");
public static string OMF_SEG_NOTE_FMT =
(string)Application.Current.FindResource("str_OmfSegNoteFmt");
public static string OMF_SELECT_FILE =
(string)Application.Current.FindResource("str_OmfSelectFile");
public static string OPEN_DATA_DOESNT_EXIST =
(string)Application.Current.FindResource("str_OpenDataDoesntExist");
public static string OPEN_DATA_EMPTY =
(string)Application.Current.FindResource("str_OpenDataEmpty");
public static string OPEN_DATA_FAIL_CAPTION =
(string)Application.Current.FindResource("str_OpenDataFailCaption");
public static string OPEN_DATA_FAIL_MESSAGE =
(string)Application.Current.FindResource("str_OpenDataFailMessage");
public static string OPEN_DATA_PARTIAL_READ =
(string)Application.Current.FindResource("str_OpenDataPartialRead");
public static string OPEN_DATA_LOAD_FAILED_FMT =
(string)Application.Current.FindResource("str_OpenDataLoadFailedFmt");
public static string OPEN_DATA_TOO_LARGE_FMT =
(string)Application.Current.FindResource("str_OpenDataTooLargeFmt");
public static string OPEN_DATA_TOO_SMALL_FMT =
(string)Application.Current.FindResource("str_OpenDataTooSmallFmt");
public static string OPEN_DATA_WRONG_CRC_FMT =
(string)Application.Current.FindResource("str_OpenDataWrongCrcFmt");
public static string OPEN_DATA_WRONG_LENGTH_FMT =
(string)Application.Current.FindResource("str_OpenDataWrongLengthFmt");
public static string OPERATION_FAILED =
(string)Application.Current.FindResource("str_OperationFailed");
public static string OPERATION_SUCCEEDED =
(string)Application.Current.FindResource("str_OperationSucceeded");
public static string PARENTHETICAL_NONE =
(string)Application.Current.FindResource("str_ParentheticalNone");
public static string PLUGIN_DIR_FAIL_FMT =
(string)Application.Current.FindResource("str_PluginDirFailFmt");
public static string PLUGIN_DIR_FAIL_CAPTION =
(string)Application.Current.FindResource("str_PluginDirFailCaption");
public static string PROGRESS_ASSEMBLING =
(string)Application.Current.FindResource("str_ProgressAssembling");
public static string PROGRESS_GENERATING_FMT =
(string)Application.Current.FindResource("str_ProgressGeneratingFmt");
public static string PROJECT_FIELD_COMMENT =
(string)Application.Current.FindResource("str_ProjectFieldComment");
public static string PROJECT_FIELD_DBR_VALUE =
(string)Application.Current.FindResource("str_ProjectFieldDbrValue");
public static string PROJECT_FIELD_LONG_COMMENT =
(string)Application.Current.FindResource("str_ProjectFieldLongComment");
public static string PROJECT_FIELD_LV_TABLE =
(string)Application.Current.FindResource("str_ProjectFieldLvTable");
public static string PROJECT_FIELD_NOTE =
(string)Application.Current.FindResource("str_ProjectFieldNote");
public static string PROJECT_FIELD_OPERAND_FORMAT =
(string)Application.Current.FindResource("str_ProjectFieldOperandFormat");
public static string PROJECT_FIELD_RELOC_DATA =
(string)Application.Current.FindResource("str_ProjectFieldRelocData");
public static string PROJECT_FIELD_STATUS_FLAGS =
(string)Application.Current.FindResource("str_ProjectFieldStatusFlags");
public static string PROJECT_FIELD_ANALYZER_TAG =
(string)Application.Current.FindResource("str_ProjectFieldAnalyzerTag");
public static string PROJECT_FIELD_USER_LABEL =
(string)Application.Current.FindResource("str_ProjectFieldUserLabel");
public static string PROJECT_FROM_NEWER_APP =
(string)Application.Current.FindResource("str_ProjectFromNewerApp");
//public static string RECENT_PROJECT_LINK_FMT =
// (string)Application.Current.FindResource("str_RecentProjectLinkFmt");
public static string RUNTIME_DIR_NOT_FOUND =
(string)Application.Current.FindResource("str_RuntimeDirNotFound");
public static string RUNTIME_DIR_NOT_FOUND_CAPTION =
(string)Application.Current.FindResource("str_RuntimeDirNotFoundCaption");
public static string SAVE_BEFORE_ASM =
(string)Application.Current.FindResource("str_SaveBeforeAsm");
public static string SAVE_BEFORE_ASM_CAPTION =
(string)Application.Current.FindResource("str_SaveBeforeAsmCaption");
public static string SCAN_LOW_ASCII =
(string)Application.Current.FindResource("str_ScanLowAscii");
public static string SCAN_LOW_HIGH_ASCII =
(string)Application.Current.FindResource("str_ScanLowHighAscii");
public static string SCAN_C64_PETSCII =
(string)Application.Current.FindResource("str_ScanC64Petscii");
public static string SCAN_C64_SCREEN_CODE =
(string)Application.Current.FindResource("str_ScanC64ScreenCode");
public static string SETUP_SYSTEM_SUMMARY_FMT =
(string)Application.Current.FindResource("str_SetupSystemSummaryFmt");
public static string SHOW_COL =
(string)Application.Current.FindResource("str_ShowCol");
public static string STATUS_BYTE_COUNT_FMT =
(string)Application.Current.FindResource("str_StatusByteCountFmt");
public static string STATUS_READY =
(string)Application.Current.FindResource("str_StatusReady");
public static string STR_VFY_DCI_MIXED_DATA =
(string)Application.Current.FindResource("str_StrVfyDciMixedData");
public static string STR_VFY_DCI_NOT_TERMINATED =
(string)Application.Current.FindResource("str_StrVfyDciNotTerminated");
public static string STR_VFY_DCI_SHORT =
(string)Application.Current.FindResource("str_StrVfyDciShort");
public static string STR_VFY_L1_LENGTH_MISMATCH =
(string)Application.Current.FindResource("str_StrVfyL1LengthMismatch");
public static string STR_VFY_L2_LENGTH_MISMATCH =
(string)Application.Current.FindResource("str_StrVfyL2LengthMismatch");
public static string STR_VFY_MISSING_NULL_TERM =
(string)Application.Current.FindResource("str_StrVfyMissingNullTerm");
public static string STR_VFY_NULL_INSIDE_NULL_TERM =
(string)Application.Current.FindResource("str_StrVfyNullInsideNullTerm");
public static string SYMBOL_IMPORT_CAPTION =
(string)Application.Current.FindResource("str_SymbolImportCaption");
public static string SYMBOL_IMPORT_GOOD_FMT =
(string)Application.Current.FindResource("str_SymbolImportGoodFmt");
public static string SYMBOL_IMPORT_NONE =
(string)Application.Current.FindResource("str_SymbolImportNone");
public static string TITLE_BASE =
(string)Application.Current.FindResource("str_TitleBase");
public static string TITLE_MODIFIED =
(string)Application.Current.FindResource("str_TitleModified");
public static string TITLE_NEW_PROJECT =
(string)Application.Current.FindResource("str_TitleNewProject");
public static string TITLE_READ_ONLY =
(string)Application.Current.FindResource("str_TitleReadOnly");
public static string UNSET =
(string)Application.Current.FindResource("str_Unset");
public static string VIS_SET_MULTIPLE_FMT =
(string)Application.Current.FindResource("str_VisSetMultipleFmt");
public static string VIS_SET_SINGLE_FMT =
(string)Application.Current.FindResource("str_VisSetSingleFmt");
}
}
| 64.311518 | 92 | 0.728905 | [
"Apache-2.0"
] | absindx/6502bench | SourceGen/Res/Strings.xaml.cs | 24,569 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TowerBlueprint {
public GameObject towerPrefab;
public int coinsCost;
public int woodCost;
public int populationCost;
public int stoneCost;
public int oreCost;
public int hqLevelRequired;
}
| 20.866667 | 33 | 0.808307 | [
"MIT"
] | Eclair/LD38-TurtleHero | Assets/Scripts/Blueprints/TowerBlueprint.cs | 315 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaskBase.Data.NotificationService
{
public record NotificationModel(Guid Id, string Title, string Description);
}
| 22.363636 | 79 | 0.804878 | [
"MIT"
] | t-rolfin/TaskBase | src/TaskBase.Data/NotificationService/NotificationModel.cs | 248 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
namespace GenerateSecurityGraphs.Models.Query
{
public class ResourceSegmentData
{
public string ResourceName { get; set; }
public string ParentResourceName { get; set; }
public string ActionName { get; set; }
public string AuthorizationStrategyName { get; set; }
}
}
| 30.842105 | 86 | 0.708191 | [
"Apache-2.0"
] | gmcelhanon/Ed-Fi-ODS-1 | Utilities/GenerateSecurityGraphs/GenerateSecurityGraphs/Models/Query/ResourceSegmentData.cs | 586 | C# |
using System;
using System.Collections.Generic;
using Core.Block.BlockInventory;
using Core.Block.Blocks.Miner;
using Core.Block.Config;
using Core.Block.Config.LoadConfig.Param;
using Core.Electric;
using Core.Item;
using Core.Ore;
using Core.Update;
using Game.World.Interface.Util;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Server;
using Server.StartServerSystem;
using Test.Module;
using Test.Module.TestConfig;
using Test.Module.TestMod;
namespace Test.CombinedTest.Core
{
public class MinerMiningTest
{
private int MinerId = 6;
//一定時間たったら鉱石が出るテスト
[Test]
public void MiningTest()
{
var (_, serviceProvider) = new PacketResponseCreatorDiContainerGenerators().Create(TestModDirectory.ForUnitTestModDirectory);
var itemStackFactory = serviceProvider.GetService<ItemStackFactory>();
var blockConfig = serviceProvider.GetService<IBlockConfig>();
var oreConfig = serviceProvider.GetService<IOreConfig>();
var minerBlockConfigParam = blockConfig.GetBlockConfig(MinerId).Param as MinerBlockConfigParam;
//手動で鉱石の設定を行う
var miningTime = minerBlockConfigParam.OreSettings[0].MiningTime;
var miningItemId = oreConfig.OreIdToItemId(minerBlockConfigParam.OreSettings[0].OreId);
var miner = new VanillaMiner(MinerId, EntityId.NewEntityId(),1, 100, 10, itemStackFactory);
miner.SetMiningItem(miningItemId, miningTime);
var dummyInventory = new DummyBlockInventory(itemStackFactory);
//接続先ブロックの設定
((IBlockInventory) miner).AddOutputConnector(dummyInventory);
//電力の設定
var segment = new ElectricSegment();
segment.AddBlockElectric(miner);
segment.AddGenerator(new TestPowerGenerator(10000, 10));
DateTime MineEndTime = DateTime.Now.AddMilliseconds(miningTime);
//テストコードの準備完了
//鉱石1個分の採掘時間待機
while (MineEndTime.AddSeconds(0.2).CompareTo(DateTime.Now) == 1)
{
GameUpdate.Update();
}
//鉱石1個が出力されているかチェック
Assert.AreEqual(miningItemId, dummyInventory.InsertedItems[0].Id);
Assert.AreEqual(1, dummyInventory.InsertedItems[0].Count);
//コネクターを外す
((IBlockInventory) miner).RemoveOutputConnector(dummyInventory);
//鉱石2個分の採掘時間待機
MineEndTime = DateTime.Now.AddMilliseconds(miningTime * 2);
while (MineEndTime.AddSeconds(0.02).CompareTo(DateTime.Now) == 1)
{
GameUpdate.Update();
}
miner.Update();
//鉱石2個が残っているかチェック
var outputSlot = (List<IItemStack>) typeof(VanillaMiner).GetField("_outputSlot",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(miner);
Assert.AreEqual(miningItemId, outputSlot[0].Id);
Assert.AreEqual(2, outputSlot[0].Count);
//またコネクターをつなげる
((IBlockInventory) miner).AddOutputConnector(dummyInventory);
//コネクターにアイテムを入れるためのアップデート
GameUpdate.Update();
//アイテムがさらに2個入っているかチェック
Assert.AreEqual(miningItemId, dummyInventory.InsertedItems[0].Id);
Assert.AreEqual(3, dummyInventory.InsertedItems[0].Count);
}
}
} | 37.326087 | 137 | 0.658998 | [
"MIT"
] | moorestech/moorestech | Test/CombinedTest/Core/MinerMiningTest.cs | 3,768 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Wei.Repository
{
public class BaseDbContext : DbContext
{
public BaseDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var assemblies = AppDomain.CurrentDomain.GetCurrentPathAssembly().Where(x => !(x.GetName().Name.Equals("Wei.Repository")));
foreach (var assembly in assemblies)
{
var entityTypes = assembly.GetTypes()
.Where(type => !string.IsNullOrWhiteSpace(type.Namespace))
.Where(type => type.IsClass)
.Where(type => type.Name != nameof(Entity))
.Where(type => type.BaseType != null)
.Where(type => typeof(ITrack).IsAssignableFrom(type));
foreach (var entityType in entityTypes)
{
if (modelBuilder.Model.FindEntityType(entityType) != null) continue;
modelBuilder.Model.AddEntityType(entityType);
}
}
base.OnModelCreating(modelBuilder);
}
public override int SaveChanges()
{
SetTrackInfo();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetTrackInfo();
return base.SaveChangesAsync(cancellationToken);
}
private void SetTrackInfo()
{
ChangeTracker.DetectChanges();
var entries = this.ChangeTracker.Entries()
.Where(x => x.Entity is ITrack)
.Where(x => x.State == EntityState.Added || x.State == EntityState.Modified);
foreach (var entry in entries)
{
var entity = entry.Entity;
var entityBase = entity as ITrack;
switch (entry.State)
{
case EntityState.Modified:
entityBase.UpdateTime = DateTime.Now;
break;
case EntityState.Added:
entityBase.CreateTime = DateTime.Now;
break;
}
}
}
}
}
| 33.383562 | 135 | 0.533032 | [
"MIT"
] | Claire-qin/Wei.Repository | src/Wei.Repository/Impl/BaseDbContext.cs | 2,439 | C# |
using System;
using System.Xml.Serialization;
namespace Niue.Alipay.Domain
{
/// <summary>
/// KbAdvertCommissionClausePercentage Data Structure.
/// </summary>
[Serializable]
public class KbAdvertCommissionClausePercentage : AopObject
{
/// <summary>
/// 分佣比例结束范围(100以内精度2位的非负小数)
/// </summary>
[XmlElement("commission_rate_end")]
public string CommissionRateEnd { get; set; }
/// <summary>
/// 分佣比例开始范围(100以内精度2位的非负小数)
/// </summary>
[XmlElement("commission_rate_start")]
public string CommissionRateStart { get; set; }
/// <summary>
/// 封顶金额结束范围(精度2位的非负小数)
/// </summary>
[XmlElement("max_limit_end")]
public string MaxLimitEnd { get; set; }
/// <summary>
/// 封顶金额开始范围(精度2位的非负小数)
/// </summary>
[XmlElement("max_limit_start")]
public string MaxLimitStart { get; set; }
}
}
| 26.189189 | 63 | 0.582043 | [
"MIT"
] | P79N6A/abp-ant-design-pro-vue | Niue.Alipay/Domain/KbAdvertCommissionClausePercentage.cs | 1,107 | C# |
namespace Lexs4SearchRetrieveWebService
{
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(TextSearchRequestMessageType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(StructuredSearchRequestMessageType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(DataItemMetadataSearchRequestMessageType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(AttachmentSearchRequestMessageType))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("WscfGen", "1.0.0.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://ulex.gov/ulex/2.0")]
public abstract partial class SearchRequestMessageType : RequestMessageType
{
private SearchRequestMetadataType searchRequestMetadataField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public SearchRequestMetadataType SearchRequestMetadata
{
get
{
return this.searchRequestMetadataField;
}
set
{
this.searchRequestMetadataField = value;
}
}
}
}
| 38.685714 | 101 | 0.677253 | [
"Apache-2.0"
] | gtri-iead/LEXS-NET-Sample-Implementation-4.0 | LEXS Search Retrieve Service Implementation/LexsSearchRetrieveCommon/SearchRequestMessageType.cs | 1,354 | C# |
//****************************************************************
// Adapted from Tim Sneath (Microsoft)
//
// Author: Yang Kok Wah
//
// Using Win32 API to implement a way to hide inputed characters
// From the console.
//
//****************************************************************
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Chat
{
public enum InputModeFlags
{
ENABLE_PROCESSED_INPUT = 0x01,
ENABLE_LINE_INPUT = 0x02,
ENABLE_ECHO_INPUT = 0x04,
ENABLE_WINDOW_INPUT = 0x08,
ENABLE_MOUSE_INPUT = 0x10
}
public class PasswordConsole{
[DllImport("kernel32.dll", EntryPoint="SetConsoleMode", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern bool SetConsoleMode(int hConsoleHandle,
int dwMode);
[DllImport("kernel32.dll", EntryPoint="ReadConsole", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern bool ReadConsole(int hConsoleInput,
StringBuilder buf, int nNumberOfCharsToRead, ref int lpNumberOfCharsRead, int lpReserved);
[DllImport("kernel32.dll", EntryPoint="GetStdHandle", SetLastError=true,
CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern int GetStdHandle(int nStdHandle);
private static char ReadChar()
{
// Temporarily disable character echo (ENABLE_ECHO_INPUT) and line input
// (ENABLE_LINE_INPUT) during this operation
int STD_INPUT_HANDLE = -10;
int hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(hConsoleInput,
(int) (InputModeFlags.ENABLE_PROCESSED_INPUT |
InputModeFlags.ENABLE_WINDOW_INPUT |
InputModeFlags.ENABLE_MOUSE_INPUT));
int lpNumberOfCharsRead = 0;
StringBuilder buf = new StringBuilder(1);
bool success = ReadConsole(hConsoleInput, buf, 1, ref lpNumberOfCharsRead, 0);
// Reenable character echo and line input
SetConsoleMode(hConsoleInput,
(int) (InputModeFlags.ENABLE_PROCESSED_INPUT |
InputModeFlags.ENABLE_ECHO_INPUT |
InputModeFlags.ENABLE_LINE_INPUT |
InputModeFlags.ENABLE_WINDOW_INPUT |
InputModeFlags.ENABLE_MOUSE_INPUT));
if (success)
return Convert.ToChar(buf[0]);
else
throw new ApplicationException("Attempt to call ReadConsole API failed.");
}
public static string ReadLine(char passwordchar){
string s="";
char c;
while((c=PasswordConsole.ReadChar())!='\r')
{
s=s+new string(c,1);
Console.Write(passwordchar);
}
Console.WriteLine();
return s;
}
}
} | 29.685393 | 92 | 0.694928 | [
"MIT"
] | SeppPenner/ChatNew | src/ChatClient/Backup/PasswordConsole.cs | 2,642 | C# |
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace SleeplessOwl.URPPostProcessing
{
[Serializable, VolumeComponentMenu("SleeplessOwl PostProcessing/World Position")]
public sealed class WorldPositionVolume : PostProcessVolumeComponent
{
public BoolParameter ColorAddMode = new BoolParameter(true);
public FloatParameter GridSize = new FloatParameter(0f);
public FloatParameter GridLineWidth = new FloatParameter(2);
Material material;
public override bool visibleInSceneView => true;
public override InjectionPoint InjectionPoint => InjectionPoint.BeforePostProcess;
public override bool IsActive()
{
return GridSize.value > 0 && GridLineWidth.value > 0;
}
static class IDs
{
internal static readonly int _UnitCubeGridCount = Shader.PropertyToID("_UnitCubeGridCount");
internal static readonly int _GridLineWidth = Shader.PropertyToID("_GridLineWidth");
internal static readonly int _InverseView = Shader.PropertyToID("_InverseView");
internal static readonly string ADD_MODE = "ADD_MODE";
}
public override void Initialize()
{
material = CoreUtils.CreateEngineMaterial("SleeplessOwl/Post-Processing/World Position");
}
public override void Render(CommandBuffer cb, Camera camera, RenderTargetIdentifier source, RenderTargetIdentifier destination)
{
material.SetMatrix(IDs._InverseView, camera.cameraToWorldMatrix);
material.SetKeyWord(IDs.ADD_MODE, ColorAddMode.value);
material.SetFloat(IDs._UnitCubeGridCount, 1 / GridSize.value);
material.SetFloat(IDs._GridLineWidth, GridLineWidth.value);
cb.SetPostProcessSourceTexture(source);
cb.DrawFullScreenTriangle(material, destination);
}
}
} | 41.020833 | 136 | 0.680041 | [
"MIT"
] | YuSiangLai/URPCustomPostProcessing | VolumeComponent/WorldPositionVolume.cs | 1,969 | C# |
// <auto-generated/>
#pragma warning disable 1591
namespace Test
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
public partial class TestComponent<TParam> : global::Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 219
private void __RazorDirectiveTokenHelpers__() {
((System.Action)(() => {
#nullable restore
#line 1 "x:\dir\subdir\Test\TestComponent.cshtml"
global::System.Object TParam = null!;
#line default
#line hidden
#nullable disable
}
))();
}
#pragma warning restore 219
#pragma warning disable 0414
private static System.Object __o = null;
#pragma warning restore 0414
#pragma warning disable 1998
protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
global::__Blazor.Test.TestComponent.TypeInference.CreateMyComponent_0(__builder, -1, -1,
#nullable restore
#line 2 "x:\dir\subdir\Test\TestComponent.cshtml"
ParentValue
#line default
#line hidden
#nullable disable
, -1,
__value => { ParentValue = __value; global::Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.InvokeSynchronousDelegate(Update); });
#nullable restore
#line 2 "x:\dir\subdir\Test\TestComponent.cshtml"
__o = typeof(global::Test.MyComponent<>);
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
#nullable restore
#line 3 "x:\dir\subdir\Test\TestComponent.cshtml"
public TParam ParentValue { get; set; }
public void Update() { }
#line default
#line hidden
#nullable disable
}
}
namespace __Blazor.Test.TestComponent
{
#line hidden
internal static class TypeInference
{
public static void CreateMyComponent_0<TValue>(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, int __seq0, TValue __arg0, int __seq1, global::System.Action<TValue> __arg1)
{
__builder.OpenComponent<global::Test.MyComponent<TValue>>(seq);
__builder.AddAttribute(__seq0, "Value", __arg0);
__builder.AddAttribute(__seq1, "ValueChanged", __arg1);
__builder.CloseComponent();
}
}
}
#pragma warning restore 1591
| 30.949367 | 219 | 0.692434 | [
"MIT"
] | dotnet/razor-compiler | src/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentDesignTimeCodeGenerationTest/GenericComponentBindToGenericComponent_InferredType_WithAfter_Action/TestComponent.codegen.cs | 2,445 | C# |
using System;
namespace ECS {
/// <summary>Component interface which describes the functions a component
/// should implement.</summary>
public interface IComponent {
/// <summary>Gets the type of the component value.</summary>
Type GetComponentType();
/// <summary>The name of the component, which can be used with <see cref="IEntity.GetComponentByName{T}(string)"/>
/// or other similar functions.</summary>
string Name { get; set; }
}
/// <summary>Component class where type-safe objects may be stored and
/// retrieved.</summary>
public class Component<T> : IComponent {
/// <summary>The value of the component, or the object which the component holds.</summary>
public T Value { get; set; }
public string Name { get; set; }
/// <summary>Constructs a new <c>Component</c> object.</summary>
/// <param name="value">The value to initialize the component with.</param>
/// <param name="name">The name to initialize the component with.</param>
public Component(T value = default, string name = default) {
Value = value;
Name = name;
}
public Type GetComponentType() => typeof(T);
}
}
| 34.297297 | 122 | 0.619385 | [
"MIT"
] | little512/cs-ecs | ECS/Component.cs | 1,269 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Spectrum.Net.Core.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Spectrum.Net.Core.Message.Create
{
public class ContentBlock
{
[JsonProperty("data")]
[JsonConverter(typeof(MessageDataConverter))]
public IEnumerable<MessageData> Data { get; set; } = new MessageData[] { };
[JsonProperty("depth")]
public Int32 Depth { get; set; }
[JsonProperty("entityRanges")]
public IEnumerable<EntityRange> EntityRanges { get; set; } = new EntityRange[] { };
[JsonProperty("inlineStyleRanges")]
public IEnumerable<StyleRange> StyleRanges { get; set; } = new StyleRange[] { };
[JsonProperty("key")]
public String Key { get; internal set; } = ContentBlock.NewKey();
[JsonProperty("text")]
public String Text { get; set; }
[JsonProperty("type")]
public String Type { get; set; } = "unstyled";
// var seenKeys = {};
// var MULTIPLIER = Math.pow(2, 24);
//
// function generateRandomKey() {
// var key = void 0;
// while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) {
// key = Math.floor(Math.random() * MULTIPLIER).toString(32);
// }
// seenKeys[key] = true;
// return key;
// }
private static String _lastKey;
private static Int64 KEY_SPACE = (Int64)Math.Pow(36, 5) - 1; // 60466175;
public static String NewKey()
{
var nextKey = (DateTime.UtcNow.Ticks % KEY_SPACE).ToBase(36);
while (_lastKey == nextKey)
{
nextKey = (DateTime.UtcNow.Ticks % KEY_SPACE).ToBase(36);
Thread.Sleep(0);
}
return _lastKey = nextKey;
}
}
} | 30.476923 | 91 | 0.577991 | [
"MIT"
] | dolkensp/Spectrum.Net | Spectrum.Net.Core/Message/Create/ContentBlock.cs | 1,983 | C# |
using UnityEngine;
public class BTN_Server_EU : MonoBehaviour
{
private void OnClick()
{
PhotonNetwork.Disconnect();
FengGameManagerMKII.OnPrivateServer = false;
if (Guardian.Networking.NetworkHelper.App == Guardian.Networking.PhotonApplication.AoTTG2)
{
PhotonNetwork.ConnectToMaster("eu.aottg.tk", Guardian.Networking.NetworkHelper.Connection.Port, FengGameManagerMKII.ApplicationId, UIMainReferences.Version);
Guardian.Networking.NetworkHelper.IsCloud = false;
}
else
{
PhotonNetwork.ConnectToMaster("app-eu.exitgamescloud.com", Guardian.Networking.NetworkHelper.Connection.Port, FengGameManagerMKII.ApplicationId, UIMainReferences.Version);
Guardian.Networking.NetworkHelper.IsCloud = true;
}
}
}
| 37.590909 | 183 | 0.708585 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | suhtiva/guardian | Assembly-CSharp/FengLi/Interface/Buttons/BTN_Server_EU.cs | 827 | C# |
namespace MethodParameter
{
class Test
{
public void TestMethod(Expected e)
{
}
}
class Expected
{
}
}
| 10.857143 | 42 | 0.493421 | [
"MIT"
] | OptiNav/ReferenceAnalyzer | src/ReferenceAnalyzer.Core.Tests/TestFiles/MethodParameter.cs | 152 | C# |
namespace Theatre.Data
{
using Microsoft.EntityFrameworkCore;
using Theatre.Data.Models;
public class TheatreContext : DbContext
{
public TheatreContext() { }
public TheatreContext(DbContextOptions options)
: base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSqlServer(Configuration.ConnectionString);
}
}
public DbSet<Cast> Casts { get; set; }
public DbSet<Play> Plays { get; set; }
public DbSet<Theatre> Theatres { get; set; }
public DbSet<Ticket> Tickets { get; set; }
}
}
| 24.612903 | 85 | 0.591088 | [
"MIT"
] | georgy-kirilov/Dobri-EFCore-Exam | src/Skeleton/Theatre/Data/TheatreContext.cs | 765 | C# |
// Copyright (c) Josef Pihrt. 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslynator.CSharp;
namespace Roslynator.Formatting.CSharp
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer : BaseDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa); }
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterSyntaxNodeAction(f => AnalyzeConditionalExpression(f), SyntaxKind.ConditionalExpression);
}
private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext context)
{
var conditionalExpression = (ConditionalExpressionSyntax)context.Node;
ExpressionSyntax condition = conditionalExpression.Condition;
if (condition.IsMissing)
return;
ExpressionSyntax whenTrue = conditionalExpression.WhenTrue;
if (whenTrue.IsMissing)
return;
if (SyntaxTriviaAnalysis.IsTokenFollowedWithNewLineAndNotPrecededWithNewLine(condition, conditionalExpression.QuestionToken, whenTrue))
{
if (!AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context))
{
ReportDiagnostic(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa, conditionalExpression.QuestionToken, ImmutableDictionary<string, string>.Empty);
return;
}
}
else if (SyntaxTriviaAnalysis.IsTokenPrecededWithNewLineAndNotFollowedWithNewLine(condition, conditionalExpression.QuestionToken, whenTrue))
{
if (AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context))
{
ReportDiagnostic(DiagnosticDescriptors.ReportOnly.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, conditionalExpression.QuestionToken, DiagnosticProperties.AnalyzerOption_Invert);
return;
}
}
ExpressionSyntax whenFalse = conditionalExpression.WhenFalse;
if (!whenFalse.IsMissing)
{
if (SyntaxTriviaAnalysis.IsTokenFollowedWithNewLineAndNotPrecededWithNewLine(whenTrue, conditionalExpression.ColonToken, whenFalse))
{
if (!AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context))
ReportDiagnostic(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa, conditionalExpression.ColonToken, ImmutableDictionary<string, string>.Empty);
}
else if (SyntaxTriviaAnalysis.IsTokenPrecededWithNewLineAndNotFollowedWithNewLine(whenTrue, conditionalExpression.ColonToken, whenFalse))
{
if (AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context))
ReportDiagnostic(DiagnosticDescriptors.ReportOnly.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, conditionalExpression.ColonToken, DiagnosticProperties.AnalyzerOption_Invert);
}
}
void ReportDiagnostic(DiagnosticDescriptor descriptor, SyntaxToken token, ImmutableDictionary<string, string> properties)
{
DiagnosticHelpers.ReportDiagnostic(
context,
descriptor,
Location.Create(token.SyntaxTree, token.Span.WithLength(0)),
properties: properties);
}
}
}
}
| 49.494118 | 205 | 0.70145 | [
"Apache-2.0"
] | joebone/Roslynator | src/Formatting.Analyzers/CSharp/AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs | 4,209 | C# |
/*******************************************************************************
* Copyright (C) 2015-2016 AgGateway and ADAPT Contributors
* Copyright (C) 2015-2016 Deere and Company
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* Tarak Reddy, Tim Shearouse - initial API and implementation
*******************************************************************************/
namespace AgGateway.ADAPT.Representation.RepresentationSystem
{
public enum RepresentationList
{
dtApplicationMethod = 1001,
dtRecordingStatus = 1003,
dtWindDirection = 1004,
dtABLineSaveMethod = 1005,
dtSkyCondition = 1006,
dtInlineOffsetType = 1007,
dtLateralOffsetType = 1008,
dtHitchType = 1009,
dtSoilMoisture = 1010,
dtSeedingApplicationMethod = 1011,
dtOperationClass = 1012,
dtSensorStatus = 1013,
dtPrescriptionState = 1014,
dtLoadType = 1015,
dtCottonLoadType = 1016,
dtCircleSaveMethod = 1017,
dtMaterialClass = 1018,
dtFunctionType = 1019,
dtFunctionHitchChange = 1020,
dtFunctionPTOChange = 1021,
dtFunctionDiffLocChange = 1022,
dtFunction4WDChange = 1023,
dtFunctionSCVChange = 1024,
dtFunctionFieldCruiseChange = 1041,
dtGuidanceBoundaryBehavior = 1025,
dtSkipPattern = 1026,
dtCoverageSetting = 1027,
dtSignalType = 1028,
dtFunctionAPSChange = 1029,
dtNavigationType = 1030,
dtNonSteeringAxleLocation = 1031,
dtSPFHLoadType = 1032,
dtSurfaceWaterManagementOpType = 1033,
dtFunctionFrontPTOChange = 1034,
dtDrainType = 1035,
dtHeaderStatus = 1036,
dtTicketStatus = 1037,
dtProductDetailsProductType = 1038,
dtProductDetailsSeedType = 1039,
dtTicketType = 1040,
dtMeasuredWeightStatus = 1042,
dtProjectionType = 1043,
dtTillageType = 1044,
dtUnloadingAugerState = 1500,
dtJDArmedDWS = 1501,
dtSectionControlMasterState = 1502,
dtSprayerSystemOperatingMode = 1503,
dtPrescriptionControlMasterState = 1504,
dtMachineType = 1505,
dtImplementType = 1506,
dtFacilityType = 1507,
dtPersonRole = 1508,
vrAppRateVolumeSetPoint = 50,
vrAppRateVolumeActual = 49,
vrAppRateVolumeTarget = 51,
vrABRowSpacing = 1,
vrABShiftTrack = 2,
vrABLineHeading = 3,
vrCommodityPricePerBale = 4,
vrCommodityPricePerVolume = 5,
vrHarvestMoisture = 6,
vrCropWeightBale = 7,
vrCropWeightVolume = 8,
vrFSAArea = 9,
vrReportedFieldArea = 10,
vrSpatialFieldArea = 11,
vrYieldTotalMass = 12,
vrYieldTotalVolume = 13,
vrHeadlandOffset = 14,
vrLatency = 15,
vrLoadArea = 16,
vrMassPer1000Seeds = 17,
vrMassPerContainer = 18,
vrMaturity = 19,
vrEquipmentWidth = 20,
vrTrackSpacing = 21,
vrPathOverlap = 22,
vrInlineOffset = 23,
vrLateralOffset = 24,
vrTotalInlineDistance = 280,
vrTotalLateralDistance = 281,
vrVerticalOffset = 25,
vrSectionWidth = 26,
vrSeedGerminationPercent = 27,
vrSeedLoadQuantity = 28,
vrSeedsPerContainer = 29,
vrSeedsPerMass = 30,
vrSolutionRateLiquid = 31,
vrSolutionRateMass = 32,
vrSwathWidth = 33,
vrYieldBale = 34,
vrYieldBalePerArea = 35,
vrYieldWetMassFlow = 36,
vrYieldWetMassPerArea = 37,
vrYieldWetVolume = 38,
vrYieldWetVolumePerArea = 39,
vrYieldMass = 40,
vrYieldMassPerArea = 41,
vrYieldVolume = 42,
vrYieldVolumePerArea = 43,
vrAppRateMassActual = 45,
vrAppRateMassSetPoint = 46,
vrAppRateMassTarget = 47,
vrAppRateVolumePerHour = 600,
vrAppHeightTarget = 52,
vrTillageDepthTarget = 53,
vrSeedRateMassActual = 55,
vrSeedRateMassSetPoint = 56,
vrSeedRateMassTarget = 57,
vrSeedRateSeedsActual = 59,
vrSeedRateSeedsSetPoint = 60,
vrSeedRateSeedsTarget = 61,
vrSeedDepthTarget = 62,
vrRelativeHumidity = 63,
vrAirTemperature = 64,
vrWindSpeed = 65,
vrSoilTemperature = 66,
vrTotalAreaCovered = 67,
vrTotalQuantityAppliedMass = 68,
vrTotalQuantityAppliedVolume = 69,
vrTotalSeedQuantityAppliedSeed = 70,
vrTotalSeedQuantityAppliedMass = 71,
vrTotalOperationTime = 72,
vrHeading = 73,
vrElevation = 74,
vrStandardPayableMoisture = 75,
vrLatitude = 76,
vrLongitude = 77,
vrDistanceTraveled = 78,
vrNonLogTime = 80,
vrVehicleSpeed = 81,
vrDeltaTime = 82,
vrEquipmentLogFrequency = 84,
vrCommodityPricePerArea = 85,
vrCommodityPricePerYield = 86,
vrCommodityPricePerContainer = 87,
vrRowWidth = 88,
vrGuidanceSmallShift = 89,
vrGuidanceLargeShift = 90,
vrPathAccuracyIndicator = 91,
vrTrackToneBeginningDistance = 92,
vrLeadCompensation = 93,
vrAccuracyBarStepSize = 94,
vrTurnDistance = 95,
vrTrackSpacingRows = 96,
vrEquipmentWidthRows = 97,
vrPathOverlapRows = 98,
vrFuelRatePerHour = 99,
vrFuelTotal = 100,
vrTotalYieldVolume = 101,
vrTotalYieldMass = 102,
vrTotalYieldWetMass = 103,
vrTotalYieldWetVolume = 104,
vrTotalYieldBale = 105,
vrHarvestMinimumMoisture = 106,
vrHarvestMaximumMoisture = 107,
vrYieldMassMinimum = 108,
vrYieldMassMaximum = 109,
vrYieldMassPerAreaMinimum = 110,
vrYieldMassPerAreaMaximum = 111,
vrYieldVolumeMinimum = 112,
vrYieldVolumeMaximum = 113,
vrYieldVolumePerAreaMinimum = 114,
vrYieldVolumePerAreaMaximum = 115,
vrYieldBaleMinimum = 116,
vrYieldBaleMaximum = 117,
vrYieldBalePerAreaMinimum = 118,
vrYieldWetMassMinimum = 119,
vrYieldWetMassMaximum = 120,
vrYieldWetMassPerAreaMinumum = 121,
vrYieldWetMassPerAreaMaximum = 122,
vrYieldWetVolumeMinimum = 123,
vrYieldWetVolumeMaximum = 124,
vrYieldWetVolumePerAreaMinimum = 125,
vrYieldWetVolumePerAreaMaximum = 126,
vrEastShiftComponent = 127,
vrNorthShiftComponent = 128,
vrTurnout = 129,
vrTaskArea = 130,
vrBoundaryOffset = 131,
vrSpatialFieldPerimeter = 132,
vrAreaProductivity = 133,
vrMassProductivity = 134,
vrVolumeProductivity = 135,
vrBaleProductivity = 136,
vrSeedsProductivity = 137,
vrRadiusOffset = 138,
vrRadialHeading = 139,
vrRadiusShift = 140,
vrRecordingTimeRemaining = 141,
vrReceiverOffset = 142,
vrManagementZoneClipping = 143,
vrTrackRowWidth = 144,
vrInoculantDosing = 145,
vrLengthOfCut = 146,
vrHeadland = 147,
vrGenericZoneValue = 148,
vrHarvestMoistureTotal = 149,
vrHarvestMoistureCount = 150,
vrCutWidthIncrement = 151,
vrCutWidthIncrementRows = 152,
vrBoundaryIntersectionDistance = 153,
vrSequenceActivationDistance = 155,
vrSequenceActivationTime = 156,
vrSequenceOffsetDistance = 157,
vrFunctionOffsetDistance = 158,
vrFunctionValueSpeed = 159,
vrFunctionValueEngineSpeed = 276,
vrMachineTurnRadius = 160,
vrImplementTurnRadius = 161,
vrInteriorHeadlandOffset = 162,
vrPhysicalImplementWidth = 163,
vrImplementLength = 164,
vrImplementFrontOffset = 165,
vrGPSToNonSteeringAxleOffset = 166,
vrNonSteeringAxleToConnectionOffset = 167,
vrLateralControlPointToConnectionOffset = 168,
vrInlineControlPointToConnectionOffset = 169,
vrInRowSteerLimitation = 170,
vrSlopeCompensation = 171,
vrInlineConnectionPointToReceiverOffset = 172,
vrLateralConnectionPointToReceiverOffset = 173,
vrImplementReceiverHeight = 174,
vrGPSHeight = 175,
vrGPSAft = 176,
vrBoundaryDistance = 177,
vrFeelerHoldOffTime = 178,
vrRowSensorOffset = 179,
vrMapDistance = 180,
vrYieldTotalMassForage = 181,
vrYieldWetMassFrgPerArea = 182,
vrYieldMassFrgPerArea = 183,
vrModuleDiameter = 184,
vrModuleWeight = 185,
vrYieldMassForage = 186,
vrSurveyTimeInterval = 187,
vrSurveyDistanceInterval = 188,
vrSurveyFrequencyInterval = 189,
vrVDOP = 190,
vrPitchAngle = 191,
vrRollAngle = 192,
vrEndTurnOffset = 193,
vrLeveeDrop = 194,
vrYieldWetMassForage = 195,
vrYieldTotalWetMassForage = 196,
vrYieldMassMinForage = 197,
vrYieldMassMaxForage = 198,
vrYieldMassPerAreaMinForage = 199,
vrYieldMassPerAreaMaxForage = 200,
vrYieldWetMassMinForage = 201,
vrYieldWetMassMaxForage = 202,
vrYieldWetMassPerAreaMinForage = 203,
vrYieldWetMassPerAreaMaxForage = 204,
vrInoculantDosingTotal = 205,
vrForageMassProductivity = 206,
vrGear = 207,
vrVerticalAccuracyIndicator = 208,
vrInlineRearConnectionPointToConnectionPointOffset = 209,
vrLateralRearConnectionPointToConnectionPointOffset = 210,
vrMachineVerticalReceiverOffset = 211,
vrImplementVerticalReceiverToCuttingEdgeOffset = 212,
vrImplementVerticalCuttingEdgeToGroundOffset = 213,
vrVerticalProfileGridSize = 214,
vrHorizontalProfileGridSize = 215,
vrLinearFitDrainSlope = 216,
vrMaxBestFitDrainCutDepth = 217,
vrMinBestFitDrainCutDepth = 218,
vrRoverDistance = 219,
vrPositiveLeveeElevationOffset = 220,
vrNegativeLeveeElevationOffset = 221,
vrLeveeDial = 222,
vrGPSAccuracy = 223,
vrGPSVerticalAccuracy = 224,
vrFlagArea = 225,
vrNormalizedMapPercent = 226,
vrRowFinderDisableTime = 227,
vrSeedsPerBag = 228,
vrSeedsPerSack = 229,
vrCommodityPricePerBag = 230,
vrMassPerBag = 231,
vrMassPerSack = 232,
vrSeedLoadQuantityContainer = 233,
vrSeedLoadQuantitySack = 234,
vrCutVolume = 235,
vrMaxBestFitDrainSlope = 236,
vrMinBestFitDrainSlope = 237,
vrLinearFitDrainOffset = 238,
vrFlagLength = 239,
vrVerticalAccuracyBarStepSize = 240,
vrRowGuidanceSensorOffset = 241,
vrTankFillSessionArea = 242,
vrTankVolume = 243,
vrCargoWeightMass = 244,
vrCargoWeightVolume = 245,
vrTankVolumePercentage = 246,
vrEngineHours = 247,
vrFuelAmount = 248,
vrBufferZone = 249,
vrWaitingTime = 250,
vrProductContent = 251,
vrActiveIngredientMass = 252,
vrActiveIngredientVolume = 253,
vrProductLimitIndicationCount = 254,
vrProductLimitIndicationPercent = 255,
vrThousandCropWeight = 256,
vrPrimingInfoVolPerMass = 257,
vrPrimingInfoMassPerMass = 258,
vrActiveIngredientVolPerVol = 259,
vrGerminationRate = 260,
vrProvidedAmountVolume = 261,
vrProvidedAmountMass = 262,
vrTimeUntilEmpty = 263,
vrBatteryVoltage = 266,
vrEngineCoolantTemperature = 267,
vrEngineOilPressure = 268,
vrHydraulicOilTemperature = 269,
vrEngineSpeed = 271,
vrAirBrakePressure = 272,
vrAmbientAirTemperature = 273,
vrLFLateralNudgeExtent = 277,
vrLFInlineNudgeExtent = 278,
vrTransportDistance = 279,
vrIngredientDensity = 282,
vrProvidedAmountTotalMass = 283,
vrProvidedAmountTotalVolume = 284,
vrActiveIngredientMassPerMass = 285,
vrSeedSpacing = 286,
vrDownForceMargin = 287,
vrTransmissionOilTemperature = 288,
vrPricePerContainer = 289,
vrPricePerBushel = 290,
vrPricePerBag = 291,
vrPricePerSack = 292,
vrPriceSolutionLiquid = 293,
vrPriceSolutionDry = 294,
vrPriceSolutionGas = 295,
vrPricePerTime = 296,
vrPricePerArea = 297,
vrPricePerField = 298,
vrPricePerBale = 299,
vrPricePerMassCrop = 300,
vrPricePerMassCotton = 301,
vrMeasuredWeight = 302,
vrBaleSize = 303,
vrBaleTotal = 304,
vrLookAheadTime = 305,
vrTankNumber = 306,
vrImplementInGroundTurnRadius = 307,
vrDeltaT = 308,
vrCountPerArea = 309,
vrConstituentCrudeProtein = 310,
vrConstituentStarch = 311,
vrConstituentAcidDetergentFiber = 312,
vrConstituentNeutralDetergentFiber = 313,
vrConstituentSugar = 314,
vrConstituentAsh = 315,
vrConstituentCrudeFat = 316,
vrConstituentCrudeFiber = 317,
vrConstituentLignin = 318,
vrConstituentLactic = 319,
vrConstituentAcetic = 320,
vrConstituentButyric = 321,
vrConstituentAmmonia = 322,
vrConstituentNonStructuralCarbohydrate = 323,
vrConstituentProteinSolubility = 324,
vrConstituentAdjustedCrudeProtein = 325,
vrConstituentRumenUndegradableProtein = 326,
vrConstituentNonProteinNitrogen = 327,
vrConstituentTotalNitrogenKjeldahl = 328,
vrConstituentNitrogenNitrate = 329,
vrConstituentNitrogenAmmonium = 330,
vrConstituentDigestibleFat = 331,
vrConstituentNeutralDetergentFiberDigestibility = 332,
vrConstituentCellulose = 333,
vrConstituentHemicellulose = 334,
vrConstituentTotalDigestibleNutrients = 335,
vrConstituentNetEnergyForLactation = 336,
vrConstituentNetEnergyForMaintenance = 337,
vrConstituentNetEnergyForGain = 338,
vrConstituentDigestibleEnergy = 339,
vrConstituentMetabolizableEnergy = 340,
vrConstituentOil = 341,
vrConstituentSuspendedNitrogen = 342,
vrConstituentTotalPhosphorus = 343,
vrConstituentSuspendedPhosphorus = 344,
vrConstituentPotassium = 345,
vrConstituentSodium = 346,
vrConstituentMagnesium = 347,
vrConstituentCalcium = 348,
vrConstituentSulphur = 349,
vrConstituentMoistureReferenceA = 350,
vrConstituentMoistureReferenceB = 351,
vrConstituentMoistureReferenceC = 352,
vrConstituentInvalid = 353,
vrConstituentNitrogenAmmonia = 354,
vrConstituentPhosphorusAllTypes = 355,
vrInoculantDosingRateLow = 356,
vrInoculantDosingRateLowTotal = 357,
vrFuelVolumePerWetMass = 358,
vrFuelVolumePerDryMass = 359,
vrWetMassPerFuelVolume = 360,
vrDryMassPerFuelVolume = 361,
vrManureTotalSolids = 362,
vrTillageDepthActual = 363,
vrTillageDepthControl = 364,
vrCircleEdgeRadius = 365,
vrABCurveRadialShift = 366,
vrABCurveRadialTotalShift = 367,
vrTillagePressureTarget = 368,
vrTillagePressureActual = 369,
vrFuelProductivity = 370,
vrGuidanceShift = 371,
vrRemainingABLineDistance = 372,
vrTrackSpacingGap = 374,
vrSlowSpeed = 375,
vrActualSeedSpacingCV = 376,
vrPlantingSingulation = 377,
vrPlantingSkips = 378,
vrPlantingDoubles = 379,
vrDownForceApplied = 380,
vrGroundContact = 381,
vrRideQuality = 382,
vrTillagePressureSetPoint = 383,
vrHarvestTrash = 384,
vrYieldMassCane = 385,
vrYieldMassCanePerArea = 386,
vrYieldRawMassCane = 387,
vrYieldRawMassCanePerArea = 388,
vrCaneBilletLossMass = 389,
vrCaneResidueMass = 390,
vrYieldRawMass = 391,
vrYieldRawMassPerArea = 392,
vrYieldNetMass = 393,
vrYieldNetMassPerArea = 394,
vrYieldRawMassTotal = 395,
vrYieldNetMassTotal = 396,
vrSpecialtyCropMassProductivity = 397,
vrSeedSpacingDistance = 398,
vrSCTurnOnTime = 500,
vrSCTurnOffTime = 501,
vrAppliedYieldLatency = 503,
vrAppliedMoistureLatency = 504,
vrHeaderHours = 505,
vrSeparatorHours = 506,
vrDeltaDistance = 507,
vrDeltaArea = 508,
vrDeltaAppliedVolume = 509,
vrSolutionSystemFlowRatePerMinute = 511,
vrSCTuningDistance = 512,
vrSCTuningSpeed = 513,
vrFanSpeedSetPoint = 514,
vrFanSpeedTarget = 515,
vrFanSpeedActual = 516,
vrThreshingSpeedSetPoint = 517,
vrThreshingSpeedTarget = 518,
vrThreshingSpeedActual = 519,
vrThreshingClearanceSetPoint = 520,
vrThreshingClearanceTarget = 521,
vrThreshingClearanceActual = 522,
vrChaferPositionSetPoint = 523,
vrChafferPositionTarget = 524,
vrChafferPositionActual = 525,
vrSievePositionSetPoint = 526,
vrSievePositionTarget = 527,
vrSievePositionActual = 528,
vrRipperDepthSetPoint = 529,
vrRipperDepthTarget = 530,
vrRipperDepthActual = 531,
vrOpeningDiscDepthSetPoint = 532,
vrOpeningDiscDepthTarget = 533,
vrOpeningDiscDepthActual = 534,
vrClosingDiscDepthSetPoint = 535,
vrClosingDiscDepthTarget = 536,
vrClosingDiscDepthActual = 537,
vrBasketPressureSetPoint = 538,
vrBasketPressureTarget = 539,
vrBasketPressureActual = 540,
vrPrescriptionRateMultiplier = 541,
vrPrescriptionLookAheadTime = 542,
vrYieldCalibration = 543,
vrAvgYieldWetMassPerArea = 544,
vrAvgYieldMassPerArea = 545,
vrAvgHarvestMoisture = 546,
vrPlantingSkipsCount = 547,
vrPlantingDoublesCount = 548,
vrDistanceFromTrack = 549,
vrEngineLoadCurrentSpeed = 550,
vrProductIndex = 551,
vrDeltaAppRateMass = 552,
vrYieldWetMass = 553,
vrSolutionRateLiquidDistance = 554,
vrSolutionRateMassDistance = 555,
}
}
| 19.124626 | 91 | 0.623605 | [
"EPL-1.0"
] | AnkitGupta777/ADAPT | source/Representation/RepresentationSystem/RepresentationList.cs | 19,182 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Note : MonoBehaviour {
bool one;
int random;
//ノーツのスピードを入れておく変数
public float note1speed;
public float note2speed;
public float note3speed;
public float note4speed;
// Use this for initialization
void Start () {
one = true;
}
// Update is called once per frame
void Update () {
//Update関数の中で一度だけ実行する条件
if (one)
{
note1speed = NoteSpeeds();
Debug.Log(note1speed);
note2speed = NoteSpeeds();
Debug.Log(note2speed);
note3speed = NoteSpeeds();
Debug.Log(note3speed);
note4speed = NoteSpeeds();
Debug.Log(note4speed);
one = false;
}
//noteを動かす処理
GameObject note1 = GameObject.Find("note1");
note1.transform.position += new Vector3(note1speed, 0, 0);
GameObject note2 = GameObject.Find("note2");
note2.transform.position += new Vector3(note2speed, 0, 0);
GameObject note3 = GameObject.Find("note3");
note3.transform.position += new Vector3(note3speed, 0, 0);
GameObject note4 = GameObject.Find("note4");
note4.transform.position += new Vector3(note4speed, 0, 0);
//画面外に出たnoteを止める条件
//画面外に出たら敵にダメージを与える処理
if (note1.transform.position.x >= 7.5f)
{
note1.transform.position = new Vector2(7.5f, 3);
}
if (note2.transform.position.x >= 7.5f)
{
note2.transform.position = new Vector2(7.5f, 1.46f);
}
if (note3.transform.position.x >= 7.5f)
{
note3.transform.position = new Vector2(7.5f, 0);
}
if (note4.transform.position.x >= 7.5f)
{
note4.transform.position = new Vector2(7.5f, -1.65f);
}
//値によってランダムなnoteを戻らせる条件
random = RandomRange();
if (note1.transform.position.x == 7.5f)
{
if (random >= 4500 && random <= 4750)
{
note1.transform.position = new Vector2(-3, 3);
}
}
if (note2.transform.position.x == 7.5f)
{
if (random > 4750 && random <= 5000)
{
note2.transform.position = new Vector2(-3, 1.46f);
}
}
if (note3.transform.position.x == 7.5f)
{
if (random > 5000 && random <= 5250)
{
note3.transform.position = new Vector2(-3, 0);
}
}
if (note4.transform.position.x == 7.5f)
{
if (random > 5250 && random <= 5500)
{
note4.transform.position = new Vector2(-3, -1.65f);
}
}
}
//noteのスピードを変える変数
private float NoteSpeeds()
{
float noteSpeed = Random.Range(0.05f, 0.15f);
return noteSpeed;
}
//noteが戻るためのランダムな値を出す関数
private int RandomRange()
{
int random = Random.Range(0, 10000);
return random;
}
}
| 29.009346 | 67 | 0.527384 | [
"MIT"
] | dependd/Fight-Animal | Assets/Scripts/Note.cs | 3,332 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09.ExtremeList
{
class Program
{
// 9. Списък от крайности
static void Main(string[] args)
{
var nums = Console.ReadLine().Split().Select(int.Parse).ToList();
List<int> result = new List<int>();
// Намираме най-малкото и най-голямото число
int min = nums[0], max = nums[0];
foreach (var item in nums)
{
if (item < min) min = item;
if (item > max) max = item;
}
for (int index = 0; index < nums.Count; index++)
{
// Добавяме стойността към списъка result
if (nums[index] == min || nums[index] == max)
result.Add(nums[index]);
}
// Сортираме и отпечатваме списъка
result.Sort();
Console.WriteLine(string.Join(" ", result));
}
}
}
| 28.236842 | 77 | 0.491146 | [
"MIT"
] | dimitarminchev/ITCareer | 02. Programming/2019/2019.02.16/09. ExtremeList/Program.cs | 1,183 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Xero.NetStandard.OAuth2.Model.Accounting;
using Xero.NetStandard.OAuth2.Token;
using Xero.NetStandard.OAuth2.Api;
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Client;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Net.Http;
namespace XeroNetStandardApp.Controllers
{
public class ContactsInfo : Controller
{
private readonly ILogger<AuthorizationController> _logger;
private readonly IOptions<XeroConfiguration> XeroConfig;
public ContactsInfo(IOptions<XeroConfiguration> XeroConfig, ILogger<AuthorizationController> logger)
{
_logger = logger;
this.XeroConfig = XeroConfig;
}
// GET: /Contacts/
public async Task<ActionResult> Index()
{
var xeroToken = TokenUtilities.GetStoredToken();
var utcTimeNow = DateTime.UtcNow;
if (utcTimeNow > xeroToken.ExpiresAtUtc)
{
var client = new XeroClient(XeroConfig.Value);
xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);
TokenUtilities.StoreToken(xeroToken);
}
string accessToken = xeroToken.AccessToken;
Guid tenantId = TokenUtilities.GetCurrentTenantId();
string xeroTenantId;
if (xeroToken.Tenants.Any((t) => t.TenantId == tenantId))
{
xeroTenantId = tenantId.ToString();
}
else
{
var id = xeroToken.Tenants.First().TenantId;
xeroTenantId = id.ToString();
TokenUtilities.StoreTenantId(id);
}
var AccountingApi = new AccountingApi();
var response = await AccountingApi.GetContactsAsync(accessToken, xeroTenantId);
ViewBag.jsonResponse = response.ToJson();
var contacts = response._Contacts;
return View(contacts);
}
// GET: /Contacts#Create
[HttpGet]
public IActionResult Create()
{
return View();
}
// POST: /Contacts#Create
[HttpPost]
public async Task<ActionResult> Create(string name, string emailAddress)
{
var xeroToken = TokenUtilities.GetStoredToken();
var utcTimeNow = DateTime.UtcNow;
if (utcTimeNow > xeroToken.ExpiresAtUtc)
{
var client = new XeroClient(XeroConfig.Value);
xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);
TokenUtilities.StoreToken(xeroToken);
}
string accessToken = xeroToken.AccessToken;
Guid tenantId = TokenUtilities.GetCurrentTenantId();
string xeroTenantId;
if (xeroToken.Tenants.Any((t) => t.TenantId == tenantId))
{
xeroTenantId = tenantId.ToString();
}
else
{
var id = xeroToken.Tenants.First().TenantId;
xeroTenantId = id.ToString();
TokenUtilities.StoreTenantId(id);
}
var contact = new Contact{
Name = name,
EmailAddress = emailAddress
};
var contacts = new Contacts();
contacts._Contacts = new List<Contact>() { contact };
var AccountingApi = new AccountingApi();
var response = await AccountingApi.CreateContactsAsync(accessToken, xeroTenantId, contacts);
return RedirectToAction("Index", "ContactsInfo");
}
}
} | 29.522124 | 104 | 0.678957 | [
"MIT"
] | XeroAPI/Xero-NetStandard-OAuth2-App | XeroNetStandardApp/Controllers/ContactsInfoController.cs | 3,336 | C# |
using System;
using System.Dynamic;
using RazorLight.Extensions;
using System.Reflection;
using System.Linq;
namespace RazorLight
{
/// <summary>
/// Stores information about model of the template page
/// </summary>
public class ModelTypeInfo
{
/// <summary>
/// Indicates whether given model is not a dynamic or anonymous object
/// </summary>
public bool IsStrongType { get; private set; }
/// <summary>
/// Real type of the model
/// </summary>
public Type Type { get; private set; }
/// <summary>
/// Type that will be used on compilation of the template.
/// If <see cref="Type"/> is anonymous or dynamic - <see cref="TemplateType"/> becomes <see cref="ExpandoObject"/>
/// </summary>
public Type TemplateType { get; private set; }
/// <summary>
/// Name of the type that will be used on compilation of the template
/// </summary>
public string TemplateTypeName { get; private set; }
/// <summary>
/// Transforms object into template type
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public object CreateTemplateModel(object model)
{
return this.IsStrongType ? model : model.ToExpando();
}
public ModelTypeInfo(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
this.Type = type;
this.IsStrongType = type != typeof(ExpandoObject) && !Type.IsAnonymousType();
this.TemplateType = IsStrongType ? Type : typeof(ExpandoObject);
this.TemplateTypeName = IsStrongType ? GetFriendlyName(Type) : "dynamic";
}
public static string GetFriendlyName(Type type)
{
if (IsGenericType(type))
return type.Namespace + "." + type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
else
return $"{type.Namespace}.{type.Name}";
}
private static bool IsGenericType(Type type)
{
#if NETSTANDARD1_6
return type.GetTypeInfo().IsGenericType;
#endif
#if NET451
return type.IsGenericType;
#endif
}
}
}
| 26.153846 | 160 | 0.670588 | [
"Apache-2.0"
] | mcintyre321/RazorLight | src/RazorLight/ModelTypeInfo.cs | 2,042 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Abp.Extensions;
namespace Book.Identity
{
public class ExternalLoginInfoHelper
{
public static (string name, string surname) GetNameAndSurnameFromClaims(List<Claim> claims)
{
string name = null;
string surname = null;
var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty())
{
name = givennameClaim.Value;
}
var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty())
{
surname = surnameClaim.Value;
}
if (name == null || surname == null)
{
var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
if (nameClaim != null)
{
var nameSurName = nameClaim.Value;
if (!nameSurName.IsNullOrEmpty())
{
var lastSpaceIndex = nameSurName.LastIndexOf(' ');
if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2))
{
name = surname = nameSurName;
}
else
{
name = nameSurName.Substring(0, lastSpaceIndex);
surname = nameSurName.Substring(lastSpaceIndex);
}
}
}
}
return (name, surname);
}
}
}
| 34.09434 | 99 | 0.481461 | [
"MIT"
] | yangcs2016/phoneBooks | aspnet-core/src/Book.Web.Core/Identity/ExternalLoginInfoHelper.cs | 1,809 | C# |
using Assets.Code.Bon.Socket;
namespace Assets.Code.Bon.Interface
{
public interface IStringSampler
{
string GetString(OutputSocket outSocket);
}
}
| 15.5 | 43 | 0.774194 | [
"MIT"
] | aphex-/BrotherhoodOfNode | Assets/Code/Bon/Interface/IStringSampler.cs | 157 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V25.Segment;
using NHapi.Model.V25.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V25.Group
{
///<summary>
///Represents the RSP_Z88_COMMON_ORDER Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: ORC (Common Order) </li>
///<li>1: RSP_Z88_TIMING (a Group object) optional repeating</li>
///<li>2: RSP_Z88_ORDER_DETAIL (a Group object) optional </li>
///<li>3: RSP_Z88_ORDER_ENCODED (a Group object) optional </li>
///<li>4: RXD (Pharmacy/Treatment Dispense) </li>
///<li>5: RXR (Pharmacy/Treatment Route) repeating</li>
///<li>6: RXC (Pharmacy/Treatment Component Order) optional repeating</li>
///<li>7: RSP_Z88_OBSERVATION (a Group object) repeating</li>
///</ol>
///</summary>
[Serializable]
public class RSP_Z88_COMMON_ORDER : AbstractGroup {
///<summary>
/// Creates a new RSP_Z88_COMMON_ORDER Group.
///</summary>
public RSP_Z88_COMMON_ORDER(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(ORC), true, false);
this.add(typeof(RSP_Z88_TIMING), false, true);
this.add(typeof(RSP_Z88_ORDER_DETAIL), false, false);
this.add(typeof(RSP_Z88_ORDER_ENCODED), false, false);
this.add(typeof(RXD), true, false);
this.add(typeof(RXR), true, true);
this.add(typeof(RXC), false, true);
this.add(typeof(RSP_Z88_OBSERVATION), true, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RSP_Z88_COMMON_ORDER - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns ORC (Common Order) - creates it if necessary
///</summary>
public ORC ORC {
get{
ORC ret = null;
try {
ret = (ORC)this.GetStructure("ORC");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of RSP_Z88_TIMING (a Group object) - creates it if necessary
///</summary>
public RSP_Z88_TIMING GetTIMING() {
RSP_Z88_TIMING ret = null;
try {
ret = (RSP_Z88_TIMING)this.GetStructure("TIMING");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RSP_Z88_TIMING
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RSP_Z88_TIMING GetTIMING(int rep) {
return (RSP_Z88_TIMING)this.GetStructure("TIMING", rep);
}
/**
* Returns the number of existing repetitions of RSP_Z88_TIMING
*/
public int TIMINGRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("TIMING").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RSP_Z88_TIMING results
*/
public IEnumerable<RSP_Z88_TIMING> TIMINGs
{
get
{
for (int rep = 0; rep < TIMINGRepetitionsUsed; rep++)
{
yield return (RSP_Z88_TIMING)this.GetStructure("TIMING", rep);
}
}
}
///<summary>
///Adds a new RSP_Z88_TIMING
///</summary>
public RSP_Z88_TIMING AddTIMING()
{
return this.AddStructure("TIMING") as RSP_Z88_TIMING;
}
///<summary>
///Removes the given RSP_Z88_TIMING
///</summary>
public void RemoveTIMING(RSP_Z88_TIMING toRemove)
{
this.RemoveStructure("TIMING", toRemove);
}
///<summary>
///Removes the RSP_Z88_TIMING at the given index
///</summary>
public void RemoveTIMINGAt(int index)
{
this.RemoveRepetition("TIMING", index);
}
///<summary>
/// Returns RSP_Z88_ORDER_DETAIL (a Group object) - creates it if necessary
///</summary>
public RSP_Z88_ORDER_DETAIL ORDER_DETAIL {
get{
RSP_Z88_ORDER_DETAIL ret = null;
try {
ret = (RSP_Z88_ORDER_DETAIL)this.GetStructure("ORDER_DETAIL");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns RSP_Z88_ORDER_ENCODED (a Group object) - creates it if necessary
///</summary>
public RSP_Z88_ORDER_ENCODED ORDER_ENCODED {
get{
RSP_Z88_ORDER_ENCODED ret = null;
try {
ret = (RSP_Z88_ORDER_ENCODED)this.GetStructure("ORDER_ENCODED");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns RXD (Pharmacy/Treatment Dispense) - creates it if necessary
///</summary>
public RXD RXD {
get{
RXD ret = null;
try {
ret = (RXD)this.GetStructure("RXD");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of RXR (Pharmacy/Treatment Route) - creates it if necessary
///</summary>
public RXR GetRXR() {
RXR ret = null;
try {
ret = (RXR)this.GetStructure("RXR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RXR
/// * (Pharmacy/Treatment Route) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RXR GetRXR(int rep) {
return (RXR)this.GetStructure("RXR", rep);
}
/**
* Returns the number of existing repetitions of RXR
*/
public int RXRRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("RXR").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RXR results
*/
public IEnumerable<RXR> RXRs
{
get
{
for (int rep = 0; rep < RXRRepetitionsUsed; rep++)
{
yield return (RXR)this.GetStructure("RXR", rep);
}
}
}
///<summary>
///Adds a new RXR
///</summary>
public RXR AddRXR()
{
return this.AddStructure("RXR") as RXR;
}
///<summary>
///Removes the given RXR
///</summary>
public void RemoveRXR(RXR toRemove)
{
this.RemoveStructure("RXR", toRemove);
}
///<summary>
///Removes the RXR at the given index
///</summary>
public void RemoveRXRAt(int index)
{
this.RemoveRepetition("RXR", index);
}
///<summary>
/// Returns first repetition of RXC (Pharmacy/Treatment Component Order) - creates it if necessary
///</summary>
public RXC GetRXC() {
RXC ret = null;
try {
ret = (RXC)this.GetStructure("RXC");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RXC
/// * (Pharmacy/Treatment Component Order) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RXC GetRXC(int rep) {
return (RXC)this.GetStructure("RXC", rep);
}
/**
* Returns the number of existing repetitions of RXC
*/
public int RXCRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("RXC").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RXC results
*/
public IEnumerable<RXC> RXCs
{
get
{
for (int rep = 0; rep < RXCRepetitionsUsed; rep++)
{
yield return (RXC)this.GetStructure("RXC", rep);
}
}
}
///<summary>
///Adds a new RXC
///</summary>
public RXC AddRXC()
{
return this.AddStructure("RXC") as RXC;
}
///<summary>
///Removes the given RXC
///</summary>
public void RemoveRXC(RXC toRemove)
{
this.RemoveStructure("RXC", toRemove);
}
///<summary>
///Removes the RXC at the given index
///</summary>
public void RemoveRXCAt(int index)
{
this.RemoveRepetition("RXC", index);
}
///<summary>
/// Returns first repetition of RSP_Z88_OBSERVATION (a Group object) - creates it if necessary
///</summary>
public RSP_Z88_OBSERVATION GetOBSERVATION() {
RSP_Z88_OBSERVATION ret = null;
try {
ret = (RSP_Z88_OBSERVATION)this.GetStructure("OBSERVATION");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RSP_Z88_OBSERVATION
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RSP_Z88_OBSERVATION GetOBSERVATION(int rep) {
return (RSP_Z88_OBSERVATION)this.GetStructure("OBSERVATION", rep);
}
/**
* Returns the number of existing repetitions of RSP_Z88_OBSERVATION
*/
public int OBSERVATIONRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("OBSERVATION").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RSP_Z88_OBSERVATION results
*/
public IEnumerable<RSP_Z88_OBSERVATION> OBSERVATIONs
{
get
{
for (int rep = 0; rep < OBSERVATIONRepetitionsUsed; rep++)
{
yield return (RSP_Z88_OBSERVATION)this.GetStructure("OBSERVATION", rep);
}
}
}
///<summary>
///Adds a new RSP_Z88_OBSERVATION
///</summary>
public RSP_Z88_OBSERVATION AddOBSERVATION()
{
return this.AddStructure("OBSERVATION") as RSP_Z88_OBSERVATION;
}
///<summary>
///Removes the given RSP_Z88_OBSERVATION
///</summary>
public void RemoveOBSERVATION(RSP_Z88_OBSERVATION toRemove)
{
this.RemoveStructure("OBSERVATION", toRemove);
}
///<summary>
///Removes the RSP_Z88_OBSERVATION at the given index
///</summary>
public void RemoveOBSERVATIONAt(int index)
{
this.RemoveRepetition("OBSERVATION", index);
}
}
}
| 28.330233 | 158 | 0.670497 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V25/Group/RSP_Z88_COMMON_ORDER.cs | 12,182 | C# |
using System.Collections.Generic;
namespace JeffSiver.ObjectPrinter.Tests.Objects
{
public class ComplexEnumerable
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<string> Values { get; set; }
public IEnumerable<Simple> SimpleList { get; set; }
public static ComplexEnumerable Build()
{
return new ComplexEnumerable
{
Id = 12,
Name = "the name of this is name",
Values = new List<string> { "first", "second"},
SimpleList = new []{Simple.Build(), Simple.Build()}
};
}
}
} | 28.125 | 67 | 0.540741 | [
"MIT"
] | jeffsiver/DotNetPrettyPrint | ObjectPrinter.Tests/Objects/ComplexEnumerable.cs | 677 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Codeworx.Identity.OAuth;
using Codeworx.Identity.View;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace Codeworx.Identity.AspNetCore.OAuth.Binder
{
public class AuthorizationSuccessResponseBinder : ResponseBinder<AuthorizationSuccessResponse>
{
private readonly IFormPostResponseTypeTemplateCache _view;
public AuthorizationSuccessResponseBinder(IFormPostResponseTypeTemplateCache view)
{
_view = view;
}
public override async Task BindAsync(AuthorizationSuccessResponse responseData, HttpResponse response)
{
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
if (responseData == null)
{
throw new ArgumentNullException(nameof(responseData));
}
if (Equals(responseData.ResponseMode, Constants.OpenId.ResponseMode.FormPost))
{
response.Headers.Add(HeaderNames.ContentType, "text/html;charset=UTF-8");
response.Headers.Add(HeaderNames.CacheControl, "no-store, must-revalidate, max-age=0");
var html = await _view.GetFormPostView(response.GetViewContextData(responseData));
await response.WriteAsync(html);
}
else
{
var redirectUriBuilder = new UriBuilder(responseData.RedirectUri);
var parameters = new Dictionary<string, string>();
if (!string.IsNullOrWhiteSpace(responseData.State))
{
parameters.Add(Constants.OAuth.StateName, responseData.State);
}
if (!string.IsNullOrWhiteSpace(responseData.Code))
{
parameters.Add(Constants.OAuth.CodeName, responseData.Code);
}
if (!string.IsNullOrWhiteSpace(responseData.Token))
{
parameters.Add(Constants.OAuth.AccessTokenName, responseData.Token);
}
if (responseData.ExpiresIn.HasValue)
{
parameters.Add(Constants.OAuth.ExpiresInName, responseData.ExpiresIn.Value.ToString());
}
if (!string.IsNullOrWhiteSpace(responseData.IdToken))
{
parameters.Add(Constants.OpenId.IdTokenName, responseData.IdToken);
}
if (responseData.ResponseMode == Constants.OAuth.ResponseMode.Query)
{
foreach (var item in parameters)
{
redirectUriBuilder.AppendQueryParameter(item.Key, item.Value);
}
}
else
{
foreach (var item in parameters)
{
redirectUriBuilder.AppendFragment(item.Key, item.Value);
}
}
response.Redirect(redirectUriBuilder.ToString());
}
}
}
} | 35.611111 | 110 | 0.563807 | [
"MIT"
] | SteSinger/identity | src/Codeworx.Identity.AspNetCore/OAuth/Binder/AuthorizationSuccessResponseBinder.cs | 3,207 | C# |
namespace Nancy.Tests.Unit.Extensions
{
using System.Collections.Generic;
using Nancy.Extensions;
using Fakes;
using Xunit;
public class RequestExtensionsFixture
{
[Fact]
public void IsAjaxRequest_should_return_true_if_request_is_ajax()
{
// Given
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "X-Requested-With", new[] { "XMLHttpRequest" } }
};
// When
var request = new FakeRequest("POST", "/", headers);
// Then
Assert.True(request.IsAjaxRequest());
}
[Fact]
public void IsAjaxRequest_should_return_false_if_request_is_not_ajax()
{
// Given when
var request = new FakeRequest("POST", "/");
// Then
Assert.False(request.IsAjaxRequest());
}
[Fact]
public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV6()
{
// Given when
var request = new FakeRequest("GET", "/", string.Empty, "::1");
request.Url.HostName = "localhost";
// Then
Assert.True(request.IsLocal());
}
[Fact]
public void IsLocal_should_return_false_if_userHostAddr_is_empty()
{
// Given when
var request = new FakeRequest("GET", "/", string.Empty, string.Empty);
// Then
Assert.False(request.IsLocal());
}
[Fact]
public void IsLocal_should_return_false_if_urlString_is_empty()
{
// Given when
var request = new FakeRequest("GET", string.Empty, string.Empty, string.Empty);
// Then
Assert.False(request.IsLocal());
}
[Fact]
public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV4()
{
// Given when
var request = new FakeRequest("POST", "/", string.Empty, "127.0.0.1");
request.Url.HostName = "localhost";
// Then
Assert.True(request.IsLocal());
}
[Fact]
public void IsLocal_should_return_false_if_userHostAddr_is_not_localhost()
{
// Given when
var request = new FakeRequest("GET", "/", string.Empty, "86.13.73.12");
request.Url.HostName = "anotherhost";
// Then
Assert.False(request.IsLocal());
}
}
}
| 29.252747 | 92 | 0.510894 | [
"MIT"
] | Adalyat/Nancy | src/Nancy.Tests/Unit/Extensions/RequestExtensionsFixture.cs | 2,664 | C# |
using System.ComponentModel.DataAnnotations;
namespace EHospital.Authorization.Model.Models
{
/// <summary>
/// Db secrets
/// </summary>
public class Secrets
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Password should be entered.")]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 5)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
}
| 27.6 | 124 | 0.608696 | [
"MIT"
] | Kropisha/EHospital.Authorization | EHospital.Authorization.Model/Models/Secrets.cs | 554 | 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 Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool SetProcessWorkingSetSizeEx(SafeProcessHandle handle, IntPtr min, IntPtr max, int flags);
}
}
| 34.588235 | 124 | 0.760204 | [
"MIT"
] | 06needhamt/runtime | src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetProcessWorkingSetSizeEx.cs | 588 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using LinkedMink.Web.EnvironManager.ViewModels;
using Microsoft.Extensions.Logging;
namespace LinkedMink.Web.EnvironManager.Services
{
public class HardwareDeviceStatusService : IHardwareDeviceStatusService
{
public HardwareDeviceStatusService(
ILogger<HardwareDeviceStatusService> logger,
IHttpClientFactory clientFactory)
{
_logger = logger;
_clientFactory = clientFactory;
}
public async Task<HardwareDeviceStatusViewModel> GetStatusAsync(string host, ushort port)
{
var request = new HttpRequestMessage(
HttpMethod.Get,
$"http://{host}:{port}/status");
try
{
using (var client = _clientFactory.CreateClient())
using (var response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
return new HardwareDeviceStatusViewModel()
{
IsOnline = true,
Response = await response.Content.ReadAsStringAsync()
};
}
}
}
catch (HttpRequestException ex)
{
_logger.LogError(ex.ToString());
}
return new HardwareDeviceStatusViewModel()
{
IsOnline = false,
Response = null
};
}
private readonly ILogger _logger;
private readonly IHttpClientFactory _clientFactory;
}
}
| 31.090909 | 97 | 0.532749 | [
"MIT"
] | LinkedMink/environ-manager-server | LinkedMink.Web.EnvironManager/Services/HardwareDeviceStatusService.cs | 1,712 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.ServiceFabric.ReliableCollectionBackup.Parser;
namespace Microsoft.ServiceFabric.ReliableCollectionBackup.RestServer.Controllers
{
/// <summary>
/// ExitController for exiting the Rest Server.
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class ExitController : ControllerBase
{
public ExitController(BackupParserManager backupParserManager)
{
this.backupParserManager = backupParserManager;
}
// GET api/exit
[HttpGet]
public void Get()
{
// Dispose backup parser for cleanup.
this.backupParserManager.Dispose();
Task.Run(async () =>
{
// give time for /api/exit to return 200.
await Task.Delay(1000);
// todo : if there are multiple web-host, don't just exit.
// create a webhost manager to exit when all web host has exited.
Environment.Exit(0);
});
}
BackupParserManager backupParserManager;
}
}
| 32.488889 | 98 | 0.569767 | [
"MIT"
] | Bhaskers-Blu-Org2/service-fabric-backup-explorer | src/Microsoft.ServiceFabric.ReliableCollectionBackup/RestServer/Controllers/ExitController.cs | 1,462 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace FooRESTApi.Areas.HelpPage.ModelDescriptions
{
internal static class ModelNameHelper
{
// Modify this to provide custom model name mapping.
public static string GetModelName(Type type)
{
ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))
{
return modelNameAttribute.Name;
}
string modelName = type.Name;
if (type.IsGenericType)
{
// Format the generic type name to something like: GenericOfAgurment1AndArgument2
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.Name;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));
}
return modelName;
}
}
} | 39.972222 | 140 | 0.635858 | [
"MIT"
] | sameerkapps/Upgrade-.csproj | FooRESTApi/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs | 1,439 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Expression")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Expression")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("c200865c-53db-49b8-9850-ffe53a5949a2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486 | 85 | 0.72823 | [
"MIT"
] | AscenKeeprov/Programming-Basics | Exercise1-FirstSteps/Expression/Properties/AssemblyInfo.cs | 1,427 | 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.
namespace StarkPlatform.Compiler.Operations
{
/// <summary>
/// Represents an operation that drops the resulting value and the type of the underlying wrapped <see cref="Operation"/>.
/// <para>
/// Current usage:
/// (1) C# expression statement.
/// (2) VB expression statement.
/// </para>
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IExpressionStatementOperation : IOperation
{
/// <summary>
/// Underlying operation with a value and type.
/// </summary>
IOperation Operation { get; }
}
}
| 34.346154 | 161 | 0.641657 | [
"BSD-2-Clause",
"MIT"
] | encrypt0r/stark | src/compiler/StarkPlatform.Compiler/Operations/IExpressionStatementOperation.cs | 895 | C# |
namespace DotEco.Application.Dtos
{
public class CouponsDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Percent { get; set; }
public string Description { get; set; }
public string Status { get; set; }
public string UserFullName { get; set; }
public string CompanyFullName { get; set; }
public int CompanyId { get; set; }
public int? UserId { get; set; }
public UserDto Users { get; set; }
}
} | 32.3125 | 51 | 0.580271 | [
"MIT"
] | Pedrolustosa/DotEco | Back/src/DotEco.Application/Dtos/CouponsDto.cs | 517 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crmf
{
public class RegTokenControl
: IControl
{
private static readonly DerObjectIdentifier type = CrmfObjectIdentifiers.id_regCtrl_regToken;
private readonly DerUtf8String token;
/// <summary>
/// Basic constructor - build from a UTF-8 string representing the token.
/// </summary>
/// <param name="token">UTF-8 string representing the token.</param>
public RegTokenControl(DerUtf8String token)
{
this.token = token;
}
/// <summary>
/// Basic constructor - build from a string representing the token.
/// </summary>
/// <param name="token">string representing the token.</param>
public RegTokenControl(string token)
{
this.token = new DerUtf8String(token);
}
/// <summary>
/// Return the type of this control.
/// </summary>
/// <returns>CRMFObjectIdentifiers.id_regCtrl_regToken</returns>
public DerObjectIdentifier Type
{
get { return type; }
}
/// <summary>
/// Return the token associated with this control (a UTF8String).
/// </summary>
/// <returns>a UTF8String.</returns>
public Asn1Encodable Value
{
get { return token; }
}
}
}
#pragma warning restore
#endif
| 29.535714 | 101 | 0.614268 | [
"MIT"
] | Bregermann/TargetCrack | Target Crack/Assets/Best HTTP/Source/SecureProtocol/crmf/RegTokenControl.cs | 1,654 | C# |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Rulesets.Scoring
{
public enum HitResult
{
/// <summary>
/// Indicates that the object has not been judged yet.
/// </summary>
[Description(@"")]
None,
/// <summary>
/// Indicates that the object has been judged as a miss.
/// </summary>
[Description(@"Miss")]
Miss,
[Description(@"Meh")]
Meh,
/// <summary>
/// Optional judgement.
/// </summary>
[Description(@"OK")]
Ok,
[Description(@"Good")]
Good,
[Description(@"Great")]
Great,
/// <summary>
/// Optional judgement.
/// </summary>
[Description(@"Perfect")]
Perfect,
}
}
| 22.568182 | 93 | 0.494461 | [
"MIT"
] | anellie/osu | osu.Game/Rulesets/Scoring/HitResult.cs | 993 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Hina;
using Hina.Collections;
using Hina.Reflection;
namespace RtmpSharp.IO
{
partial class AmfWriter
{
class Amf0
{
readonly SerializationContext context;
readonly ReferenceList<object> refs;
readonly Base b;
readonly Amf3 amf3;
public Amf0(SerializationContext context, Base b, Amf3 amf3)
{
this.b = b;
this.amf3 = amf3;
this.context = context;
this.refs = new ReferenceList<object>();
}
// helper methods
public void Reset() => refs.Clear();
void ReferenceAdd(object value) => refs.Add(value, out var _);
bool ReferenceAdd(object value, out ushort index) => refs.Add(value, out index);
bool ReferenceGet(object value, out ushort index) => refs.TryGetValue(value, out index);
// writers
public void WriteItem(object value)
{
if (value == null)
{
WriteMarker(Marker.Null);
}
else if (ReferenceGet(value, out var index))
{
WriteMarker(Marker.Reference);
b.WriteUInt16(index);
}
else
{
WriteItemInternal(value);
}
}
// writes an object, with the specified encoding. if amf3 encoding is specified, then it is wrapped in an
// amf0 envelope that says to upgrade the encoding to amf3
public void WriteBoxedItem(ObjectEncoding encoding, object value)
{
if (value == null)
{
WriteMarker(Marker.Null);
}
else if (ReferenceGet(value, out var index))
{
WriteMarker(Marker.Reference);
b.WriteUInt16(index);
}
else
{
switch (encoding)
{
case ObjectEncoding.Amf0:
WriteItemInternal(value);
break;
case ObjectEncoding.Amf3:
WriteMarker(Marker.Amf3Object);
amf3.WriteItem(value);
break;
default:
throw new ArgumentOutOfRangeException(nameof(encoding));
}
}
}
void WriteItemInternal(object value)
{
var type = value.GetType();
if (NumberTypes.Contains(type)) WriteNumber(Convert.ToDouble(value));
else if (Writers.TryGetValue(type, out var write)) write(this, value);
else DispatchGenericWrite(value);
}
// writes a string, either as a short or long strong depending on length.
void WriteVariantString(string value)
{
CheckDebug.NotNull(value);
var utf8 = Encoding.UTF8.GetBytes(value);
var length = utf8.Length;
if (length < ushort.MaxValue)
{
// unsigned 16-bit length
WriteMarker(Marker.String);
b.WriteUInt16((ushort)utf8.Length);
b.WriteBytes(utf8);
}
else
{
// unsigned 32-bit length
WriteMarker(Marker.LongString);
b.WriteUInt32((uint)utf8.Length);
b.WriteBytes(utf8);
}
}
void WriteAsObject(AsObject value)
{
CheckDebug.NotNull(value);
ReferenceAdd(value);
if (string.IsNullOrEmpty(value.TypeName))
{
WriteMarker(Marker.Object);
}
else
{
WriteMarker(Marker.TypedObject);
b.WriteUtfPrefixed(value.TypeName);
}
foreach (var property in value)
{
b.WriteUtfPrefixed(property.Key);
WriteItem(property.Value);
}
// object end is marked with a zero-length field name, and an end of object marker.
b.WriteUInt16(0);
WriteMarker(Marker.ObjectEnd);
}
void WriteTypedObject(object value)
{
CheckDebug.NotNull(value);
ReferenceAdd(value);
var klass = context.GetClassInfo(value);
WriteMarker(Marker.TypedObject);
b.WriteUtfPrefixed(klass.Name);
foreach (var member in klass.Members)
{
b.WriteUtfPrefixed(member.Name);
WriteItem(member.GetValue(value));
}
// object end is marked with a zero-length field name, and an end of object marker.
b.WriteUInt16(0);
WriteMarker(Marker.ObjectEnd);
}
void WriteDateTime(DateTime value)
{
// http://download.macromedia.com/pub/labs/amf/amf0_spec_121207.pdf
// """
// While the design of this type reserves room for time zone offset information,
// it should not be filled in, nor used, as it is unconventional to change time
// zones when serializing dates on a network. It is suggested that the time zone
// be queried independently as needed.
// -- AMF0 specification, 2.13 Date Type
// """
var duration = value.ToUniversalTime() - UnixDateTime.Epoch;
WriteMarker(Marker.Date);
b.WriteDouble(duration.TotalMilliseconds);
b.WriteUInt16(0); // time zone offset
}
void WriteXDocument(XDocument value)
{
CheckDebug.NotNull(value);
ReferenceAdd(value);
UnmarkedWriteLongString(
value.ToString(SaveOptions.DisableFormatting));
}
void WriteXElement(XElement value)
{
CheckDebug.NotNull(value);
ReferenceAdd(value);
UnmarkedWriteLongString(
value.ToString(SaveOptions.DisableFormatting));
}
void WriteArray(IEnumerable enumerable, int length)
{
CheckDebug.NotNull(enumerable);
ReferenceAdd(enumerable);
b.WriteInt32(length);
foreach (var element in enumerable)
WriteItem(element);
}
void WriteAssociativeArray(IDictionary<string, object> dictionary)
{
CheckDebug.NotNull(dictionary);
ReferenceAdd(dictionary);
WriteMarker(Marker.EcmaArray);
b.WriteInt32(dictionary.Count);
foreach (var (key, value) in dictionary)
{
b.WriteUtfPrefixed(key);
WriteItem(value);
}
// object end is marked with a zero-length field name, and an end of object marker.
b.WriteUInt16(0);
WriteMarker(Marker.ObjectEnd);
}
void WriteBoolean(bool value)
{
WriteMarker(Marker.Boolean);
b.WriteBoolean(value);
}
void WriteNumber(double value)
{
WriteMarker(Marker.Number);
b.WriteDouble(value);
}
void DispatchGenericWrite(object value)
{
switch (value)
{
case Enum e:
WriteNumber(Convert.ToDouble(e));
break;
case IDictionary<string, object> dictionary:
WriteAssociativeArray(dictionary);
break;
case IList list:
WriteArray(list, list.Count);
break;
case ICollection collection:
WriteArray(collection, collection.Count);
break;
case IEnumerable enumerable:
var type = value.GetType();
if (type.ImplementsGenericInterface(typeof(ICollection<>)) || type.ImplementsGenericInterface(typeof(IList<>)))
{
dynamic d = value;
int count = d.Count;
WriteArray(enumerable, count);
}
else
{
var values = enumerable.Cast<object>().ToArray();
WriteArray(values, values.Length);
}
break;
default:
WriteTypedObject(value);
break;
}
}
void UnmarkedWriteLongString(string value)
{
CheckDebug.NotNull(value);
var utf8 = Encoding.UTF8.GetBytes(value);
WriteMarker(Marker.LongString);
b.WriteUInt32((uint)utf8.Length);
b.WriteBytes(utf8);
}
void WriteMarker(Marker marker)
{
b.WriteByte((byte)marker);
}
static readonly Type[] NumberTypes =
{
typeof(Byte),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(SByte),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal)
};
// ordering is important, entries here are checked sequentially
static readonly IDictionary<Type, Action<Amf0, object>> Writers = new KeyDictionary<Type, Action<Amf0, object>>()
{
{ typeof(bool), (x, v) => x.WriteBoolean((bool)v) },
{ typeof(char), (x, v) => x.WriteVariantString(v.ToString()) },
{ typeof(string), (x, v) => x.WriteVariantString((string)v) },
{ typeof(DateTime), (x, v) => x.WriteDateTime((DateTime)v) },
{ typeof(AsObject), (x, v) => x.WriteAsObject((AsObject)v) },
{ typeof(Guid), (x, v) => x.WriteVariantString(v.ToString()) },
{ typeof(XDocument), (x, v) => x.WriteXDocument((XDocument)v) },
{ typeof(XElement), (x, v) => x.WriteXElement((XElement)v) },
};
enum Marker : byte
{
Number = 0x00, // 0x00 | 0
Boolean = 0x01, // 0x01 | 1
String = 0x02, // 0x02 | 2
Object = 0x03, // 0x03 | 3
Movieclip = 0x04, // 0x04 | 4
Null = 0x05, // 0x05 | 5
Undefined = 0x06, // 0x06 | 6
Reference = 0x07, // 0x07 | 7
EcmaArray = 0x08, // 0x08 | 8
ObjectEnd = 0x09, // 0x09 | 9
StrictArray = 0x0A, // 0x0A | 10
Date = 0x0B, // 0x0B | 11
LongString = 0x0C, // 0x0C | 12
Unsupported = 0x0D, // 0x0D | 13
Recordset = 0x0E, // 0x0E | 14
Xml = 0x0F, // 0x0F | 15
TypedObject = 0x10, // 0x10 | 16
Amf3Object = 0x11, // 0x11 | 17
};
}
}
}
| 34 | 135 | 0.447988 | [
"MIT"
] | louisgv/rtmp-sharp | src/IO/AmfWriter.Amf0.cs | 12,480 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BurstBotShared.Shared.Models.Game.Serializables;
public record GenericJoinRequest
{
[JsonProperty("client_type")]
[JsonConverter(typeof(StringEnumConverter))]
public ClientType ClientType { get; init; }
[JsonProperty("game_type")]
[JsonConverter(typeof(StringEnumConverter))]
public GameType GameType { get; init; }
[JsonProperty("player_ids")] public List<ulong> PlayerIds { get; init; } = new();
[JsonProperty("base_bet")] public float BaseBet { get; init; }
}; | 31.888889 | 85 | 0.719512 | [
"BSD-3-Clause"
] | AllBurst/BurstBotNET | BurstBotShared/Shared/Models/Game/Serializables/GenericJoinRequest.cs | 574 | C# |
// <copyright file="MonsterAttribute.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.DataModel.Configuration;
using MUnique.OpenMU.AttributeSystem;
/// <summary>
/// The attribute and value of a monster.
/// </summary>
/// <remarks>
/// Just needed for entity framework, because it does not support the mapping of dictionaries. May be removed in the future.
/// </remarks>
public class MonsterAttribute
{
/// <summary>
/// Gets or sets the attribute definition.
/// </summary>
public virtual AttributeDefinition? AttributeDefinition { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
public float Value { get; set; }
/// <inheritdoc />
public override string ToString()
{
return $"{this.AttributeDefinition}: {this.Value}";
}
} | 28.96875 | 124 | 0.677454 | [
"MIT"
] | ADMTec/OpenMU | src/DataModel/Configuration/MonsterAttribute.cs | 929 | C# |
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Extensions.Logging;
using Annytab.Fortnox.Client.V3;
namespace TestProgram
{
[TestClass]
public class TestPrices
{
#region Variables
private Config config { get; set; }
#endregion
#region Constructors
/// <summary>
/// Create a new test instance
/// </summary>
public TestPrices()
{
this.config = new Config();
} // End of the constructor
#endregion
#region Methods
/// <summary>
/// Test to add a post
/// </summary>
[TestMethod]
public async Task TestAddPost()
{
// Create a post
PriceRoot post = new PriceRoot
{
Price = new Price
{
ArticleNumber = "1",
FromQuantity = 0M,
PriceList = "AD",
Amount = 86.88M
}
};
// Add the post
FortnoxResponse<PriceRoot> fr = await config.fortnox_client.Add<PriceRoot>(post, "prices");
// Log the error
if (fr.model == null)
{
config.logger.LogError(fr.error);
}
// Test evaluation
Assert.AreNotEqual(null, fr.model);
} // End of the TestAddPost method
/// <summary>
/// Test to update a post
/// </summary>
[TestMethod]
public async Task TestUpdatePost()
{
// Create a post
PriceRoot post = new PriceRoot
{
Price = new Price
{
ArticleNumber = "1",
FromQuantity = 200M,
PriceList = "AD",
Amount = 30.33M
}
};
// Update the post
FortnoxResponse<PriceRoot> fr = await config.fortnox_client.Update<PriceRoot>(post, "prices/AD/1/200.00");
// Log the error
if (fr.model == null)
{
config.logger.LogError(fr.error);
}
// Test evaluation
Assert.AreNotEqual(null, fr.model);
} // End of the TestUpdatePost method
/// <summary>
/// Test to get a post
/// </summary>
[TestMethod]
public async Task TestGetPost()
{
// Get a post
FortnoxResponse<PriceRoot> fr = await config.fortnox_client.Get<PriceRoot>("prices/AD/1/200.00");
// Log the error
if (fr.model == null)
{
config.logger.LogError(fr.error);
}
// Test evaluation
Assert.AreNotEqual(null, fr.model);
} // End of the TestGetPost method
/// <summary>
/// Test to get a list
/// </summary>
[TestMethod]
public async Task TestGetList()
{
// Get a list
FortnoxResponse<PricesRoot> fr = await config.fortnox_client.Get<PricesRoot>("prices/sublist/AD/1?limit=3&page=1");
// Log the error
if (fr.model == null)
{
config.logger.LogError(fr.error);
}
// Test evaluation
Assert.AreNotEqual(null, fr.model);
} // End of the TestGetList method
/// <summary>
/// Test to delete a post
/// </summary>
[TestMethod]
public async Task TestDeletePost()
{
// Get a list
FortnoxResponse<bool> fr = await config.fortnox_client.Delete("prices/AD/1/200.00");
// Log the error
if (fr.model == false)
{
config.logger.LogError(fr.error);
}
// Test evaluation
Assert.AreEqual(true, fr.model);
} // End of the TestDeletePost method
#endregion
} // End of the class
} // End of the namespace | 25.625 | 127 | 0.478537 | [
"MIT"
] | annytab/a-fortnox-client | TestProgram/TestPrices.cs | 4,100 | C# |
using IntoTheCode;
using System;
using System.Linq;
namespace IntoTheCodeExample.DomainLanguage.Executers
{
public class VariableDef : OperationBase
{
public string Name;
public DefType VariableType;
public ExpBase Expression;
public override bool Run(Variables runtime)
{
runtime.DeclareVariable(VariableType, Name, Expression);
return false;
}
}
}
| 19.954545 | 68 | 0.653759 | [
"MIT"
] | Krixohub/IntoTheCode | CSharp/IntoTheCodeExample/DomainLanguage/Executers/VariableDef.cs | 441 | C# |
using System.Threading;
using Caliburn.Micro;
using JD_XI_Editor.Models.Enums.Program.Effects;
using JD_XI_Editor.Models.Patches.Program.Effects.Effect1;
using JD_XI_Editor.ViewModels.Effects.Assignable;
namespace JD_XI_Editor.ViewModels.Effects
{
internal class Effect1ViewModel : Conductor<Screen>
{
/// <inheritdoc />
/// <summary>
/// Create new instance of Effect 1 View Model
/// </summary>
public Effect1ViewModel(Patch patch)
{
Patch = patch;
ThruViewModel = new ThruViewModel();
DistortionViewModel = new DistortionViewModel(patch.DistortionParameters);
FuzzViewModel = new FuzzViewModel(patch.FuzzParameters);
CompressorViewModel = new CompressorViewModel(patch.CompressorParameters);
BitCrusherViewModel = new BitCrusherViewModel(patch.BitCrusherParameters);
Patch.Basic.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == nameof(BasicData.Type))
switch (((BasicData) Patch.Basic).Type)
{
case Effect1Type.Thru:
ActivateItemAsync(ThruViewModel, default);
break;
case Effect1Type.Distortion:
ActivateItemAsync(DistortionViewModel, default);
break;
case Effect1Type.Fuzz:
ActivateItemAsync(FuzzViewModel, default);
break;
case Effect1Type.Compressor:
ActivateItemAsync(CompressorViewModel, default);
break;
case Effect1Type.BitCrusher:
ActivateItemAsync(BitCrusherViewModel, default);
break;
default:
ActivateItemAsync(ThruViewModel, default);
break;
}
};
}
#region Properties
/// <summary>
/// Effect 1 patch
/// </summary>
public Patch Patch { get; }
/// <summary>
/// Thru View Model
/// </summary>
public ThruViewModel ThruViewModel { get; }
/// <summary>
/// Distortion View Model
/// </summary>
public DistortionViewModel DistortionViewModel { get; }
/// <summary>
/// Fuzz View Model
/// </summary>
public FuzzViewModel FuzzViewModel { get; }
/// <summary>
/// Compressor View Model
/// </summary>
public CompressorViewModel CompressorViewModel { get; }
/// <summary>
/// Bit Crusher View Model
/// </summary>
public BitCrusherViewModel BitCrusherViewModel { get; }
#endregion
}
} | 32.89011 | 86 | 0.520548 | [
"MIT"
] | Magiczne/JD-XI-Editor | JD-XI Editor/ViewModels/Effects/Effect1ViewModel.cs | 2,995 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.