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
using System; using System.Collections.Generic; namespace Bet.Extensions.Resilience.Abstractions { public static class Backoff { /// <summary> /// Creates Jittered timespan. /// https://github.com/App-vNext/Polly/wiki/Retry-with-jitter/86fc200c672e87cc24fe444ec61f38da19e861ec#more-complex-jitter. /// </summary> /// <param name="maxRetries"></param> /// <param name="seedDelay"></param> /// <param name="maxDelay"></param> /// <returns></returns> public static IEnumerable<TimeSpan> DecorrelatedJitter(int maxRetries, TimeSpan seedDelay, TimeSpan maxDelay) { var jitterer = new Random(); var retries = 0; var seed = seedDelay.TotalMilliseconds; var max = maxDelay.TotalMilliseconds; var current = seed; while (++retries <= maxRetries) { // adopting the 'Decorrelated Jitter' formula from https://www.awsarchitectureblog.com/2015/03/backoff.html. Can be between seed and previous * 3. Mustn't exceed max. current = Math.Min(max, Math.Max(seed, current * 3 * jitterer.NextDouble())); yield return TimeSpan.FromMilliseconds(current); } } /// <summary> /// Generates sleep durations in an exponentially backing-off, jittered manner, making sure to mitigate any correlations. /// For example: 850ms, 1455ms, 3060ms. /// Per discussion in Polly issue 530, the jitter of this implementation exhibits fewer spikes and a smoother distribution than the AWS jitter formula. /// </summary> /// <param name="medianFirstRetryDelay">The median delay to target before the first retry, call it f (= f * 2^0). /// Choose this value both to approximate the first delay, and to scale the remainder of the series. /// Subsequent retries will (over a large sample size) have a median approximating retries at time f * 2^1, f * 2^2 ... f * 2^t etc for try t. /// The actual amount of delay-before-retry for try t may be distributed between 0 and f * (2^(t+1) - 2^(t-1)) for t >= 2; /// or between 0 and f * 2^(t+1), for t is 0 or 1.</param> /// <param name="retryCount">The maximum number of retries to use, in addition to the original call.</param> /// <param name="seed">An optional <see cref="Random"/> seed to use. /// If not specified, will use a shared instance with a random seed, per Microsoft recommendation for maximum randomness.</param> /// <param name="fastFirst">Whether the first retry will be immediate or not.</param> public static IEnumerable<TimeSpan> DecorrelatedJitterBackoffV2( TimeSpan medianFirstRetryDelay, int retryCount, int? seed = null, bool fastFirst = false) { if (medianFirstRetryDelay < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(medianFirstRetryDelay), medianFirstRetryDelay, "should be >= 0ms"); } if (retryCount < 0) { throw new ArgumentOutOfRangeException(nameof(retryCount), retryCount, "should be >= 0"); } if (retryCount == 0) { return Empty(); } return Enumerate(medianFirstRetryDelay, retryCount, fastFirst, new ConcurrentRandom(seed)); // The original author/credit for this jitter formula is @george-polevoy . Jitter formula used with permission as described at https://github.com/App-vNext/Polly/issues/530#issuecomment-526555979 // Minor adaptations (pFactor = 4.0 and rpScalingFactor = 1 / 1.4d) by @reisenberger, to scale the formula output for easier parameterisation to users. IEnumerable<TimeSpan> Enumerate(TimeSpan scaleFirstTry, int maxRetries, bool fast, ConcurrentRandom random) { // A factor used within the formula to help smooth the first calculated delay. const double pFactor = 4.0; // A factor used to scale the median values of the retry times generated by the formula to be _near_ whole seconds, to aid Polly user comprehension. // This factor allows the median values to fall approximately at 1, 2, 4 etc seconds, instead of 1.4, 2.8, 5.6, 11.2. const double rpScalingFactor = 1 / 1.4d; var i = 0; if (fast) { i++; yield return TimeSpan.Zero; } var targetTicksFirstDelay = scaleFirstTry.Ticks; var prev = 0.0; for (; i < maxRetries; i++) { var t = (double)i + random.NextDouble(); var next = Math.Pow(2, t) * Math.Tanh(Math.Sqrt(pFactor * t)); var formulaIntrinsicValue = next - prev; yield return TimeSpan.FromTicks((long)(formulaIntrinsicValue * rpScalingFactor * targetTicksFirstDelay)); prev = next; } } } private static IEnumerable<TimeSpan> Empty() { yield break; } } }
48.290909
207
0.59695
[ "MIT" ]
kdcllc/Bet.Extensions.Resilience
src/Bet.Extensions.Resilience.Abstractions/Backoff.cs
5,314
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPG2.GameLogic { public static class Highscore { public static List<string> Highscores { get; set; } static Highscore() { Highscores = new List<string>(); } } }
18.473684
59
0.623932
[ "MIT" ]
Marcus-Kanon/Skola
RPG2/RPG2/GameLogic/Highscore.cs
353
C#
namespace OakIdeas.Schema.Core.MedicalEntities { public class MedicineSystem { } }
13.571429
46
0.705263
[ "MIT" ]
oakcool/OakIdeas.Schema
OakIdeas.Schema.Core/MedicalEntities/MedicineSystem.cs
95
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Cutscene8 : MonoBehaviour { public GameObject Cam1; public GameObject ThePlayer; public GameObject TheCanvas; public GameObject TextBox; void OnTriggerEnter(){ StartCoroutine (CutSceneShow ()); } IEnumerator CutSceneShow() { //TheCanvas.SetActive (false); Cam1.SetActive (true); ThePlayer.SetActive (false); TextBox.GetComponent<Text> ().text = "An electricity room..."; yield return new WaitForSeconds (4f); TextBox.GetComponent<Text> ().text = "I need to place fuses in here to open the exit door"; yield return new WaitForSeconds (5f); TextBox.GetComponent<Text> ().text = "A Dead body??"; yield return new WaitForSeconds (4f); ThePlayer.SetActive (true); Cam1.SetActive (false); TextBox.GetComponent<Text> ().text = ""; //TheCanvas.SetActive (true); Destroy (gameObject); } }
23.02439
93
0.724576
[ "Apache-2.0" ]
Jetatomic17/PuppetsTear
Assets/CutsceneScript/Cutscene8.cs
946
C#
using System; using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; namespace Perfor.Lib.Helpers.Mssql { /** * @ 自定义SQL命令执行,完全开放和自由的语法 * */ public class MssqlCustomCmd : SQLHelper { #region Identity /** * @ 默认构造函数 * */ public MssqlCustomCmd() : base() { InitializeComponent(null); } /** * @ 构造函数第一次重载 * @ tableName :要插入的表名 * */ public MssqlCustomCmd(string sqlCmdText) { InitializeComponent(sqlCmdText); } /** * @ 构造函数第二次重载 * @ tableName :要插入的表名 * @ context 数据库上下文对象 * */ public MssqlCustomCmd(SQLContext context) : base(context) { } /** * @ 构造函数第二次重载 * @ tableName :要插入的表名 * @ context 数据库上下文对象 * */ public MssqlCustomCmd(SQLContext context, string sqlCmdText) : base(context) { InitializeComponent(sqlCmdText); } /** * @ 初始化内部数据 * */ private void InitializeComponent(string sqlCmdText) { this.SQLCmdText = SQLCmdText; } #endregion /** * @ 返回执行命令所影响的行数 * */ public new int ExecuteNonQuery() { int result = base.ExecuteNonQuery(); Dispose(false); return result; } /** * @ 返回一个查询后的可读数据流 * */ public new DbDataReader ExecuteReader() { return base.ExecuteReader(); } /** * @ 返回一个结果集合 * */ public List<SQLDataResult> ExecuteToDataResult() { List<SQLDataResult> dataList = null; try { base.ExecuteReader(); DbDataReader reader = Context.DbReader; if (reader.HasRows == false) { return null; } reader.Read(); do { SQLDataResult result = new SQLDataResult(); int len = reader.FieldCount; for (int i = 0; i < len; i++) { result.Add(reader.GetName(i), reader.GetValue(i)); } dataList.Add(result); } while (Context.DbReader.Read()); } finally { Dispose(false); } return dataList; } /** * @ 返回执行结果后的首行首列(如果有结果) * */ public new object ExecuteScalar() { object result = base.ExecuteScalar(); Dispose(false); return result; } /** * @ 添加SQL命令对应的参数 * */ public void AddParams(string name, object value) { base.AddParameter(name, value); } /** * @ 所有初始化SQL语句的逻辑都可以写在这里 * */ protected override bool InitSQLWithCmdText() { throw new NotImplementedException("自定义命令不应该调用该方法"); } #region Properties /** * @ 当前命令中的条件 * */ public new List<DbParameter> Parameters { get { return Context.DbParas; } } #endregion } }
22.403846
74
0.441488
[ "MIT" ]
lianggx/danny.lib
Perfor.Lib/Helpers/Mssql/MssqlCustomCmd.cs
3,885
C#
using System; using Torii.Event; using UnityEngine; namespace Torii.Systems { [CreateAssetMenu(menuName = "System/Pause")] public class PauseSystem : ScriptableObject { public bool Paused => Math.Abs(Time.timeScale) < float.Epsilon; [NonSerialized] public bool CanPause = true; public ToriiEvent OnGamePause; public ToriiEvent OnGameUnpause; public void TogglePause() { if (Paused) Unpause(); else Pause(); } public void Pause() { if (!CanPause) return; Time.timeScale = 0; OnGamePause.Raise(); } public void Unpause() { Time.timeScale = 1; OnGameUnpause.Raise(); } } }
21.081081
71
0.55
[ "MIT" ]
Figglewatts/torii-framework
Packages/com.figglewatts.torii/Runtime/Systems/PauseSystem.cs
780
C#
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace StackExchange.Redis { /// <summary> /// Describes functionality that is common to both standalone redis servers and redis clusters /// </summary> public interface IDatabaseAsync : IRedisAsync { /// <summary> /// Indicates whether the instance can communicate with the server (resolved /// using the supplied key and optional flags) /// </summary> /// <param name="key">The key to check for.</param> /// <param name="flags">The flags to use for this operation.</param> bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance by default, and is guaranteed to exist in the target instance. /// </summary> /// <param name="key">The key to migrate.</param> /// <param name="toServer">The server to migrate the key to.</param> /// <param name="toDatabase">The database to migrate the key to.</param> /// <param name="timeoutMilliseconds">The timeout to use for the transfer.</param> /// <param name="migrateOptions">The options to use for this migration.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/MIGRATE</remarks> Task KeyMigrateAsync(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the raw DEBUG OBJECT output for a key; this command is not fully documented and should be avoided unless you have good reason, and then avoided anyway. /// </summary> /// <param name="key">The key to debug.</param> /// <param name="flags">The flags to use for this migration.</param> /// <returns>The raw output from DEBUG OBJECT.</returns> /// <remarks>https://redis.io/commands/debug-object</remarks> Task<RedisValue> DebugObjectAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Add the specified member to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="longitude">The longitude of geo entry.</param> /// <param name="latitude">The latitude of the geo entry.</param> /// <param name="member">The value to set at this entry.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the specified member was not already present in the set, else False.</returns> /// <remarks>https://redis.io/commands/geoadd</remarks> Task<bool> GeoAddAsync(RedisKey key, double longitude, double latitude, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Add the specified member to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="value">The geo value to store.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the specified member was not already present in the set, else False</returns> /// <remarks>https://redis.io/commands/geoadd</remarks> Task<bool> GeoAddAsync(RedisKey key, StackExchange.Redis.GeoEntry value, CommandFlags flags = CommandFlags.None); /// <summary> /// Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="values">The geo values add to the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements that were added to the set, not including all the elements already present into the set.</returns> /// <remarks>https://redis.io/commands/geoadd</remarks> Task<long> GeoAddAsync(RedisKey key, GeoEntry[] values, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified member from the geo sorted set stored at key. Non existing members are ignored. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="member">The geo value to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the member existed in the sorted set and was removed; False otherwise.</returns> /// <remarks>https://redis.io/commands/zrem</remarks> Task<bool> GeoRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the distance between two members in the geospatial index represented by the sorted set. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="member1">The first member to check.</param> /// <param name="member2">The second member to check.</param> /// <param name="unit">The unit of distance to return (defaults to meters).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns the distance as a double (represented as a string) in the specified unit, or NULL if one or both the elements are missing.</returns> /// <remarks>https://redis.io/commands/geodist</remarks> Task<double?> GeoDistanceAsync(RedisKey key, RedisValue member1, RedisValue member2, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None); /// <summary> /// Return valid Geohash strings representing the position of one or more elements in a sorted set value representing a geospatial index (where elements were added using GEOADD). /// </summary> /// <param name="key">The key of the set.</param> /// <param name="members">The members to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns an array where each element is the Geohash corresponding to each member name passed as argument to the command.</returns> /// <remarks>https://redis.io/commands/geohash</remarks> Task<string[]> GeoHashAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None); /// <summary> /// Return valid Geohash strings representing the position of one or more elements in a sorted set value representing a geospatial index (where elements were added using GEOADD). /// </summary> /// <param name="key">The key of the set.</param> /// <param name="member">The member to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns an array where each element is the Geohash corresponding to each member name passed as argument to the command.</returns> /// <remarks>https://redis.io/commands/geohash</remarks> Task<string> GeoHashAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the positions (longitude,latitude) of all the specified members of the geospatial index represented by the sorted set at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="members">The members to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns an array where each element is a two elements array representing longitude and latitude (x,y) of each member name passed as argument to the command.Non existing elements are reported as NULL elements of the array.</returns> /// <remarks>https://redis.io/commands/geopos</remarks> Task<GeoPosition?[]> GeoPositionAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the positions (longitude,latitude) of all the specified members of the geospatial index represented by the sorted set at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="member">The member to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns an array where each element is a two elements array representing longitude and latitude (x,y) of each member name passed as argument to the command.Non existing elements are reported as NULL elements of the array.</returns> /// <remarks>https://redis.io/commands/geopos</remarks> Task<GeoPosition?> GeoPositionAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the members of a sorted set populated with geospatial information using GEOADD, which are within the borders of the area specified with the center location and the maximum distance from the center (the radius). /// </summary> /// <param name="key">The key of the set.</param> /// <param name="member">The member to get a radius of results from.</param> /// <param name="radius">The radius to check.</param> /// <param name="unit">The unit of <paramref name="radius"/> (defaults to meters).</param> /// <param name="count">The count of results to get, -1 for unlimited.</param> /// <param name="order">The order of the results.</param> /// <param name="options">The search options to use.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The results found within the radius, if any.</returns> /// <remarks>https://redis.io/commands/georadius</remarks> Task<GeoRadiusResult[]> GeoRadiusAsync(RedisKey key, RedisValue member, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the members of a sorted set populated with geospatial information using GEOADD, which are within the borders of the area specified with the center location and the maximum distance from the center (the radius). /// </summary> /// <param name="key">The key of the set.</param> /// <param name="longitude">The longitude of the point to get a radius of results from.</param> /// <param name="latitude">The latitude of the point to get a radius of results from.</param> /// <param name="radius">The radius to check.</param> /// <param name="unit">The unit of <paramref name="radius"/> (defaults to meters).</param> /// <param name="count">The count of results to get, -1 for unlimited.</param> /// <param name="order">The order of the results.</param> /// <param name="options">The search options to use.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The results found within the radius, if any.</returns> /// <remarks>https://redis.io/commands/georadius</remarks> Task<GeoRadiusResult[]> GeoRadiusAsync(RedisKey key, double longitude, double latitude, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None); /// <summary> /// Decrements the number stored at field in the hash stored at key by decrement. If key does not exist, a new key holding a hash is created. If field does not exist the value is set to 0 before the operation is performed. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to decrement.</param> /// <param name="value">The amount to decrement by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value at field after the decrement operation.</returns> /// <remarks>The range of values supported by HINCRBY is limited to 64 bit signed integers.</remarks> /// <remarks>https://redis.io/commands/hincrby</remarks> Task<long> HashDecrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None); /// <summary> /// Decrement the specified field of an hash stored at key, and representing a floating point number, by the specified decrement. If the field does not exist, it is set to 0 before performing the operation. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to decrement.</param> /// <param name="value">The amount to decrement by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value at field after the decrement operation.</returns> /// <remarks>The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation.</remarks> /// <remarks>https://redis.io/commands/hincrbyfloat</remarks> Task<double> HashDecrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified fields from the hash stored at key. Non-existing fields are ignored. Non-existing keys are treated as empty hashes and this command returns 0. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to delete.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of fields that were removed.</returns> /// <remarks>https://redis.io/commands/hdel</remarks> Task<bool> HashDeleteAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified fields from the hash stored at key. Non-existing fields are ignored. Non-existing keys are treated as empty hashes and this command returns 0. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashFields">The fields in the hash to delete.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of fields that were removed.</returns> /// <remarks>https://redis.io/commands/hdel</remarks> Task<long> HashDeleteAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns if field is an existing field in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to check.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the hash contains field. 0 if the hash does not contain field, or key does not exist.</returns> /// <remarks>https://redis.io/commands/hexists</remarks> Task<bool> HashExistsAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the value associated with field in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value associated with field, or nil when field is not present in the hash or key does not exist.</returns> /// <remarks>https://redis.io/commands/hget</remarks> Task<RedisValue> HashGetAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the value associated with field in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value associated with field, or nil when field is not present in the hash or key does not exist.</returns> /// <remarks>https://redis.io/commands/hget</remarks> Task<Lease<byte>> HashGetLeaseAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the values associated with the specified fields in the hash stored at key. /// For every field that does not exist in the hash, a nil value is returned.Because a non-existing keys are treated as empty hashes, running HMGET against a non-existing key will return a list of nil values. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashFields">The fields in the hash to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of values associated with the given fields, in the same order as they are requested.</returns> /// <remarks>https://redis.io/commands/hmget</remarks> Task<RedisValue[]> HashGetAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns all fields and values of the hash stored at key. /// </summary> /// <param name="key">The key of the hash to get all entries from.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of fields and their values stored in the hash, or an empty list when key does not exist.</returns> /// <remarks>https://redis.io/commands/hgetall</remarks> Task<HashEntry[]> HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Increments the number stored at field in the hash stored at key by increment. If key does not exist, a new key holding a hash is created. If field does not exist the value is set to 0 before the operation is performed. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to increment.</param> /// <param name="value">The amount to increment by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value at field after the increment operation.</returns> /// <remarks>The range of values supported by HINCRBY is limited to 64 bit signed integers.</remarks> /// <remarks>https://redis.io/commands/hincrby</remarks> Task<long> HashIncrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None); /// <summary> /// Increment the specified field of an hash stored at key, and representing a floating point number, by the specified increment. If the field does not exist, it is set to 0 before performing the operation. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field in the hash to increment.</param> /// <param name="value">The amount to increment by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value at field after the increment operation.</returns> /// <remarks>The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation.</remarks> /// <remarks>https://redis.io/commands/hincrbyfloat</remarks> Task<double> HashIncrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns all field names in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of fields in the hash, or an empty list when key does not exist.</returns> /// <remarks>https://redis.io/commands/hkeys</remarks> Task<RedisValue[]> HashKeysAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the number of fields contained in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of fields in the hash, or 0 when key does not exist.</returns> /// <remarks>https://redis.io/commands/hlen</remarks> Task<long> HashLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// The HSCAN command is used to incrementally iterate over a hash; note: to resume an iteration via <i>cursor</i>, cast the original enumerable or enumerator to <i>IScanningCursor</i>. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="pattern">The pattern of keys to get entries for.</param> /// <param name="pageSize">The page size to iterate by.</param> /// <param name="cursor">The cursor position to start at.</param> /// <param name="pageOffset">The page offset to start at.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Yields all elements of the hash matching the pattern.</returns> /// <remarks>https://redis.io/commands/hscan</remarks> IAsyncEnumerable<HashEntry> HashScanAsync(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None); /// <summary> /// Sets the specified fields to their respective values in the hash stored at key. This command overwrites any specified fields that already exist in the hash, leaving other unspecified fields untouched. If key does not exist, a new key holding a hash is created. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashFields">The entries to set in the hash.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/hmset</remarks> Task HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None); /// <summary> /// Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field to set in the hash.</param> /// <param name="value">The value to set.</param> /// <param name="when">Which conditions under which to set the field value (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if field is a new field in the hash and value was set. 0 if field already exists in the hash and the value was updated.</returns> /// <remarks>https://redis.io/commands/hset</remarks> /// <remarks>https://redis.io/commands/hsetnx</remarks> Task<bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the string length of the value associated with field in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="hashField">The field containing the string</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>the length of the string at field, or 0 when key does not exist.</returns> /// <remarks>https://redis.io/commands/hstrlen</remarks> Task<long> HashStringLengthAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns all values in the hash stored at key. /// </summary> /// <param name="key">The key of the hash.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of values in the hash, or an empty list when key does not exist.</returns> /// <remarks>https://redis.io/commands/hvals</remarks> Task<RedisValue[]> HashValuesAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds the element to the HyperLogLog data structure stored at the variable name specified as first argument. /// </summary> /// <param name="key">The key of the hyperloglog.</param> /// <param name="value">The value to add.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if at least 1 HyperLogLog internal register was altered, false otherwise.</returns> /// <remarks>https://redis.io/commands/pfadd</remarks> Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds all the element arguments to the HyperLogLog data structure stored at the variable name specified as first argument. /// </summary> /// <param name="key">The key of the hyperloglog.</param> /// <param name="values">The values to add.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if at least 1 HyperLogLog internal register was altered, false otherwise.</returns> /// <remarks>https://redis.io/commands/pfadd</remarks> Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the approximated cardinality computed by the HyperLogLog data structure stored at the specified variable, or 0 if the variable does not exist. /// </summary> /// <param name="key">The key of the hyperloglog.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The approximated number of unique elements observed via HyperLogLogAdd.</returns> /// <remarks>https://redis.io/commands/pfcount</remarks> Task<long> HyperLogLogLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the approximated cardinality of the union of the HyperLogLogs passed, by internally merging the HyperLogLogs stored at the provided keys into a temporary hyperLogLog, or 0 if the variable does not exist. /// </summary> /// <param name="keys">The keys of the hyperloglogs.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The approximated number of unique elements observed via HyperLogLogAdd.</returns> /// <remarks>https://redis.io/commands/pfcount</remarks> Task<long> HyperLogLogLengthAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures. /// </summary> /// <param name="destination">The key of the merged hyperloglog.</param> /// <param name="first">The key of the first hyperloglog to merge.</param> /// <param name="second">The key of the first hyperloglog to merge.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/pfmerge</remarks> Task HyperLogLogMergeAsync(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None); /// <summary> /// Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures. /// </summary> /// <param name="destination">The key of the merged hyperloglog.</param> /// <param name="sourceKeys">The keys of the hyperloglogs to merge.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/pfmerge</remarks> Task HyperLogLogMergeAsync(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None); /// <summary> /// Indicate exactly which redis server we are talking to. /// </summary> /// <param name="key">The key to check.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The endpoint serving the key.</returns> Task<EndPoint> IdentifyEndpointAsync(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified key. A key is ignored if it does not exist. /// If UNLINK is available (Redis 4.0+), it will be used. /// </summary> /// <param name="key">The key to delete.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the key was removed.</returns> /// <remarks>https://redis.io/commands/del</remarks> /// <remarks>https://redis.io/commands/unlink</remarks> Task<bool> KeyDeleteAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified keys. A key is ignored if it does not exist. /// If UNLINK is available (Redis 4.0+), it will be used. /// </summary> /// <param name="keys">The keys to delete.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of keys that were removed.</returns> /// <remarks>https://redis.io/commands/del</remarks> /// <remarks>https://redis.io/commands/unlink</remarks> Task<long> KeyDeleteAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command. /// </summary> /// <param name="key">The key to dump.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>the serialized value.</returns> /// <remarks>https://redis.io/commands/dump</remarks> Task<byte[]> KeyDumpAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns if key exists. /// </summary> /// <param name="key">The key to check.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the key exists. 0 if the key does not exist.</returns> /// <remarks>https://redis.io/commands/exists</remarks> Task<bool> KeyExistsAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Indicates how many of the supplied keys exists. /// </summary> /// <param name="keys">The keys to check.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of keys that existed.</returns> /// <remarks>https://redis.io/commands/exists</remarks> Task<long> KeyExistsAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is said to be volatile in Redis terminology. /// </summary> /// <param name="key">The key to set the expiration for.</param> /// <param name="expiry">The timeout to set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the timeout was set. 0 if key does not exist or the timeout could not be set.</returns> /// <remarks>If key is updated before the timeout has expired, then the timeout is removed as if the PERSIST command was invoked on key. /// For Redis versions &lt; 2.1.3, existing timeouts cannot be overwritten. So, if key already has an associated timeout, it will do nothing and return 0. Since Redis 2.1.3, you can update the timeout of a key. It is also possible to remove the timeout using the PERSIST command. See the page on key expiry for more information.</remarks> /// <remarks>https://redis.io/commands/expire</remarks> /// <remarks>https://redis.io/commands/pexpire</remarks> /// <remarks>https://redis.io/commands/persist</remarks> Task<bool> KeyExpireAsync(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None); /// <summary> /// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is said to be volatile in Redis terminology. /// </summary> /// <param name="key">The key to set the expiration for.</param> /// <param name="expiry">The exact date to expiry to set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the timeout was set. 0 if key does not exist or the timeout could not be set.</returns> /// <remarks>If key is updated before the timeout has expired, then the timeout is removed as if the PERSIST command was invoked on key. /// For Redis versions &lt; 2.1.3, existing timeouts cannot be overwritten. So, if key already has an associated timeout, it will do nothing and return 0. Since Redis 2.1.3, you can update the timeout of a key. It is also possible to remove the timeout using the PERSIST command. See the page on key expiry for more information.</remarks> /// <remarks>https://redis.io/commands/expireat</remarks> /// <remarks>https://redis.io/commands/pexpireat</remarks> /// <remarks>https://redis.io/commands/persist</remarks> Task<bool> KeyExpireAsync(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the time since the object stored at the specified key is idle (not requested by read or write operations) /// </summary> /// <param name="key">The key to get the time of.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The time since the object stored at the specified key is idle</returns> /// <remarks>https://redis.io/commands/object</remarks> Task<TimeSpan?> KeyIdleTimeAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Move key from the currently selected database (see SELECT) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use MOVE as a locking primitive because of this. /// </summary> /// <param name="key">The key to move.</param> /// <param name="database">The database to move the key to.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if key was moved; 0 if key was not moved.</returns> /// <remarks>https://redis.io/commands/move</remarks> Task<bool> KeyMoveAsync(RedisKey key, int database, CommandFlags flags = CommandFlags.None); /// <summary> /// Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated). /// </summary> /// <param name="key">The key to persist.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the timeout was removed. 0 if key does not exist or does not have an associated timeout.</returns> /// <remarks>https://redis.io/commands/persist</remarks> Task<bool> KeyPersistAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Return a random key from the currently selected database. /// </summary> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The random key, or nil when the database is empty.</returns> /// <remarks>https://redis.io/commands/randomkey</remarks> Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None); /// <summary> /// Renames key to newkey. It returns an error when the source and destination names are the same, or when key does not exist. /// </summary> /// <param name="key">The key to rename.</param> /// <param name="newKey">The key to rename to.</param> /// <param name="when">What conditions to rename under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the key was renamed, false otherwise.</returns> /// <remarks>https://redis.io/commands/rename</remarks> /// <remarks>https://redis.io/commands/renamenx</remarks> Task<bool> KeyRenameAsync(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP). /// If ttl is 0 the key is created without any expire, otherwise the specified expire time(in milliseconds) is set. /// </summary> /// <param name="key">The key to restore.</param> /// <param name="value">The value of the key.</param> /// <param name="expiry">The expiry to set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/restore</remarks> Task KeyRestoreAsync(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset. /// </summary> /// <param name="key">The key to check.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>TTL, or nil when key does not exist or does not have a timeout.</returns> /// <remarks>https://redis.io/commands/ttl</remarks> Task<TimeSpan?> KeyTimeToLiveAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset and hash. /// </summary> /// <param name="key">The key to get the type of.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Type of key, or none when key does not exist.</returns> /// <remarks>https://redis.io/commands/type</remarks> Task<RedisType> KeyTypeAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the element at index index in the list stored at key. The index is zero-based, so 0 means the first element, 1 the second element and so on. Negative indices can be used to designate elements starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate and so forth. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="index">The index position to ge the value at.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The requested element, or nil when index is out of range.</returns> /// <remarks>https://redis.io/commands/lindex</remarks> Task<RedisValue> ListGetByIndexAsync(RedisKey key, long index, CommandFlags flags = CommandFlags.None); /// <summary> /// Inserts value in the list stored at key either before or after the reference value pivot. /// When key does not exist, it is considered an empty list and no operation is performed. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="pivot">The value to insert after.</param> /// <param name="value">The value to insert.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the insert operation, or -1 when the value pivot was not found.</returns> /// <remarks>https://redis.io/commands/linsert</remarks> Task<long> ListInsertAfterAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Inserts value in the list stored at key either before or after the reference value pivot. /// When key does not exist, it is considered an empty list and no operation is performed. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="pivot">The value to insert before.</param> /// <param name="value">The value to insert.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the insert operation, or -1 when the value pivot was not found.</returns> /// <remarks>https://redis.io/commands/linsert</remarks> Task<long> ListInsertBeforeAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns the first element of the list stored at key. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of the first element, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/lpop</remarks> Task<RedisValue> ListLeftPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert the specified value at the head of the list stored at key. If key does not exist, it is created as empty list before performing the push operations. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="value">The value to add to the head of the list.</param> /// <param name="when">Which conditions to add to the list under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operations.</returns> /// <remarks>https://redis.io/commands/lpush</remarks> /// <remarks>https://redis.io/commands/lpushx</remarks> Task<long> ListLeftPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert the specified value at the head of the list stored at key. If key does not exist, it is created as empty list before performing the push operations. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="values">The value to add to the head of the list.</param> /// <param name="when">Which conditions to add to the list under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operations.</returns> /// <remarks>https://redis.io/commands/lpush</remarks> /// <remarks>https://redis.io/commands/lpushx</remarks> Task<long> ListLeftPushAsync(RedisKey key, RedisValue[] values, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert all the specified values at the head of the list stored at key. If key does not exist, it is created as empty list before performing the push operations. /// Elements are inserted one after the other to the head of the list, from the leftmost element to the rightmost element. So for instance the command LPUSH mylist a b c will result into a list containing c as first element, b as second element and a as third element. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="values">The values to add to the head of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operations.</returns> /// <remarks>https://redis.io/commands/lpush</remarks> Task<long> ListLeftPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags); /// <summary> /// Returns the length of the list stored at key. If key does not exist, it is interpreted as an empty list and 0 is returned. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list at key.</returns> /// <remarks>https://redis.io/commands/llen</remarks> Task<long> ListLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the specified elements of the list stored at key. The offsets start and stop are zero-based indexes, with 0 being the first element of the list (the head of the list), 1 being the next element and so on. /// These offsets can also be negative numbers indicating offsets starting at the end of the list.For example, -1 is the last element of the list, -2 the penultimate, and so on. /// Note that if you have a list of numbers from 0 to 100, LRANGE list 0 10 will return 11 elements, that is, the rightmost item is included. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="start">The start index of the list.</param> /// <param name="stop">The stop index of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of elements in the specified range.</returns> /// <remarks>https://redis.io/commands/lrange</remarks> Task<RedisValue[]> ListRangeAsync(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the first count occurrences of elements equal to value from the list stored at key. The count argument influences the operation in the following ways: /// count &gt; 0: Remove elements equal to value moving from head to tail. /// count &lt; 0: Remove elements equal to value moving from tail to head. /// count = 0: Remove all elements equal to value. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="value">The value to remove from the list.</param> /// <param name="count">The count behavior (see method summary).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of removed elements.</returns> /// <remarks>https://redis.io/commands/lrem</remarks> Task<long> ListRemoveAsync(RedisKey key, RedisValue value, long count = 0, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns the last element of the list stored at key. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The element being popped.</returns> /// <remarks>https://redis.io/commands/rpop</remarks> Task<RedisValue> ListRightPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Atomically returns and removes the last element (tail) of the list stored at source, and pushes the element at the first element (head) of the list stored at destination. /// </summary> /// <param name="source">The key of the source list.</param> /// <param name="destination">The key of the destination list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The element being popped and pushed.</returns> /// <remarks>https://redis.io/commands/rpoplpush</remarks> Task<RedisValue> ListRightPopLeftPushAsync(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert the specified value at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="value">The value to add to the tail of the list.</param> /// <param name="when">Which conditions to add to the list under.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operation.</returns> /// <remarks>https://redis.io/commands/rpush</remarks> /// <remarks>https://redis.io/commands/rpushx</remarks> Task<long> ListRightPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert the specified value at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="values">The values to add to the tail of the list.</param> /// <param name="when">Which conditions to add to the list under.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operation.</returns> /// <remarks>https://redis.io/commands/rpush</remarks> /// <remarks>https://redis.io/commands/rpushx</remarks> Task<long> ListRightPushAsync(RedisKey key, RedisValue[] values, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Insert all the specified values at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation. /// Elements are inserted one after the other to the tail of the list, from the leftmost element to the rightmost element. So for instance the command RPUSH mylist a b c will result into a list containing a as first element, b as second element and c as third element. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="values">The values to add to the tail of the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the list after the push operation.</returns> /// <remarks>https://redis.io/commands/rpush</remarks> Task<long> ListRightPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags); /// <summary> /// Sets the list element at index to value. For more information on the index argument, see ListGetByIndex. An error is returned for out of range indexes. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="index">The index to set the value at.</param> /// <param name="value">The values to add to the list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/lset</remarks> Task ListSetByIndexAsync(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Trim an existing list so that it will contain only the specified range of elements specified. Both start and stop are zero-based indexes, where 0 is the first element of the list (the head), 1 the next element and so on. /// For example: LTRIM foobar 0 2 will modify the list stored at foobar so that only the first three elements of the list will remain. /// start and end can also be negative numbers indicating offsets from the end of the list, where -1 is the last element of the list, -2 the penultimate element and so on. /// </summary> /// <param name="key">The key of the list.</param> /// <param name="start">The start index of the list to trim to.</param> /// <param name="stop">The end index of the list to trim to.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/ltrim</remarks> Task ListTrimAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None); /// <summary> /// Extends a lock, if the token value is correct. /// </summary> /// <param name="key">The key of the lock.</param> /// <param name="value">The value to set at the key.</param> /// <param name="expiry">The expiration of the lock key.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the lock was successfully extended.</returns> Task<bool> LockExtendAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None); /// <summary> /// Queries the token held against a lock. /// </summary> /// <param name="key">The key of the lock.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The current value of the lock, if any.</returns> Task<RedisValue> LockQueryAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Releases a lock, if the token value is correct. /// </summary> /// <param name="key">The key of the lock.</param> /// <param name="value">The value at the key tht must match.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the lock was successfully released, false otherwise.</returns> Task<bool> LockReleaseAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Takes a lock (specifying a token value) if it is not already taken. /// </summary> /// <param name="key">The key of the lock.</param> /// <param name="value">The value to set at the key.</param> /// <param name="expiry">The expiration of the lock key.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the lock was successfully taken, false otherwise.</returns> Task<bool> LockTakeAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None); /// <summary> /// Posts a message to the given channel. /// </summary> /// <param name="channel">The channel to publish to.</param> /// <param name="message">The message to send.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of clients that received the message.</returns> /// <remarks>https://redis.io/commands/publish</remarks> Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None); /// <summary> /// Execute an arbitrary command against the server; this is primarily intended for /// executing modules, but may also be used to provide access to new features that lack /// a direct API. /// </summary> /// <param name="command">The command to run.</param> /// <param name="args">The arguments to pass for the command.</param> /// <remarks>This API should be considered an advanced feature; inappropriate use can be harmful</remarks> /// <returns>A dynamic representation of the command's result</returns> Task<RedisResult> ExecuteAsync(string command, params object[] args); /// <summary> /// Execute an arbitrary command against the server; this is primarily intended for /// executing modules, but may also be used to provide access to new features that lack /// a direct API. /// </summary> /// <param name="command">The command to run.</param> /// <param name="args">The arguments to pass for the command.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>This API should be considered an advanced feature; inappropriate use can be harmful</remarks> /// <returns>A dynamic representation of the command's result</returns> Task<RedisResult> ExecuteAsync(string command, ICollection<object> args, CommandFlags flags = CommandFlags.None); /// <summary> /// Execute a Lua script against the server. /// </summary> /// <param name="script">The script to execute.</param> /// <param name="keys">The keys to execute against.</param> /// <param name="values">The values to execute against.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A dynamic representation of the script's result</returns> /// <remarks>https://redis.io/commands/eval</remarks> /// <remarks>https://redis.io/commands/evalsha</remarks> Task<RedisResult> ScriptEvaluateAsync(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Execute a Lua script against the server using just the SHA1 hash /// </summary> /// <param name="hash">The hash of the script to execute.</param> /// <param name="keys">The keys to execute against.</param> /// <param name="values">The values to execute against.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A dynamic representation of the script's result</returns> /// <remarks>https://redis.io/commands/evalsha</remarks> Task<RedisResult> ScriptEvaluateAsync(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Execute a lua script against the server, using previously prepared script. /// Named parameters, if any, are provided by the `parameters` object. /// </summary> /// <param name="script">The script to execute.</param> /// <param name="parameters">The parameters to pass to the script.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A dynamic representation of the script's result</returns> /// <remarks>https://redis.io/commands/eval</remarks> Task<RedisResult> ScriptEvaluateAsync(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Execute a lua script against the server, using previously prepared and loaded script. /// This method sends only the SHA1 hash of the lua script to Redis. /// Named parameters, if any, are provided by the `parameters` object. /// </summary> /// <param name="script">The already-loaded script to execute.</param> /// <param name="parameters">The parameters to pass to the script.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A dynamic representation of the script's result</returns> /// <remarks>https://redis.io/commands/eval</remarks> Task<RedisResult> ScriptEvaluateAsync(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Add the specified member to the set stored at key. /// Specified members that are already a member of this set are ignored. /// If key does not exist, a new set is created before adding the specified members. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="value">The value to add to the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the specified member was not already present in the set, else False</returns> /// <remarks>https://redis.io/commands/sadd</remarks> Task<bool> SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Add the specified members to the set stored at key. /// Specified members that are already a member of this set are ignored. /// If key does not exist, a new set is created before adding the specified members. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="values">The values to add to the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements that were added to the set, not including all the elements already present into the set.</returns> /// <remarks>https://redis.io/commands/sadd</remarks> Task<long> SetAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the members of the set resulting from the specified operation against the given sets. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="first">The key of the first set.</param> /// <param name="second">The key of the second set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List with members of the resulting set.</returns> /// <remarks>https://redis.io/commands/sunion</remarks> /// <remarks>https://redis.io/commands/sinter</remarks> /// <remarks>https://redis.io/commands/sdiff</remarks> Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the members of the set resulting from the specified operation against the given sets. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="keys">The keys of the sets to operate on.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List with members of the resulting set.</returns> /// <remarks>https://redis.io/commands/sunion</remarks> /// <remarks>https://redis.io/commands/sinter</remarks> /// <remarks>https://redis.io/commands/sdiff</remarks> Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// This command is equal to SetCombine, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The key of the destination set.</param> /// <param name="first">The key of the first set.</param> /// <param name="second">The key of the second set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements in the resulting set.</returns> /// <remarks>https://redis.io/commands/sunionstore</remarks> /// <remarks>https://redis.io/commands/sinterstore</remarks> /// <remarks>https://redis.io/commands/sdiffstore</remarks> Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None); /// <summary> /// This command is equal to SetCombine, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The key of the destination set.</param> /// <param name="keys">The keys of the sets to operate on.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements in the resulting set.</returns> /// <remarks>https://redis.io/commands/sunionstore</remarks> /// <remarks>https://redis.io/commands/sinterstore</remarks> /// <remarks>https://redis.io/commands/sdiffstore</remarks> Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns if member is a member of the set stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="value">The value to check for .</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the element is a member of the set. 0 if the element is not a member of the set, or if key does not exist.</returns> /// <remarks>https://redis.io/commands/sismember</remarks> Task<bool> SetContainsAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the set cardinality (number of elements) of the set stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The cardinality (number of elements) of the set, or 0 if key does not exist.</returns> /// <remarks>https://redis.io/commands/scard</remarks> Task<long> SetLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns all the members of the set value stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>All elements of the set.</returns> /// <remarks>https://redis.io/commands/smembers</remarks> Task<RedisValue[]> SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. /// When the specified element already exists in the destination set, it is only removed from the source set. /// </summary> /// <param name="source">The key of the source set.</param> /// <param name="destination">The key of the destination set.</param> /// <param name="value">The value to move.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>1 if the element is moved. 0 if the element is not a member of source and no operation was performed.</returns> /// <remarks>https://redis.io/commands/smove</remarks> Task<bool> SetMoveAsync(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns a random element from the set value stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The removed element, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/spop</remarks> Task<RedisValue> SetPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns the specified number of random elements from the set value stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="count">The number of elements to return.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An array of elements, or an empty array when key does not exist.</returns> /// <remarks>https://redis.io/commands/spop</remarks> Task<RedisValue[]> SetPopAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None); /// <summary> /// Return a random element from the set value stored at key. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The randomly selected element, or nil when key does not exist</returns> /// <remarks>https://redis.io/commands/srandmember</remarks> Task<RedisValue> SetRandomMemberAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Return an array of count distinct elements if count is positive. If called with a negative count the behavior changes and the command is allowed to return the same element multiple times. /// In this case the number of returned elements is the absolute value of the specified count. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="count">The count of members to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An array of elements, or an empty array when key does not exist</returns> /// <remarks>https://redis.io/commands/srandmember</remarks> Task<RedisValue[]> SetRandomMembersAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None); /// <summary> /// Remove the specified member from the set stored at key. Specified members that are not a member of this set are ignored. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="value">The value to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the specified member was already present in the set, else False</returns> /// <remarks>https://redis.io/commands/srem</remarks> Task<bool> SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Remove the specified members from the set stored at key. Specified members that are not a member of this set are ignored. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="values">The values to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of members that were removed from the set, not including non existing members.</returns> /// <remarks>https://redis.io/commands/srem</remarks> Task<long> SetRemoveAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None); /// <summary> /// Sorts a list, set or sorted set (numerically or alphabetically, ascending by default); By default, the elements themselves are compared, but the values can also be /// used to perform external key-lookups using the <c>by</c> parameter. By default, the elements themselves are returned, but external key-lookups (one or many) can /// be performed instead by specifying the <c>get</c> parameter (note that <c>#</c> specifies the element itself, when used in <c>get</c>). /// Referring to the <a href="https://redis.io/commands/sort">redis SORT documentation </a> for examples is recommended. When used in hashes, <c>by</c> and <c>get</c> /// can be used to specify fields using <c>-&gt;</c> notation (again, refer to redis documentation). /// </summary> /// <param name="key">The key of the list, set, or sorted set.</param> /// <param name="skip">How many entries to skip on the return.</param> /// <param name="take">How many entries to take on the return.</param> /// <param name="order">The ascending or descending order (defaults to ascending).</param> /// <param name="sortType">The sorting method (defaults to numeric).</param> /// <param name="by">The key pattern to sort by, if any. e.g. ExternalKey_* would sort by ExternalKey_{listvalue} as a lookup.</param> /// <param name="get">The key pattern to sort by, if any e.g. ExternalKey_* would return the value of ExternalKey_{listvalue} for each entry.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The sorted elements, or the external values if <c>get</c> is specified.</returns> /// <remarks>https://redis.io/commands/sort</remarks> Task<RedisValue[]> SortAsync(RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Sorts a list, set or sorted set (numerically or alphabetically, ascending by default); By default, the elements themselves are compared, but the values can also be /// used to perform external key-lookups using the <c>by</c> parameter. By default, the elements themselves are returned, but external key-lookups (one or many) can /// be performed instead by specifying the <c>get</c> parameter (note that <c>#</c> specifies the element itself, when used in <c>get</c>). /// Referring to the <a href="https://redis.io/commands/sort">redis SORT documentation </a> for examples is recommended. When used in hashes, <c>by</c> and <c>get</c> /// can be used to specify fields using <c>-&gt;</c> notation (again, refer to redis documentation). /// </summary> /// <param name="destination">The destination key to store results in.</param> /// <param name="key">The key of the list, set, or sorted set.</param> /// <param name="skip">How many entries to skip on the return.</param> /// <param name="take">How many entries to take on the return.</param> /// <param name="order">The ascending or descending order (defaults to ascending).</param> /// <param name="sortType">The sorting method (defaults to numeric).</param> /// <param name="by">The key pattern to sort by, if any. e.g. ExternalKey_* would sort by ExternalKey_{listvalue} as a lookup.</param> /// <param name="get">The key pattern to sort by, if any e.g. ExternalKey_* would return the value of ExternalKey_{listvalue} for each entry.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements stored in the new list.</returns> /// <remarks>https://redis.io/commands/sort</remarks> Task<long> SortAndStoreAsync(RedisKey destination, RedisKey key, long skip = 0, long take = -1, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds the specified member with the specified score to the sorted set stored at key. If the specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to add to the sorted set.</param> /// <param name="score">The score for the member to add to the sorted set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the value was added, False if it already existed (the score is still updated)</returns> /// <remarks>https://redis.io/commands/zadd</remarks> Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags); /// <summary> /// Adds the specified member with the specified score to the sorted set stored at key. If the specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to add to the sorted set.</param> /// <param name="score">The score for the member to add to the sorted set.</param> /// <param name="when">What conditions to add the element under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the value was added, False if it already existed (the score is still updated)</returns> /// <remarks>https://redis.io/commands/zadd</remarks> Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds all the specified members with the specified scores to the sorted set stored at key. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="values">The members and values to add to the sorted set.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements added to the sorted sets, not including elements already existing for which the score was updated.</returns> /// <remarks>https://redis.io/commands/zadd</remarks> Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, CommandFlags flags); /// <summary> /// Adds all the specified members with the specified scores to the sorted set stored at key. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="values">The members and values to add to the sorted set.</param> /// <param name="when">What conditions to add the element under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements added to the sorted sets, not including elements already existing for which the score was updated.</returns> /// <remarks>https://redis.io/commands/zadd</remarks> Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Computes a set operation over two sorted sets, and stores the result in destination, optionally performing /// a specific aggregation (defaults to sum). /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The key to store the results in.</param> /// <param name="first">The key of the first sorted set.</param> /// <param name="second">The key of the second sorted set.</param> /// <param name="aggregate">The aggregation method (defaults to sum).</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/zunionstore</remarks> /// <remarks>https://redis.io/commands/zinterstore</remarks> /// <returns>the number of elements in the resulting sorted set at destination</returns> Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None); /// <summary> /// Computes a set operation over multiple sorted sets (optionally using per-set weights), and stores the result in destination, optionally performing /// a specific aggregation (defaults to sum). /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The key to store the results in.</param> /// <param name="keys">The keys of the sorted sets.</param> /// <param name="weights">The optional weights per set that correspond to <paramref name="keys"/>.</param> /// <param name="aggregate">The aggregation method (defaults to sum).</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/zunionstore</remarks> /// <remarks>https://redis.io/commands/zinterstore</remarks> /// <returns>the number of elements in the resulting sorted set at destination</returns> Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None); /// <summary> /// Decrements the score of member in the sorted set stored at key by decrement. If member does not exist in the sorted set, it is added with -decrement as its score (as if its previous score was 0.0). /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to decrement.</param> /// <param name="value">The amount to decrement by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The new score of member.</returns> /// <remarks>https://redis.io/commands/zincrby</remarks> Task<double> SortedSetDecrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Increments the score of member in the sorted set stored at key by increment. If member does not exist in the sorted set, it is added with increment as its score (as if its previous score was 0.0). /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to increment.</param> /// <param name="value">The amount to increment by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The new score of member.</returns> /// <remarks>https://redis.io/commands/zincrby</remarks> Task<double> SortedSetIncrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the sorted set cardinality (number of elements) of the sorted set stored at key. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="min">The min score to filter by (defaults to negative infinity).</param> /// <param name="max">The max score to filter by (defaults to positive infinity).</param> /// <param name="exclude">Whether to exclude <paramref name="min"/> and <paramref name="max"/> from the range check (defaults to both inclusive).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The cardinality (number of elements) of the sorted set, or 0 if key does not exist.</returns> /// <remarks>https://redis.io/commands/zcard</remarks> Task<long> SortedSetLengthAsync(RedisKey key, double min = double.NegativeInfinity, double max = double.PositiveInfinity, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None); /// <summary> /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns the number of elements in the sorted set at key with a value between min and max. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="min">The min value to filter by.</param> /// <param name="max">The max value to filter by.</param> /// <param name="exclude">Whether to exclude <paramref name="min"/> and <paramref name="max"/> from the range check (defaults to both inclusive).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements in the specified score range.</returns> /// <remarks>https://redis.io/commands/zlexcount</remarks> Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the specified range of elements in the sorted set stored at key. By default the elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. /// Both start and stop are zero-based indexes, where 0 is the first element, 1 is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with -1 being the last element of the sorted set, -2 the penultimate element and so on. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The start index to get.</param> /// <param name="stop">The stop index to get.</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of elements in the specified range.</returns> /// <remarks>https://redis.io/commands/zrange</remarks> /// <remarks>https://redis.io/commands/zrevrange</remarks> Task<RedisValue[]> SortedSetRangeByRankAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the specified range of elements in the sorted set stored at key. By default the elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. /// Both start and stop are zero-based indexes, where 0 is the first element, 1 is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with -1 being the last element of the sorted set, -2 the penultimate element and so on. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The start index to get.</param> /// <param name="stop">The stop index to get.</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of elements in the specified range.</returns> /// <remarks>https://redis.io/commands/zrange</remarks> /// <remarks>https://redis.io/commands/zrevrange</remarks> Task<SortedSetEntry[]> SortedSetRangeByRankWithScoresAsync(RedisKey key, long start = 0, long stop = -1, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the specified range of elements in the sorted set stored at key. By default the elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. /// Start and stop are used to specify the min and max range for score values. Similar to other range methods the values are inclusive. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The minimum score to filter by.</param> /// <param name="stop">The maximum score to filter by.</param> /// <param name="exclude">Which of <paramref name="start"/> and <paramref name="stop"/> to exclude (defaults to both inclusive).</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="skip">How many items to skip.</param> /// <param name="take">How many items to take.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of elements in the specified score range.</returns> /// <remarks>https://redis.io/commands/zrangebyscore</remarks> /// <remarks>https://redis.io/commands/zrevrangebyscore</remarks> Task<RedisValue[]> SortedSetRangeByScoreAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the specified range of elements in the sorted set stored at key. By default the elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. /// Start and stop are used to specify the min and max range for score values. Similar to other range methods the values are inclusive. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The minimum score to filter by.</param> /// <param name="stop">The maximum score to filter by.</param> /// <param name="exclude">Which of <paramref name="start"/> and <paramref name="stop"/> to exclude (defaults to both inclusive).</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="skip">How many items to skip.</param> /// <param name="take">How many items to take.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>List of elements in the specified score range.</returns> /// <remarks>https://redis.io/commands/zrangebyscore</remarks> /// <remarks>https://redis.io/commands/zrevrangebyscore</remarks> Task<SortedSetEntry[]> SortedSetRangeByScoreWithScoresAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at key with a value between min and max. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="min">The min value to filter by.</param> /// <param name="max">The max value to filter by.</param> /// <param name="exclude">Which of <paramref name="min"/> and <paramref name="max"/> to exclude (defaults to both inclusive).</param> /// <param name="skip">How many items to skip.</param> /// <param name="take">How many items to take.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/zrangebylex</remarks> /// <returns>list of elements in the specified score range.</returns> Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take = -1, CommandFlags flags = CommandFlags.None); // defaults removed to avoid ambiguity with overload with order /// <summary> /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at key with a value between min and max. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="min">The min value to filter by.</param> /// <param name="max">The max value to filter by.</param> /// <param name="exclude">Which of <paramref name="min"/> and <paramref name="max"/> to exclude (defaults to both inclusive).</param> /// <param name="order">Whether to order the data ascending or descending</param> /// <param name="skip">How many items to skip.</param> /// <param name="take">How many items to take.</param> /// <param name="flags">The flags to use for this operation.</param> /// <remarks>https://redis.io/commands/zrangebylex</remarks> /// <remarks>https://redis.io/commands/zrevrangebylex</remarks> /// <returns>list of elements in the specified score range.</returns> Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the rank of member in the sorted set stored at key, by default with the scores ordered from low to high. The rank (or index) is 0-based, which means that the member with the lowest score has rank 0. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to get the rank of.</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>If member exists in the sorted set, the rank of member; If member does not exist in the sorted set or key does not exist, null</returns> /// <remarks>https://redis.io/commands/zrank</remarks> /// <remarks>https://redis.io/commands/zrevrank</remarks> Task<long?> SortedSetRankAsync(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified member from the sorted set stored at key. Non existing members are ignored. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the member existed in the sorted set and was removed; False otherwise.</returns> /// <remarks>https://redis.io/commands/zrem</remarks> Task<bool> SortedSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes the specified members from the sorted set stored at key. Non existing members are ignored. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="members">The members to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of members removed from the sorted set, not including non existing members.</returns> /// <remarks>https://redis.io/commands/zrem</remarks> Task<long> SortedSetRemoveAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes all elements in the sorted set stored at key with rank between start and stop. Both start and stop are 0 -based indexes with 0 being the element with the lowest score. These indexes can be negative numbers, where they indicate offsets starting at the element with the highest score. For example: -1 is the element with the highest score, -2 the element with the second highest score and so forth. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The minimum rank to remove.</param> /// <param name="stop">The maximum rank to remove.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements removed.</returns> /// <remarks>https://redis.io/commands/zremrangebyrank</remarks> Task<long> SortedSetRemoveRangeByRankAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes all elements in the sorted set stored at key with a score between min and max (inclusive by default). /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="start">The minimum score to remove.</param> /// <param name="stop">The maximum score to remove.</param> /// <param name="exclude">Which of <paramref name="start"/> and <paramref name="stop"/> to exclude (defaults to both inclusive).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of elements removed.</returns> /// <remarks>https://redis.io/commands/zremrangebyscore</remarks> Task<long> SortedSetRemoveRangeByScoreAsync(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None); /// <summary> /// When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command removes all elements in the sorted set stored at key between the lexicographical range specified by min and max. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="min">The minimum value to remove.</param> /// <param name="max">The maximum value to remove.</param> /// <param name="exclude">Which of <paramref name="min"/> and <paramref name="max"/> to exclude (defaults to both inclusive).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>the number of elements removed.</returns> /// <remarks>https://redis.io/commands/zremrangebylex</remarks> Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None); /// <summary> /// The SSCAN command is used to incrementally iterate over set; note: to resume an iteration via <i>cursor</i>, cast the original enumerable or enumerator to <i>IScanningCursor</i>. /// </summary> /// <param name="key">The key of the set.</param> /// <param name="pattern">The pattern to match.</param> /// <param name="pageSize">The page size to iterate by.</param> /// <param name="cursor">The cursor position to start at.</param> /// <param name="pageOffset">The page offset to start at.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Yields all matching elements of the set.</returns> /// <remarks>https://redis.io/commands/sscan</remarks> IAsyncEnumerable<RedisValue> SetScanAsync(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None); /// <summary> /// The ZSCAN command is used to incrementally iterate over a sorted set /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="pattern">The pattern to match.</param> /// <param name="pageSize">The page size to iterate by.</param> /// <param name="flags">The flags to use for this operation.</param> /// <param name="cursor">The cursor position to start at.</param> /// <param name="pageOffset">The page offset to start at.</param> /// <returns>Yields all matching elements of the sorted set.</returns> /// <remarks>https://redis.io/commands/zscan</remarks> IAsyncEnumerable<SortedSetEntry> SortedSetScanAsync(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = RedisBase.CursorUtils.DefaultLibraryPageSize, long cursor = RedisBase.CursorUtils.Origin, int pageOffset = 0, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the score of member in the sorted set at key; If member does not exist in the sorted set, or key does not exist, nil is returned. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="member">The member to get a score for.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The score of the member.</returns> /// <remarks>https://redis.io/commands/zscore</remarks> Task<double?> SortedSetScoreAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns the first element from the sorted set stored at key, by default with the scores ordered from low to high. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The removed element, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/zpopmin</remarks> /// <remarks>https://redis.io/commands/zpopmax</remarks> Task<SortedSetEntry?> SortedSetPopAsync(RedisKey key, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Removes and returns the specified number of first elements from the sorted set stored at key, by default with the scores ordered from low to high. /// </summary> /// <param name="key">The key of the sorted set.</param> /// <param name="count">The number of elements to return.</param> /// <param name="order">The order to sort by (defaults to ascending).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An array of elements, or an empty array when key does not exist.</returns> /// <remarks>https://redis.io/commands/zpopmin</remarks> /// <remarks>https://redis.io/commands/zpopmax</remarks> Task<SortedSetEntry[]> SortedSetPopAsync(RedisKey key, long count, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Allow the consumer to mark a pending message as correctly processed. Returns the number of messages acknowledged. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group that received the message.</param> /// <param name="messageId">The ID of the message to acknowledge.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of messages acknowledged.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<long> StreamAcknowledgeAsync(RedisKey key, RedisValue groupName, RedisValue messageId, CommandFlags flags = CommandFlags.None); /// <summary> /// Allow the consumer to mark a pending message as correctly processed. Returns the number of messages acknowledged. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group that received the message.</param> /// <param name="messageIds">The IDs of the messages to acknowledge.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of messages acknowledged.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<long> StreamAcknowledgeAsync(RedisKey key, RedisValue groupName, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds an entry using the specified values to the given stream key. If key does not exist, a new key holding a stream is created. The command returns the ID of the newly created stream entry. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="streamField">The field name for the stream entry.</param> /// <param name="streamValue">The value to set in the stream entry.</param> /// <param name="messageId">The ID to assign to the stream entry, defaults to an auto-generated ID ("*").</param> /// <param name="maxLength">The maximum length of the stream.</param> /// <param name="useApproximateMaxLength">If true, the "~" argument is used to allow the stream to exceed max length by a small number. This improves performance when removing messages.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The ID of the newly created message.</returns> /// <remarks>https://redis.io/commands/xadd</remarks> Task<RedisValue> StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None); /// <summary> /// Adds an entry using the specified values to the given stream key. If key does not exist, a new key holding a stream is created. The command returns the ID of the newly created stream entry. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="streamPairs">The fields and their associated values to set in the stream entry.</param> /// <param name="messageId">The ID to assign to the stream entry, defaults to an auto-generated ID ("*").</param> /// <param name="maxLength">The maximum length of the stream.</param> /// <param name="useApproximateMaxLength">If true, the "~" argument is used to allow the stream to exceed max length by a small number. This improves performance when removing messages.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The ID of the newly created message.</returns> /// <remarks>https://redis.io/commands/xadd</remarks> Task<RedisValue> StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, int? maxLength = null, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None); /// <summary> /// Change ownership of messages consumed, but not yet acknowledged, by a different consumer. This method returns the complete message for the claimed message(s). /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="consumerGroup">The consumer group.</param> /// <param name="claimingConsumer">The consumer claiming the given messages.</param> /// <param name="minIdleTimeInMs">The minimum message idle time to allow the reassignment of the message(s).</param> /// <param name="messageIds">The IDs of the messages to claim for the given consumer.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The messages successfully claimed by the given consumer.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<StreamEntry[]> StreamClaimAsync(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None); /// <summary> /// Change ownership of messages consumed, but not yet acknowledged, by a different consumer. This method returns the IDs for the claimed message(s). /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="consumerGroup">The consumer group.</param> /// <param name="claimingConsumer">The consumer claiming the given message(s).</param> /// <param name="minIdleTimeInMs">The minimum message idle time to allow the reassignment of the message(s).</param> /// <param name="messageIds">The IDs of the messages to claim for the given consumer.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The message IDs for the messages successfully claimed by the given consumer.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<RedisValue[]> StreamClaimIdsOnlyAsync(RedisKey key, RedisValue consumerGroup, RedisValue claimingConsumer, long minIdleTimeInMs, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None); /// <summary> /// Set the position from which to read a stream for a consumer group. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="position">The position from which to read for the consumer group.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if successful, otherwise false.</returns> Task<bool> StreamConsumerGroupSetPositionAsync(RedisKey key, RedisValue groupName, RedisValue position, CommandFlags flags = CommandFlags.None); /// <summary> /// Retrieve information about the consumers for the given consumer group. This is the equivalent of calling "XINFO GROUPS key group". /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The consumer group name.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An instance of <see cref="StreamConsumerInfo"/> for each of the consumer group's consumers.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<StreamConsumerInfo[]> StreamConsumerInfoAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None); /// <summary> /// Create a consumer group for the given stream. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the group to create.</param> /// <param name="position">The position to begin reading the stream. Defaults to <see cref="StreamPosition.NewMessages"/>.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the group was created.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<bool> StreamCreateConsumerGroupAsync(RedisKey key, RedisValue groupName, RedisValue? position, CommandFlags flags); /// <summary> /// Create a consumer group for the given stream. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the group to create.</param> /// <param name="position">The position to begin reading the stream. Defaults to <see cref="StreamPosition.NewMessages"/>.</param> /// <param name="createStream">Create the stream if it does not already exist.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the group was created.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<bool> StreamCreateConsumerGroupAsync(RedisKey key, RedisValue groupName, RedisValue? position = null, bool createStream = true, CommandFlags flags = CommandFlags.None); /// <summary> /// Delete messages in the stream. This method does not delete the stream. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="messageIds">The IDs of the messages to delete.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Returns the number of messages successfully deleted from the stream.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<long> StreamDeleteAsync(RedisKey key, RedisValue[] messageIds, CommandFlags flags = CommandFlags.None); /// <summary> /// Delete a consumer from a consumer group. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="consumerName">The name of the consumer.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of messages that were pending for the deleted consumer.</returns> Task<long> StreamDeleteConsumerAsync(RedisKey key, RedisValue groupName, RedisValue consumerName, CommandFlags flags = CommandFlags.None); /// <summary> /// Delete a consumer group. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if deleted, otherwise false.</returns> Task<bool> StreamDeleteConsumerGroupAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None); /// <summary> /// Retrieve information about the groups created for the given stream. This is the equivalent of calling "XINFO GROUPS key". /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An instance of <see cref="StreamGroupInfo"/> for each of the stream's groups.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<StreamGroupInfo[]> StreamGroupInfoAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Retrieve information about the given stream. This is the equivalent of calling "XINFO STREAM key". /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A <see cref="StreamInfo"/> instance with information about the stream.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<StreamInfo> StreamInfoAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the number of entries in a stream. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of entries inside the given stream.</returns> /// <remarks>https://redis.io/commands/xlen</remarks> Task<long> StreamLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// View information about pending messages for a stream. A pending message is a message read using StreamReadGroup (XREADGROUP) but not yet acknowledged. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An instance of <see cref="StreamPendingInfo"/>. <see cref="StreamPendingInfo"/> contains the number of pending messages, the highest and lowest ID of the pending messages, and the consumers with their pending message count.</returns> /// <remarks>The equivalent of calling XPENDING key group.</remarks> /// <remarks>https://redis.io/commands/xpending</remarks> Task<StreamPendingInfo> StreamPendingAsync(RedisKey key, RedisValue groupName, CommandFlags flags = CommandFlags.None); /// <summary> /// View information about each pending message. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="count">The maximum number of pending messages to return.</param> /// <param name="consumerName">The consumer name for the pending messages. Pass RedisValue.Null to include pending messages for all consumers.</param> /// <param name="minId">The minimum ID from which to read the stream of pending messages. The method will default to reading from the beginning of the stream.</param> /// <param name="maxId">The maximum ID to read to within the stream of pending messages. The method will default to reading to the end of the stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>An instance of <see cref="StreamPendingMessageInfo"/> for each pending message.</returns> /// <remarks>Equivalent of calling XPENDING key group start-id end-id count consumer-name.</remarks> /// <remarks>https://redis.io/commands/xpending</remarks> Task<StreamPendingMessageInfo[]> StreamPendingMessagesAsync(RedisKey key, RedisValue groupName, int count, RedisValue consumerName, RedisValue? minId = null, RedisValue? maxId = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Read a stream using the given range of IDs. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="minId">The minimum ID from which to read the stream. The method will default to reading from the beginning of the stream.</param> /// <param name="maxId">The maximum ID to read to within the stream. The method will default to reading to the end of the stream.</param> /// <param name="count">The maximum number of messages to return.</param> /// <param name="messageOrder">The order of the messages. <see cref="Order.Ascending"/> will execute XRANGE and <see cref="Order.Descending"/> wil execute XREVRANGE.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Returns an instance of <see cref="StreamEntry"/> for each message returned.</returns> /// <remarks>https://redis.io/commands/xrange</remarks> Task<StreamEntry[]> StreamRangeAsync(RedisKey key, RedisValue? minId = null, RedisValue? maxId = null, int? count = null, Order messageOrder = Order.Ascending, CommandFlags flags = CommandFlags.None); /// <summary> /// Read from a single stream. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="position">The position from which to read the stream.</param> /// <param name="count">The maximum number of messages to return.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Returns an instance of <see cref="StreamEntry"/> for each message returned.</returns> /// <remarks>Equivalent of calling XREAD COUNT num STREAMS key id.</remarks> /// <remarks>https://redis.io/commands/xread</remarks> Task<StreamEntry[]> StreamReadAsync(RedisKey key, RedisValue position, int? count = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Read from multiple streams. /// </summary> /// <param name="streamPositions">Array of streams and the positions from which to begin reading for each stream.</param> /// <param name="countPerStream">The maximum number of messages to return from each stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A value of <see cref="RedisStream"/> for each stream.</returns> /// <remarks>Equivalent of calling XREAD COUNT num STREAMS key1 key2 id1 id2.</remarks> /// <remarks>https://redis.io/commands/xread</remarks> Task<RedisStream[]> StreamReadAsync(StreamPosition[] streamPositions, int? countPerStream = null, CommandFlags flags = CommandFlags.None); /// <summary> /// Read messages from a stream into an associated consumer group. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="consumerName">The consumer name.</param> /// <param name="position">The position from which to read the stream. Defaults to <see cref="StreamPosition.NewMessages"/> when null.</param> /// <param name="count">The maximum number of messages to return.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Returns a value of <see cref="StreamEntry"/> for each message returned.</returns> /// <remarks>https://redis.io/commands/xreadgroup</remarks> Task<StreamEntry[]> StreamReadGroupAsync(RedisKey key, RedisValue groupName, RedisValue consumerName, RedisValue? position, int? count, CommandFlags flags); /// <summary> /// Read messages from a stream into an associated consumer group. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="consumerName">The consumer name.</param> /// <param name="position">The position from which to read the stream. Defaults to <see cref="StreamPosition.NewMessages"/> when null.</param> /// <param name="count">The maximum number of messages to return.</param> /// <param name="noAck">When true, the message will not be added to the pending message list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>Returns a value of <see cref="StreamEntry"/> for each message returned.</returns> /// <remarks>https://redis.io/commands/xreadgroup</remarks> Task<StreamEntry[]> StreamReadGroupAsync(RedisKey key, RedisValue groupName, RedisValue consumerName, RedisValue? position = null, int? count = null, bool noAck = false, CommandFlags flags = CommandFlags.None); /// <summary> /// Read from multiple streams into the given consumer group. The consumer group with the given <paramref name="groupName"/> /// will need to have been created for each stream prior to calling this method. /// </summary> /// <param name="streamPositions">Array of streams and the positions from which to begin reading for each stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="consumerName"></param> /// <param name="countPerStream">The maximum number of messages to return from each stream.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A value of <see cref="RedisStream"/> for each stream.</returns> /// <remarks>Equivalent of calling XREADGROUP GROUP groupName consumerName COUNT countPerStream STREAMS stream1 stream2 id1 id2</remarks> /// <remarks>https://redis.io/commands/xreadgroup</remarks> Task<RedisStream[]> StreamReadGroupAsync(StreamPosition[] streamPositions, RedisValue groupName, RedisValue consumerName, int? countPerStream, CommandFlags flags); /// <summary> /// Read from multiple streams into the given consumer group. The consumer group with the given <paramref name="groupName"/> /// will need to have been created for each stream prior to calling this method. /// </summary> /// <param name="streamPositions">Array of streams and the positions from which to begin reading for each stream.</param> /// <param name="groupName">The name of the consumer group.</param> /// <param name="consumerName"></param> /// <param name="countPerStream">The maximum number of messages to return from each stream.</param> /// <param name="noAck">When true, the message will not be added to the pending message list.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>A value of <see cref="RedisStream"/> for each stream.</returns> /// <remarks>Equivalent of calling XREADGROUP GROUP groupName consumerName COUNT countPerStream STREAMS stream1 stream2 id1 id2</remarks> /// <remarks>https://redis.io/commands/xreadgroup</remarks> Task<RedisStream[]> StreamReadGroupAsync(StreamPosition[] streamPositions, RedisValue groupName, RedisValue consumerName, int? countPerStream = null, bool noAck = false, CommandFlags flags = CommandFlags.None); /// <summary> /// Trim the stream to a specified maximum length. /// </summary> /// <param name="key">The key of the stream.</param> /// <param name="maxLength">The maximum length of the stream.</param> /// <param name="useApproximateMaxLength">If true, the "~" argument is used to allow the stream to exceed max length by a small number. This improves performance when removing messages.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of messages removed from the stream.</returns> /// <remarks>https://redis.io/topics/streams-intro</remarks> Task<long> StreamTrimAsync(RedisKey key, int maxLength, bool useApproximateMaxLength = false, CommandFlags flags = CommandFlags.None); /// <summary> /// If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, /// so APPEND will be similar to SET in this special case. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The value to append to the string.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the string after the append operation.</returns> /// <remarks>https://redis.io/commands/append</remarks> Task<long> StringAppendAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Count the number of set bits (population counting) in a string. /// By default all the bytes contained in the string are examined. It is possible to specify the counting operation only in an interval passing the additional arguments start and end. /// Like for the GETRANGE command start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, -2 is the penultimate, and so forth. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="start">The start byte to count at.</param> /// <param name="end">The end byte to count at.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of bits set to 1.</returns> /// <remarks>https://redis.io/commands/bitcount</remarks> Task<long> StringBitCountAsync(RedisKey key, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. /// The BITOP command supports four bitwise operations; note that NOT is a unary operator: the second key should be omitted in this case /// and only the first key will be considered. /// The result of the operation is always stored at destkey. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The destination key to store the result in.</param> /// <param name="first">The first key to get the bit value from.</param> /// <param name="second">The second key to get the bit value from.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns> /// <remarks>https://redis.io/commands/bitop</remarks> Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None); /// <summary> /// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. /// The BITOP command supports four bitwise operations; note that NOT is a unary operator. /// The result of the operation is always stored at destkey. /// </summary> /// <param name="operation">The operation to perform.</param> /// <param name="destination">The destination key to store the result in.</param> /// <param name="keys">The keys to get the bit values from.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns> /// <remarks>https://redis.io/commands/bitop</remarks> Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Return the position of the first bit set to 1 or 0 in a string. /// The position is returned thinking at the string as an array of bits from left to right where the first byte most significant bit is at position 0, the second byte most significant bit is at position 8 and so forth. /// An start and end may be specified; these are in bytes, not bits; start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, -2 is the penultimate, and so forth. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="bit">True to check for the first 1 bit, false to check for the first 0 bit.</param> /// <param name="start">The position to start looking (defaults to 0).</param> /// <param name="end">The position to stop looking (defaults to -1, unlimited).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The command returns the position of the first bit set to 1 or 0 according to the request. /// If we look for set bits(the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned.</returns> /// <remarks>https://redis.io/commands/bitpos</remarks> Task<long> StringBitPositionAsync(RedisKey key, bool bit, long start = 0, long end = -1, CommandFlags flags = CommandFlags.None); /// <summary> /// Decrements the number stored at key by decrement. If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type or contains a string that is not representable as integer. This operation is limited to 64 bit signed integers. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The amount to decrement by (defaults to 1).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key after the decrement.</returns> /// <remarks>https://redis.io/commands/decrby</remarks> /// <remarks>https://redis.io/commands/decr</remarks> Task<long> StringDecrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None); /// <summary> /// Decrements the string representing a floating point number stored at key by the specified decrement. If the key does not exist, it is set to 0 before performing the operation. The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The amount to decrement by (defaults to 1).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key after the decrement.</returns> /// <remarks>https://redis.io/commands/incrbyfloat</remarks> Task<double> StringDecrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/get</remarks> Task<RedisValue> StringGetAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. /// </summary> /// <param name="keys">The keys of the strings.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The values of the strings with nil for keys do not exist.</returns> /// <remarks>https://redis.io/commands/mget</remarks> Task<RedisValue[]> StringGetAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None); /// <summary> /// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/get</remarks> Task<Lease<byte>> StringGetLeaseAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the bit value at offset in the string value stored at key. /// When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="offset">The offset in the string to get a bit at.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The bit value stored at offset.</returns> /// <remarks>https://redis.io/commands/getbit</remarks> Task<bool> StringGetBitAsync(RedisKey key, long offset, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). Negative offsets can be used in order to provide an offset starting from the end of the string. So -1 means the last character, -2 the penultimate and so forth. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="start">The start index of the substring to get.</param> /// <param name="end">The end index of the substring to get.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The substring of the string value stored at key.</returns> /// <remarks>https://redis.io/commands/getrange</remarks> Task<RedisValue> StringGetRangeAsync(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None); /// <summary> /// Atomically sets key to value and returns the old value stored at key. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The value to replace the existing value with.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The old value stored at key, or nil when key did not exist.</returns> /// <remarks>https://redis.io/commands/getset</remarks> Task<RedisValue> StringGetSetAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key and its expiry, or nil when key does not exist.</returns> /// <remarks>https://redis.io/commands/get</remarks> Task<RedisValueWithExpiry> StringGetWithExpiryAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Increments the number stored at key by increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that is not representable as integer. This operation is limited to 64 bit signed integers. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The amount to increment by (defaults to 1).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key after the increment.</returns> /// <remarks>https://redis.io/commands/incrby</remarks> /// <remarks>https://redis.io/commands/incr</remarks> Task<long> StringIncrementAsync(RedisKey key, long value = 1, CommandFlags flags = CommandFlags.None); /// <summary> /// Increments the string representing a floating point number stored at key by the specified increment. If the key does not exist, it is set to 0 before performing the operation. The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The amount to increment by (defaults to 1).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The value of key after the increment.</returns> /// <remarks>https://redis.io/commands/incrbyfloat</remarks> Task<double> StringIncrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None); /// <summary> /// Returns the length of the string value stored at key. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>the length of the string at key, or 0 when key does not exist.</returns> /// <remarks>https://redis.io/commands/strlen</remarks> Task<long> StringLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="value">The value to set.</param> /// <param name="expiry">The expiry to set.</param> /// <param name="when">Which condition to set the value under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the string was set, false otherwise.</returns> /// <remarks>https://redis.io/commands/set</remarks> Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Sets the given keys to their respective values. If "not exists" is specified, this will not perform any operation at all even if just a single key already exists. /// </summary> /// <param name="values">The keys and values to set.</param> /// <param name="when">Which condition to set the value under (defaults to always).</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the keys were set, else False</returns> /// <remarks>https://redis.io/commands/mset</remarks> /// <remarks>https://redis.io/commands/msetnx</remarks> Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None); /// <summary> /// Sets or clears the bit at offset in the string value stored at key. /// The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created.The string is grown to make sure it can hold a bit at offset. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="offset">The offset in the string to set <paramref name="bit"/>.</param> /// <param name="bit">The bit value to set, true for 1, false for 0.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The original bit value stored at offset.</returns> /// <remarks>https://redis.io/commands/setbit</remarks> Task<bool> StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None); /// <summary> /// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset. /// </summary> /// <param name="key">The key of the string.</param> /// <param name="offset">The offset in the string to overwrite.</param> /// <param name="value">The value to overwrite with.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The length of the string after it was modified by the command.</returns> /// <remarks>https://redis.io/commands/setrange</remarks> Task<RedisValue> StringSetRangeAsync(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None); /// <summary> /// Touch the specified key. /// </summary> /// <param name="key">The key to touch.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>True if the key was touched.</returns> /// <remarks>https://redis.io/commands/touch</remarks> Task<bool> KeyTouchAsync(RedisKey key, CommandFlags flags = CommandFlags.None); /// <summary> /// Youch the specified keys. A key is ignored if it does not exist. /// </summary> /// <param name="keys">The keys to touch.</param> /// <param name="flags">The flags to use for this operation.</param> /// <returns>The number of keys that were touched.</returns> /// <remarks>https://redis.io/commands/touch</remarks> Task<long> KeyTouchAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None); } }
73.209717
416
0.659057
[ "Apache-2.0" ]
AlphaGremlin/StackExchange.Redis
src/StackExchange.Redis/Interfaces/IDatabaseAsync.cs
147,666
C#
/***************************************************************************** * * ReoGrid - .NET Spreadsheet Control * * http://reogrid.net * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * ReoGrid and ReoGrid Demo project is released under MIT license. * * Copyright (c) 2012-2016 Jing <lujing at unvell.com> * Copyright (c) 2012-2016 unvell.com, all rights reserved. * ****************************************************************************/ namespace unvell.ReoGrid.Demo.Features { partial class ZoomDemo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.trackBar1 = new System.Windows.Forms.TrackBar(); this.label1 = new System.Windows.Forms.Label(); this.grid = new unvell.ReoGrid.ReoGridControl(); this.label2 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // trackBar1 // this.trackBar1.Location = new System.Drawing.Point(15, 40); this.trackBar1.Maximum = 40; this.trackBar1.Minimum = 1; this.trackBar1.Name = "trackBar1"; this.trackBar1.Size = new System.Drawing.Size(160, 45); this.trackBar1.TabIndex = 3; this.trackBar1.Value = 10; this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 14); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(37, 13); this.label1.TabIndex = 4; this.label1.Text = "Zoom:"; // // grid // this.grid.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.grid.ColumnHeaderContextMenuStrip = null; this.grid.Dock = System.Windows.Forms.DockStyle.Fill; this.grid.LeadHeaderContextMenuStrip = null; this.grid.Location = new System.Drawing.Point(0, 0); this.grid.Name = "grid"; this.grid.RowHeaderContextMenuStrip = null; this.grid.Script = null; this.grid.SheetTabContextMenuStrip = null; this.grid.SheetTabWidth = 400; this.grid.Size = new System.Drawing.Size(630, 564); this.grid.TabIndex = 2; this.grid.TabStop = false; this.grid.Text = "reoGridControl1"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(52, 101); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(73, 13); this.label2.TabIndex = 5; this.label2.Text = "Current: 100%"; // // panel1 // this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.trackBar1); this.panel1.Dock = System.Windows.Forms.DockStyle.Right; this.panel1.Location = new System.Drawing.Point(630, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(192, 564); this.panel1.TabIndex = 6; // // ZoomForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(822, 564); this.Controls.Add(this.grid); this.Controls.Add(this.panel1); this.Name = "ZoomForm"; this.Text = "Zoom"; ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private ReoGridControl grid; private System.Windows.Forms.TrackBar trackBar1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panel1; } }
33.05036
127
0.665433
[ "MIT" ]
DevX-Realtobiz/ReoGrid
Demo/Features/ZoomDemo.Designer.cs
4,596
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Sql { internal enum SqlObjectKind { AliasedCollectionExpression, ArrayCreateScalarExpression, ArrayIteratorCollectionExpression, ArrayScalarExpression, BetweenScalarExpression, BinaryScalarExpression, BooleanLiteral, CoalesceScalarExpression, ConditionalScalarExpression, ExistsScalarExpression, FromClause, FunctionCallScalarExpression, GroupByClause, Identifier, IdentifierPathExpression, InScalarExpression, InputPathCollection, JoinCollectionExpression, LimitSpec, LiteralArrayCollection, LiteralScalarExpression, MemberIndexerScalarExpression, NullLiteral, NumberLiteral, NumberPathExpression, ObjectCreateScalarExpression, ObjectProperty, OffsetLimitClause, OffsetSpec, OrderByClause, OrderByItem, Parameter, ParameterRefScalarExpression, Program, PropertyName, PropertyRefScalarExpression, Query, SelectClause, SelectItem, SelectListSpec, SelectStarSpec, SelectValueSpec, StringLiteral, StringPathExpression, SubqueryCollection, SubqueryScalarExpression, TopSpec, UnaryScalarExpression, UndefinedLiteral, WhereClause, } }
27.716667
63
0.597114
[ "MIT" ]
DashThis/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/SqlObjects/SqlObjectKind.cs
1,665
C#
namespace Ejercicio13 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox5 = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(629, 375); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(112, 34); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(60, 50); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(137, 25); this.label1.TabIndex = 1; this.label1.Text = "Horas normales"; this.label1.Click += new System.EventHandler(this.label1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(60, 95); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(99, 25); this.label2.TabIndex = 2; this.label2.Text = "horas extra"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(60, 303); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(143, 25); this.label3.TabIndex = 2; this.label3.Text = "nomina mensual"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(282, 50); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(150, 31); this.textBox1.TabIndex = 3; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(282, 105); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(150, 31); this.textBox2.TabIndex = 3; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(252, 303); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(150, 31); this.textBox3.TabIndex = 3; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(507, 69); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(150, 31); this.textBox4.TabIndex = 3; this.textBox4.TextChanged += new System.EventHandler(this.textBox4_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(496, 29); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(175, 25); this.label4.TabIndex = 4; this.label4.Text = "euro horas normales"; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(507, 195); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(150, 31); this.textBox5.TabIndex = 5; this.textBox5.TextChanged += new System.EventHandler(this.textBox5_TextChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(507, 142); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(148, 25); this.label5.TabIndex = 6; this.label5.Text = "euro horas extras"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.label5); this.Controls.Add(this.textBox5); this.Controls.Add(this.label4); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Horas normales"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.Label label5; } }
40.40678
107
0.551874
[ "MIT" ]
Ter15/Trabajos-Casa
Ejercicio instituto/Ejercicio13/Ejercicio13/Ejercicio13/Form1.Designer.cs
7,154
C#
using System; using System.Threading.Tasks; using GRA.Controllers.ViewModel.ParticipatingBranches; using GRA.Domain.Service; using Microsoft.AspNetCore.Mvc; namespace GRA.Controllers { public class ParticipatingLibrariesController : Base.UserController { private readonly SiteService _siteService; public ParticipatingLibrariesController(ServiceFacade.Controller context, SiteService siteService) : base(context) { _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService)); } public static string Name { get { return "ParticipatingLibraries"; } } public async Task<IActionResult> Index() { return View(nameof(Index), new ParticipatingLibrariesViewModel { Systems = await _siteService.GetSystemList() }); } } }
29.16129
95
0.667035
[ "MIT" ]
MCLD/greatreadingadventure
src/GRA.Controllers/ParticipatingLibrariesController.cs
906
C#
using System.Collections; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Reflection; using Microsoft.PowerShell; using Xunit; namespace Test { public partial class ReadLine { [SkippableFact] public void TabComplete() { TestSetup(KeyMode.Cmd); Test("$true", Keys( "$tr", _.Tab, CheckThat(() => AssertCursorLeftIs(5)))); // Validate no change on no match Test("$zz", Keys( "$zz", _.Tab, CheckThat(() => AssertCursorLeftIs(3)))); Test("$this", Keys( "$t", _.Tab, CheckThat(() => AssertLineIs("$thing")), _.Tab, CheckThat(() => AssertLineIs("$this")), _.Tab, CheckThat(() => AssertLineIs("$true")), _.Shift_Tab, CheckThat(() => AssertLineIs("$this")))); } [SkippableFact] public void InvalidCompletionResult() { TestSetup(KeyMode.Cmd); for (int i = 1; i <= 4; i++) { var input = $"invalid result {i}"; Test(input, Keys(input, _.Tab)); } } [SkippableFact] public void Complete() { TestSetup(KeyMode.Emacs); Test("ambiguous1", Keys( "ambig", _.Tab, CheckThat(() => AssertLineIs("ambiguous")), '1')); } [SkippableFact] public void PossibleCompletions() { TestSetup(KeyMode.Emacs); _console.Clear(); // Test empty input, make sure line after the cursor is blank and cursor didn't move Test("", Keys( _.Alt_Equals, CheckThat(() => { AssertCursorLeftTopIs(0, 0); AssertScreenIs(2, NextLine); }))); const string promptLine1 = "c:\\windows"; const string promptLine2 = "PS> "; using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) { ps.AddScript($@"function prompt {{ ""{promptLine1}`n{promptLine2}"" }}"); ps.Invoke(); } PSConsoleReadLine.SetOptions(new SetPSReadLineOption {ExtraPromptLineCount = 1}); _console.Clear(); Test("psvar", Keys( "psvar", _.Alt_Equals, CheckThat(() => AssertScreenIs(5, TokenClassification.None, promptLine1, NextLine, promptLine2, TokenClassification.Command, "psvar", NextLine, "$pssomething", NextLine, TokenClassification.None, promptLine1, NextLine, promptLine2, TokenClassification.Command, "psvar"))), prompt: promptLine1 + "\n" + promptLine2); using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) { ps.AddCommand("Remove-Item").AddArgument("function:prompt"); ps.Invoke(); } _console.Clear(); TestMustDing("none", Keys( "none", _.Alt_Equals, CheckThat(() => AssertScreenIs(2, TokenClassification.Command, "none", NextLine)))); } [SkippableFact] public void PossibleCompletionsPrompt() { TestSetup(KeyMode.Cmd, new KeyHandler("Ctrl+Spacebar", PSConsoleReadLine.PossibleCompletions)); PSConsoleReadLine.GetOptions().CompletionQueryItems = 10; _console.Clear(); Test("Get-Many", Keys( "Get-Many", _.Ctrl_Spacebar, CheckThat(() => AssertScreenIs(2, TokenClassification.Command, "Get-Many", NextLine, TokenClassification.None, "Display all 15 possibilities? (y or n) _")), "n")); _console.Clear(); Test("Get-Many", Keys( "Get-Many", _.Ctrl_Spacebar, CheckThat(() => AssertScreenIs(2, TokenClassification.Command, "Get-Many", NextLine, TokenClassification.None, "Display all 15 possibilities? (y or n) _")), "y", CheckThat(() => AssertScreenIs(4, TokenClassification.Command, "Get-Many", NextLine, TokenClassification.None, "Get-Many0 Get-Many3 Get-Many6 Get-Many9 Get-Many12", NextLine, "Get-Many1 Get-Many4 Get-Many7 Get-Many10 Get-Many13", NextLine, "Get-Many2 Get-Many5 Get-Many8 Get-Many11 Get-Many14")))); } [SkippableFact] public void MenuCompletions() { TestSetup(KeyMode.Cmd, new KeyHandler("Ctrl+Spacebar", PSConsoleReadLine.MenuComplete)); _console.Clear(); Test("Get-Many4", Keys( "Get-Many", _.Ctrl_Spacebar, CheckThat(() => AssertScreenIs(4, TokenClassification.Command, "Get-Many", TokenClassification.Selection, "0", NextLine, TokenClassification.Selection, "Get-Many0 ", TokenClassification.None, "Get-Many3 Get-Many6 Get-Many9 Get-Many12", NextLine, "Get-Many1 Get-Many4 Get-Many7 Get-Many10 Get-Many13", NextLine, "Get-Many2 Get-Many5 Get-Many8 Get-Many11 Get-Many14")), "4", CheckThat(() => AssertScreenIs(4, TokenClassification.Command, "Get-Many4", NextLine, TokenClassification.Selection, "Get-Many4 ", NextLine, " ", NextLine, " ", NextLine)), _.Enter, _.Enter )); } [SkippableFact] public void ShowTooltips() { TestSetup(KeyMode.Cmd, new KeyHandler("Ctrl+Spacebar", PSConsoleReadLine.PossibleCompletions)); PSConsoleReadLine.GetOptions().ShowToolTips = true; _console.Clear(); // TODO: } [SkippableFact] public void DirectoryCompletion() { TestSetup(KeyMode.Cmd); Test("", Keys( "Get-Directory", _.Tab, CheckThat(() => AssertLineIs("abc" + Path.DirectorySeparatorChar)), _.Tab, CheckThat(() => AssertLineIs("'e f" + Path.DirectorySeparatorChar + "'")), CheckThat(() => AssertCursorLeftIs(5)), _.Tab, CheckThat(() => AssertLineIs("a" + Path.DirectorySeparatorChar)), _.Tab, CheckThat(() => AssertLineIs("'a b" + Path.DirectorySeparatorChar + "'")), CheckThat(() => AssertCursorLeftIs(5)), _.Tab, CheckThat(() => AssertLineIs("\"a b" + Path.DirectorySeparatorChar + "\"")), CheckThat(() => AssertCursorLeftIs(5)), _.Ctrl_c, InputAcceptedNow)); } internal static CommandCompletion MockedCompleteInput(string input, int cursor, Hashtable options, PowerShell powerShell) { var ctor = typeof (CommandCompletion).GetConstructor( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new [] {typeof (Collection<CompletionResult>), typeof (int), typeof (int), typeof (int)}, null); var completions = new Collection<CompletionResult>(); const int currentMatchIndex = -1; var replacementIndex = 0; var replacementLength = 0; switch (input) { case "$t": replacementIndex = 0; replacementLength = 2; completions.Add(new CompletionResult("$thing")); completions.Add(new CompletionResult("$this")); completions.Add(new CompletionResult("$true")); break; case "$tr": replacementIndex = 0; replacementLength = 3; completions.Add(new CompletionResult("$true")); break; case "psvar": replacementIndex = 0; replacementLength = 5; completions.Add(new CompletionResult("$pssomething")); break; case "ambig": replacementIndex = 0; replacementLength = 5; completions.Add(new CompletionResult("ambiguous1")); completions.Add(new CompletionResult("ambiguous2")); completions.Add(new CompletionResult("ambiguous3")); break; case "Get-Many": replacementIndex = 0; replacementLength = 8; for (int i = 0; i < 15; i++) { completions.Add(new CompletionResult("Get-Many" + i)); } break; case "Get-Tooltips": replacementIndex = 0; replacementLength = 12; completions.Add(new CompletionResult("something really long", "item1", CompletionResultType.Command, "useful description goes here")); break; case "Get-Directory": replacementIndex = 0; replacementLength = 13; completions.Add(new CompletionResult("abc", "abc", CompletionResultType.ProviderContainer, "abc")); completions.Add(new CompletionResult("'e f'", "'e f'", CompletionResultType.ProviderContainer, "'e f'")); completions.Add(new CompletionResult("a", "a", CompletionResultType.ProviderContainer, "a")); completions.Add(new CompletionResult("'a b" + Path.DirectorySeparatorChar + "'", "a b" + Path.DirectorySeparatorChar + "'", CompletionResultType.ProviderContainer, "a b" + Path.DirectorySeparatorChar + "'")); completions.Add(new CompletionResult("\"a b" + Path.DirectorySeparatorChar + "\"", "\"a b" + Path.DirectorySeparatorChar + "\"", CompletionResultType.ProviderContainer, "\"a b" + Path.DirectorySeparatorChar + "\"")); break; case "invalid result 1": replacementIndex = -1; replacementLength = 1; completions.Add(new CompletionResult("result")); break; case "invalid result 2": replacementIndex = 0; replacementLength = -1; completions.Add(new CompletionResult("result")); break; case "invalid result 3": replacementIndex = int.MaxValue; replacementLength = 1; completions.Add(new CompletionResult("result")); break; case "invalid result 4": replacementIndex = 0; replacementLength = int.MaxValue; completions.Add(new CompletionResult("result")); break; case "ls -H": replacementIndex = cursor; replacementLength = 0; completions.Add(new CompletionResult("idden")); break; case "none": break; } return (CommandCompletion)ctor.Invoke( new object[] {completions, currentMatchIndex, replacementIndex, replacementLength}); } } }
41.2
232
0.48754
[ "BSD-2-Clause" ]
ForNeVeR/PSReadLine
test/CompletionTest.cs
12,362
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Domain { /// <summary> /// House Data Structure. /// </summary> [Serializable] public class House : AopObject { /// <summary> /// 房屋所在区县编号 /// </summary> [XmlElement("area_code")] public string AreaCode { get; set; } /// <summary> /// 建成年份 /// </summary> [XmlElement("built_year")] public string BuiltYear { get; set; } /// <summary> /// 房屋产权人列表 /// </summary> [XmlArray("house_owners")] [XmlArrayItem("house_owner")] public List<HouseOwner> HouseOwners { get; set; } /// <summary> /// 不动产单元号(可能多个) /// </summary> [XmlArray("house_unit_codes")] [XmlArrayItem("string")] public List<string> HouseUnitCodes { get; set; } /// <summary> /// 房屋所在层数 /// </summary> [XmlElement("its_floor")] public string ItsFloor { get; set; } /// <summary> /// 土地证号 /// </summary> [XmlElement("land_cert_no")] public string LandCertNo { get; set; } /// <summary> /// 房屋坐落地址 /// </summary> [XmlElement("location")] public string Location { get; set; } /// <summary> /// 是否有抵押。enum (Y, N) /// </summary> [XmlElement("mortgaged")] public string Mortgaged { get; set; } /// <summary> /// 房产共有情况。 enum (INDIVIDUALLY-单独所有, SHARE_COOWNER-共同共有, SEVERAL_COOWNER-按份共有, OTHER_COOWNER-其他共有, UNKNOWN--) /// </summary> [XmlElement("owner_ship_status")] public string OwnerShipStatus { get; set; } /// <summary> /// 房屋建筑面积 /// </summary> [XmlElement("structure_area")] public string StructureArea { get; set; } /// <summary> /// 房屋建筑面积单位。 enum (SQUARE_METER-平方米, MU-亩, SQUARE_CENTIMETER-平方厘米, HECTARE-公顷) /// </summary> [XmlElement("structure_area_unit")] public string StructureAreaUnit { get; set; } /// <summary> /// 总层数 /// </summary> [XmlElement("total_floor")] public string TotalFloor { get; set; } } }
27.215909
118
0.500626
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/House.cs
2,599
C#
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace AnsuzNet.Utility.ConsoleCore.Abstractions { public interface IStartup { void Configure(IServiceCollection collection); } }
20.769231
54
0.774074
[ "MIT" ]
AnsuzPantognestous/ConsoleCore
ConsoleCore/Abstractions/IStartup.cs
272
C#
using System; using System.Collections.Generic; using System.Text; using Windows.Foundation; #if XAMARIN_IOS using View = UIKit.UIView; #elif XAMARIN_ANDROID using View = Android.Views.View; #else using View = Windows.UI.Xaml.UIElement; #endif namespace Windows.UI.Xaml.Controls.Primitives { public partial class FlyoutBase : DependencyObject { public event EventHandler Opened; public event EventHandler Closed; public event EventHandler Opening; public event TypedEventHandler<FlyoutBase, FlyoutBaseClosingEventArgs> Closing; private bool _isOpen = false; public FlyoutBase() { InitializeBinder(); } #region Placement /// <summary> /// Preferred placement of the flyout. /// </summary> /// <remarks> /// If there's not enough place, the following logic will be used: /// https://docs.microsoft.com/en-us/previous-versions/windows/apps/dn308515(v=win.10)#placing-a-flyout /// </remarks> public FlyoutPlacementMode Placement { get { return (FlyoutPlacementMode)GetValue(PlacementProperty); } set { SetValue(PlacementProperty, value); } } public static DependencyProperty PlacementProperty { get; } = DependencyProperty.Register( "Placement", typeof(FlyoutPlacementMode), typeof(FlyoutBase), new FrameworkPropertyMetadata(default(FlyoutPlacementMode)) ); #endregion public FrameworkElement Target { get; private set; } public void Hide() { Hide(canCancel: true); } internal void Hide(bool canCancel) { if (!_isOpen) { return; } if (canCancel) { var closing = new FlyoutBaseClosingEventArgs(); Closing?.Invoke(this, closing); if (closing.Cancel) { return; } } Close(); _isOpen = false; Closed?.Invoke(this, EventArgs.Empty); } internal protected virtual void Close(){} public void ShowAt(FrameworkElement placementTarget) { if (_isOpen) { if (placementTarget == Target) { return; } else { // Close at previous placement target before opening at new one (without raising Closing) Hide(canCancel: false); } } Target = placementTarget; Opening?.Invoke(this, EventArgs.Empty); Open(); _isOpen = true; Opened?.Invoke(this, EventArgs.Empty); } internal protected virtual void Open() { } protected virtual Control CreatePresenter() { return null; } } }
20.487179
105
0.687943
[ "Apache-2.0" ]
dansiegel/Uno
src/Uno.UI/UI/Xaml/Controls/Flyout/FlyoutBase.cs
2,399
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the marketplace-catalog-2018-09-17.normal.json service model. */ using Amazon.Runtime.Internal; namespace Amazon.MarketplaceCatalog.Internal { /// <summary> /// Service metadata for Amazon MarketplaceCatalog service /// </summary> public partial class AmazonMarketplaceCatalogMetadata : IServiceMetadata { /// <summary> /// Gets the value of the Service Id. /// </summary> public string ServiceId { get { return "Marketplace Catalog"; } } /// <summary> /// Gets the dictionary that gives mapping of renamed operations /// </summary> public System.Collections.Generic.IDictionary<string, string> OperationNameMapping { get { return new System.Collections.Generic.Dictionary<string, string>(0) { }; } } } }
29.363636
117
0.621672
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/MarketplaceCatalog/Generated/Internal/AmazonMarketplaceCatalogMetadata.cs
1,615
C#
using System.Collections.Generic; using System.Threading.Tasks; using QYQ.DataManagement.Extension.Customs.Dtos; using QYQ.DataManagement.IdentityServers.ApiResources.Dtos; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace QYQ.DataManagement.IdentityServers.ApiResources { public interface IApiResourceAppService : IApplicationService { Task<PagedResultDto<ApiResourceOutput>> GetListAsync(PagingApiRseourceListInput input); /// <summary> /// 获取所有api resource /// </summary> /// <returns></returns> Task<List<ApiResourceOutput>> GetApiResources(); /// <summary> /// 新增 ApiResource /// </summary> /// <returns></returns> Task CreateAsync(CreateApiResourceInput input); /// <summary> /// 删除 ApiResource /// </summary> /// <returns></returns> Task DeleteAsync(IdInput input); /// <summary> /// 更新 ApiResource /// </summary> /// <returns></returns> Task UpdateAsync(UpdateApiResourceInput input); } }
29.236842
95
0.639964
[ "MIT" ]
zhaoweijie1213/QYQDataManagement
aspnet-core/services/src/QYQ.DataManagement.Application.Contracts/IdentityServers/ApiResources/IApiResourceAppService.cs
1,131
C#
using System; namespace WebAPIs.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
23.864865
140
0.531144
[ "MIT" ]
CDOTAD/HospitalManageSystem
WebAPIs/WebAPIs/Areas/HelpPage/SampleGeneration/TextSample.cs
883
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace HikingPathFinder.App.Views { /// <summary> /// Page that shows the hamburger menu content /// </summary> public class MenuPage : ContentPage { /// <summary> /// List of menu items /// </summary> public ListView Menu { get; set; } /// <summary> /// Creates a new menu page /// </summary> public MenuPage() { this.Title = "Menu"; this.Icon = "icon.png"; this.BackgroundColor = Color.FromHex(Constants.AppBackgroundColorHex); this.Menu = new MenuListView(); var menuLabel = new ContentView { Padding = new Thickness(10, 36, 0, 5), Content = new Label { TextColor = Color.FromHex(Constants.AppForegroundColorHex), Text = "Menu", } }; var layout = new StackLayout { Spacing = 0, VerticalOptions = LayoutOptions.FillAndExpand }; layout.Children.Add(menuLabel); layout.Children.Add(this.Menu); this.Content = layout; } } }
25.314815
82
0.513533
[ "BSD-2-Clause" ]
vividos/HikingPathFinder
src/Frontend/App/Core/Views/MenuPage.cs
1,369
C#
using System.Collections; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace PlayTests { public class ExamplePlayTest { [UnityTest] public IEnumerator ExampleTest() { Time.timeScale = 20f; GameObject gameObject = new GameObject(); gameObject.transform.position = Vector3.zero; var rb = gameObject.AddComponent<Rigidbody>(); rb.useGravity = true; float time = 0; while (time < 5) { time += Time.fixedDeltaTime; yield return new WaitForFixedUpdate(); } Assert.IsTrue(gameObject.transform.position.y < -1f); Time.timeScale = 1f; } } }
22.542857
65
0.548796
[ "MIT" ]
AVR-Team-5/a-particular-project
Game/Assets/Source/Tests/PlayTests/ExamplePlayTest.cs
789
C#
using System; using System.Collections.Generic; using CppSharp.AST; namespace CppSharp.Generators { public abstract class CodeGenerator : BlockGenerator, IDeclVisitor<bool> { public BindingContext Context { get; } public DriverOptions Options => Context.Options; public List<TranslationUnit> TranslationUnits { get; } public TranslationUnit TranslationUnit => TranslationUnits[0]; public abstract string FileExtension { get; } protected CodeGenerator(BindingContext context, TranslationUnit unit) : this(context, new List<TranslationUnit> { unit }) { } protected CodeGenerator(BindingContext context, IEnumerable<TranslationUnit> units) { Context = context; TranslationUnits = new List<TranslationUnit>(units); } public abstract void Process(); public override string Generate() { if (Options.IsCSharpGenerator && Options.CompileCode) return base.GenerateUnformatted(); return base.Generate(); } public virtual void GenerateFilePreamble() { PushBlock(BlockKind.Header); WriteLine("//----------------------------------------------------------------------------"); WriteLine("// <auto-generated>"); WriteLine("// This is autogenerated code by CppSharp."); WriteLine("// Do not edit this file or all your changes will be lost after re-generation."); WriteLine("// </auto-generated>"); WriteLine("//----------------------------------------------------------------------------"); PopBlock(); } #region Visitor methods public virtual bool VisitDeclaration(Declaration decl) { throw new NotImplementedException(); } public virtual bool VisitTranslationUnit(TranslationUnit unit) { return VisitDeclContext(unit); } public virtual bool VisitDeclContext(DeclarationContext context) { foreach (var decl in context.Declarations) if (!decl.IsGenerated) decl.Visit(this); return true; } public virtual bool VisitClassDecl(Class @class) { return VisitDeclContext(@class); } public virtual bool VisitFieldDecl(Field field) { throw new NotImplementedException(); } public virtual bool VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public virtual bool VisitMethodDecl(Method method) { throw new NotImplementedException(); } public virtual bool VisitParameterDecl(Parameter parameter) { throw new NotImplementedException(); } public virtual bool VisitTypedefNameDecl(TypedefNameDecl typedef) { throw new NotImplementedException(); } public virtual bool VisitTypedefDecl(TypedefDecl typedef) { return VisitTypedefNameDecl(typedef); } public virtual bool VisitTypeAliasDecl(TypeAlias typeAlias) { return VisitTypedefNameDecl(typeAlias); } public virtual bool VisitEnumDecl(Enumeration @enum) { throw new NotImplementedException(); } public virtual bool VisitEnumItemDecl(Enumeration.Item item) { throw new NotImplementedException(); } public virtual bool VisitVariableDecl(Variable variable) { throw new NotImplementedException(); } public virtual bool VisitMacroDefinition(MacroDefinition macro) { throw new NotImplementedException(); } public virtual bool VisitNamespace(Namespace @namespace) { return VisitDeclContext(@namespace); } public virtual bool VisitEvent(Event @event) { throw new NotImplementedException(); } public virtual bool VisitProperty(Property property) { throw new NotImplementedException(); } public virtual bool VisitFriend(Friend friend) { throw new NotImplementedException(); } public virtual bool VisitClassTemplateDecl(ClassTemplate template) { throw new NotImplementedException(); } public virtual bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecialization specialization) { return VisitClassDecl(specialization); } public virtual bool VisitFunctionTemplateDecl(FunctionTemplate template) { throw new NotImplementedException(); } public virtual bool VisitFunctionTemplateSpecializationDecl(FunctionTemplateSpecialization specialization) { throw new NotImplementedException(); } public virtual bool VisitVarTemplateDecl(VarTemplate template) { throw new NotImplementedException(); } public virtual bool VisitVarTemplateSpecializationDecl(VarTemplateSpecialization template) { throw new NotImplementedException(); } public virtual bool VisitTemplateTemplateParameterDecl(TemplateTemplateParameter templateTemplateParameter) { throw new NotImplementedException(); } public virtual bool VisitTemplateParameterDecl(TypeTemplateParameter templateParameter) { throw new NotImplementedException(); } public virtual bool VisitNonTypeTemplateParameterDecl(NonTypeTemplateParameter nonTypeTemplateParameter) { throw new NotImplementedException(); } public virtual bool VisitTypeAliasTemplateDecl(TypeAliasTemplate typeAliasTemplate) { throw new NotImplementedException(); } #endregion } }
29.650485
115
0.603143
[ "MIT" ]
JackWangCUMT/CppSharp
src/Generator/Generators/CodeGenerator.cs
6,108
C#
using Aspect.Abstractions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Aspect.Formatting { public static class ServiceExtensions { public static IServiceCollection AddFormatters(this IServiceCollection services) { services.TryAddSingleton<IFormatterFactory, FormatterFactory>(); services.TryAddEnumerable(ServiceDescriptor.Scoped<IFormatter, JsonFormatter>()); services.TryAddEnumerable(ServiceDescriptor.Scoped<IFormatter, YamlFormatter>()); return services; } } }
34.722222
93
0.7376
[ "MIT" ]
Im5tu/aspect
src/Aspect.Formatting/ServiceExtensions.cs
627
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The enum KerberosSignOnMappingAttributeType. /// </summary> [JsonConverter(typeof(EnumConverter))] public enum KerberosSignOnMappingAttributeType { /// <summary> /// User Principal Name /// </summary> UserPrincipalName = 0, /// <summary> /// On Premises User Principal Name /// </summary> OnPremisesUserPrincipalName = 1, /// <summary> /// User Principal Username /// </summary> UserPrincipalUsername = 2, /// <summary> /// On Premises User Principal Username /// </summary> OnPremisesUserPrincipalUsername = 3, /// <summary> /// On Premises SAMAccount Name /// </summary> OnPremisesSAMAccountName = 4, } }
27.26
153
0.527513
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/KerberosSignOnMappingAttributeType.cs
1,363
C#
using System; using System.Threading; namespace EasyNetQ.Scheduling { public static class SchedulerExtensions { /// <summary> /// Schedule a message to be published at some time in the future. /// This required the EasyNetQ.Scheduler service to be running. /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="scheduler">The scheduler instance</param> /// <param name="delay">The delay for message to publish in future</param> /// <param name="message">The message to response with</param> /// <param name="topic">The topic string</param> /// <param name="cancellationToken">The cancellation token</param> public static void FuturePublish<T>( this IScheduler scheduler, T message, TimeSpan delay, string topic = null, CancellationToken cancellationToken = default ) { Preconditions.CheckNotNull(scheduler, "scheduler"); scheduler.FuturePublishAsync(message, delay, topic, cancellationToken) .GetAwaiter() .GetResult(); } } }
36.757576
82
0.596867
[ "MIT" ]
Eu-JinOoi/EasyNetQ
Source/EasyNetQ/Scheduling/SchedulerExtensions.cs
1,215
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Collections.Generic; using System.Linq; using Microsoft.PythonTools.Analysis.Documentation; namespace Microsoft.Python.LanguageServer.Implementation { public sealed partial class Server { private RestTextConverter _restTextConverter = new RestTextConverter(); private MarkupContent GetMarkupContent(string plainTextContent, IEnumerable<string> preferences) { if(string.IsNullOrEmpty(plainTextContent)) { return string.Empty; } switch (SelectBestMarkup(preferences, MarkupKind.Markdown, MarkupKind.PlainText)) { case MarkupKind.Markdown: return new MarkupContent { kind = MarkupKind.Markdown, value = _restTextConverter.ToMarkdown(plainTextContent) }; } return plainTextContent; } private string SelectBestMarkup(IEnumerable<string> requested, params string[] supported) { if (requested == null) { return supported.First(); } foreach (var k in requested) { if (supported.Contains(k)) { return k; } } return MarkupKind.PlainText; } } }
38.980769
106
0.648249
[ "Apache-2.0" ]
DalavanCloud/python-language-server
src/LanguageServer/Impl/Implementation/Server.PrivateHelpers.cs
2,029
C#
using Lucene.Net.Analysis.Util; using Lucene.Net.Support; using System.Collections.Generic; using System.Linq; namespace Lucene.Net.Analysis.Core { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Factory class for <see cref="TypeTokenFilter"/>. /// <code> /// &lt;fieldType name="chars" class="solr.TextField" positionIncrementGap="100"&gt; /// &lt;analyzer&gt; /// &lt;tokenizer class="solr.StandardTokenizerFactory"/&gt; /// &lt;filter class="solr.TypeTokenFilterFactory" types="stoptypes.txt" /// useWhitelist="false"/&gt; /// &lt;/analyzer&gt; /// &lt;/fieldType&gt; /// </code> /// </summary> public class TypeTokenFilterFactory : TokenFilterFactory, IResourceLoaderAware { private readonly bool useWhitelist; private readonly bool enablePositionIncrements; private readonly string stopTypesFiles; private HashSet<string> stopTypes; /// <summary> /// Creates a new <see cref="TypeTokenFilterFactory"/> </summary> public TypeTokenFilterFactory(IDictionary<string, string> args) : base(args) { stopTypesFiles = Require(args, "types"); enablePositionIncrements = GetBoolean(args, "enablePositionIncrements", true); useWhitelist = GetBoolean(args, "useWhitelist", false); if (args.Count > 0) { throw new System.ArgumentException("Unknown parameters: " + args); } } public virtual void Inform(IResourceLoader loader) { IList<string> files = SplitFileNames(stopTypesFiles); if (files.Count() > 0) { stopTypes = new HashSet<string>(); foreach (string file in files) { IList<string> typesLines = GetLines(loader, file.Trim()); stopTypes.UnionWith(typesLines); } } } public virtual bool EnablePositionIncrements { get { return enablePositionIncrements; } } public virtual ICollection<string> StopTypes { get { return stopTypes; } } public override TokenStream Create(TokenStream input) { #pragma warning disable 612, 618 TokenStream filter = new TypeTokenFilter(m_luceneMatchVersion, enablePositionIncrements, input, stopTypes, useWhitelist); #pragma warning restore 612, 618 return filter; } } }
37.177083
134
0.589801
[ "Apache-2.0" ]
NikolayXHD/Lucene.Net.Contrib
Lucene.Net.Analysis.Common/Analysis/Core/TypeTokenFilterFactory.cs
3,571
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EvilFlowerMeleeState : IEvilFlowerState { private EvilFlower enemy; private float attackCoolDown = 2; private bool preAttacked; bool preparated = false; public void Enter(EvilFlower enemy) { this.enemy = enemy; preAttacked = false; } public void Execute() { if (!preAttacked && !enemy.isAttacked) { preAttacked = true; enemy.armature.animation.FadeIn("pre_atk", -1, 1); } if (enemy.armature.animation.lastAnimationName == ("pre_atk") && enemy.armature.animation.isCompleted) { enemy.armature.animation.FadeIn("atk", -1, 1); enemy.AttackCollider.enabled = true; SoundManager.PlaySound("bite"); } if (enemy.armature.animation.lastAnimationName == ("atk") && enemy.armature.animation.isCompleted) { enemy.AttackCollider.enabled = false; enemy.isAttacked = true; enemy.ChangeState(new EvilFlowerIdleState()); } } public void Exit() {} public void OnTriggerEnter2D(Collider2D other) {} }
26.276596
110
0.616194
[ "Apache-2.0" ]
MadGriffonGames/BiltyBlop
Assets/Scripts/Enemies&States/EvilFlower/EvilFlowerMeleeState.cs
1,237
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BIModel.Access { /// <summary> /// 接口配置表 /// </summary> public class InterfaceList { public string InterfaceName { get; set; } public string Comment { get; set; } public int Active { get; set; } } }
17.952381
49
0.628647
[ "MIT" ]
ysjr-2002/BatteryTest
BIModel/Access/InterfaceList.cs
389
C#
/* * Wirekite for Windows * Copyright (c) 2018 Manuel Bleichenbacher * Licensed under MIT License * https://opensource.org/licenses/MIT * * This code is based on code in the Arduino RF24 library. * Portions Copyright (c) 2011 J. Coliz <maniacbug@ymail.com> */ using Codecrete.Wirekite.Device; using System; using System.Diagnostics; using System.Threading; namespace Codecrete.Wirekite.Test.UI { /// <summary> /// RF transceiver with NRF24L01(+) chip /// </summary> public class RF24Radio { public enum RFDataRate { _1mbps, _2mbps, _250kbps } public enum RFOutputPower { Min = 0, Low = 1, High = 2, Max = 3 } public delegate void PacketReadCallback(RF24Radio radio, int pipe, byte[] packet); private const byte SetContrast = 0x81; private const byte OutputRAMToDisplay = 0xA4; private const byte SetDisplayOn = 0xA5; private const byte SetNormalDisplay = 0xA6; private const byte SetInvertedDisplay = 0xA7; private const byte DisplayOff = 0xAE; private const byte DisplayOn = 0xAF; private const byte SetDisplayOffset = 0xD3; private const byte SetComPin = 0xDA; private const byte SetVCOMH = 0xDB; private const byte SetClockDivideRatio = 0xD5; private const byte SetPrecharge = 0xD9; private const byte SetMultiplexRatio = 0xA8; private const byte SetColumnAddressLow = 0x00; private const byte SetColumnAddressHigh = 0x10; private const byte SetPageAddress = 0xb0; private const byte SetStartLineBase = 0x40; private const byte PageAddressingMode = 0x20; private const byte ScanDirectionIncreasing = 0xC0; private const byte ScanDirectionDecreasing = 0xC8; private const byte SegmentRampBase = 0xA0; private const byte ChargePump = 0x8D; private const byte DeactivateScroll = 0x2E; private WirekiteDevice device; private int spiPort; private int cePort; private int csnPort; private int irqPort = WirekiteDevice.InvalidPortId; // shadow registers private byte regConfig = RF24.CONFIG.EN_CRC; private byte regSetupRetr = 3; private byte regRFSetup = RF24.RF_SETUP.RF_DR_HIGH | (3 << 1); private byte regSetupAW = 3; private byte regRFCh = 2; private byte regEnAA = 0x3f; private byte regEnRXAddr = 3; private byte regFeature = 0; private bool isPlusModel = false; private bool dynamicPayloadEnabled = true; private int payloadSize = 32; private UInt64 pipe0ReadingAddress = 0; private object irqLock = new object(); private int txQueueCount = 0; private object txQueueLock = new object(); private PacketReadCallback packetReadCallback; private int expectedPayloadSize = 32; public RF24Radio(WirekiteDevice device, int spiPort, int cePin, int csnPin) { this.device = device; this.spiPort = spiPort; cePort = device.ConfigureDigitalOutputPin(cePin, DigitalOutputPinAttributes.Default, false); csnPort = device.ConfigureDigitalOutputPin(csnPin, DigitalOutputPinAttributes.Default, true); } ~RF24Radio() { device.ReleaseDigitalPin(cePort); device.ReleaseDigitalPin(csnPort); if (irqPort != WirekiteDevice.InvalidPortId) device.ReleaseDigitalPin(irqPort); } public void InitModule() { // Reset CONFIG and enable 16-bit CRC. regConfig = RF24.CONFIG.EN_CRC | RF24.CONFIG.CRCO; WriteRegister(regConfig, Register.CONFIG); SetRetransmissions(15, 5); // check for connected module and if this is a p nRF24l01 variant DataRate = RFDataRate._250kbps; isPlusModel = GetDataRate(ReadRegister(Register.RF_SETUP)) == RFDataRate._250kbps; // Default speed DataRate = RFDataRate._1mbps; // Disable dynamic payloads, to match dynamic_payloads_enabled setting - Reset value is 0 ToggleFeatures(); regFeature = 0; WriteRegister(regFeature, Register.FEATURE); WriteRegister(0, Register.DYNPD); dynamicPayloadEnabled = false; // Reset current status // Notice reset and flush is the last thing we do WriteRegister(RF24.STATUS.RX_DR | RF24.STATUS.TX_DS | RF24.STATUS.MAX_RT, Register.STATUS); // Set up default configuration. Callers can always change it later. // This channel should be universally safe and not bleed over into adjacent // spectrum. RFChannel = 76; // Flush buffers DiscardReceivedPackets(); DiscardQueuedTransmitPackets(); PowerUp(); // Power up by default when begin() is called // Enable PTX, do not write CE high so radio will remain in standby I mode // (130us max to transition to RX or TX instead of 1500us from powerUp) // PTX should use only 22uA of power regConfig = (byte)(regConfig & ~RF24.CONFIG.PRIM_RX); WriteRegister(regConfig, Register.CONFIG); } #region Configuration public void ConfigureIRQPin(int irqPin, int payloadSize, PacketReadCallback callback) { packetReadCallback = callback; expectedPayloadSize = payloadSize; irqPort = device.ConfigureDigitalInputPin(irqPin, DigitalInputPinAttributes.TriggerFalling, IrqPinTriggered); } public int AddressWidth { get { return regSetupAW + 2; } set { regSetupAW = (byte)(Clamp(value, 3, 5) - 2); WriteRegister(regSetupAW, Register.SETUP_AW); } } public int PayloadSize { get { return payloadSize; } set { payloadSize = Clamp(value, 1, 32); } } public void GetRetransmissions(out int count, out int delay) { count = regSetupRetr & 0x0f; delay = ((regSetupRetr >> 4) - 1) *250; } public void SetRetransmissions(int count, int delay) { int delayCode = Clamp((delay + 124) / 250 - 1, 0, 15); int retransmissions = Clamp(count, 0, 15); regSetupRetr = (byte)((delayCode << 4) | retransmissions); WriteRegister(regSetupRetr, Register.SETUP_RETR); } public RFDataRate DataRate { get { return GetDataRate(regRFSetup); } set { regRFSetup = (byte)(regRFSetup & ~(RF24.RF_SETUP.RF_DR_LOW | RF24.RF_SETUP.RF_DR_HIGH)); regRFSetup = (byte)(value == RFDataRate._250kbps ? RF24.RF_SETUP.RF_DR_LOW : (value == RFDataRate._2mbps ? RF24.RF_SETUP.RF_DR_HIGH : 0)); WriteRegister(regRFSetup, Register.RF_SETUP); } } private RFDataRate GetDataRate(byte regValue) { RFDataRate rate; if ((regValue & RF24.RF_SETUP.RF_DR_LOW) != 0) { rate = RFDataRate._250kbps; } else if ((regValue & RF24.RF_SETUP.RF_DR_HIGH) != 0) { rate = RFDataRate._2mbps; } else { rate = RFDataRate._1mbps; } return rate; } public RFOutputPower OutputPower { get { int value = (regRFSetup >> 1) & 0x03; return (RFOutputPower)value; } set { regRFSetup = (byte)(regRFSetup & ~RF24.RF_SETUP.RF_PWR_MASK); regRFSetup |= (byte)((int)value << 1); WriteRegister(regRFSetup, Register.RF_SETUP); } } public byte StatusRegister { get { byte[] data = device.RequestOnSPIPort(spiPort, 1, csnPort, RF24.CMD.NOP); return data[0]; } } public bool IsConnected { get { byte value = ReadRegister(Register.SETUP_AW); return value >= 1 && value <= 3; } } public int RFChannel { get { return regRFCh; } set { if (value >= 0 && value <= 125) { regRFCh = (byte)value; WriteRegister(regRFCh, Register.RF_CH); } } } public bool AutoAck { get { return regEnAA == 0x3f; } set { regEnAA = value ? (byte)0x3f : (byte)0; WriteRegister(regEnAA, Register.EN_AA); } } public bool IsPlusModel { get { return isPlusModel; } } public void PowerDown() { if ((regConfig & RF24.CONFIG.PWR_UP) == 0) return; SetCE(false); regConfig = (byte)(regConfig & ~RF24.CONFIG.PWR_UP); WriteRegister(regConfig, Register.CONFIG); } public void PowerUp() { if ((regConfig & RF24.CONFIG.PWR_UP) != 0) return; regConfig |= RF24.CONFIG.PWR_UP; WriteRegister(regConfig, Register.CONFIG); Thread.Sleep(5); } #endregion #region Receiving public void OpenReceivePipe(int pipe, UInt64 address) { if (pipe < 0 || pipe > 6) return; if (pipe == 0) pipe0ReadingAddress = address; Register addrRegister = RegisterOffset(Register.RX_ADDR_P0, pipe); if (pipe < 2) { WriteAddress(address, addrRegister); } else { WriteRegister((byte)(address & 0xff), addrRegister); } Register payloadRegister = RegisterOffset(Register.RX_PW_P0, pipe); WriteRegister((byte)payloadSize, payloadRegister); regEnRXAddr |= (byte)(1 << pipe); WriteRegister(regEnRXAddr, Register.EN_RXADDR); } public void CloseReceivePipe(int pipe) { regEnRXAddr = (byte)(regEnRXAddr & ~(1 << pipe)); WriteRegister(regEnRXAddr, Register.EN_RXADDR); } public bool IsPacketAvailable { get { byte status = ReadRegister(Register.FIFO_STATUS); return (status & RF24.FIFO_STATUS.RX_EMPTY) == 0; } } public byte[] FetchPacket(int packetLength) { byte[] data = ReadQueuedPacket(packetLength); WriteRegister(RF24.STATUS.RX_DR, Register.STATUS); return data; } private byte[] ReadQueuedPacket(int numBytes) { int plSize = Math.Min(numBytes, payloadSize); int padSize = dynamicPayloadEnabled ? 0 : payloadSize - plSize; byte[] txData = new byte[plSize + padSize + 1]; txData[0] = RF24.CMD.R_RX_PAYLOAD; for (int i = 1; i < txData.Length; i++) txData[i] = RF24.CMD.NOP; byte[] rxData = TransmitAndRequest(txData); byte[] result = new byte[plSize]; Array.Copy(rxData, 1, result, 0, plSize); return result; } public void DiscardReceivedPackets() { WriteCommand(RF24.CMD.FLUSH_RX); } public void StartListening() { PowerUp(); lock (txQueueLock) { while (txQueueCount > 0) Monitor.Wait(txQueueLock); } regConfig |= RF24.CONFIG.PRIM_RX; WriteRegister(regConfig, Register.CONFIG); SetCE(true); if ((pipe0ReadingAddress & 0xff) != 0) WriteAddress(pipe0ReadingAddress, Register.RX_ADDR_P0); else CloseReceivePipe(pipe: 0); if ((regFeature & RF24.FEATURE.EN_ACK_PAY) != 0) DiscardQueuedTransmitPackets(); } public void StopListening() { SetCE(false); if ((regFeature & RF24.FEATURE.EN_ACK_PAY) != 0) DiscardQueuedTransmitPackets(); regConfig = (byte)(regConfig & ~RF24.CONFIG.PRIM_RX); WriteRegister(regConfig, Register.CONFIG); regEnRXAddr |= 1; WriteRegister(regEnRXAddr, Register.EN_RXADDR); } #endregion #region Transmission public void OpenTransmitPipe(UInt64 address) { WriteAddress(address, Register.RX_ADDR_P0); WriteAddress(address, Register.TX_ADDR); WriteRegister((byte)payloadSize, Register.RX_PW_P0); } public void Transmit(byte[] packet, bool multicast = false) { lock (txQueueLock) { while (txQueueCount == 3) Monitor.Wait(txQueueLock); if (txQueueCount == 0) SetCE(true); QueuePacket(packet, multicast); txQueueCount += 1; } } private void QueuePacket(byte[] packet, bool multicast) { int plSize = Math.Min(packet.Length, payloadSize); int padSize = dynamicPayloadEnabled ? 0 : payloadSize - plSize; byte[] data = new byte[plSize + padSize + 1]; data[0] = multicast ? RF24.CMD.W_TX_PAYLOAD_NOACK : RF24.CMD.W_TX_PAYLOAD; Array.Copy(packet, 0, data, 1, plSize); for (int i = plSize + 1; i < payloadSize - 1; i++) data[i] = 0; Transmit(data); } public void DiscardQueuedTransmitPackets() { WriteCommand(RF24.CMD.FLUSH_TX); } #endregion #region Low Level private void IrqPinTriggered(int port, bool value) { lock (irqLock) { while (true) { byte status = ReadRegister(Register.STATUS); if ((status & RF24.STATUS.RX_DR) != 0) { while (true) { // read packet byte[] data; if (expectedPayloadSize > 0) data = FetchPacket(expectedPayloadSize); else data = null; // callback int pipe = (status >> 1) & 0x07; packetReadCallback(this, pipe, data); // clear RX_DR WriteRegister(RF24.STATUS.TX_DS, Register.STATUS); byte fifoStatus = ReadRegister(Register.FIFO_STATUS); if ((fifoStatus & RF24.FIFO_STATUS.RX_EMPTY) != 0) break; } } else if ((status & RF24.STATUS.TX_DS) != 0) { WriteRegister(RF24.STATUS.TX_DS, Register.STATUS); lock (txQueueLock) { txQueueCount -= 1; if (txQueueCount == 0) SetCE(false); Monitor.Pulse(txQueueLock); } } else if ((status & RF24.STATUS.MAX_RT) != 0) { DiscardQueuedTransmitPackets(); WriteRegister(RF24.STATUS.MAX_RT, Register.STATUS); lock (txQueueLock) { Debug.WriteLine("Maximum number of TX retransmissions reached, flushing {0} packets", txQueueCount); txQueueCount = 0; SetCE(false); Monitor.Pulse(txQueueCount); } } else { break; } } } } private byte[] AddressToByteArray(UInt64 address) { // convert to byte array, LSB first byte[] bytes = new byte[AddressWidth]; for (int i = 0; i < AddressWidth; i++) { bytes[i] = (byte)(address & 0xff); address >>= 8; } return bytes; } private void ToggleFeatures() { byte[] data = { 0x50, 0x73 }; Transmit(data); } private void WriteRegister(byte value, Register register) { byte[] data = { WriteCode(register), value }; Transmit(data); } private void WriteAddress(UInt64 address, Register register) { byte[] addressBytes = AddressToByteArray(address); byte[] data = new byte[addressBytes.Length + 1]; data[0] = WriteCode(register); Array.Copy(addressBytes, 0, data, 1, addressBytes.Length); Transmit(data); } private byte WriteCommand(byte command) { byte[] txData = { command }; byte[] rxData = TransmitAndRequest(txData); return rxData[0]; } private byte ReadRegister(Register register) { byte[] txData = { ReadCode(register), RF24.CMD.NOP }; byte[] rxData = TransmitAndRequest(txData); return rxData[1]; } private byte[] ReadAddress(Register register, int length) { byte[] txData = new byte[length + 1]; txData[0] = ReadCode(register); for (int i = 1; i < length + 1; i++) txData[i] = RF24.CMD.NOP; byte[] rxData = TransmitAndRequest(txData); byte[] result = new byte[length]; Array.Copy(rxData, 1, result, 0, length); return result; } private byte WriteCode(Register register) { return (byte)(RF24.CMD.W_REGISTER | (int)register); } private byte ReadCode(Register register) { return (byte)(RF24.CMD.R_REGISTER | (int)register); } private void Transmit(byte[] txData) { device.TransmitOnSPIPort(spiPort, txData, csnPort); } private byte[] TransmitAndRequest(byte[] txData) { return device.TransmitAndRequestOnSPIPort(spiPort, txData, csnPort); } private void SetCE(bool high) { device.WriteDigitalPinSynchronizedWithSPI(cePort, high, spiPort); } #endregion #region Debugging public void DebugRegisters() { // status DebugStatus(StatusRegister); // addresses DebugAddressRegister(Register.RX_ADDR_P0, AddressWidth); DebugAddressRegister(Register.RX_ADDR_P1, AddressWidth); DebugByteRegisters(Register.RX_ADDR_P2, 4, "RX_ADDR_P2..5"); DebugAddressRegister(Register.TX_ADDR, AddressWidth); DebugByteRegisters(Register.RX_PW_P0, 6, "RX_PW_P0..5"); DebugByteRegister(Register.EN_AA); DebugByteRegister(Register.EN_RXADDR); DebugByteRegister(Register.RF_CH); DebugByteRegister(Register.RF_SETUP); DebugByteRegister(Register.SETUP_AW); DebugByteRegister(Register.CONFIG); DebugByteRegister(Register.DYNPD); DebugByteRegister(Register.FEATURE); } private void DebugStatus(byte status) { Debug.WriteLine("STATUS: RX_DR = {0}, TX_DS = {1}, MAX_RT = {2}, RX_P_NO = {3}, RX_FULL = {4}", (status & RF24.STATUS.RX_DR) == 0 ? 0 : 1, (status & RF24.STATUS.TX_DS) == 0 ? 0 : 1, (status & RF24.STATUS.MAX_RT) == 0 ? 0 : 1, (status & 0x0e) >> 1, (status & RF24.STATUS.TX_FULL) == 0 ? 0 : 1); } private void DebugByteRegister(Register register) { string valueStr = ReadRegister(register).ToString("X2"); Debug.WriteLine("{0}: {1}", register.ToString(), valueStr); } private void DebugByteRegisters(Register register, int count, string label) { string dataStr = ""; for (int i = 0; i < count; i++) { byte value = ReadRegister(RegisterOffset(register, i)); dataStr += " " + value.ToString("X2"); } Debug.WriteLine("{0}: {1}", label, dataStr); } private void DebugAddressRegister(Register register, int addressLength) { byte[] address = ReadAddress(register, addressLength); string addressStr = ""; for (int i = 0; i < addressLength; i++) { addressStr += address[addressLength - i - 1].ToString("X2"); } Debug.WriteLine("{0}: {1}", register.ToString(), addressStr); } private void DebugAddressRegisters(Register register, int length = 1) { string dataStr = ""; for (int i = 0; i < length; i++) { byte value = ReadRegister(RegisterOffset(register, i)); dataStr += " " + value.ToString("X2"); } Debug.WriteLine("{0}:{1}", register.ToString(), dataStr); } #endregion private static int Clamp(int value, int minValue, int maxValue) { if (value < minValue) return minValue; if (value > maxValue) return maxValue; return value; } private static Register RegisterOffset(Register register, int offset) { return (Register)((int)register + offset); } internal enum Register { CONFIG = 0x00, EN_AA = 0x01, EN_RXADDR = 0x02, SETUP_AW = 0x03, SETUP_RETR = 0x04, RF_CH = 0x05, RF_SETUP = 0x06, STATUS = 0x07, OBSERVE_TX = 0x08, RPD = 0x09, RX_ADDR_P0 = 0x0A, RX_ADDR_P1 = 0x0B, RX_ADDR_P2 = 0x0C, RX_ADDR_P3 = 0x0D, RX_ADDR_P4 = 0x0E, RX_ADDR_P5 = 0x0F, TX_ADDR = 0x10, RX_PW_P0 = 0x11, RX_PW_P1 = 0x12, RX_PW_P2 = 0x13, RX_PW_P3 = 0x14, RX_PW_P4 = 0x15, RX_PW_P5 = 0x16, FIFO_STATUS = 0x17, DYNPD = 0x1C, FEATURE = 0x1D } internal class RF24 { internal class CONFIG { internal const byte MASK_RX_DR = 0x40; internal const byte MASK_TX_DS = 0x20; internal const byte MASK_MAX_RT = 0x10; internal const byte EN_CRC = 0x08; internal const byte CRCO = 0x04; internal const byte PWR_UP = 0x02; internal const byte PRIM_RX = 0x01; } internal class RF_SETUP { internal const byte CONT_WAVE = 0x80; internal const byte RF_DR_LOW = 0x20; internal const byte PLL_LOCK = 0x10; internal const byte RF_DR_HIGH = 0x08; internal const byte RF_PWR_MASK = 0x06; } internal class STATUS { internal const byte RX_DR = 0x40; internal const byte TX_DS = 0x20; internal const byte MAX_RT = 0x10; internal const byte TX_FULL = 0x01; } internal class FEATURE { internal const byte EN_DPL = 0x04; internal const byte EN_ACK_PAY = 0x02; internal const byte EN_DYN_ACK = 0x01; } internal class FIFO_STATUS { internal const byte RX_REUSE = 0x40; internal const byte TX_FULL = 0x20; internal const byte TX_EMPTY = 0x10; internal const byte RX_FULL = 0x02; internal const byte RX_EMPTY = 0x01; } internal class CMD { internal const byte R_REGISTER = 0x00; internal const byte W_REGISTER = 0x20; internal const byte R_RX_PAYLOAD = 0x61; internal const byte W_TX_PAYLOAD = 0xA0; internal const byte FLUSH_TX = 0xE1; internal const byte FLUSH_RX = 0xE2; internal const byte REUSE_TX_PL = 0xE3; internal const byte R_RX_PL_WID = 0x60; internal const byte W_ACK_PAYLOAD = 0xA8; internal const byte W_TX_PAYLOAD_NOACK = 0xB0; internal const byte NOP = 0xFF; } } } }
31.412048
154
0.508898
[ "MIT" ]
manuelbl/WirekiteWin
WirekiteWinTest/RF24Radio.cs
26,074
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions; /// <summary>Returns a database.</summary> /// <remarks> /// [OpenAPI] Databases_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/Clusters/{clusterName}/Databases/{databaseName}" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzKustoDatabase_GetViaIdentity")] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase))] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Description(@"Returns a database.")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Generated] public partial class GetAzKustoDatabase_GetViaIdentity : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Kusto Client => Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Backing field for <see cref="InputObject" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity _inputObject; /// <summary>Identity Parameter</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Path)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary> /// Intializes a new instance of the <see cref="GetAzKustoDatabase_GetViaIdentity" /> cmdlet class. /// </summary> public GetAzKustoDatabase_GetViaIdentity() { } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Information: { var data = messageData(); WriteInformation(data, new[] { data.Message }); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token); } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } if (InputObject?.Id != null) { await this.Client.DatabasesGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); } else { // try to call with PATH parameters from Input Object if (null == InputObject.ResourceGroupName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ClusterName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.DatabaseName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DatabaseName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.SubscriptionId) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } await this.Client.DatabasesGet(InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, InputObject.DatabaseName ?? null, InputObject.SubscriptionId ?? null, onOk, onDefault, this, Pipeline); } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudError" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IDatabase WriteObject((await response)); } } } }
74.034121
451
0.660297
[ "MIT" ]
Click4PV/azure-powershell
src/Kusto/generated/cmdlets/GetAzKustoDatabase_GetViaIdentity.cs
27,827
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MinionRelayPointBuilder : MonoBehaviour { [SerializeField] public bool blueTeam; [SerializeField] int laneNum; //Top:0, Mid:1, Bot:2 [SerializeField] int index; public MinionRelayPointInfo GetInfo() { return new MinionRelayPointInfo() { x = transform.position.x, y = transform.position.z, blueTeam = blueTeam, laneNum = laneNum, index = index }; } }
24.043478
55
0.622061
[ "MIT" ]
LaudateCorpus1/MOBA_CSharp_Unity
Map_Editor/MOBA_CSharp_Map_Editor/Assets/Scripts/Builder/MinionRelayPointBuilder.cs
555
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace StarfallTactics.StarfallTacticsServers.Database { public class SkinColorEntry { [JsonPropertyName("id")] public int Id { get; set; } = 0; [JsonPropertyName("name")] public string Name { get; set; } = ""; } }
22.052632
57
0.677804
[ "MIT" ]
MenY-dev/StarfallTacticsLauncher
StarfallTacticsServers/Database/SkinColorEntry.cs
421
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; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Direct3D11 { [Guid("b2daad8b-03d4-4dbf-95eb-32ab4b63d0ab")] [NativeName("Name", "ID3DUserDefinedAnnotation")] public unsafe partial struct ID3DUserDefinedAnnotation { public static readonly Guid Guid = new("b2daad8b-03d4-4dbf-95eb-32ab4b63d0ab"); public static implicit operator Silk.NET.Core.Native.IUnknown(ID3DUserDefinedAnnotation val) => Unsafe.As<ID3DUserDefinedAnnotation, Silk.NET.Core.Native.IUnknown>(ref val); public ID3DUserDefinedAnnotation ( void** lpVtbl = null ) : this() { if (lpVtbl is not null) { LpVtbl = lpVtbl; } } [NativeName("Type", "")] [NativeName("Type.Name", "")] [NativeName("Name", "lpVtbl")] public void** LpVtbl; /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(Guid* riid, void** ppvObject) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObject); return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(Guid* riid, ref void* ppvObject) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (void** ppvObjectPtr = &ppvObject) { ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObjectPtr); } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(ref Guid riid, void** ppvObject) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObject); } return ret; } /// <summary>To be documented.</summary> public readonly unsafe int QueryInterface(ref Guid riid, ref void* ppvObject) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (Guid* riidPtr = &riid) { fixed (void** ppvObjectPtr = &ppvObject) { ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObjectPtr); } } return ret; } /// <summary>To be documented.</summary> public readonly uint AddRef() { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); uint ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3DUserDefinedAnnotation*, uint>)LpVtbl[1])(@this); return ret; } /// <summary>To be documented.</summary> public readonly uint Release() { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); uint ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3DUserDefinedAnnotation*, uint>)LpVtbl[2])(@this); return ret; } /// <summary>To be documented.</summary> public readonly unsafe int BeginEvent(char* Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, char*, int>)LpVtbl[3])(@this, Name); return ret; } /// <summary>To be documented.</summary> public readonly int BeginEvent(ref char Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; fixed (char* NamePtr = &Name) { ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, char*, int>)LpVtbl[3])(@this, NamePtr); } return ret; } /// <summary>To be documented.</summary> public readonly int BeginEvent([UnmanagedType(Silk.NET.Core.Native.UnmanagedType.LPWStr)] string Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; var NamePtr = (byte*) SilkMarshal.StringToPtr(Name, NativeStringEncoding.LPWStr); ret = ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, byte*, int>)LpVtbl[3])(@this, NamePtr); SilkMarshal.Free((nint)NamePtr); return ret; } /// <summary>To be documented.</summary> public readonly int EndEvent() { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3DUserDefinedAnnotation*, int>)LpVtbl[4])(@this); return ret; } /// <summary>To be documented.</summary> public readonly unsafe void SetMarker(char* Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, char*, void>)LpVtbl[5])(@this, Name); } /// <summary>To be documented.</summary> public readonly void SetMarker(ref char Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); fixed (char* NamePtr = &Name) { ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, char*, void>)LpVtbl[5])(@this, NamePtr); } } /// <summary>To be documented.</summary> public readonly void SetMarker([UnmanagedType(Silk.NET.Core.Native.UnmanagedType.LPWStr)] string Name) { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); var NamePtr = (byte*) SilkMarshal.StringToPtr(Name, NativeStringEncoding.LPWStr); ((delegate* unmanaged[Cdecl]<ID3DUserDefinedAnnotation*, byte*, void>)LpVtbl[5])(@this, NamePtr); SilkMarshal.Free((nint)NamePtr); } /// <summary>To be documented.</summary> public readonly int GetStatus() { var @this = (ID3DUserDefinedAnnotation*) Unsafe.AsPointer(ref Unsafe.AsRef(in this)); int ret = default; ret = ((delegate* unmanaged[Stdcall]<ID3DUserDefinedAnnotation*, int>)LpVtbl[6])(@this); return ret; } } }
40.079787
144
0.592568
[ "MIT" ]
Zellcore/Silk.NET
src/Microsoft/Silk.NET.Direct3D11/Structs/ID3DUserDefinedAnnotation.gen.cs
7,535
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200601.Outputs { /// <summary> /// Identity for the resource. /// </summary> [OutputType] public sealed class ManagedServiceIdentityResponse { /// <summary> /// The principal id of the system assigned identity. This property will only be provided for a system assigned identity. /// </summary> public readonly string PrincipalId; /// <summary> /// The tenant id of the system assigned identity. This property will only be provided for a system assigned identity. /// </summary> public readonly string TenantId; /// <summary> /// The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. /// </summary> public readonly string? Type; /// <summary> /// The list of user identities associated with resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. /// </summary> public readonly ImmutableDictionary<string, Outputs.ManagedServiceIdentityResponseUserAssignedIdentities>? UserAssignedIdentities; [OutputConstructor] private ManagedServiceIdentityResponse( string principalId, string tenantId, string? type, ImmutableDictionary<string, Outputs.ManagedServiceIdentityResponseUserAssignedIdentities>? userAssignedIdentities) { PrincipalId = principalId; TenantId = tenantId; Type = type; UserAssignedIdentities = userAssignedIdentities; } } }
42.018868
291
0.690615
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200601/Outputs/ManagedServiceIdentityResponse.cs
2,227
C#
using System; using System.Collections.Generic; using System.Text; namespace BlazorBootstrap.Components { public enum NamedColor { Primary, Secondary, Success, Danger, Warning, Info, Light, Dark, White, White50, Black50 } }
14.818182
36
0.542945
[ "Apache-2.0" ]
MikaBerglund/Blazor-Bootstrap
BlazorBootstrap.Components/NamedColor.cs
328
C#
/* Government Usage Rights Notice: The U.S. Government retains unlimited, royalty-free usage rights to this software, but not ownership, as provided by Federal law. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: • Redistributions of source code must retain the above Government Usage Rights Notice, this list of conditions and the following disclaimer. • Redistributions in binary form must reproduce the above Government Usage Rights Notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. • Neither the names of the National Library of Medicine, the National Institutes of Health, nor the names of any of the software developers may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE U.S. GOVERNMENT AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITEDTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE U.S. GOVERNMENT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Imppoa.HtmlZoning { public enum ZoneType { Unknown, Inline, Linebreak, } }
72.2
475
0.792798
[ "BSD-3-Clause" ]
raear/html-zoning
Serialization/ZoneTree/ZoneType.cs
1,813
C#
namespace MdlpApiClient.DataContracts { using System; using System.Runtime.Serialization; /// <summary> /// 8.1.2. Фильтр для мест осуществления деятельности. /// Содержит информацию для фильтрации списка мест осуществления деятельности. /// </summary> [DataContract] public class BranchFilter { /// <summary> /// Уникальный идентификатор места осуществления деятельности /// </summary> [DataMember(Name = "branch_id", IsRequired = false)] public string BranchID { get; set; } /// <summary> /// Уникальный идентификатор дома /// </summary> [DataMember(Name = "houseguid", IsRequired = false)] public string HouseGuid { get; set; } /// <summary> /// Код субъекта РФ /// </summary> [DataMember(Name = "federal_subject_code", IsRequired = false)] public string FederalSubjectCode { get; set; } /// <summary> /// Код округа РФ /// </summary> [DataMember(Name = "federal_district_code", IsRequired = false)] public string FederalDistrictCode { get; set; } /// <summary> /// Статус: 0 — не действует, 1 — действует, 2 — в процессе приостановления /// </summary> [DataMember(Name = "status", IsRequired = false)] public int? Status { get; set; } /// <summary> /// Дата начала периода фильтрации /// </summary> [DataMember(Name = "start_date", IsRequired = false)] public CustomDateTime StartDate { get; set; } /// <summary> /// Дата окончания периода фильтрации /// </summary> [DataMember(Name = "end_date", IsRequired = false)] public CustomDateTime EndDate { get; set; } /// <summary> /// Возможность вывода ЛП из оборота через РВ или соответствующий документ. /// • true — вывод ЛП из оборота возможен через РВ или документ /// • false — вывод ЛП из оборота возможен только через РВ /// </summary> [DataMember(Name = "is_withdrawal_via_document_allowed", IsRequired = false)] public bool? IsWithdrawalViaDocumentAllowed { get; set; } /// <summary> /// Лицензия на фармацевтическую деятельность /// </summary> [DataMember(Name = "has_pharm_license", IsRequired = false)] public bool? HasPharmLicense { get; set; } /// <summary> /// Лицензия на производственную деятельность /// </summary> [DataMember(Name = "has_prod_license", IsRequired = false)] public bool? HasProdLicense { get; set; } /// <summary> /// Лицензия на медицинскую деятельность /// </summary> [DataMember(Name = "has_med_license", IsRequired = false)] public bool? HasMedLicense { get; set; } } }
37.75641
90
0.575212
[ "MIT" ]
cm4ker/MdlpClient
MdlpApiClient/DataContracts/BranchFilter.cs
3,529
C#
using System; namespace VKS.MHS.Elements { /// <summary> /// Interface for lights that support hue/color change. /// </summary> public interface IColorfulLight: ILight { /// <summary> /// Fades the lights off from current color to black. /// </summary> void FadeOff(); /// <summary> /// Fades the on from black to the last color. /// </summary> void FadeOn(); /// <summary> /// Fades light from current color to a specified <paramref name="ATargetColor"/>. /// </summary> /// <param name="ATargetColor">A target color.</param> void FadeTo(LightColor ATargetColor); /// <summary> /// Gets or sets the color of light. /// </summary> /// <value> /// The color. /// </value> LightColor Color { get; set; } } }
24.888889
90
0.526786
[ "Apache-2.0" ]
VladimirKey/VKS.MHS
VKS.MHS.Elements/IColorfulLight.cs
898
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Singleton { public class Policy { private static Policy _instance; public static Policy Instance { get { if (_instance == null) { _instance = new Policy(); } return _instance; } } public Policy() { } private int Id { get; set; } = 123; private string Insured { get; set; } = "John Roy"; public string GetInsuredName() => Insured; } }
20.53125
58
0.508371
[ "MIT" ]
jenmcquade/csharp-snippets
Ex_Files_C_Sharp_Design_Patterns/Ch04/04_02/Finish/Singleton/Policy.cs
659
C#
using RabbitMQ.Client.Framing; using RestBus.Client; using RestBus.Common; using RestBus.Common.Amqp; using RestBus.Common.Http; using RestBus.RabbitMQ.ChannelPooling; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace RestBus.RabbitMQ.Client { public class RestBusClient : MessageInvokerBase { static SequenceGenerator correlationIdGen = SequenceGenerator.FromUtcNow(); readonly IMessageMapper messageMapper; readonly MessagingConfiguration messagingConfig; readonly ConnectionManager connectionMgr; readonly IRPCStrategy directStrategy; readonly IRPCStrategy callbackStrategy; readonly object exchangeDeclareSync = new object(); volatile int lastExchangeDeclareTickCount = 0; volatile bool disposed = false; volatile bool hasKickStarted = false; private Uri baseAddress; private HttpRequestHeaders defaultRequestHeaders; private TimeSpan timeout; static readonly RabbitMQMessagingProperties _defaultMessagingProperties = new RabbitMQMessagingProperties(); //TODO: Consider moving this into Common, Maybe Client (Requires a reference to System.Net.Http) internal static readonly ByteArrayContent _emptyByteArrayContent = new ByteArrayContent(new byte[0]); /// <summary> /// Initializes a new instance of the <see cref="T:RestBus.RabbitMQ.RestBusClient" /> class. /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper" /> the client uses to route messages.</param> public RestBusClient(IMessageMapper messageMapper) : this(messageMapper, null) { } /// <summary> /// Initializes a new instance of the <see cref="T:RestBus.RabbitMQ.RestBusClient" /> class. /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper" /> the client uses to route messages.</param> /// <param name="settings">Client settings.</param> public RestBusClient(IMessageMapper messageMapper, ClientSettings settings ) : base(new HttpClientHandler(), true) { //Set default HttpClient related fields timeout = TimeSpan.FromSeconds(100); MaxResponseContentBufferSize = int.MaxValue; //TODO: Setup cancellation token here. //Ensure messageMapper server uris are valid AmqpConnectionInfo.EnsureValid(messageMapper.ServerUris, "messageMapper.ServerUris"); //Configure RestBus fields/properties this.messageMapper = messageMapper; this.messagingConfig = messageMapper.MessagingConfig; //Fetched only once. if (messagingConfig == null) throw new ArgumentException("messageMapper.MessagingConfig returned null"); //Set ClientSettings this.Settings = settings ?? new ClientSettings(); // Always have a default instance, if it wasn't passed in. this.Settings.Client = this; //Indicate that the settings is owned by this client. //Instantiate connection manager and RPC strategies; connectionMgr = new ConnectionManager(messageMapper.ServerUris); directStrategy = new DirectReplyToRPCStrategy(); callbackStrategy = new CallbackQueueRPCStrategy(this.Settings, messageMapper.GetServiceName(null)); } /// <summary>Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.</summary> /// <returns>Returns <see cref="T:System.Uri" />.The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.</returns> public Uri BaseAddress { get { return baseAddress; } set { EnsureNotStartedOrDisposed(); baseAddress = value; } } /// <summary>Gets the headers which should be sent with each request.</summary> /// <returns>Returns <see cref="T:System.Net.Http.Headers.HttpRequestHeaders" />.The headers which should be sent with each request.</returns> public HttpRequestHeaders DefaultRequestHeaders { //HTTPRequestHeaders ctor is internal so this property cannot be instantiated by this class and so is useless ...sigh... //Fortunately, you can specify Headers per message when using the RequestOptions class //TODO: Consider throwing a NotSupported Exception here instead, since a caller will not expect null. get { return defaultRequestHeaders; } } /// <summary>Gets or sets the maximum number of bytes to buffer when reading the response content.</summary> /// <returns>Returns <see cref="T:System.Int32" />.The maximum number of bytes to buffer when reading the response content. The default value for this property is 64K.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The size specified is less than or equal to zero.</exception> /// <exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has been disposed. </exception> public long MaxResponseContentBufferSize { //Entire Message is dequeued from queue //So this property is only here for compatibilty with HttpClient and does nothing get; set; } /// <summary>Gets or sets the number of milliseconds to wait before the request times out.</summary> /// <returns>Returns <see cref="T:System.TimeSpan" />.The number of milliseconds to wait before the request times out.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The timeout specified is less than zero and is not <see cref="F:System.Threading.Timeout.Infinite" />.</exception> /// <exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has been disposed.</exception> public TimeSpan Timeout { get { return timeout; } set { if (value != System.Threading.Timeout.InfiniteTimeSpan && value < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("value"); } EnsureNotStartedOrDisposed(); timeout = value; } } public ClientSettings Settings { get; } /// <summary>Cancel all pending requests on this instance.</summary> public void CancelPendingRequests() { throw new NotImplementedException(); //TODO: Implement CancelPendingRequests() } /// <summary>Send an HTTP request as an asynchronous operation.</summary> /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns> /// <param name="request">The HTTP request message to send.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception> public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { if (request == null) throw new ArgumentNullException("request"); if (request.RequestUri == null && BaseAddress == null ) { throw new InvalidOperationException("The request URI must either be set or BaseAddress must be set"); } if (disposed) throw new ObjectDisposedException(GetType().FullName); hasKickStarted = true; PrepareMessage(request); //Get Request Options RequestOptions requestOptions = GetRequestOptions(request); var messageProperties = GetMessagingProperties(requestOptions); //Determine if message expects a response TimeSpan requestTimeout = GetRequestTimeout(requestOptions); //TODO: expectingResponse has a slightly different meaning in publisher confirms //where timespan may be longer than zero but MessageExpectsReply is false //in which case the timeout only applies to how long to wait for the publisher confirmation. bool expectingResponse = requestTimeout != TimeSpan.Zero && GetExpectsReply(request); //Declare messaging resources ExpectedResponse arrival = null; AmqpModelContainer model = null; bool modelClosed = false; string correlationId = null; //Get channel pool and decide on RPC strategy var pool = connectionMgr.GetConnectedPool(); IRPCStrategy rpcStrategy = pool.IsDirectReplyToCapable && !Settings.DisableDirectReplies ? directStrategy : callbackStrategy; try { #region Ensure CallbackQueue is started (If Using CallbackQueue Strategy) rpcStrategy.StartStrategy(pool, expectingResponse); #endregion #region Populate BasicProperties //Fill BasicProperties BasicProperties basicProperties = new BasicProperties(); //Set message delivery mode -- Make message persistent if either: // 1. Properties.Persistent is true // 2. messagingConfig.PersistentMessages is true and Properties.Persistent is null // 3. messagingConfig.PersistentMessages is true and Properties.Persistent is true if (messageProperties.Persistent == true || (messagingConfig.PersistentMessages && messageProperties.Persistent != false)) { basicProperties.Persistent = true; } //Set Exchange Headers var exchangeHeaders = messageProperties.Headers ?? messageMapper.GetHeaders(request); if (exchangeHeaders != null) { basicProperties.Headers = exchangeHeaders; } if (expectingResponse) { //Set CorrelationId correlationId = correlationIdGen.GetNextId(); basicProperties.CorrelationId = correlationId; //Set Expiration if messageProperties doesn't override Client.Timeout, RequestOptions and MessageMapper. if (!messageProperties.Expiration.HasValue && requestTimeout != System.Threading.Timeout.InfiniteTimeSpan && ( messagingConfig.MessageExpires == null || messagingConfig.MessageExpires(request))) { if (requestTimeout.TotalMilliseconds > Int32.MaxValue) { basicProperties.Expiration = Int32.MaxValue.ToString(); } else { basicProperties.Expiration = ((int)requestTimeout.TotalMilliseconds).ToString(); } } } else if (!messageProperties.Expiration.HasValue && (messagingConfig.MessageExpires == null || messagingConfig.MessageExpires(request))) { //Request has a zero timeout and the message mapper indicates it should expire and messageproperties expiration is not set: //Set the expiration to zero which means RabbitMQ will only transmit if there is a consumer ready to receive it. //If there is no ready consumer, RabbitMQ drops the message. See https://www.rabbitmq.com/ttl.html basicProperties.Expiration = "0"; } //Set expiration if set in message properties if (messageProperties.Expiration.HasValue) { if (messageProperties.Expiration != System.Threading.Timeout.InfiniteTimeSpan) { var expiration = messageProperties.Expiration.Value.Duration(); if (expiration.TotalMilliseconds > Int32.MaxValue) { basicProperties.Expiration = Int32.MaxValue.ToString(); } else { basicProperties.Expiration = ((int)expiration.TotalMilliseconds).ToString(); } } else { //Infinite Timespan indicates that message should never expire basicProperties.ClearExpiration(); } } #endregion #region Get Ready to Send Message model = rpcStrategy.GetModel(pool, false); var serviceName = (requestOptions == null || requestOptions.ServiceName == null) ? (messageMapper.GetServiceName(request) ?? String.Empty).Trim() : requestOptions.ServiceName.Trim(); RedeclareExchangesAndQueues(model, serviceName); //TODO: Check if cancellation token was set before operation even began var taskSource = new TaskCompletionSource<HttpResponseMessage>(); var exchangeKind = ExchangeKind.Direct; //TODO: Get ExchangeKind from CLient.Settings.ExchangeKind //TODO: Pull exchangeName from a concurrent dictionary that has a key of serviceName, exchangeKind //exchangeKind could be an index into arrays that have concurrentDictionaries. var exchangeName = AmqpUtils.GetExchangeName(messagingConfig, serviceName, exchangeKind); #endregion #region Start waiting for response //Start waiting for response if a request timeout is set. if (expectingResponse) { //TODO: Better to just check if cancellationHasbeen requested instead of checking if it's None if (!cancellationToken.Equals(System.Threading.CancellationToken.None)) { //TODO: Have cancellationtokens cancel event trigger callbackHandle //In fact turn this whole thing into an extension } arrival = rpcStrategy.PrepareForResponse(correlationId, basicProperties, model, request, requestTimeout, cancellationToken, taskSource); } #endregion #region Send Message //TODO: Implement routing to a different exchangeKind via substituting exchangeName //Send message model.Channel.BasicPublish(exchangeName, messageProperties.RoutingKey ?? messageMapper.GetRoutingKey(request, exchangeKind) ?? AmqpUtils.GetWorkQueueRoutingKey(), basicProperties, request.ToHttpRequestPacket().Serialize()); //Close channel if (!expectingResponse || rpcStrategy.ReturnModelAfterSending) { CloseAmqpModel(model); modelClosed = true; } #endregion #region Cleanup if not expecting response //Exit with OK result if no request timeout was set. if (!expectingResponse) { //TODO: Investigate adding a publisher confirm for zero timeout messages so we know that RabbitMQ did pick up the message before replying OK. //Might add extra complexity to this class. //Zero timespan means the client isn't interested in a response taskSource.SetResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = _emptyByteArrayContent }); rpcStrategy.CleanupMessagingResources(correlationId, arrival); } #endregion return taskSource.Task; } catch (Exception ex) { //TODO: Log this if (model != null && !modelClosed) { if (expectingResponse && model.Flags == ChannelFlags.RPC || model.Flags == ChannelFlags.RPCWithPublisherConfirms) { //Model might still be in use in waiting thread and so unsafe to be recycled model.Discard = true; } CloseAmqpModel(model); } rpcStrategy.CleanupMessagingResources(correlationId, arrival); if (ex is HttpRequestException) { throw; } else { throw GetWrappedException("An error occurred while sending the request.", ex); } } } internal void EnsureNotStartedOrDisposed() { if (disposed) throw new ObjectDisposedException(GetType().FullName); if (hasKickStarted) throw new InvalidOperationException("This instance has already started one or more requests. Properties can only be modified before sending the first request."); } protected override void Dispose(bool disposing) { disposed = true; directStrategy.Dispose(); callbackStrategy.Dispose(); connectionMgr.Dispose(); base.Dispose(disposing); } private void RedeclareExchangesAndQueues(AmqpModelContainer model, string serviceName) { //Redeclare exchanges and queues every minute if exchanges and queues are transient, or the first time client is sending a message TimeSpan elapsedSinceLastDeclareExchange = TimeSpan.FromMilliseconds(Environment.TickCount - lastExchangeDeclareTickCount); //TODO: Partition elapsedSinceLastDeclareExchange by serviceName and connection so that redeclares take place on new servicenames and connections. //Discovering firstDeclare by comparing lastExchangeDeclareTickCount to zero is not perfect //because tickcount can wrap back to zero (through the negative number range), if client is running long enough. //However, redeclaring exchanges and queues are a safe operation, so this is okay if it occurs more than once in persistent queues. bool firstDeclare = lastExchangeDeclareTickCount == 0; if (firstDeclare || (!messagingConfig.PersistentWorkQueuesAndExchanges && (elapsedSinceLastDeclareExchange.TotalMilliseconds < 0 || elapsedSinceLastDeclareExchange.TotalSeconds > 60))) { if (!firstDeclare) { //All threads must attempt to declare exchanges and queues if it hasn't been previously declared //(for instance, all threads were started at once) //So do not swap out this value on first declare lastExchangeDeclareTickCount = Environment.TickCount; } AmqpUtils.DeclareExchangeAndQueues(model.Channel, messageMapper, messagingConfig, serviceName, exchangeDeclareSync, null); if (firstDeclare) { //Swap out this value after declaring on firstdeclare lastExchangeDeclareTickCount = Environment.TickCount; } } } private void CloseAmqpModel(AmqpModelContainer model) { if (model != null) { model.Close(); } } private TimeSpan GetRequestTimeout(RequestOptions options) { TimeSpan timeoutVal = this.Timeout; if (options != null && options.Timeout.HasValue) { timeoutVal = options.Timeout.Value; } return timeoutVal.Duration(); } private bool GetExpectsReply(HttpRequestMessage request) { var options = GetRequestOptions(request); if (options == null || options.ExpectsReply == null) { return messagingConfig.MessageExpectsReply == null ? true : messagingConfig.MessageExpectsReply(request); } else { return options.ExpectsReply.Value; } } private void PrepareMessage(HttpRequestMessage request) { //Combine RequestUri with BaseRequest if (request.RequestUri == null) { request.RequestUri = this.BaseAddress; } else if (!request.RequestUri.IsAbsoluteUri) { if (this.BaseAddress != null) { request.RequestUri = new Uri(this.BaseAddress, request.RequestUri); } } //Append default request headers if (this.DefaultRequestHeaders != null) { foreach (var header in this.DefaultRequestHeaders) { if (!request.Headers.Contains(header.Key)) { request.Headers.Add(header.Key, header.Value); } } } } internal static HttpRequestException GetWrappedException(string message, Exception innerException) { return new HttpRequestException(message, innerException); } private static RabbitMQMessagingProperties GetMessagingProperties(RequestOptions options) { if (options == null) return _defaultMessagingProperties; return (options.Properties as RabbitMQMessagingProperties) ?? _defaultMessagingProperties; } } }
45.870707
196
0.601603
[ "Apache-2.0" ]
lucksuper/RestBus
src/Brokers/RabbitMQ/RestBus.RabbitMQ/Client/RestBusClient.cs
22,706
C#
// Generated class v2.19.0.0, can be modified namespace NHtmlUnit.Javascript.Host.Media { public partial class DynamicsCompressorNode { } }
13.818182
46
0.723684
[ "Apache-2.0" ]
HtmlUnit/NHtmlUnit
app/NHtmlUnit/NonGenerated/Javascript/Host/Media/DynamicsCompressorNode.cs
152
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Network { /// <summary> A class representing collection of FirewallPolicy and their operations over its parent. </summary> public partial class FirewallPolicyCollection : ArmCollection, IEnumerable<FirewallPolicy>, IAsyncEnumerable<FirewallPolicy> { private readonly ClientDiagnostics _firewallPolicyClientDiagnostics; private readonly FirewallPoliciesRestOperations _firewallPolicyRestClient; /// <summary> Initializes a new instance of the <see cref="FirewallPolicyCollection"/> class for mocking. </summary> protected FirewallPolicyCollection() { } /// <summary> Initializes a new instance of the <see cref="FirewallPolicyCollection"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the parent resource that is the target of operations. </param> internal FirewallPolicyCollection(ArmClient client, ResourceIdentifier id) : base(client, id) { _firewallPolicyClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", FirewallPolicy.ResourceType.Namespace, DiagnosticOptions); TryGetApiVersion(FirewallPolicy.ResourceType, out string firewallPolicyApiVersion); _firewallPolicyRestClient = new FirewallPoliciesRestOperations(_firewallPolicyClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, firewallPolicyApiVersion); #if DEBUG ValidateResourceId(Id); #endif } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceGroup.ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroup.ResourceType), nameof(id)); } /// <summary> /// Creates or updates the specified Firewall Policy. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_CreateOrUpdate /// </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="parameters"> Parameters supplied to the create or update Firewall Policy operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> or <paramref name="parameters"/> is null. </exception> public async virtual Task<ArmOperation<FirewallPolicy>> CreateOrUpdateAsync(bool waitForCompletion, string firewallPolicyName, FirewallPolicyData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.CreateOrUpdate"); scope.Start(); try { var response = await _firewallPolicyRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, parameters, cancellationToken).ConfigureAwait(false); var operation = new NetworkArmOperation<FirewallPolicy>(new FirewallPolicyOperationSource(Client), _firewallPolicyClientDiagnostics, Pipeline, _firewallPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates or updates the specified Firewall Policy. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_CreateOrUpdate /// </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="parameters"> Parameters supplied to the create or update Firewall Policy operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> or <paramref name="parameters"/> is null. </exception> public virtual ArmOperation<FirewallPolicy> CreateOrUpdate(bool waitForCompletion, string firewallPolicyName, FirewallPolicyData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.CreateOrUpdate"); scope.Start(); try { var response = _firewallPolicyRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, parameters, cancellationToken); var operation = new NetworkArmOperation<FirewallPolicy>(new FirewallPolicyOperationSource(Client), _firewallPolicyClientDiagnostics, Pipeline, _firewallPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the specified Firewall Policy. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public async virtual Task<Response<FirewallPolicy>> GetAsync(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.Get"); scope.Start(); try { var response = await _firewallPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, expand, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _firewallPolicyClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new FirewallPolicy(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the specified Firewall Policy. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public virtual Response<FirewallPolicy> Get(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.Get"); scope.Start(); try { var response = _firewallPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, expand, cancellationToken); if (response.Value == null) throw _firewallPolicyClientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new FirewallPolicy(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Lists all Firewall Policies in a resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies /// Operation Id: FirewallPolicies_List /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="FirewallPolicy" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<FirewallPolicy> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<FirewallPolicy>> FirstPageFunc(int? pageSizeHint) { using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetAll"); scope.Start(); try { var response = await _firewallPolicyRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new FirewallPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<FirewallPolicy>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetAll"); scope.Start(); try { var response = await _firewallPolicyRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new FirewallPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// Lists all Firewall Policies in a resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies /// Operation Id: FirewallPolicies_List /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="FirewallPolicy" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<FirewallPolicy> GetAll(CancellationToken cancellationToken = default) { Page<FirewallPolicy> FirstPageFunc(int? pageSizeHint) { using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetAll"); scope.Start(); try { var response = _firewallPolicyRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new FirewallPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<FirewallPolicy> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetAll"); scope.Start(); try { var response = _firewallPolicyRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new FirewallPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public async virtual Task<Response<bool>> ExistsAsync(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.Exists"); scope.Start(); try { var response = await GetIfExistsAsync(firewallPolicyName, expand: expand, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public virtual Response<bool> Exists(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.Exists"); scope.Start(); try { var response = GetIfExists(firewallPolicyName, expand: expand, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Tries to get details for this resource from the service. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public async virtual Task<Response<FirewallPolicy>> GetIfExistsAsync(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetIfExists"); scope.Start(); try { var response = await _firewallPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, expand, cancellationToken: cancellationToken).ConfigureAwait(false); if (response.Value == null) return Response.FromValue<FirewallPolicy>(null, response.GetRawResponse()); return Response.FromValue(new FirewallPolicy(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Tries to get details for this resource from the service. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName} /// Operation Id: FirewallPolicies_Get /// </summary> /// <param name="firewallPolicyName"> The name of the Firewall Policy. </param> /// <param name="expand"> Expands referenced resources. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="firewallPolicyName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="firewallPolicyName"/> is null. </exception> public virtual Response<FirewallPolicy> GetIfExists(string firewallPolicyName, string expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(firewallPolicyName, nameof(firewallPolicyName)); using var scope = _firewallPolicyClientDiagnostics.CreateScope("FirewallPolicyCollection.GetIfExists"); scope.Start(); try { var response = _firewallPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, firewallPolicyName, expand, cancellationToken: cancellationToken); if (response.Value == null) return Response.FromValue<FirewallPolicy>(null, response.GetRawResponse()); return Response.FromValue(new FirewallPolicy(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<FirewallPolicy> IEnumerable<FirewallPolicy>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<FirewallPolicy> IAsyncEnumerable<FirewallPolicy>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } } }
57.906566
349
0.662466
[ "MIT" ]
AntonioVT/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/FirewallPolicyCollection.cs
22,931
C#
using System.Collections.Generic; using Enums.Aspects; using Enums.Equipment; using Interfaces.Aspects.Equipment; using Serializable.Aspects.Equipment; using UnityEngine; namespace ScriptableObjects.Aspects.Equipment { /// <summary> /// Weapon equipment Aspect /// </summary> [CreateAssetMenu(fileName = "New Weapon Equipment", menuName = "Aspects/Equipment/Create Weapon Equipment Aspect", order = 0)] public class WeaponEquipmentAspectObj : BaseEquipmentAspectObj, IWeaponEquipmentAspect { public WeaponType weaponType; public WeaponType WeaponType => weaponType; public List<CharacteristicPair> weaponDamages; public List<CharacteristicPair> WeaponDamages => weaponDamages; } }
33.772727
130
0.748318
[ "Apache-2.0" ]
gellios3/FateSimulator
Assets/Scripts/ScriptableObjects/Aspects/Equipment/WeaponEquipmentAspectObj.cs
745
C#
using UnityEngine; using System.Collections; using UnityEngine.AI; public class Shooter : MonoBehaviour { public WeaponConfig weapon = new WeaponConfig(); public float turnSpeed = 1000.0f; public Transform shootTransform; Vector3 currentTarget; float lastShotTime; bool isAttacking; public bool IsAttacking { get { return isAttacking; } set { if (isAttacking != value) { isAttacking = value; if (isAttacking) { OnStartAttack (); } else { OnStopAttack (); } } } } public void StartShootingAt(Vector3 target) { currentTarget = target; IsAttacking = true; } public void StopShooting() { IsAttacking = false; } void OnStartAttack () { } void OnStopAttack () { //lastShotTime = Time.time; } // Use this for initialization void Awake () { if (weapon == null) { print("Shooter is missing Weapon"); return; } if (weapon.bulletPrefab == null) { print("Shooter's Weapon is missing Bullet Prefab"); return; } if (shootTransform == null) { shootTransform = transform; } isAttacking = false; } void Update() { if (isAttacking) { // some debug stuff var dir = currentTarget - transform.position; Debug.DrawRay (transform.position, dir); // rotate toward target RotateTowardTarget(); // keep shooting var delay = Time.time - lastShotTime; if (delay < weapon.attackDelay) { // still on cooldown return; } ShootAt (currentTarget); } } Quaternion GetRotationToward(Vector3 target) { Vector3 dir = target - shootTransform.position; return GetRotationFromDirection(dir); } Quaternion GetRotationFromDirection(Vector3 dir) { var angle = Mathf.Atan2 (dir.x, dir.z) * Mathf.Rad2Deg; return Quaternion.AngleAxis(angle, Vector3.up); } void RotateTowardTarget() { var rigidbody = GetComponent<Rigidbody> (); if (rigidbody != null && (rigidbody.constraints & RigidbodyConstraints.FreezePositionY) != 0) { // don't rotate if rotation has been constrained return; } //transform.LookAt (); var agent = GetComponent<NavMeshAgent> (); if (agent != null) { turnSpeed = agent.angularSpeed; } var targetRotation = GetRotationToward(currentTarget); shootTransform.rotation = Quaternion.RotateTowards(shootTransform.rotation, targetRotation, Time.deltaTime * turnSpeed); } public void ShootAt(Transform t) { ShootAt (t.position); } public void ShootAt(Vector3 target) { if (weapon == null || weapon.bulletPrefab == null) { return; } var dir = target - transform.position; dir.y = 0; dir.Normalize (); if (weapon.bulletCount > 1) { // shoot N bullets in a cone from -coneAngle/2 to +coneAngle/2 dir = Quaternion.Euler (0, -weapon.ConeAngle / 2, 0) * dir; var deltaAngle = weapon.ConeAngle / (weapon.bulletCount-1); for (var i = 0; i < weapon.bulletCount; ++i) { //dir.Normalize (); ShootBullet (dir); dir = Quaternion.Euler (0, deltaAngle, 0) * dir; } } else { // just one bullet straight toward the target ShootBullet (dir); } // reset shoot time lastShotTime = Time.time; } void ShootBullet(Vector3 dir) { // create a new bullet (make sure, it's on same height as target) var pos = transform.position; pos.y = currentTarget.y; var bullet = (Bullet)Instantiate(weapon.bulletPrefab, pos, GetRotationFromDirection(dir)); // set bullet faction FactionManager.SetFaction (bullet.gameObject, gameObject); // set velocity var rigidbody = bullet.GetComponent<Rigidbody> (); rigidbody.velocity = dir * bullet.speed; bullet.owner = gameObject; bullet.damageMin = weapon.damageMin; bullet.damageMax = weapon.damageMax; } void OnDeath(DamageInfo damageInfo) { enabled = false; } }
23.067901
122
0.681563
[ "MIT" ]
Domiii/EvilBoxesMultiplayer
Assets/Scripts/Combat/Shooter.cs
3,739
C#
#if DLL_EXPORT using System; #endif using System.Collections.Generic; using System.IO; using UnityEngine; namespace TrainJetsMod { public class TrainJetsMod #if DLL_EXPORT : AbstractMod { public static string NAME = "Train Jets"; public static string DESCRIPT = "Allows jet deco objects to be placed on ride cars.\nCode by Draco18s"; public static string VERSION = "1.0.0"; private List<DecoLink> linksDict; public static TrainJetsMod instance; public string path { get { return Application.persistentDataPath + "/Parkitect/Mods/TrainJetsData"; } } public TrainJetsMod() { try { Directory.CreateDirectory(path); } catch { Debug.LogError("Creating path failed: " + path); return; } linksDict = new List<DecoLink>(); instance = this; } public override string getName() { return NAME; } public override string getDescription() { return DESCRIPT; } public override string getVersionNumber() { return VERSION; } public override string getIdentifier() { return NAME + "-" + VERSION; } public override bool isMultiplayerModeCompatible() { return true; } public override void onEnabled() { base.onEnabled(); EventManager.Instance.OnBuildableObjectBuilt += BuildTrigger; Deserializer.Instance.addAfterDeserializationHandler(LoadData); EventManager.Instance.OnGameSaved += SaveData; CommandController.Instance.commandSerializer.registerCommandType<DecoLinkCommand>(); } public override void onDisabled() { base.onDisabled(); EventManager.Instance.OnBuildableObjectBuilt -= BuildTrigger; EventManager.Instance.OnGameSaved -= SaveData; } private void BuildTrigger(BuildableObject buildableObject) { if(buildableObject.GetType() == typeof(Deco)) { if(buildableObject.transform.parent != null) return; Bounds bounds = buildableObject.GetComponent<MeshFilter>().sharedMesh.bounds; if(bounds.size.x > 0.333f || bounds.size.y > 0.333f || bounds.size.z > 0.333f) return; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BuilderMousePositionInfo builderMousePositionInfo = default(BuilderMousePositionInfo); builderMousePositionInfo.hitDistance = float.MaxValue; GameObject nozzleMeshObj = null; foreach(MouseCollider.HitInfo hitInfo in MouseCollisions.Instance.raycastAll(ray, builderMousePositionInfo.hitDistance)) { if(hitInfo.hitDistance < builderMousePositionInfo.hitDistance) { IMouseSelectable componentInParent = hitInfo.hitObject.GetComponentInParent<IMouseSelectable>(); if((componentInParent == null || componentInParent.canBeSelected()) && hitInfo.hitObject != buildableObject.gameObject) { int num = 1 << hitInfo.hitObject.layer; builderMousePositionInfo.hitSomething = true; builderMousePositionInfo.hitObject = hitInfo.hitObject; builderMousePositionInfo.hitPosition = hitInfo.hitPosition; builderMousePositionInfo.hitDistance = hitInfo.hitDistance; builderMousePositionInfo.hitNormal = hitInfo.hitNormal; builderMousePositionInfo.hitLayerMask = num; } if((componentInParent == null || componentInParent.canBeSelected()) && hitInfo.hitObject == buildableObject.gameObject) { nozzleMeshObj = hitInfo.hitObject; } } } if(builderMousePositionInfo.hitSomething) { Car car = builderMousePositionInfo.hitObject.GetComponent<Car>(); if(car != null) { Debug.Log("Link distance: " + Vector3.Distance(builderMousePositionInfo.hitPosition, buildableObject.transform.position)); if(Vector3.Distance(builderMousePositionInfo.hitPosition, buildableObject.transform.position) < 0.1f) { Link(buildableObject, car); } } } } } private void Link(BuildableObject buildableObject, Car car) { buildableObject.gameObject.transform.SetParent(car.transform, true); ChunkedMesh[] componentsInChildren = buildableObject.GetComponentsInChildren<ChunkedMesh>(); foreach(ChunkedMesh cm in componentsInChildren) { GameObject.Destroy(cm); } ParticleSystem[] systems = buildableObject.GetComponentsInChildren<ParticleSystem>(); foreach(ParticleSystem sys in systems) { ParticleSystem.MainModule m = sys.main; m.simulationSpace = ParticleSystemSimulationSpace.World; } DecoLink link = new DecoLink { buildableID = buildableObject.getId(), attachedCarID = car.getId(), localpos = buildableObject.transform.localPosition, localrot = buildableObject.transform.localRotation }; linksDict.Add(link); if(CommandController.Instance.isInMultiplayerMode()) { CommandController.Instance.addCommand(new DecoLinkCommand(link), null, true); } } private void SaveData() { string parkName = GameController.Instance.park.parkName; string saveDir = System.IO.Path.Combine(path, parkName); try { Directory.CreateDirectory(saveDir); } catch { Debug.LogError("Creating path failed: " + saveDir); return; } try { File.WriteAllText(saveDir + "/links.json", MiniJSON.Json.Serialize(linksDict)); } catch { Debug.LogError("Writing failed: " + saveDir + "/links.json"); return; } } private void LoadData() { string parkName = GameController.Instance.park.parkName; string saveDir = System.IO.Path.Combine(path, parkName); if(File.Exists(saveDir + "/links.json")) { object jsonStr = MiniJSON.Json.Deserialize(File.ReadAllText(saveDir + "/links.json")); List<object> l = (List<object>)jsonStr; foreach(object o in l) { DecoLink d = JsonToDecoLink(o); if(!string.IsNullOrEmpty(d.attachedCarID)) linksDict.Add(d); } foreach(DecoLink ln in linksDict) { DoLinkFrom(ln); } } else { Debug.Log(saveDir + "/links.json not found"); } } public static DecoLink JsonToDecoLink(object o) { if(o is string) { object j = MiniJSON.Json.Deserialize((string)o); if(j is Dictionary<string, object> d) { double px = (double)d["px"]; double py = (double)d["py"]; double pz = (double)d["pz"]; double rw = (double)d["rw"]; double rx = (double)d["rx"]; double ry = (double)d["ry"]; double rz = (double)d["rz"]; return new DecoLink { attachedCarID = (string)d["attachedCarID"], buildableID = (string)d["buildableID"], localpos = new Vector3((float)px, (float)py, (float)pz), localrot = new Quaternion((float)rw, (float)rx, (float)ry, (float)rz) }; } } return new DecoLink(); } public static void DoLinkFrom(DecoLink link) { BuildableObject buildableObject = Deserializer.Instance.resolveReference<BuildableObject>(link.buildableID); Car car = Deserializer.Instance.resolveReference<Car>(link.attachedCarID); if(!(car && buildableObject)) { Debug.Log("Invalid " + link.buildableID + " or " + link.attachedCarID); return; } else { Debug.Log("Relinking " + link.buildableID + " to " + link.attachedCarID); } if(link.localpos.magnitude > 1) { Debug.Log("localpos is insane! " + link.localpos); } buildableObject.transform.SetParent(car.transform); buildableObject.transform.localPosition = link.localpos; buildableObject.transform.localRotation = link.localrot; ChunkedMesh[] componentsInChildren = buildableObject.GetComponentsInChildren<ChunkedMesh>(); foreach(ChunkedMesh cm in componentsInChildren) { GameObject.Destroy(cm); } ParticleSystem[] systems = buildableObject.GetComponentsInChildren<ParticleSystem>(); foreach(ParticleSystem sys in systems) { ParticleSystem.MainModule m = sys.main; m.simulationSpace = ParticleSystemSimulationSpace.World; } if(!instance.linksDict.Contains(link)) { instance.linksDict.Add(link); } } } #else { } #endif }
34.356828
128
0.709065
[ "MIT" ]
Draco18s/Parkitect-Modding
Assets/TrainJets/TrainJetsMod.cs
7,801
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutomaticAvatarSetup : MonoBehaviour { PlayerManager pm; FacialController fc; PhotonView pv; ScaleAdjust sa; SetHeadPos shp; SyncAvatarToHMD satHMD; void StartBasicSetup(GameObject _avatar){ pm = _avatar.AddComponent (typeof(PlayerManager)) as PlayerManager; pm.FindCameraRig (); sa = _avatar.AddComponent (typeof(ScaleAdjust)) as ScaleAdjust; pv = _avatar.transform.parent.parent.GetComponent<PhotonView>(); pm.photonView = pv; pv.ObservedComponents = new List<Component> (); pv.ObservedComponents.Add (pm); } public void StartHMDSetup(GameObject _avatar, string skeletonName, string faceExpressions){ StartBasicSetup (_avatar); fc = _avatar.AddComponent (typeof(FacialController)) as FacialController; fc.photonView = pv; fc.OtherMeshes = new Transform[0]; IterateAndAddComponentsToThroughChildren (_avatar.transform, true); IterateAndAssignValuesDependenciesInChildren (_avatar.transform); pv.ObservedComponents.Add (fc); pv.ObservedComponents.Add (shp); pm.localOptitrackAnimator.SkeletonAssetName = skeletonName; pm.remoteOptitrackAnimator.SkeletonAssetName = skeletonName; pm.localOptitrackAnimator.enabled = true; pm.remoteOptitrackAnimator.enabled = true; fc.expressionTargets = new string[faceExpressions.Split ('\n').Length - 1]; fc.expressionWeights = new float[fc.expressionTargets.Length]; for (int i = 0; i < faceExpressions.Split ('\n').Length -1; i++) { string[] entries = GetLine (faceExpressions, i).Split(','); fc.expressionTargets [i] = entries [0]; fc.expressionWeights [i] = float.Parse(entries [1]); } } public void StartHMDLessSetup(GameObject _avatar, string skeletonName, string faceExpressions){ StartBasicSetup (_avatar); IterateAndAddComponentsToThroughChildren (_avatar.transform, false); pm.remoteOptitrackAnimator.SkeletonAssetName = skeletonName; pm.remoteOptitrackAnimator.enabled = true; pm.isHmdLess = true; } string GetLine(string text, int lineNr){ string[] lines = text.Replace ("\r", "").Split ('\n'); return lines.Length >= lineNr ? lines [lineNr] : null; } void IterateAndAddComponentsToThroughChildren(Transform parent, bool withHmd){ foreach(Transform child in parent){ switch(child.tag){ case "AAS_HMD_Avatar": if (withHmd) { pm.localOptitrackAnimator = child.gameObject.AddComponent (typeof(OptitrackSkeletonAnimator)) as OptitrackSkeletonAnimator; pm.localOptitrackAnimator.DestinationAvatar = child.GetComponent<Animator> ().avatar; satHMD = child.gameObject.AddComponent (typeof(SyncAvatarToHMD)) as SyncAvatarToHMD; } else { Destroy (child.gameObject); } break; case "AAS_Optitrack_Avatar": pm.remoteOptitrackAnimator = child.gameObject.AddComponent (typeof(OptitrackSkeletonAnimator)) as OptitrackSkeletonAnimator; pm.remoteOptitrackAnimator.DestinationAvatar = child.GetComponent<Animator> ().avatar; break; case "AAS_HeadBone": if (withHmd) { shp = child.gameObject.AddComponent (typeof(SetHeadPos)) as SetHeadPos; shp.lerpRate = 15f; shp._playerPhotonView = pv; } else { Destroy (child.gameObject); } break; case "AAS_EyeLevel": sa.eyeLevel = child; break; case "AAS_OtherMeshes": if (withHmd) { Transform[] t = new Transform[fc.OtherMeshes.Length + 1]; for (int i = 0; i < fc.OtherMeshes.Length; i++) { t [i] = fc.OtherMeshes [i]; } t [fc.OtherMeshes.Length] = child; fc.OtherMeshes = t; } break; } IterateAndAddComponentsToThroughChildren (child, withHmd); } } void IterateAndAssignValuesDependenciesInChildren(Transform parent){ foreach(Transform child in parent){ switch(child.tag){ case "AAS_HMD_Face": fc.HmdFace = child.GetComponent<SkinnedMeshRenderer> (); break; case "AAS_Optitrack_Face": fc.OptitrackFace = child.GetComponent<SkinnedMeshRenderer> (); break; case "AAS_HMD_EyeL": fc.eye_L = child; break; case "AAS_HMD_EyeR": fc.eye_R = child; break; case "AAS_Optitrack_EyeL": fc.r_eye_L = child; break; case "AAS_Optitrack_EyeR": fc.r_eye_R = child; break; case "AAS_NeckUpper": satHMD.neckUpper = child; break; case "AAS_HeadLower": satHMD.headLower = child; break; } IterateAndAssignValuesDependenciesInChildren (child); } } }
32.510949
128
0.723844
[ "MIT" ]
MTGTech/StudioV
Assets/Script/AvatarSpecific/AutomaticAvatarSetup.cs
4,456
C#
namespace MedicalExaminer.Common.Settings { /// <summary> /// Cosmos Database Settings. /// </summary> public class CosmosDbSettings { /// <summary> /// URL. /// </summary> public string URL { get; set; } /// <summary> /// Primary Key. /// </summary> public string PrimaryKey { get; set; } /// <summary> /// Database Id. /// </summary> public string DatabaseId { get; set; } /// <summary> /// Bypass SSL certificate check /// </summary> /// <remarks>Used on the emulator which has a self signed cert.</remarks> public bool BypassSsl { get; set; } } }
23.833333
81
0.504895
[ "MIT" ]
neiltait/medex_api_pub
MedicalExaminer.Common/Settings/CosmosDBSettings.cs
717
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { /// <summary> /// The action to be taken when the queue overflows. /// </summary> public enum AsyncTargetWrapperOverflowAction { /// <summary> /// Grow the queue. /// </summary> Grow, /// <summary> /// Discard the overflowing item. /// </summary> Discard, /// <summary> /// Block until there's more room in the queue. /// </summary> Block, } }
38
100
0.698061
[ "BSD-3-Clause" ]
304NotModified/NLog
src/NLog/Targets/Wrappers/AsyncTargetWrapperOverflowAction.cs
2,166
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cvm.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeImageSharePermissionResponse : AbstractModel { /// <summary> /// 镜像共享信息 /// </summary> [JsonProperty("SharePermissionSet")] public SharePermission[] SharePermissionSet{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArrayObj(map, prefix + "SharePermissionSet.", this.SharePermissionSet); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.686275
96
0.656559
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cvm/V20170312/Models/DescribeImageSharePermissionResponse.cs
1,686
C#
using System; namespace Tomlet.Models { public class TomlOffsetDateTime : TomlValue { private readonly DateTimeOffset _value; public TomlOffsetDateTime(DateTimeOffset value) { _value = value; } public DateTimeOffset Value => _value; public override string StringValue => Value.ToString("O"); public static TomlOffsetDateTime? Parse(string input) { if (!DateTimeOffset.TryParse(input, out var dt)) return null; return new TomlOffsetDateTime(dt); } public override string SerializedValue => StringValue; } }
24.321429
66
0.591777
[ "MIT" ]
ChadKeating/Tomlet
Tomlet/Models/TomlOffsetDateTime.cs
683
C#
using Improbable.Gdk.Core; using Improbable.Worker.CInterop; using Improbable.Worker.CInterop.Alpha; namespace Fps { public class GetPlayerIdentityTokenState : SessionState { private readonly State nextState; private Future<PlayerIdentityTokenResponse?> pitResponse; public GetPlayerIdentityTokenState(State nextState, UIManager manager, ConnectionStateMachine owner) : base(manager, owner) { this.nextState = nextState; } public override void StartState() { pitResponse = DevelopmentAuthentication.CreateDevelopmentPlayerIdentityTokenAsync( RuntimeConfigDefaults.LocatorHost, RuntimeConfigDefaults.AnonymousAuthenticationPort, new PlayerIdentityTokenRequest { DevelopmentAuthenticationToken = Blackboard.DevAuthToken, PlayerId = Blackboard.PlayerName, DisplayName = string.Empty, } ); } public override void ExitState() { pitResponse.Dispose(); } public override void Tick() { if (!pitResponse.TryGet(out var result)) { return; } if (!result.HasValue) { ScreenManager.StartStatus.ShowFailedToGetDeploymentsText( $"Failed to retrieve player identity token.\nUnknown error - Please report this to us!"); Owner.SetState(Owner.StartState, 2f); } if (result.Value.Status.Code != ConnectionStatusCode.Success) { ScreenManager.StartStatus.ShowFailedToGetDeploymentsText( $"Failed to retrieve player identity token.\n Error code: {result.Value.Status.Code}"); Owner.SetState(Owner.StartState, 2f); } Blackboard.PlayerIdentityToken = result.Value.PlayerIdentityToken; Owner.SetState(new GetDeploymentsState(nextState, Manager, Owner)); } } }
33.967742
131
0.597341
[ "MIT" ]
footman136/fps-starter-project-yuanjue
workers/unity/Assets/Fps/Scripts/GameLogic/StateMachine/Session/GetPlayerIdentityTokenState.cs
2,106
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; namespace SimpleAuth { public abstract class WebAuthenticator : Authenticator { public bool ClearCookiesBeforeLogin { get; set; } public CookieHolder [] Cookies { get; set; } public abstract string BaseUrl { get;set;} public abstract Uri RedirectUrl{get;set;} public List<string> Scope { get; set; } = new List<string>(); public virtual bool CheckUrl(Uri url, Cookie[] cookies) { try { if (url == null || string.IsNullOrWhiteSpace(url.Query)) return false; if (url.Host != RedirectUrl.Host) return false; var parts = HttpUtility.ParseQueryString(url.Query); var code = parts["code"]; if (!string.IsNullOrWhiteSpace(code)) { Cookies = cookies?.Select (x => new CookieHolder { Domain = x.Domain, Path = x.Path, Name = x.Name, Value = x.Value }).ToArray (); FoundAuthCode(code); return true; } } catch (Exception ex) { Console.WriteLine(ex); } return false; } public virtual Task<Uri> GetInitialUrl() { var uri = new Uri(BaseUrl); var collection = GetInitialUrlQueryParameters(); return Task.FromResult(uri.AddParameters(collection)); } public virtual Dictionary<string, string> GetInitialUrlQueryParameters() { var data = new Dictionary<string, string>() { {"client_id",ClientId}, {"response_type","code"}, {"redirect_uri",RedirectUrl.OriginalString} }; if (Scope?.Count > 0) { var scope = string.Join (" ", Scope); data ["scope"] = scope; } return data; } public virtual Task<Dictionary<string, string>> GetTokenPostData(string clientSecret) { var tokenPostData = new Dictionary<string, string> { { "grant_type", "authorization_code" }, { "code", AuthCode }, { "client_id", ClientId }, { "client_secret", clientSecret }, }; if (RedirectUrl != null) { tokenPostData["redirect_uri"] = RedirectUrl.OriginalString; } return Task.FromResult(tokenPostData); } } }
21.409524
135
0.650801
[ "Apache-2.0" ]
PatchesTheFirst/SimpleAuth
src/SimpleAuth/Api/WebAuthenticator.cs
2,250
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Asp.net_Core_Project.Data.Migrations { public partial class InitialCreateXtrellsPCDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
20
71
0.688889
[ "MIT" ]
Xtreller/ShishaWeb-Asp.NetCore
Data/Migrations/20200418193237_InitialCreateXtrellsPCDb.cs
362
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; using System.IO; using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.DotNet.UpgradeAssistant.Extensions { public class DefaultUpgradeAssistantConfigurationLoader : IUpgradeAssistantConfigurationLoader { private readonly JsonSerializerOptions _options = new() { WriteIndented = true, }; private readonly string _path; private readonly ILogger<DefaultUpgradeAssistantConfigurationLoader> _logger; public DefaultUpgradeAssistantConfigurationLoader( IOptions<ExtensionOptions> options, ILogger<DefaultUpgradeAssistantConfigurationLoader> logger) { if (options is null) { throw new ArgumentNullException(nameof(options)); } _path = options.Value.ConfigurationFilePath; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public UpgradeAssistantConfiguration Load() { if (File.Exists(_path)) { var bytes = File.ReadAllBytes(_path); try { var data = JsonSerializer.Deserialize<UpgradeAssistantConfiguration>(bytes, _options); if (data is not null) { return data; } } catch (JsonException e) { _logger.LogError(e, "Unexpected error reading configuration file at {Path}", _path); } } return new(); } public void Save(UpgradeAssistantConfiguration configuration) { var bytes = JsonSerializer.SerializeToUtf8Bytes(configuration, _options); File.WriteAllBytes(_path, bytes); } } }
31.181818
106
0.592809
[ "MIT" ]
ScriptBox21/dotnet-upgrade-assistant
src/components/Microsoft.DotNet.UpgradeAssistant.Extensions/DefaultUpgradeAssistantConfigurationLoader.cs
2,060
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using dotnet_example.Models; using Microsoft.AspNetCore.Authorization; namespace dotnet_example.Controllers { [Authorize] public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
24.06383
113
0.577365
[ "Apache-2.0" ]
18F/gcp-appengine-template
dotnet-example/Controllers/HomeController.cs
1,133
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using ProtoBuf; using ROMZOOM.Logic; namespace ROMZOOM.Model { [ProtoContract] public class LibraryData { [ProtoMember(1)] public string RootPath { get; set; } [ProtoMember(2)] public Dictionary<PlatformId, Platform> Platforms { get; } = new Dictionary<PlatformId, Platform>(); [ProtoMember(3)] public Dictionary<PlatformId, List<Rom>> Roms { get; } = new Dictionary<PlatformId, List<Rom>>(); [ProtoMember(4)] public Dictionary<int, Emulator> Emulators = new Dictionary<int, Emulator>(); [ProtoMember(5)] public DateTime ModifyDate; [ProtoMember(6)] public Dictionary<string, RomImageData> RomImageBank = new Dictionary<string, RomImageData>(); public Dictionary<string, Bitmap> RomImages = new Dictionary<string, Bitmap>(); } [ProtoContract] public class RomImageData { [ProtoMember(1)] public byte[] ImageData { get; set; } [ProtoMember(2)] public int Width { get; set; } [ProtoMember(3)] public int Height { get; set; } [ProtoMember(4)] public PixelFormat PixelFormat { get; set; } } public static class Library { public static string RootPath { get => _data.RootPath; set { _data.RootPath = value; MarkDirty(); } } public static Dictionary<PlatformId, Platform> Platforms => _data.Platforms; public static Dictionary<PlatformId, List<Rom>> Roms => _data.Roms; public static Dictionary<int, Emulator> Emulators => _data.Emulators; public static Dictionary<string, Bitmap> RomsImages => _data.RomImages; private static LibraryData _data; private static DateTime _modify_time; public static void Load() { var path = Path.Combine( Application.StartupPath, "library.bin"); if (File.Exists(path)) { using (var file = File.OpenRead(path)) { _data = Serializer.Deserialize<LibraryData>(file); LoadRomImages(); _modify_time = _data.ModifyDate; } } else { _data = new LibraryData(); Save(); } } private static void LoadRomImages() { foreach (var rom_image_data in _data.RomImageBank) { var rom_image = Utils.ByteArrayToBitmap(rom_image_data.Value.ImageData, rom_image_data.Value.Width, rom_image_data.Value.Height, rom_image_data.Value.PixelFormat); _data.RomImages.Add(rom_image_data.Key, rom_image); } } public static void Save() { if (_data.ModifyDate != default && DateTime.Compare(_modify_time, _data.ModifyDate) <= 0) { return; } Messager.Emit((int) MessageCodes.LibraryModified); var path = Path.Combine(Application.StartupPath, "library.bin"); _data.ModifyDate = _modify_time; using (var file = File.Open(path, FileMode.Create)) { Serializer.Serialize(file, _data); } } public static bool ContainsPlatform(PlatformId platform_id) { return _data.Platforms.TryGetValue(platform_id, out _); } public static bool ContainsRom(PlatformId platform_id, Rom rom) { return _data.Roms.TryGetValue(platform_id, out _) && _data.Roms[platform_id].Contains(rom); } public static void AddPlatform(Platform platform) { _data.Platforms.Add(platform.PlatformId, platform); _data.Roms[platform.PlatformId] = new List<Rom>(); MarkDirty(); } public static void RemovePlatform(Platform platform) { List<Rom> to_remove = new List<Rom>(_data.Roms.Count); foreach (var rom in _data.Roms[platform.PlatformId]) { to_remove.Add(rom); } foreach (var rom in to_remove) { RemoveRom(rom); } _data.Roms.Remove(platform.PlatformId); _data.Platforms.Remove(platform.PlatformId); MarkDirty(); } public static void AddRom(Rom rom) { _data.Roms[rom.PlatformId].Add(rom); MarkDirty(); } public static void RemoveRom(Rom rom) { _data.Roms[rom.PlatformId].Remove(rom); if (_data.RomImages.ContainsKey(rom.Hash)) { _data.RomImages[rom.Hash].Dispose(); _data.RomImages.Remove(rom.Hash); _data.RomImageBank.Remove(rom.Hash); } MarkDirty(); } public static void AddEmulator(Emulator emu) { MarkDirty(); _data.Emulators.Add(emu.Uid, emu); } public static void SetRomImage(Rom rom, Bitmap bitmap) { if (_data.RomImages.ContainsKey(rom.Hash)) { _data.RomImages[rom.Hash].Dispose(); } _data.RomImages[rom.Hash] = bitmap; _data.RomImageBank[rom.Hash] = new RomImageData() { ImageData = Utils.BitmapToByteArray(bitmap), Width = bitmap.Width, Height = bitmap.Height, PixelFormat = bitmap.PixelFormat }; MarkDirty(); } public static void SetRomImage(Rom rom, string image_path) { Bitmap bitmap = Utils.LoadBitmapFromFile(image_path); SetRomImage(rom, bitmap); } public static void Clear() { _data.Platforms.Clear(); _data.Emulators.Clear(); _data.Roms.Clear(); ClearImages(); MarkDirty(); } public static void ClearImages() { _data.RomImageBank.Clear(); ReleaseRomImages(); _data.RomImages.Clear(); MarkDirty(); } public static void ClearRomImage(Rom rom) { _data.RomImageBank.Remove(rom.Hash); _data.RomImages[rom.Hash].Dispose(); _data.RomImages.Remove(rom.Hash); MarkDirty(); } public static void ReleaseRomImages() { foreach (var data_rom_image in _data.RomImages) { data_rom_image.Value.Dispose(); } } public static void MarkDirty() { _modify_time = DateTime.Now; } } }
26.27037
115
0.53588
[ "MIT" ]
rafaelvasco/ROMZOOM
Model/Library.cs
7,095
C#
using EngineeringUnits.Units; namespace EngineeringUnits { //This class is auto-generated, changes to the file will be overwritten! public partial class Acceleration { /// <summary> /// Get Acceleration in SI. /// </summary> public double SI => As(AccelerationUnit.SI); /// <summary> /// Get Acceleration in KilometerPerSecondSquared. /// </summary> public double KilometerPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); /// <summary> /// Get Acceleration in MeterPerSecondSquared. /// </summary> public double MeterPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); /// <summary> /// Get Acceleration in DecimeterPerSecondSquared. /// </summary> public double DecimeterPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); /// <summary> /// Get Acceleration in CentimeterPerSecondSquared. /// </summary> public double CentimeterPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); /// <summary> /// Get Acceleration in MicrometerPerSecondSquared. /// </summary> public double MicrometerPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); /// <summary> /// Get Acceleration in MillimeterPerSecondSquared. /// </summary> public double MillimeterPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); /// <summary> /// Get Acceleration in NanometerPerSecondSquared. /// </summary> public double NanometerPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); /// <summary> /// Get Acceleration in InchPerSecondSquared. /// </summary> public double InchPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); /// <summary> /// Get Acceleration in FootPerSecondSquared. /// </summary> public double FootPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); /// <summary> /// Get Acceleration in KnotPerSecond. /// </summary> public double KnotPerSecond => As(AccelerationUnit.KnotPerSecond); /// <summary> /// Get Acceleration in KnotPerMinute. /// </summary> public double KnotPerMinute => As(AccelerationUnit.KnotPerMinute); /// <summary> /// Get Acceleration in KnotPerHour. /// </summary> public double KnotPerHour => As(AccelerationUnit.KnotPerHour); /// <summary> /// Get Acceleration in StandardGravity. /// </summary> public double StandardGravity => As(AccelerationUnit.StandardGravity); /// <summary> /// Get Acceleration in MillistandardGravity. /// </summary> public double MillistandardGravity => As(AccelerationUnit.MillistandardGravity); } }
43.144737
104
0.584629
[ "MIT" ]
AtefeBahrani/EngineeringUnits
EngineeringUnits/CombinedUnits/Acceleration/AccelerationGet.cs
3,279
C#
using BasicShopDemo.Api.Core.DTO; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using System.Web; namespace BasicShopDemo.Api.Core.ModelBinder { public class QueryModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelType == null) { bindingContext.Model = null; return Task.CompletedTask; } NameValueCollection result = HttpUtility.ParseQueryString(bindingContext.HttpContext.Request.QueryString.Value); var query = new Query(); foreach (string key in result.AllKeys.Select(s => s.Trim().ToLower())) { switch (key) { case "$skip": query.Skip = Convert.ToUInt32(result.Get(key)); break; case "$top": query.Take = Convert.ToUInt32(result.Get(key)); break; case "$filter": query.Filter = result.Get(key); break; } } bindingContext.Result = ModelBindingResult.Success(query); return Task.CompletedTask; } } }
30.12766
124
0.536017
[ "MIT" ]
cristofima/BasicShopDemo
src/BasicShopDemo.Api/ModelBinder/QueryModelBinder.cs
1,418
C#
using Marketplace.PaidServices.Messages.Ads; using static Marketplace.EventSourcing.TypeMapper; using static Marketplace.PaidServices.Messages.Orders.Events; namespace Marketplace.PaidServices { public static class EventMappings { public static void MapEventTypes() { Map<V1.OrderCreated>("OrderCreated"); Map<V1.ServiceAddedToOrder>("ServiceAddedToOrder"); Map<V1.ServiceRemovedFromOrder>("ServiceRemovedFromOrder"); Map<Events.V1.Created>("PaidClassifiedAdCreated"); Map<Events.V1.ServiceActivated>("AdServiceActivated"); Map<Events.V1.ServiceDeactivated>("AdServiceDeactivated"); } } }
34.9
71
0.697708
[ "MIT" ]
ChrisDev3110/Hands-On-Domain-Driven-Design-with-.NET-Core
Chapter13/src/Marketplace.PaidServices/EventMappings.cs
698
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. using System; namespace Xtensive.Sql { /// <summary> /// Levels of checking to be done when inserting or updating data through a view. /// </summary> [Serializable] public enum CheckOptions { /// <summary> /// The same as <see cref="None"/>. /// </summary> Default = None, /// <summary> /// None check options are set. /// </summary> None = 0, /// <summary> /// This option is identical to <see cref="Cascaded"/> option except that you can update /// a row so that it no longer can be retrieved through the view. /// This can only happen when the view is directly or indirectly dependent on a view /// that was defined with no WITH CHECK OPTION clause. /// </summary> Local = 1, /// <summary> /// This option specifies that every row that is inserted or updated through the view /// must conform to the definition of the view. In addition, the search conditions /// of all dependent views are checked when a row is inserted or updated. If a row /// does not conform to the definition of the view, that row cannot be retrieved using the view. /// </summary> Cascaded = 2, } }
31.166667
100
0.648587
[ "MIT" ]
DataObjects-NET/dataobjects-net
Orm/Xtensive.Orm/Sql/Model/CheckOptions.cs
1,309
C#
using System; namespace _04.Elevator { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int p = int.Parse(Console.ReadLine()); int courses = (int)Math.Ceiling((double)n / p); Console.WriteLine(courses); } } }
18.722222
59
0.522255
[ "Apache-2.0" ]
kaliopa1983/Programming-Fundamentals
04. PFDataTypesandVariablesLab/04. Elevator/Program.cs
339
C#
using System.Linq; using UnityEngine; using UnityEngine.Events; namespace CustomUnity { /// <summary> /// map string to unityevent, and fire by AnimationEvent or other. /// </summary> [AddComponentMenu("CustomUnity/Named Event")] public class NamedEvent : MonoBehaviour { [System.Serializable] public class NamedUnityEvent { public string name; public UnityEvent @event; } public NamedUnityEvent[] events; public void Fire(string name) { events.FirstOrDefault(x => x.name == name)?.@event.Invoke(); } } }
23.814815
72
0.59409
[ "MIT" ]
SAM-tak/CustomUnity
Assets/CustomUnity/Components/NamedEvent.cs
643
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; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Text; namespace System.Data.SqlClient.SNI { internal sealed class LocalDB { private static readonly LocalDB Instance = new LocalDB(); //HKEY_LOCAL_MACHINE private const string LocalDBInstalledVersionRegistryKey = "SOFTWARE\\Microsoft\\Microsoft SQL Server Local DB\\Installed Versions\\"; private const string InstanceAPIPathValueName = "InstanceAPIPath"; private const string ProcLocalDBStartInstance = "LocalDBStartInstance"; private const int MAX_LOCAL_DB_CONNECTION_STRING_SIZE = 260; private IntPtr _startInstanceHandle = IntPtr.Zero; // Local Db api doc https://msdn.microsoft.com/en-us/library/hh217143.aspx // HRESULT LocalDBStartInstance( [Input ] PCWSTR pInstanceName, [Input ] DWORD dwFlags,[Output] LPWSTR wszSqlConnection,[Input/Output] LPDWORD lpcchSqlConnection); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int LocalDBStartInstance( [In] [MarshalAs(UnmanagedType.LPWStr)] string localDBInstanceName, [In] int flags, [Out] [MarshalAs(UnmanagedType.LPWStr)] StringBuilder sqlConnectionDataSource, [In, Out]ref int bufferLength); private LocalDBStartInstance localDBStartInstanceFunc = null; private volatile SafeLibraryHandle _sqlUserInstanceLibraryHandle; private LocalDB() { } internal static string GetLocalDBConnectionString(string localDbInstance) => Instance.LoadUserInstanceDll() ? Instance.GetConnectionString(localDbInstance) : null; internal static IntPtr GetProcAddress(string functionName) => Instance.LoadUserInstanceDll() ? Interop.Kernel32.GetProcAddress(LocalDB.Instance._sqlUserInstanceLibraryHandle, functionName) : IntPtr.Zero; private string GetConnectionString(string localDbInstance) { StringBuilder localDBConnectionString = new StringBuilder(MAX_LOCAL_DB_CONNECTION_STRING_SIZE + 1); int sizeOfbuffer = localDBConnectionString.Capacity; localDBStartInstanceFunc(localDbInstance, 0, localDBConnectionString, ref sizeOfbuffer); return localDBConnectionString.ToString(); } internal enum LocalDBErrorState { NO_INSTALLATION, INVALID_CONFIG, NO_SQLUSERINSTANCEDLL_PATH, INVALID_SQLUSERINSTANCEDLL_PATH, NONE } internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) { switch (errorState) { case LocalDBErrorState.NO_INSTALLATION: return SNICommon.LocalDBNoInstallation; case LocalDBErrorState.INVALID_CONFIG: return SNICommon.LocalDBInvalidConfig; case LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH: return SNICommon.LocalDBNoSqlUserInstanceDllPath; case LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH: return SNICommon.LocalDBInvalidSqlUserInstanceDllPath; case LocalDBErrorState.NONE: return 0; default: return SNICommon.LocalDBInvalidConfig; } } /// <summary> /// Loads the User Instance dll. /// </summary> private bool LoadUserInstanceDll() { // Check in a non thread-safe way if the handle is already set for performance. if (_sqlUserInstanceLibraryHandle != null) { return true; } lock (this) { if(_sqlUserInstanceLibraryHandle !=null) { return true; } //Get UserInstance Dll path LocalDBErrorState registryQueryErrorState; // Get the LocalDB instance dll path from the registry string dllPath = GetUserInstanceDllPath(out registryQueryErrorState); // If there was no DLL path found, then there is an error. if (dllPath == null) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), string.Empty); return false; } // In case the registry had an empty path for dll if (string.IsNullOrWhiteSpace(dllPath)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBInvalidSqlUserInstanceDllPath, string.Empty); return false; } // Load the dll SafeLibraryHandle libraryHandle = Interop.Kernel32.LoadLibraryExW(dllPath.Trim(), IntPtr.Zero, 0); if (libraryHandle.IsInvalid) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBFailedToLoadDll, string.Empty); libraryHandle.Dispose(); return false; } // Load the procs from the DLLs _startInstanceHandle = Interop.Kernel32.GetProcAddress(libraryHandle, ProcLocalDBStartInstance); if (_startInstanceHandle == IntPtr.Zero) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty); libraryHandle.Dispose(); return false; } // Set the delegate the invoke. localDBStartInstanceFunc = (LocalDBStartInstance)Marshal.GetDelegateForFunctionPointer(_startInstanceHandle, typeof(LocalDBStartInstance)); if (localDBStartInstanceFunc == null) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty); libraryHandle.Dispose(); _startInstanceHandle = IntPtr.Zero; return false; } _sqlUserInstanceLibraryHandle = libraryHandle; return true; } } /// <summary> /// Retrieves the part of the sqlUserInstance.dll from the registry /// </summary> /// <param name="errorState">In case the dll path is not found, the error is set here.</param> /// <returns></returns> private string GetUserInstanceDllPath(out LocalDBErrorState errorState) { string dllPath = null; using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalDBInstalledVersionRegistryKey)) { if (key == null) { errorState = LocalDBErrorState.NO_INSTALLATION; return null; } Version zeroVersion = new Version(); Version latestVersion = zeroVersion; foreach (string subKey in key.GetSubKeyNames()) { Version currentKeyVersion; if (!Version.TryParse(subKey, out currentKeyVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; return null; } if (latestVersion.CompareTo(currentKeyVersion) < 0) { latestVersion = currentKeyVersion; } } // If no valid versions are found, then error out if (latestVersion.Equals(zeroVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; return null; } // Use the latest version to get the DLL path using (RegistryKey latestVersionKey = key.OpenSubKey(latestVersion.ToString())) { object instanceAPIPathRegistryObject = latestVersionKey.GetValue(InstanceAPIPathValueName); if (instanceAPIPathRegistryObject == null) { errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH; return null; } RegistryValueKind valueKind = latestVersionKey.GetValueKind(InstanceAPIPathValueName); if (valueKind != RegistryValueKind.String) { errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH; return null; } dllPath = (string)instanceAPIPathRegistryObject; errorState = LocalDBErrorState.NONE; return dllPath; } } } } }
41.482301
174
0.594987
[ "MIT" ]
Larhwally/corefx
src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs
9,375
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchBodyGetArgs : Pulumi.ResourceArgs { public WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchBodyGetArgs() { } } }
37.05
191
0.805668
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchBodyGetArgs.cs
741
C#
using Data.Common; using Microsoft.Extensions.Configuration; using System; using System.Runtime.InteropServices; namespace Test.Data { public static class GrepAdminDataHelper { private static string GetConfigSection(string section, string property) { var env = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "Docker" : AppEnvironment.Development.ToString(); var configuration = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env}.json", optional: true) .Build(); var value = configuration.GetSection(section) .GetValue<string>(property); return value; } public static Guid SystemUserId => new Guid(GetConfigSection("AppSettings", "SystemUserId")); public static string DbConnectionString => GetConfigSection("ConnectionStrings", "Connection"); } }
33
103
0.598485
[ "MIT" ]
odinr/codin
docs/static/code-highlight/test.cs
1,188
C#
namespace Netch.Models.Config { public class ProcessMode { /// <summary> /// 伪造 ICMP 延迟 /// </summary> [Newtonsoft.Json.JsonProperty("icmping")] public int Icmping = 1; /// <summary> /// 仅劫持规则内进程 /// </summary> [Newtonsoft.Json.JsonProperty("dnsOnly")] public bool DNSOnly = false; /// <summary> /// 远程 DNS 查询 /// </summary> [Newtonsoft.Json.JsonProperty("dnsProx")] public bool DNSProx = true; /// <summary> /// DNS 地址 /// </summary> [Newtonsoft.Json.JsonProperty("dnsHost")] public string DNSHost = "1.1.1.1"; /// <summary> /// DNS 端口 /// </summary> [Newtonsoft.Json.JsonProperty("dnsPort")] public ushort DNSPort = 53; } }
24.944444
50
0.467706
[ "MIT" ]
esmivn/netch
Netch/Models/Config/ProcessMode.cs
940
C#
// Copyright (c) 2020 Nathan Williams. All rights reserved. // Licensed under the MIT license. See LICENCE file in the project root // for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; [module: SkipLocalsInit] namespace ApiDump { /* TODO: The following need to be handled correctly: * - Type names should be qualified where ambiguous or nested and not in scope. * - Add option to control whether forwarded types are hidden, listed, or defined. * - Some attributes should be displayed. * + Use command line options to explicitly show or hide specific attributes. * + Need to support attributes that compile into IL metadata, such as StructLayout. * + There should be a default list of known attributes that are shown/hidden. * ~ Includes attributes that visibly affect consumers, like Obsolete, etc. * ~ Excludes attributes that should be implementation details. * ~ Includes nullability attributes like AllowNull only if not --no-nullable. * ~ Allow specifying default for unknown attributes. * - C# 9 features: * + Unmanaged calling convention methods. * + Records (distinguished from classes with ITypeSymbol.IsRecord). * - C# 10 features: * + Record structs. * + Reevaluate when 10.0 leaves preview. */ static class Program { private static bool showAllInterfaces; private static bool showUnsafeValueTypes; internal static bool ShowNullable { get; private set; } = true; static int Main(string[] args) { var dlls = new FList<string>(args.Length); bool useInternalBCL = true; foreach (string arg in args) { if (arg.StartsWith('-')) { switch (arg) { case "--no-bcl": useInternalBCL = false; break; case "--all-interfaces": showAllInterfaces = true; break; case "--show-array-structs": showUnsafeValueTypes = true; break; case "--no-nullable": ShowNullable = false; break; case "-h": case "--help": PrintHelp(); return 0; case "-v": case "--version": if (args.Contains("--help")) goto case "--help"; PrintVersion(); return 0; default: Console.Error.WriteLine("Error: Unknown option '{0}'", arg); return 1; } } else { dlls.Add(arg); } } if (dlls.Count == 0) { Console.Error.WriteLine("Error: No input files. Use --help to show usage."); return 1; } try { var refs = new FList<MetadataReference>(4 + dlls.Count); foreach (string path in dlls) { try { refs.Add(MetadataReference.CreateFromFile(path)); } catch (ArgumentException) { Console.Error.WriteLine("Error: Invalid file path: '{0}'", path); return 1; } catch (FileNotFoundException) { Console.Error.WriteLine("Error: File not found: '{0}'", path); return 1; } catch (IOException e) { Console.Error.WriteLine("Error: Failed to open '{0}': {1}", path, e.Message); return 1; } catch (BadImageFormatException) { Console.Error.WriteLine("Error: File is not a valid IL assembly: '{0}'", path); return 1; } } if (useInternalBCL) { using var zip = new ZipArchive( typeof(Program).Assembly.GetManifestResourceStream("ApiDump.DummyBCL.zip")!); foreach (var entry in zip.Entries) { // CreateFromStream() requires a seekable stream for some reason. // ZipArchiveEntry streams are not, so we need to copy. using var memStream = new MemoryStream((int)entry.Length); using (var zipStream = entry.Open()) zipStream.CopyTo(memStream); memStream.Position = 0; refs.Add(MetadataReference.CreateFromStream(memStream)); } } var comp = CSharpCompilation.Create("dummy", null, refs, new(OutputKind.DynamicallyLinkedLibrary)); var diagnostics = comp.GetDiagnostics(); if (!diagnostics.IsDefaultOrEmpty) { Console.Error.WriteLine("Warning: Compilation has diagnostics:"); foreach (var diagnostic in diagnostics) Console.Error.WriteLine(diagnostic); } var globalNamespaces = comp.GlobalNamespace.ConstituentNamespaces; if (globalNamespaces.Length != refs.Count + 1) { throw new($"Unexpected number of global namespaces: {globalNamespaces.Length}"); } if (!SymbolEqualityComparer.Default.Equals( globalNamespaces[0], comp.Assembly.GlobalNamespace)) { throw new("Unexpected first global namespace:" + $" {globalNamespaces[0].ContainingAssembly.Name}"); } for (int i = 1; i <= dlls.Count; ++i) { PrintNamespace(globalNamespaces[i]); } } catch (Exception ex) { Console.Error.WriteLine("Error: {0}", ex); return -1; } return 0; } private static void PrintVersion(Assembly? assembly = null) { assembly ??= typeof(Program).Assembly; var attribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>(); Console.WriteLine($"{nameof(ApiDump)} version {{0}}", attribute?.InformationalVersion ?? assembly.GetName().Version!.ToString(3)); var copyright = assembly.GetCustomAttribute<AssemblyCopyrightAttribute>(); if (copyright is not null) { Console.WriteLine(copyright.Copyright.Replace("\u00A9", "(C)", StringComparison.Ordinal)); } } public static bool StartsWith(this ReadOnlySpan<char> span, char value) => !span.IsEmpty && span[0] == value; private static void PrintHelp() { var assembly = typeof(Program).Assembly; PrintVersion(assembly); Console.WriteLine(); Console.WriteLine("Usage: {0} [options] <dllpaths>...", assembly.GetName().Name); string readme; using (var stream = assembly.GetManifestResourceStream($"{nameof(ApiDump)}.README.md")) { if (stream is null) return; if (stream is MemoryStream ms && ms.TryGetBuffer(out var msBuffer)) { // Optimistic case that avoids an extra copy/buffering layer. // Realistically only one of these paths should ever be used on any // given runtime, but it can't hurt to have both this and a fallback. readme = Encoding.UTF8.GetString(msBuffer); } else { using var reader = new StreamReader(stream, Encoding.UTF8, false); readme = reader.ReadToEnd(); } } int start = 1 + readme.IndexOf('\n', 9 + readme.IndexOf("# Options", StringComparison.Ordinal)); readme = readme[start..].Replace("`", "", StringComparison.Ordinal); readme = Regex.Replace(readme, @"\[([^\]]*)\]\([^\)]*\)", "$1").Trim(); Console.WriteLine(); Console.WriteLine("Options:"); int width = Math.Max(Console.WindowWidth, 80) - 6; foreach (string para in Regex.Split(readme, @"\s*\n(?:\s*\n)+\s*", RegexOptions.ECMAScript)) { if (para.AsSpan().TrimStart().StartsWith('-')) { // Option line, eg: "- `-h`, `--help`" Console.WriteLine(); Console.Write(" "); Console.Out.WriteLine(para.AsSpan(1 + para.IndexOf('-', StringComparison.Ordinal)).Trim()); } else if (!para.Contains('\n', StringComparison.Ordinal)) { // Single-line option description Console.WriteLine(); Console.Write(" "); Console.Out.WriteLine(para.AsSpan().Trim()); } else { // Multi-line option description int pos = width; foreach (var word in new SpanSplitter(para)) { if (pos + 1 + word.Length > width) { Console.WriteLine(); Console.Write(" "); Console.Out.Write(word); pos = word.Length; } else { Console.Write(' '); Console.Out.Write(word); pos += 1 + word.Length; } } Console.WriteLine(); } } } private static bool emptyBlockOpen; private static void PrintLine(string line, int indent, bool openBlock = false) { if (emptyBlockOpen) { Console.WriteLine(); for (int i = 1; i < indent; ++i) Console.Write(" "); Console.WriteLine('{'); } for (int i = 0; i < indent; ++i) Console.Write(" "); Console.Write(line); if (!(emptyBlockOpen = openBlock)) { Console.WriteLine(); } } private static void PrintEndBlock(int indent) { if (emptyBlockOpen) { Console.WriteLine(" { }"); emptyBlockOpen = false; } else { for (int i = 0; i < indent; ++i) Console.Write(" "); Console.WriteLine('}'); } } private static readonly Func<ISymbol?, ISymbol?> identity = static s => s; private static IOrderedEnumerable<T> Sort<T>(IEnumerable<T> symbols) where T : class?, ISymbol? => symbols.OrderBy<T, ISymbol?>(identity, MemberOrdering.Comparer); private static void PrintNamespace(INamespaceSymbol ns) { bool printed = false; bool isGlobal = ns.IsGlobalNamespace; foreach (var type in Sort(ns.GetTypeMembers())) { if (type.DeclaredAccessibility == Accessibility.Public) { if (!printed && !isGlobal) { var sb = new StringBuilder("namespace ", 64); AppendName(sb, ns); PrintLine(sb.ToString(), 0); PrintLine("{", 0); printed = true; } PrintType(type, isGlobal ? 0 : 1); } } if (printed) PrintLine("}", 0); foreach (var subNs in ns.GetNamespaceMembers().OrderBy(static t => t.MetadataName)) { PrintNamespace(subNs); } static void AppendName(StringBuilder sb, INamespaceSymbol ns) { var parent = ns.ContainingNamespace; if (parent is not null && !parent.IsGlobalNamespace) { AppendName(sb, parent); sb.Append('.'); } sb.Append(ns.Name); } } private static void PrintType(INamedTypeSymbol type, int indent) { var sb = new StringBuilder(); switch (type.DeclaredAccessibility) { case Accessibility.Public: sb.Append("public "); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: sb.Append("protected "); break; default: throw new($"Type {type} has unexpected visibility {type.DeclaredAccessibility}"); } var kind = type.TypeKind; switch (kind) { case TypeKind.Class: if (type.IsStatic) sb.Append("static "); else if (type.IsAbstract) sb.Append("abstract "); else if (type.IsSealed) sb.Append("sealed "); sb.Append("class "); sb.Append(type.Name); break; case TypeKind.Struct: if (!showUnsafeValueTypes && type.IsUnsafeValueType()) return; if (type.IsReadOnly) sb.Append("readonly "); if (type.IsRefLikeType) sb.Append("ref "); sb.Append("struct "); sb.Append(type.Name); break; case TypeKind.Interface: sb.Append("interface "); sb.Append(type.Name); break; case TypeKind.Enum: sb.Append("enum "); sb.Append(type.Name); var underlyingType = type.EnumUnderlyingType; if (underlyingType is not null) { sb.Append(" : "); sb.AppendType(underlyingType); } PrintLine(sb.ToString(), indent, openBlock: true); foreach (var member in Sort(type.GetMembers())) { if (member is IFieldSymbol field) { sb.Clear(); sb.Append(field.Name); sb.Append(" = "); sb.AppendConstant(field.ConstantValue, underlyingType); sb.Append(','); PrintLine(sb.ToString(), indent + 1); } } PrintEndBlock(indent); return; case TypeKind.Delegate: var invokeMethod = type.DelegateInvokeMethod; if (invokeMethod is null) { throw new($"Delegate type has null invoke method: {type}"); } sb.Append("delegate "); sb.AppendReturnSignature(invokeMethod); sb.Append(' '); sb.Append(type.Name); sb.AppendTypeParameters(type.TypeParameters, out var delegateConstraints); sb.AppendParameters(invokeMethod.Parameters); sb.AppendTypeConstraints(delegateConstraints); sb.Append(';'); PrintLine(sb.ToString(), indent); return; default: throw new($"Named type {type} has unexpected kind {kind}"); } sb.AppendTypeParameters(type.TypeParameters, out var constraints); FList<INamedTypeSymbol> bases = default; if (kind == TypeKind.Class) { var baseType = type.BaseType; if (baseType is not null && baseType.SpecialType != SpecialType.System_Object) { bases.Add(baseType); } } foreach (var iface in Sort(type.Interfaces)) { if (!showAllInterfaces) { // Don't add an interface inherited by one already added. foreach (var t in bases) { if (t.Interfaces.Contains(iface, SymbolEqualityComparer.Default)) { continue; } } // Remove any previously added interfaces inherited by the one we're adding now. var inherited = iface.Interfaces; for (int firstToRemove = 0; firstToRemove < bases.Count; ++firstToRemove) { if (inherited.Contains(bases[firstToRemove], SymbolEqualityComparer.Default)) { int pos = firstToRemove; while (++pos < bases.Count) { var current = bases[pos]; if (!inherited.Contains(current, SymbolEqualityComparer.Default)) { bases[firstToRemove++] = current; } } bases.TrimEnd(firstToRemove); break; } } } bases.Add(iface); } for (int i = 0; i < bases.Count; ++i) { sb.Append(i == 0 ? " : " : ", "); sb.AppendType(bases[i]); } sb.AppendTypeConstraints(constraints); PrintLine(sb.ToString(), indent, openBlock: true); foreach (var member in Sort(type.GetMembers())) { PrintMember(member, indent + 1); } PrintEndBlock(indent); } private static bool IsWellKnownConversionName(string name, [NotNullWhen(true)] out string? keyword) { switch (name) { case WellKnownMemberNames.ExplicitConversionName: keyword = "explicit"; break; case WellKnownMemberNames.ImplicitConversionName: keyword = "implicit"; break; default: keyword = null; return false; } return true; } private static readonly Dictionary<string, string> operators = new() { [WellKnownMemberNames.AdditionOperatorName] = "+", [WellKnownMemberNames.BitwiseAndOperatorName] = "&", [WellKnownMemberNames.BitwiseOrOperatorName] = "|", [WellKnownMemberNames.DecrementOperatorName] = "--", [WellKnownMemberNames.DivisionOperatorName] = "/", [WellKnownMemberNames.EqualityOperatorName] = "==", [WellKnownMemberNames.ExclusiveOrOperatorName] = "^", [WellKnownMemberNames.FalseOperatorName] = "false", [WellKnownMemberNames.GreaterThanOperatorName] = ">", [WellKnownMemberNames.GreaterThanOrEqualOperatorName] = ">=", [WellKnownMemberNames.IncrementOperatorName] = "++", [WellKnownMemberNames.InequalityOperatorName] = "!=", [WellKnownMemberNames.LeftShiftOperatorName] = "<<", [WellKnownMemberNames.LessThanOperatorName] = "<", [WellKnownMemberNames.LessThanOrEqualOperatorName] = "<=", [WellKnownMemberNames.LogicalNotOperatorName] = "!", [WellKnownMemberNames.ModulusOperatorName] = "%", [WellKnownMemberNames.MultiplyOperatorName] = "*", [WellKnownMemberNames.OnesComplementOperatorName] = "~", [WellKnownMemberNames.RightShiftOperatorName] = ">>", [WellKnownMemberNames.SubtractionOperatorName] = "-", [WellKnownMemberNames.TrueOperatorName] = "true", [WellKnownMemberNames.UnaryNegationOperatorName] = "-", [WellKnownMemberNames.UnaryPlusOperatorName] = "+", }; private static void PrintMember(ISymbol member, int indent) { var containingType = member.ContainingType; var containingTypeKind = containingType.TypeKind; MethodKind methodKind = default; if (member is IMethodSymbol m) { methodKind = m.MethodKind; switch (methodKind) { case MethodKind.Destructor: PrintLine($"~{containingType.Name}();", indent); return; case MethodKind.Constructor: if (containingTypeKind == TypeKind.Struct && m.IsImplicitlyDeclared && m.Parameters.IsDefaultOrEmpty) { return; } break; case MethodKind.StaticConstructor: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: return; } var explicitImpls = m.ExplicitInterfaceImplementations; if (!explicitImpls.IsDefaultOrEmpty) { foreach (var impl in explicitImpls) { PrintExplicitImplementation(m, impl, indent); } if (!m.CanBeReferencedByName) return; } } else if (member is IEventSymbol eventSymbol) { var explicitImpls = eventSymbol.ExplicitInterfaceImplementations; if (!explicitImpls.IsDefaultOrEmpty) { foreach (var impl in explicitImpls) { PrintExplicitImplementation(eventSymbol, impl, indent); } if (!eventSymbol.CanBeReferencedByName) return; } } else if (member is IPropertySymbol property) { var explicitImpls = property.ExplicitInterfaceImplementations; if (!explicitImpls.IsDefaultOrEmpty) { foreach (var impl in explicitImpls) { PrintExplicitImplementation(property, impl, indent); } if (!property.CanBeReferencedByName) return; } } var sb = new StringBuilder(); bool inInterface = containingTypeKind == TypeKind.Interface; switch (member.DeclaredAccessibility) { case Accessibility.Public: // Try to use pre-8.0 C# syntax for interface members wherever possible. // This means that for public abstract members, we hide these modifiers, // as they are implied and previously could not be made explicit. if (!inInterface || !member.IsAbstract) sb.Append("public "); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: sb.Append("protected "); break; case Accessibility.Private: case Accessibility.ProtectedAndInternal: case Accessibility.Internal: return; case Accessibility.NotApplicable when inInterface: break; default: throw new($"{member.Kind} member has unexpected" + $" visibility {member.DeclaredAccessibility}: {member}"); } bool inMutableStruct = containingTypeKind == TypeKind.Struct && !containingType.IsReadOnly && !member.IsStatic; switch (member) { case INamedTypeSymbol nestedType: PrintType(nestedType, indent); break; case IFieldSymbol field: bool isFixed = field.IsFixedSizeBuffer; if (isFixed) { sb.Append("fixed "); } else if (field.IsConst) { sb.Append("const "); } else { if (field.IsStatic) sb.Append("static "); if (field.IsReadOnly) sb.Append("readonly "); else if (field.IsVolatile) sb.Append("volatile "); } var type = field.Type; if (isFixed) { sb.AppendType(((IPointerTypeSymbol)type).PointedAtType); } else { sb.AppendType(type); } sb.Append(' '); sb.Append(field.Name); if (isFixed) { sb.Append('['); sb.Append(field.FixedSize); sb.Append(']'); } else if (field.HasConstantValue) { sb.Append(" = "); sb.AppendConstant(field.ConstantValue, type); } sb.Append(';'); PrintLine(sb.ToString(), indent); break; case IEventSymbol eventSymbol: bool showAccessors = false; bool? addIsReadOnly = null, removeIsReadOnly = null; if (inMutableStruct) { addIsReadOnly = eventSymbol.AddMethod?.IsReadOnly; removeIsReadOnly = eventSymbol.RemoveMethod?.IsReadOnly; switch ((addIsReadOnly, removeIsReadOnly)) { case (true, true): case (true, null): case (null, true): sb.Append("readonly "); break; case (true, false): case (false, true): // Although not allowed in C#, it is technically possible in IL // to mark add/remove accessors individually as readonly. // Show this case using accessor syntax similar to properties. showAccessors = true; break; } } sb.AppendCommonModifiers(eventSymbol, false); sb.Append("event "); sb.AppendType(eventSymbol.Type); sb.Append(' '); sb.Append(eventSymbol.Name); if (showAccessors) { sb.Append(" { "); if (addIsReadOnly.GetValueOrDefault()) sb.Append("readonly "); sb.Append("add; "); if (removeIsReadOnly.GetValueOrDefault()) sb.Append("readonly "); sb.Append("remove; }"); } else { sb.Append(';'); } PrintLine(sb.ToString(), indent); break; case IMethodSymbol method: switch (methodKind) { case MethodKind.Constructor: sb.Append(containingType.Name); sb.AppendParameters(method.Parameters); sb.Append(';'); PrintLine(sb.ToString(), indent); return; case MethodKind.Ordinary: case MethodKind.Conversion: case MethodKind.UserDefinedOperator: if (inMutableStruct && method.IsReadOnly) sb.Append("readonly "); sb.AppendCommonModifiers(method, false); string name = method.Name; if (methodKind == MethodKind.Conversion && IsWellKnownConversionName(name, out var keyword)) { sb.Append(keyword); sb.Append(" operator "); sb.AppendType(method.ReturnType); } else { sb.AppendReturnSignature(method); sb.Append(' '); if (methodKind == MethodKind.UserDefinedOperator && operators.TryGetValue(name, out var opToken)) { sb.Append("operator "); sb.Append(opToken); } else { sb.Append(name); } } sb.AppendTypeParameters(method.TypeParameters, out var constraints); sb.AppendParameters(method.Parameters, method.IsExtensionMethod); sb.AppendTypeConstraints(constraints); sb.Append(';'); PrintLine(sb.ToString(), indent); break; default: throw new($"Unexpected method kind {methodKind}: {method}"); } break; case IPropertySymbol property: var getter = property.GetMethod; var setter = property.SetMethod; if (inMutableStruct && getter?.IsReadOnly != false && (setter is null or { IsInitOnly: true } or { IsReadOnly: true })) { // All non-init accessors are readonly, so display the keyword on the property. // Unsetting inMutableStruct prevents duplicating it onto the accessors. sb.Append("readonly "); inMutableStruct = false; } sb.AppendCommonModifiers(property, false); if (property.ReturnsByRefReadonly) sb.Append("ref readonly "); else if (property.ReturnsByRef) sb.Append("ref "); sb.AppendType(property.Type); sb.Append(' '); if (property.IsIndexer) { sb.Append("this"); sb.AppendParameters(property.Parameters, false, '[', ']'); } else { sb.Append(property.Name); } sb.Append(" { "); if (getter is not null) { sb.AppendAccessor(false, getter, property, inMutableStruct); } if (setter is not null) { sb.AppendAccessor(true, setter, property, inMutableStruct); } sb.Append('}'); PrintLine(sb.ToString(), indent); break; default: throw new($"Unexpected member kind {member.Kind}: {member}"); } } private static void PrintExplicitImplementation( IMethodSymbol method, IMethodSymbol implemented, int indent) { var sb = new StringBuilder(); sb.AppendCommonModifiers(method, true); sb.AppendReturnSignature(method); sb.Append(' '); sb.AppendType(implemented.ContainingType); sb.Append('.'); sb.Append(implemented.Name); sb.AppendTypeParameters(method.TypeParameters, out var constraints); sb.AppendParameters(method.Parameters, method.IsExtensionMethod); sb.AppendTypeConstraints(constraints); sb.Append(';'); PrintLine(sb.ToString(), indent); } private static void PrintExplicitImplementation( IPropertySymbol property, IPropertySymbol implemented, int indent) { var sb = new StringBuilder(); sb.AppendCommonModifiers(property, true); if (property.ReturnsByRefReadonly) sb.Append("ref readonly "); else if (property.ReturnsByRef) sb.Append("ref "); sb.AppendType(property.Type); sb.Append(' '); sb.AppendType(implemented.ContainingType); sb.Append('.'); if (property.IsIndexer) { sb.Append("this"); sb.AppendParameters(property.Parameters, false, '[', ']'); } else { sb.Append(implemented.Name); } sb.Append(" { "); var getter = property.GetMethod; if (getter is not null) { sb.AppendAccessor(false, getter, property, false); } var setter = property.SetMethod; if (setter is not null) { sb.AppendAccessor(true, setter, property, false); } sb.Append('}'); PrintLine(sb.ToString(), indent); } private static void PrintExplicitImplementation( IEventSymbol eventSymbol, IEventSymbol implemented, int indent) { var sb = new StringBuilder(); sb.AppendCommonModifiers(eventSymbol, true); sb.Append("event "); sb.AppendType(eventSymbol.Type); sb.Append(' '); sb.AppendType(implemented.ContainingType); sb.Append('.'); sb.Append(implemented.Name); sb.Append(';'); PrintLine(sb.ToString(), indent); } // TODO: Generalise this attribute handling code. private static bool IsSystem(INamespaceSymbol? ns) { if (ns is null || ns.IsGlobalNamespace || ns.Name != "System") return false; ns = ns.ContainingNamespace; return ns is null || ns.IsGlobalNamespace; } public static bool IsCompilerServices(INamespaceSymbol? ns) { if (ns is null || ns.IsGlobalNamespace || ns.Name != "CompilerServices") return false; ns = ns.ContainingNamespace; if (ns is null || ns.IsGlobalNamespace || ns.Name != "Runtime") return false; return IsSystem(ns.ContainingNamespace); } public static bool IsUnsafeValueType(this INamedTypeSymbol structType) { foreach (var attr in structType.GetAttributes()) { var type = attr.AttributeClass; if (type is not null && type.Name == "UnsafeValueTypeAttribute" && IsCompilerServices(type.ContainingNamespace) && type.Arity == 0 && type.ContainingType is null) { return true; } } return false; } public static bool IsFlagsEnum(this INamedTypeSymbol enumType) { foreach (var attr in enumType.GetAttributes()) { var type = attr.AttributeClass; if (type is not null && type.Name == "FlagsAttribute" && IsSystem(type.ContainingNamespace) && type.Arity == 0 && type.ContainingType is null) { return true; } } return false; } } }
41.131991
111
0.473322
[ "MIT" ]
Naine/api-dump
ApiDump/Program.cs
36,772
C#
/* * Henry C Reeves IV * Home.aspx.cs * Due: December 6 , 2017 * * This is Signup.aspx.cs, this is where the user an sign up for our page. It * is impossible for a user to signup as an Admin unless the administator goes * to the database and adds himeself/herself. There is a password format requirement. */ using System; using System.Collections.Generic; using System.Linq; using System.Data.Sql; using System.Data.SqlClient; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CoastalBendKidneyFoundation { public partial class Signup : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { bool pass = false; bool passwordStatus = checkPassword(); // If username doesn't exist already and password is in correct format if (check() == false && passwordStatus) { pass = true; } // Otherwise, do nothing and inform user else if (passwordStatus == false) { pass = false; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Password is not in the correct format. Must begin with a letter, " + "include a uppercase letter, lowercase letter, " + "and a digit. Passwords should at least be 8 characters long.')", true); } // Checking to see if everything is correct if (pass) { SqlConnection db = new SqlConnection(SqlDataSource1.ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = "INSERT INTO [User] (User_Username, User_Password, User_Email, User_FName, User_LName, User_Country) VALUES ('" + txtUsername.Text + "', '" + txtPassword.Text + "', '" + txtEmail.Text + "', '" + txtFirstname.Text + "', '" + txtLastname.Text + "', '" + txtCountry.Text + "')"; cmd.Connection = db; // Trying to execute sql statement to insert a user to the User table try { db.Open(); // Opening connection cmd.ExecuteNonQuery(); // executing command pass = true; // success } catch (System.Data.SqlClient.SqlException ex) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Error: Database error occured.')", true); pass = false; // failed } // Closing the database connection finally { db.Close(); } // If inserition was successful if (pass) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Registration successful! Try logging in.')", true); // This will not show up for some reason, I do not know why.... Response.Redirect("Login.aspx"); } } } // This function checks to see if the password is in the correct format public bool checkPassword() { bool correctForm = false; string password = txtPassword.Text; //Passwords should begin with a letter, should include an uppercase letter, a lowercase letter and a digit. if (Char.IsLetter(password[0])) { if (password.Any(Char.IsUpper)) { if (password.Any(Char.IsLower)) { if (password.Any(Char.IsDigit)) { if (password.Length >= 8) { correctForm = true; } else { correctForm = false; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Passwords should begin with a letter, should include an uppercase letter , a lowercase letter and a digit.')", true); } } else { correctForm = false; } } else { correctForm = false; } } else { correctForm = false; } } else { correctForm = false; } return correctForm; } // Checking to see if username already exists public bool check() { SqlConnection db = new SqlConnection(SqlDataSource1.ConnectionString); bool pass = false; string username = txtUsername.Text; // Checking to see if username already exists try { // Creating sql command SqlCommand check = new SqlCommand(); check.CommandText = "select * from [User]"; check.Connection = db; db.Open(); SqlDataReader dr = check.ExecuteReader(); // Checking to see if username exists while (dr.Read()) { if (dr[1].ToString() == username) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('This username already Exists.')", true); pass = true; break; } } } catch { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Error trying to execute command into database, this is in check.')", true); pass = false; } finally { db.Close(); } return pass; } // Takes the user to Login.aspx if they already have an account protected void LinkButton1_Click(object sender, EventArgs e) { Response.Redirect("Login.aspx"); } } }
35.823529
309
0.487386
[ "MIT" ]
nwright3/KidneyFoundationTest
CoastalBendKidneyFoundation/CoastalBendKidneyFoundation/Signup.aspx.cs
6,701
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace HUD.Data.Migrations { public partial class AddOrgNameToUserSettings : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "OrgName", table: "userSettings", type: "nvarchar(max)", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "OrgName", table: "userSettings"); } } }
26.958333
71
0.574961
[ "MIT" ]
kysu1313/Ticket-Dashboard-2
Data/Migrations/20210506004743_AddOrgNameToUserSettings.cs
649
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.ObjectModel; using System.ServiceModel; // Neighbor interface interface IPeerNeighbor : IExtensibleObject<IPeerNeighbor> { bool IsConnected { get; } // True if the neighbor is connected PeerNodeAddress ListenAddress { get; set; } // Neighbor's listen address bool IsInitiator { get; } ulong NodeId { get; set; } // NodeID of the neighboring node PeerNeighborState State { get; set; } bool IsClosing { get; } IAsyncResult BeginSend(Message message, AsyncCallback callback, object state); IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state); void EndSend(IAsyncResult result); void Send(Message message); bool TrySetState(PeerNeighborState state); void Abort(PeerCloseReason reason, PeerCloseInitiator initiator); Message RequestSecurityToken(Message request); void Ping(Message request); UtilityExtension Utility { get; } } // Neighbor states // If add new states, carefully consider where they should occur in state transition and make // appropriate changes to PeerNeighbor implementation. enum PeerNeighborState { Created, Opened, Authenticated, Connecting, Connected, Disconnecting, Disconnected, Faulted, Closed, } static class PeerNeighborStateHelper { // Returns true if the specified state can be set for the neighbor public static bool IsSettable(PeerNeighborState state) { return ( (state == PeerNeighborState.Authenticated) || (state == PeerNeighborState.Connecting) || (state == PeerNeighborState.Connected) || (state == PeerNeighborState.Disconnecting) || (state == PeerNeighborState.Disconnected)); } // Returns true if the specified state is a "connected" state public static bool IsConnected(PeerNeighborState state) { return ((state == PeerNeighborState.Connected)); } // Returns true if the specified state is either authenticated or closing public static bool IsAuthenticatedOrClosed(PeerNeighborState state) { return ((state == PeerNeighborState.Authenticated) || (state == PeerNeighborState.Faulted) || (state == PeerNeighborState.Closed)); } } }
37.972973
104
0.603203
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/Channels/IPeerNeighbor.cs
2,810
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatement { /// <summary> /// Part of a web request that you want AWS WAF to inspect. See Field to Match below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch? FieldToMatch; /// <summary> /// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details. /// </summary> public readonly ImmutableArray<Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformation> TextTransformations; [OutputConstructor] private WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatement( Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch? fieldToMatch, ImmutableArray<Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformation> textTransformations) { FieldToMatch = fieldToMatch; TextTransformations = textTransformations; } } }
52.916667
200
0.793176
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatement.cs
1,905
C#
using Spoondrift.Code.PlugIn; using Spoondrift.Code.Util; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Microsoft.Extensions.DependencyInjection; using Spoondrift.Code.Dapper; using Dapper; using Spoondrift.Code.Config.Form; using System.Globalization; using Microsoft.AspNetCore.Http; namespace Spoondrift.Code.Data { public abstract class BaseDataTableSource : ListDataTable { public const string REG_NAME = "DataTableSource"; public const string PAGE_SQL = "select * from {2} WHERE 1=1 {3} limit @skip,@pageSize"; private string fRegName; private string fPrimaryKey; /// <summary> /// 请求上下文 获取当前登录人信息使用 /// </summary> protected IHttpContextAccessor httpContextAccessor { get; } private IUnitOfDapper fDbContext; protected IServiceProvider provider; public BaseDataTableSource(IServiceProvider serviceProvider) { provider = serviceProvider; httpContextAccessor = provider.GetService<IHttpContextAccessor>(); //PageItems = AppContext.Current.PageFlyweight.PageItems; //if (!DataXmlPath.IsEmpty()) // DataFormConfig = DataXmlPath.PlugInPageGet<DataFormConfig>(); } #region Unique private bool HasOnlyUniqueColumns(DataRow row, List<ObjectDataView> updateDataViewList) { string _key = row[PrimaryKey].ToString(); var _odv = updateDataViewList.FirstOrDefault(a => a.KeyId == _key); if (_odv != null) { var _colColumns = GetModifyColumnName(_odv.objectData); _colColumns.ForEach(a => { row[a] = _odv.objectData.Row[a]; }); return true; //_odv.objectData.MODEFY_COLUMNS.Contains( } return false; } private List<string> GetModifyColumnName(ObjectData od) { List<string> strs = new List<string>(); foreach (string str in od.MODEFY_COLUMNS) { var _str = UniqueList.FirstOrDefault(a => a == str); if (!_str.IsEmpty()) { strs.Add(_str); } } // Debug.ThrowImpossibleCode(this); return strs; } private bool HasAllUniqueColumns(ObjectData od) { //---------- foreach (string uniStr in UniqueList) { bool _is = od.MODEFY_COLUMNS.Contains(uniStr); // bool _isB = od.MODEFY_COLUMNS.Contains(uniStr); // if (_is && _isB) return true; if (!_is) return false; } return true; } private List<string> GetColumnTexts(DataRow row) { return UniqueList.Select(a => { //string _str = row[a].ToString(); var _col = DataFormConfig.Columns.FirstOrDefault(b => b.Name == a); // if (_col) return _col.GetValue(row, provider); // return _str; } ).ToList(); } private List<string> GetColumnValues(DataRow row) { return UniqueList.Select(a => { string _str = row[a].ToString(); //var _col = DataFormConfig.Columns.FirstOrDefault(b => b.Name == a); // if(_col) // return _col.GetValue(row); return _str; } ).ToList(); } private string fColumnDisPlayName; private string GetColumnDisPlayName() { if (fColumnDisPlayName.IsEmpty()) { var _l = DataFormConfig.Columns.FindAll(a => UniqueList.Contains(a.Name)).Select(a => a.DisplayName).ToList(); fColumnDisPlayName = String.Join(", ", _l); } return fColumnDisPlayName; } // private List<string> GetList public virtual string CheckUniqueFilterSql { get; set; } public void CheckUnique(List<ObjectDataView> insertDataViewList, List<ObjectDataView> updateDataViewList, List<string> deleteStringList) { string _columSelect = String.Join(",", UniqueList); // var _updateObjs = updateDataViewList.FindAll(a => HasAllUniqueColumns(a.objectData)); // var _updateIds = updateDataViewList.Select(a => a.KeyId); // deleteStringList.AddRange(_updateIds); if (CheckUniqueFilterSql.IsEmpty()) { CheckUniqueFilterSql = " 1 = 1"; } string _strSql = "SELECT {0},{1} FROM {2} WHERE ({3}) ".SFormat(PrimaryKey, _columSelect, RegName, CheckUniqueFilterSql); var _sqlCmd = SqlUtil.SqlByNotAnd(_strSql, PrimaryKey, deleteStringList); DataSet ds = _sqlCmd.QueryDataSet(DbContext); UniqueRowArrange list = new UniqueRowArrange(); foreach (DataRow row in ds.Tables[0].Rows) { HasOnlyUniqueColumns(row, updateDataViewList); //----------- var _isCheck = list.CheckInsert(new UniqueRow(GetColumnValues(row).ToArray())); if (!_isCheck) { string str = " {0} : {1} ".SFormat(GetColumnDisPlayName(), String.Join(",", GetColumnTexts(row))); ThrowUniError(str); } } //--------------xxxxxxxx--------------------------- // insertDataViewList. insertDataViewList.ForEach(a => { if (!ForeignKeyValue.IsEmpty() && UniqueList.Contains(ForeignKey)) { if (!a.objectData.Row.Table.Columns.Contains(ForeignKey)) { a.objectData.Row.Table.Columns.Add(ForeignKey); } a.objectData.Row[ForeignKey] = ForeignKeyValue; } var _isCheck = list.CheckInsert(new UniqueRow(GetColumnValues(a.objectData.Row).ToArray())); if (!_isCheck) { string str = " {0} : {1} ".SFormat(GetColumnDisPlayName(), String.Join(",", GetColumnTexts(a.objectData.Row))); ThrowUniError(str); //ThrowUniError(GetColumnDisPlayName() + ":" + String.Join(",", GetColumnTexts(a.objectData.Row))); } }); } public override bool CheckPostData(List<ObjectDataView> insertDataViewList, List<ObjectDataView> updateDataViewList, List<string> deleteStringList) { CheckServerLegalofInsert(insertDataViewList); /* add by zgl */ CheckServerLegalofUpdate(updateDataViewList); /* add by zgl */ if (UniqueList != null && UniqueList.Count() > 0) CheckUnique(insertDataViewList, updateDataViewList, deleteStringList); return base.CheckPostData(insertDataViewList, updateDataViewList, deleteStringList); } /* add by zgl */ public virtual void CheckServerLegalofInsert(List<ObjectDataView> dataViewlist) { dataViewlist.ForEach(a => { //musterofControlLegal集合XML中配置ControlLegal的字段 List<string> musterofControlLegal = new List<string>(); foreach (var kind in DataFormConfig.Columns) { if (kind.ControlLegal != null && kind.ControlLegal.Kind.ToString() != "custom" && kind.ControlLegal.Kind.ToString() != "ExpressionLegal") { musterofControlLegal.Add(kind.Name); } } //验证musterofControlLegal对应的更新数据 //包括xml中配置有ControlLegal,但是未在提交数据中的字段 foreach (string col in musterofControlLegal) { var colConfig = DataFormConfig.Columns.FirstOrDefault(c => c.Name == col); if (a.objectData.MODEFY_COLUMNS.Contains(col)) { var errorMessage = colConfig.ControlLegal.ErrMsg; if (colConfig.ControlLegal.Kind != LegalKind.ExpressionLegal) { var legal = provider.GetCodePlugService<IServerLegal>(colConfig.ControlLegal.Kind.ToString()); var obj = legal.CheckLegal(colConfig, a.objectData); if (!obj.IsLegal) { if (errorMessage == null) { throw new Exception(obj.ErrorMessage); } else { throw new Exception(errorMessage); } } } } //验证提交数据中没有的字段 else { var errorMessage = colConfig.ControlLegal.ErrMsg; if (colConfig.ControlLegal.Kind != LegalKind.ExpressionLegal) { //var legal = colConfig.ControlLegal.Kind.ToString().PlugGet<IServerLegal>(); var legal = provider.GetCodePlugService<IServerLegal>(colConfig.ControlLegal.Kind.ToString()); //虚字段的提交验证 if (!colConfig.SourceName.IsEmpty()) a.objectData.SetDataRowValue(colConfig.Name, a.objectData.Row[colConfig.Name].ToString()); else a.objectData.SetDataRowValue(colConfig.Name, null); var obj = legal.CheckLegal(colConfig, a.objectData); if (!obj.IsLegal) { if (errorMessage == null) { throw new Exception(obj.ErrorMessage); } else { throw new Exception(errorMessage); } } } } } }); } public virtual void CheckServerLegalofUpdate(List<ObjectDataView> dataViewlist) { dataViewlist.ForEach(a => { //musterofControlLegal集合XML中配置ControlLegal的字段 * add by zgl List<string> musterofControlLegal = new List<string>(); foreach (var kind in DataFormConfig.Columns) { if (kind.ControlLegal != null && kind.ControlLegal.Kind.ToString() != "custom" && kind.ControlLegal.Kind.ToString() != "ExpressionLegal") { musterofControlLegal.Add(kind.Name); } } //验证musterofControlLegal对应的更新数据 * add by zgl //只验证提交数据和musterofControlLegal都有的字段 foreach (string col in musterofControlLegal) { var colConfig = DataFormConfig.Columns.FirstOrDefault(c => c.Name == col); if (a.objectData.MODEFY_COLUMNS.Contains(col)) { var errorMessage = colConfig.ControlLegal.ErrMsg; var legal = provider.GetCodePlugService<IServerLegal>(colConfig.ControlLegal.Kind.ToString()); //var legal = colConfig.ControlLegal.Kind.ToString().PlugGet<IServerLegal>(); var obj = legal.CheckLegal(colConfig, a.objectData); if (!obj.IsLegal) { if (errorMessage == null) { throw new Exception(obj.ErrorMessage); } else { throw new Exception(errorMessage); } } } } }); } private void ThrowUniError(string name) { throw new Exception("{0}已经存在".SFormat(name)); } #endregion protected virtual string SetSelectTable(string tableName) { return tableName; } public virtual IUnitOfDapper DbContext { get { if (fDbContext == null) { fDbContext = provider.GetService<IUnitOfDapper>(); } return fDbContext; } } public override Type ObjectType { get; set; } public override string RegName { get { return fRegName; } } public override string PrimaryKey { get { return fPrimaryKey; } set { fPrimaryKey = value; } } protected DataSet DataSet { get; set; } private List<ObjectData> fList; protected virtual ObjectData ForeachGetList(ObjectData od) { return od; } public override IEnumerable<ObjectData> List { get { if (fList == null) { InitializeDataSet(); fList = new List<ObjectData>(); DataTable dt = DataSet.Tables[0]; dt.TableName = RegName; var rows = dt.Rows; // Pagination.TotalCount = rows.Count; for (int i = 0; i < rows.Count; i++) { ObjectData od = new ObjectData(); od.Row = rows[i]; fList.Add(od); } foreach (var od in fList) ForeachGetList(od); } if (fList == null) fList = new List<ObjectData>(); return fList; } set { fList = value.ToList(); //base.List = value; } } private string WhereNaviStringBuilder(ColumnConfig column, DynamicParameters sqlList, string val) { if (string.IsNullOrEmpty(val)) return string.Empty; var naviControlType = column.Navigation.ControlType; if (naviControlType == default(ControlType)) { switch (column.ControlType) { case ControlType.CheckBox: naviControlType = ControlType.CheckBoxNavi; break; case ControlType.Combo: case ControlType.Radio: naviControlType = ControlType.RadioNavi; break; case ControlType.TreeSingleSelector: naviControlType = ControlType.TreeSingleNavi; break; case ControlType.TreeMultiSelector: naviControlType = ControlType.TreeMultiNavi; break; } } string navColName = column.SourceName.IsEmpty() ? column.Name : column.SourceName; switch (naviControlType) { case ControlType.CheckBoxNavi: string[] _valCheckBox = val.Split(','); // List<string> paramCheckBox = new List<string>(); string _sql = "1=2"; for (int i = 0; i < _valCheckBox.Length; i++) { //string _paramName = navColName + i.ToString(); //paramCheckBox.Add("@{0}{1}".SFormat(seachColName, i.ToString())); if (column.ControlType == ControlType.CheckBox || column.ControlType == ControlType.MultiSelector || column.ControlType == ControlType.MultiSelector) { sqlList.Add("@{0}{1}".SFormat(navColName, i.ToString()), "%{0}%".SFormat(_valCheckBox[i])); _sql = " {2} OR {0} like @{0}{1} ".SFormat(navColName, i.ToString(), _sql); } else { _valCheckBox[i] = _valCheckBox[i].Replace("\"", ""); sqlList.Add("@{0}{1}".SFormat(navColName, i.ToString()), "{0}".SFormat(_valCheckBox[i])); _sql = " {2} OR {0} = @{0}{1} ".SFormat(navColName, i.ToString(), _sql); } } //return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", seachColName, String.Join<string>(",", paramCheckBox)); return " AND ({0})".SFormat(_sql); // break; case ControlType.RadioNavi: case ControlType.NaviFilter: case ControlType.TreeMultiNavi: string[] _val = val.Split(','); List<string> param = new List<string>(); for (int i = 0; i < _val.Length; i++) { param.Add("@{0}{1}".SFormat(column.Name, i.ToString())); sqlList.Add(string.Format("@{0}", navColName + i.ToString()), _val[i]); } return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", navColName, String.Join<string>(",", param)); case ControlType.SingleRadioNavi: if (val == "1") { sqlList.Add(string.Format("@{0}", column.Name), true); return string.Format(CultureInfo.CurrentCulture, " AND {0} = @{0}", column.Name); } else if (val == "0") { sqlList.Add(string.Format("@{0}", column.Name), false); return string.Format(CultureInfo.CurrentCulture, " AND ({0} = @{0} or {0} is null)", column.Name); } return string.Empty; case ControlType.TreeSingleNavi: var ids = val.Split(',').ToList(); if (column.Selector != null && column.Selector.Descendant) { string NaviRegName = column.Navigation.RegName; if (NaviRegName == null) { throw new Exception("请检查RegName"); } var treeCodeTable = provider.GetCodePlugService< CodeTable < CodeDataModel >>(NaviRegName) as TreeCodeTable; var _list = treeCodeTable.GetDescendent(val); ids = _list.Select(a => a.CodeValue).ToList(); ids.Add(val); } List<string> treeSingleNaviParam = new List<string>(); for (int i = 0; i < ids.Count; i++) { treeSingleNaviParam.Add("@{0}{1}".SFormat(navColName, i.ToString())); sqlList.Add(string.Format("@{0}", navColName + i.ToString()), ids[i]); } return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", navColName, String.Join<string>(",", treeSingleNaviParam)); default: return string.Empty; } } private string WhereSearchStringBuilder(ColumnConfig column, DynamicParameters sqlList, string val, bool isEndTime) { // if (column.Search == null) return string.Empty; if (column.Navigation != null && column.Navigation.IsAvailable) return string.Empty; string seachColName = column.SourceName.IsEmpty() ? column.Name : column.SourceName; ControlType searchControlType = column.ControlType; if (column.Search != null && column.Search.ControlType != ControlType.None) { searchControlType = column.Search.ControlType; } //()&& (column.Search.ControlType != null) switch (searchControlType) { case ControlType.Selector: //如果配置了Search的islike是true if (column.Search.IsLike == true) { var rN = column.RegName; DataSet dataSet = null; if (column.DetailRegName != null && !column.DetailRegName.Equals("")) { rN = column.DetailRegName; } //根据配置的column.RegName和输入的关键字val查询 var dt = provider.GetCodePlugService<CodeTable<CodeDataModel>>(rN); //as TreeCodeTable; IocContext.Current.FetchInstance<CodeTable<CodeDataModel>>(rN); string sql = ""; if ((dt as SingleCodeTable<CodeDataModel>) != null && (dt as SingleCodeTable<CodeDataModel>).TableName != null && (dt as SingleCodeTable<CodeDataModel>).TextField != null && (dt as SingleCodeTable<CodeDataModel>).ValueField != null) { sql = string.Format("select {0} from {1} where {2} like '%{3}%'", (dt as SingleCodeTable<CodeDataModel>).ValueField, (dt as SingleCodeTable<CodeDataModel>).TableName, (dt as SingleCodeTable<CodeDataModel>).TextField, val); if ((dt as SingleCodeTable<CodeDataModel>).Where != null && !(dt as SingleCodeTable<CodeDataModel>).Where.Equals("")) { sql = string.Format("{0} and {1}", sql, (dt as SingleCodeTable<CodeDataModel>).Where); dataSet = DbContext.QueryDataSet(sql); } } //var codemodels = dt.Search(null, val); //if (codemodels != null && codemodels.Count() != 0) if (dataSet != null && dataSet.Tables[0] != null) { //var searchVal = codemodels.Select(m => m.CODE_VALUE).ToList(); //List<string> selectorParam = new List<string>(); //for (int i = 0; i < searchVal.Count; i++) //{ // selectorParam.Add("@" + seachColName + i.ToString()); // sqlList.Add(new SqlParameter(string.Format("@{0}", seachColName + i.ToString()), searchVal[i])); //} string myFid = ""; for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++) { myFid = "{0}'{1}',".SFormat(myFid, dataSet.Tables[0].Rows[i][0]); //myFid += "'" + dataSet.Tables[0].Rows[i][0] + "',"; } if (!myFid.IsEmpty()) { myFid = myFid.Substring(0, myFid.Length - 1); return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", seachColName, myFid); } else { return " AND 1=2 "; } } else { string temp = "%{0}%".SFormat(val); sqlList.Add(string.Format("@{0}", seachColName), temp); return string.Format(CultureInfo.CurrentCulture, " AND {0} LIKE @{0}", seachColName); } } else { sqlList.Add(string.Format("@{0}", seachColName), val); return string.Format(CultureInfo.CurrentCulture, " AND {0} = @{0}", seachColName); } case ControlType.Date: case ControlType.DateTime: if (isEndTime) { if (searchControlType == ControlType.Date) { DateTime time = val.Value<DateTime>(); if (time != default(DateTime)) { time = time.AddDays(1); sqlList.Add(string.Format("@{0}{1}", seachColName, "_END"), time); } } else { sqlList.Add(string.Format("@{0}{1}", seachColName, "_END"), val);//若有dataspan则时间参数会重复,故需加_END } return string.Format(CultureInfo.CurrentCulture, " AND {0} < @{1}", seachColName, seachColName + "_END"); } else { sqlList.Add(string.Format("@{0}", seachColName), val); return string.Format(CultureInfo.CurrentCulture, " AND {0} >= @{0}", seachColName); } case ControlType.CheckBox: string[] _valCheckBox = val.Split(','); // List<string> paramCheckBox = new List<string>(); string _sql = " 1=1 "; for (int i = 0; i < _valCheckBox.Length; i++) { string _paramName = seachColName + i.ToString(); //paramCheckBox.Add("@{0}{1}".SFormat(seachColName, i.ToString())); sqlList.Add("@" + _paramName, "%{0}%".SFormat(_valCheckBox[i])); _sql = " {2} AND {0} LIKE @{0}{1} ".SFormat(seachColName, i.ToString(), _sql); } //return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", seachColName, String.Join<string>(",", paramCheckBox)); return " AND ({0})".SFormat(_sql); case ControlType.Combo: case ControlType.Radio: case ControlType.TreeMultiSelector: string[] _val = val.Split(','); List<string> param = new List<string>(); for (int i = 0; i < _val.Length; i++) { param.Add("@" + seachColName + i.ToString()); sqlList.Add(string.Format("@{0}{1}", seachColName, i.ToString()), _val[i]); } return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", seachColName, String.Join<string>(",", param)); case ControlType.TreeSingleSelector: var strs = val.Split(',').ToList(); if (column.Selector != null && column.Selector.Descendant) { string _treeRegName = column.RegName; if (_treeRegName == null) { throw new Exception("请检查RegName"); } //var dt = _treeRegName.CodePlugIn<CodeTable<CodeDataModel>>(); var _cd = provider.GetCodePlugService<CodeTable<CodeDataModel>>(_treeRegName)as TreeCodeTable; var _list = _cd.GetDescendent(val); strs = _list.Select(a => a.CodeValue).ToList(); strs.Add(val); } List<string> treeSingleSelectorParam = new List<string>(); for (int i = 0; i < strs.Count; i++) { treeSingleSelectorParam.Add("@{0}{1}".SFormat(seachColName, i.ToString())); sqlList.Add(string.Format("@{0}{1}", seachColName, i.ToString()), strs[i]); } return string.Format(CultureInfo.CurrentCulture, " AND {0} IN ({1})", seachColName, String.Join<string>(",", treeSingleSelectorParam)); case ControlType.SingleCheckBox: sqlList.Add(string.Format("@{0}", seachColName), val == "1" ? true : false); if (val == "1") { return string.Format(CultureInfo.CurrentCulture, " AND {0} = @{0}", seachColName); } else { return string.Format(CultureInfo.CurrentCulture, " AND ({0} = @{0} or {0} is null)", seachColName); } default: if (column.Search != null && column.Search.IsLike == true) { string temp = "%{0}%".SFormat(val); sqlList.Add(string.Format("@{0}", seachColName), temp); return string.Format(CultureInfo.CurrentCulture, " AND {0} LIKE @{0}", seachColName); } else { sqlList.Add(string.Format("@{0}", seachColName), val); return string.Format(CultureInfo.CurrentCulture, " AND {0} = @{0}", seachColName); } //sqlList.Add(new SqlParameter(string.Format("@{0}", seachColName), val)); //return string.Format(CultureInfo.CurrentCulture, " AND {0} = @{0}", seachColName); } } protected virtual string WhereStringBuilder(DataRow row, DynamicParameters sqlList)//增加参数sqlList,参数化查询 { string res = ""; var columns = row.Table.Columns; //预处理 foreach (DataColumn col in columns) { string colName = col.ColumnName; bool isLike = colName.EndsWith("_END"); //这种情况,控件肯定是时间控件这种的 if (isLike) { colName = colName.Replace("_END", ""); var _timeCol = DataFormConfig.Columns.FirstOrDefault(a => a.Name == colName); if (_timeCol != null) { _timeCol.ControlType = ControlType.DateTime; } } } foreach (DataColumn col in columns) { string val = row[col.ColumnName].ToString(); if (!val.IsEmpty()) { string colName = col.ColumnName; var column = DataFormConfig.Columns.FirstOrDefault(a => a.Name == colName); bool isLike = colName.EndsWith("_LIKE"); bool isEndTime = false; if (isLike && column == null) { colName = colName.Replace("_LIKE", ""); } isEndTime = colName.EndsWith("_END"); if (isEndTime && column == null) { colName = colName.Replace("_END", ""); } column = DataFormConfig.Columns.FirstOrDefault(a => a.Name == colName); if (column != null) { if (column.Kind == ColumnKind.Data) { if (column.Navigation != null && column.Navigation.IsAvailable) { res += WhereNaviStringBuilder(column, sqlList, val); } else { res += WhereSearchStringBuilder(column, sqlList, val, isEndTime); } } else { res += WhereSearchStringBuilderByVisualData(column, sqlList, val, isEndTime); } } } } return res; } protected virtual string WhereSearchStringBuilderByVisualData(ColumnConfig column, DynamicParameters sqlList, string val, bool isEndTime) { return ""; } private string SetWhereFilterSqlByFormConfig(string where) { //MacroConfig mconfig = ModuleFormConfig.AndFilterSql; //if (mconfig != null && !mconfig.Value.IsEmpty()) //{ // string _andSql = mconfig.ExeValue(); // where += " AND " + _andSql; //} return where; } private void SetPrimaryKey() { if (PrimaryKey.IsEmpty()) { var bean = DataFormConfig.Columns.FirstOrDefault(a => a.IsKey); PrimaryKey = bean.Name; } } protected virtual string SetSelectSql() { return string.Join(",", DataFormConfig.Columns.Where(b => b.Kind == ColumnKind.Data). Select(a => " {0} AS {1} ".SFormat(a.SourceName.IsEmpty() ? a.Name : a.SourceName, a.Name))); } private DynamicParameters paraList; private string sql; protected virtual void InitializeDataSet() { SetSqlSelect(); StringBuilder sb = new StringBuilder(); sb.AppendLine(Environment.NewLine); sb.AppendLine(sql); sb.AppendLine(Environment.NewLine); //DBUtil.DbCommandToString(paraList.ToList(), sb); //Trace.WriteCustomFile("BaseDataTableSource", sb.ToString()); DataSet = DbContext.QueryDataSet(sql, paraList); //设置外键的值 //this.ModuleFormConfig. } private void SetSqlSelect() { string where = ""; DynamicParameters sqlList = new DynamicParameters(); if (KeyValues.Count() == 0) { string searchTable = RegName + "_SEARCH"; if (PostDataSet != null && PostDataSet.Tables[searchTable] != null && PostDataSet.Tables[searchTable].Rows.Count > 0) { DataRow row = PostDataSet.Tables[searchTable].Rows[0]; where = WhereStringBuilder(row, sqlList); } else { if (IsFillEmpty) { where = " AND 1=2 "; } } } else { //当外键也为空的时候 if (ForeignKeyValue.IsEmpty()) where = SetWhereByKeyValue(sqlList); else { where = string.Format(" AND {0}=@{0}", ForeignKey); sqlList.Add(string.Format("@{0}", ForeignKey), ChangeForeignKeyValue(ForeignKeyValue));//获取子表过滤条件 } } where = SetWhereFilterSqlByFormConfig(where); where = AdditionalConditionSql(where); string countSql = string.Format(CultureInfo.CurrentCulture, "SELECT COUNT(*) FROM {0} WHERE 1=1 {1}", SetSelectTable(RegName), where); Pagination.TotalCount = DbContext.QueryObject<int>(countSql, sqlList); string _selectStr = SetSelectSql(); string orderName = PrimaryKey + " DESC "; if (Order.IsEmpty()) { if (XmlColumns.Contains("CREATE_TIME")) { orderName = "CREATE_TIME DESC "; } if (XmlColumns.Contains("UPDATE_TIME")) { orderName = "UPDATE_TIME DESC "; } } else { orderName = Order; } if (!Pagination.SortName.IsEmpty()) { if (Pagination.IsASC) orderName = Pagination.SortName + " ASC"; else orderName = Pagination.SortName + " DESC"; } paraList = new DynamicParameters(); paraList = sqlList; //foreach (var qsql in sqlList)//对象克隆,防止参数重复 //{ // SqlParameter sqlP = new SqlParameter(); // qsql.ObjectClone(sqlP); // paraList.Add(sqlP); //} sql = string.Format(CultureInfo.CurrentCulture, PAGE_SQL, _selectStr, orderName, SetSelectTable(RegName), where); paraList.Add("@skip",Pagination.PageIndex ); paraList.Add("@pageSize",Pagination.PageSize); } protected virtual string ChangeForeignKeyValue(string value) { //string __relationKey = "_foreignkey_{0}_{1}".SFormat(_relation.MasterForm, _relation.MasterField); //AppContext.Current.SetItem(__relationKey, _value); return value; } private string SetWhereByKeyValue(DynamicParameters sqlList) { string where = "AND ("; int flag = 0; foreach (string val in KeyValues) { string parm = val.Replace("-", "_"); flag++; if (flag == KeyValues.Count()) { where = where + string.Format(CultureInfo.CurrentCulture, "{0} = @{1}", PrimaryKey, parm); } else { where = where + string.Format(CultureInfo.CurrentCulture, "{0} = @{1} OR ", PrimaryKey, parm); } sqlList.Add(string.Format("@{0}", parm), val); } where = where + ")"; return where; } public override void Initialize(ModuleFormInfo info) { base.Initialize(info); // base.Initialize(dataSet, pageSize, keyValue, foreignKeyValue, tableName, primaryKey, foreignKey, isFillEmpty, dataXmlPath); XmlColumns = new HashSet<string>(); DataFormConfig.Columns.ForEach(a => { XmlColumns.Add(a.Name); }); if (fRegName.IsEmpty()) { //修复配置表制定名称的bug if (!info.ModuleFormConfig.TableName.IsEmpty()) { fRegName = info.ModuleFormConfig.TableName; } else { fRegName = DataFormConfig.TableName; } } if (fPrimaryKey.IsEmpty()) { fPrimaryKey = DataFormConfig.PrimaryKey; } SetPrimaryKey(); } protected override void Dispose(bool disposing) { if (disposing) { if (DataSet != null) DataSet.Dispose(); } base.Dispose(disposing); } public override void AppendTo(DataSet ds) { //base.AppendTo(ds); DataTable dt = DataSet.Tables[RegName]; bool isRight = dt.Columns.Contains("BUTTON_RIGHT"); if (!isRight) { dt.Columns.Add("BUTTON_RIGHT", typeof(string)); } foreach (var obj in List) { obj.Row["BUTTON_RIGHT"] = obj.BUTTON_RIGHT; } if (!ds.Tables.Contains(dt.TableName)) { ds.Tables.Add(dt.Copy()); } else DataSetUtil.MegerDataTable(dt, ds.Tables[dt.TableName], PrimaryKey); this.Pagination.AppendToDataSet(ds, RegName); } public override void Merge(bool isBat) { // SetPrinaryKey(); base.Merge(isBat); if (!isBat) { //int res = DbContext.ADOSubmit(); //Result = new JsResponseResult<int>() { ActionType = JsActionType.Object, Obj = res }; } } public override void InsertForeach(ObjectData data, DataRow row, string key) { // base.InsertForeach(data, row); data.SetDataRowValue("TIMESSTAMP", TimeUtil.GetTimesSpan()); DynamicParameters sqlList = new DynamicParameters(); string inserSql = CreateInsertSql(data, sqlList, key); if (!inserSql.IsEmpty()) { DbContext.RegisterSqlCommand(inserSql, sqlList); } } private void LegalRow(ObjectData data) { foreach (string str in data.MODEFY_COLUMNS) { // ColumnLegalHashTable. } } public override void UpdateForeach(ObjectData data, DataRow row, string key) { //base.UpdateForeach(data, row); if (data.MODEFY_COLUMNS.Count > 1) { if (ModuleFormConfig.IsSafeMode) { string sql = string.Format(CultureInfo.CurrentCulture, "SELECT TIMESSTAMP FROM {0} WHERE {1}=@FID", RegName, PrimaryKey); DynamicParameters parameters = new DynamicParameters(); parameters.Add("@FID", key); var timesStamp = DbContext.QueryObject(sql, parameters); var originTimeStamp = data.GetDataRowValue("TIMESSTAMP"); if (timesStamp != DBNull.Value && originTimeStamp != null) { if (timesStamp.ToString() != originTimeStamp.ToString()) { throw new Exception("数据已发生变化,请刷新后重新更新"); } } } data.SetDataRowValue("TIMESSTAMP", TimeUtil.GetTimesSpan()); DynamicParameters sqlList = new DynamicParameters(); string updateSql = CreateUpdateSql(data, sqlList); if (!updateSql.IsEmpty()) { DbContext.RegisterSqlCommand(updateSql, sqlList); } } } public override void DeleteForeach(string key, string data) { DynamicParameters sqlList = new DynamicParameters(); string sql = CreateDeleteSql(key, sqlList); if (!sql.IsEmpty()) { DbContext.RegisterSqlCommand(sql, sqlList); } //base.DeleteForeach(key, data); } protected virtual string CreatePhyDeleteSql(string key, DynamicParameters sqlList) { string sql = " DELETE FROM {0} WHERE {1}=@key "; sqlList.Add("@key", key); //sql = string.Format(CultureInfo.CurrentCulture, sql, RegName, PrimaryKey, key); sql = string.Format(CultureInfo.CurrentCulture, sql, RegName, PrimaryKey); return sql; } protected virtual string CreateDeleteSql(string key, DynamicParameters sqlList) { //string sql = string.Format(" DELETE FROM {0} WHERE {1}=@key AND 1=1 "); return CreatePhyDeleteSql(key, sqlList); } protected virtual string CreateInsertSql(ObjectData od, DynamicParameters sqlList, string key)//增加参数sqlList,参数化查询 { string paraName = ""; HashSet<string> _modefyColumns = od.MODEFY_COLUMNS; if (!_modefyColumns.Contains(PrimaryKey)) { _modefyColumns.Add(PrimaryKey); } //added by sj if (!ForeignKey.IsEmpty()) { _modefyColumns.Add(ForeignKey); } string sql = "INSERT INTO {0} ({1}) VALUES ({2})"; List<string> vals = new List<string>(); List<string> colNames = new List<string>(); bool hasPriKey = false; bool isNull = true; foreach (string col in _modefyColumns) { if (FullColumns.FirstOrDefault(a => a.Name == col && a.Kind == ColumnKind.Data) != null) { string val = ""; if (col == PrimaryKey) { //Debug.AssertArgument(!hasPriKey, col, string.Format(CultureInfo.CurrentCulture, "表{0}主键只能有一个", RegName), this); hasPriKey = true; val = key; // FileID = ""; //added by sj 保存主表主键,当有它子表时作为外键 if (this.PostDataSet.Tables[PAGE_SYS] != null && ForeignKey.IsEmpty()) { this.PostDataSet.Tables[PAGE_SYS].Rows[0][KEYVALUE] = val; } } else if (col == ForeignKey) { val = ForeignKeyValue; } else { val = od.Row[col].ToString(); } paraName = "@" + col; sqlList.Add(paraName, val); vals.Add(paraName); colNames.Add(col); isNull = false; } } string cols = string.Join(",", colNames); foreach (ColumnConfig column in FullColumns.Where(a => a.Kind == ColumnKind.Data)) { string mod = column.Name; if (!_modefyColumns.Contains(mod)) { if (mod == "CREATE_TIME" || mod == "UPDATE_TIME") { cols += "," + mod; paraName = "@" + mod; sqlList.Add(paraName, DbContext.Now); vals.Add(paraName); isNull = false; } if (mod == "CREATE_ID" || mod == "UPDATE_ID") { cols += "," + mod; paraName = "@" + mod; sqlList.Add(paraName, "");//当前用户id vals.Add(paraName); isNull = false; } } } if (isNull) return ""; sql = string.Format(CultureInfo.CurrentCulture, sql, RegName, cols, string.Join(",", vals)); return sql; } protected virtual string CreateUpdateSql(ObjectData od, DynamicParameters sqlList)//增加参数sqlList,参数化查询 { //if(od.MODEFY_COLUMNS.) string cols = string.Join(",", od.MODEFY_COLUMNS); string sql = "UPDATE {0} SET {1} WHERE {2} = '{3}' "; List<string> vals = new List<string>(); //List<string> colNames = new List<string>(); bool isNull = true; string key = ""; foreach (string col in od.MODEFY_COLUMNS) { if (FullColumns.FirstOrDefault(a => a.Name == col && a.Kind == ColumnKind.Data) != null) { string val = od.Row[col].ToString(); if (col != PrimaryKey) { string temp = val; val = string.Format(CultureInfo.CurrentCulture, "{0} = @{0} ", col); sqlList.Add(string.Format("@{0}", col), temp); vals.Add(val); //colNames.Add(col); isNull = false; } else key = val; } } foreach (ColumnConfig column in FullColumns.Where(a => a.Kind == ColumnKind.Data)) { string mod = column.Name; if (!od.MODEFY_COLUMNS.Contains(mod)) { if (mod == "UPDATE_TIME") { string val2 = string.Format(CultureInfo.CurrentCulture, " UPDATE_TIME = @{0} ", mod); sqlList.Add(string.Format("@{0}", mod), DbContext.Now.ToString()); vals.Add(val2); isNull = false; } if (mod == "UPDATE_ID") { string val2 = string.Format(CultureInfo.CurrentCulture, " UPDATE_ID = @{0} ", mod); sqlList.Add(string.Format("@{0}", mod), ""); //当前用户id vals.Add(val2); isNull = false; } } } if (isNull) return ""; sql = string.Format(CultureInfo.CurrentCulture, sql, RegName, string.Join(",", vals), PrimaryKey, key); return sql; } protected virtual string AdditionalConditionSql(string sql) { if (true) //"IsSysAdditionalTypeFControlUnit".AppKv<bool>(false) { if (this.DataFormConfig.TableName.Length > 2 && this.DataFormConfig.TableName.Substring(0, 3) != "WF_") return "{0} AND FControlUnitID='{1}' AND ((ISDELETE IS NULL) OR (ISDELETE = 0))".SFormat(sql, "1");//当前组织id else return sql; } else return sql; } //private public override string GetInsertKey(ObjectData data) { //throw new NotImplementedException(); return DbContext.GetUniId(); } } }
41.419935
256
0.460353
[ "MIT" ]
RookieXie/spoondrift.core
src/Spoondrift.Code/Data/BaseDataTableSource.cs
51,284
C#
using Core.Audio; using System.Collections; using System.Collections.Generic; using UnityDI; using UnityEngine; public class BackgroundMusic : MonoBehaviour { public string BackgroundTrackName; [Dependency] private readonly AudioService _AudioService; public AudioEffect AudioTrack; private void Start() { ContainerHolder.Container.BuildUp(this); AudioTrack = _AudioService.PlayMusic(BackgroundTrackName); } private void Update() { if (Input.GetKeyDown(KeyCode.P)) { AudioTrack.gameObject.SetActive(true); AudioTrack.Play(false); } } }
23.333333
66
0.692063
[ "MIT" ]
AlexandrKlimkin/StickmanWars
Assets/Scripts/Core/Services/AudioService/BackgroundMusic.cs
632
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute(Namespace="urn:hl7-org:v3", IsNullable=false)] public enum ResidentialStatusType_code { /// <remarks/> H, /// <remarks/> O, } }
75.83871
1,368
0.742237
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/ResidentialStatusType_code.cs
2,351
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("nl.pleduc.TsumTsumHeartTracker.Resource", IsApplication=true)] namespace nl.pleduc.TsumTsumHeartTracker { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Array { // aapt resource value: 0x7f060000 public const int sorting_types = 2131099648; static Array() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Array() { } } public partial class Attribute { // aapt resource value: 0x7f010001 public const int maxValue = 2130771969; // aapt resource value: 0x7f010000 public const int minValue = 2130771968; static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int ic_action_content_create = 2130837504; // aapt resource value: 0x7f020001 public const int ic_action_content_save = 2130837505; // aapt resource value: 0x7f020002 public const int ic_autorenew_white_48dp = 2130837506; // aapt resource value: 0x7f020003 public const int ic_menu_copy_holo_dark = 2130837507; // aapt resource value: 0x7f020004 public const int ic_menu_cut_holo_dark = 2130837508; // aapt resource value: 0x7f020005 public const int ic_menu_paste_holo_dark = 2130837509; // aapt resource value: 0x7f020006 public const int ic_menu_search_holo_dark = 2130837510; // aapt resource value: 0x7f020007 public const int ic_settings_white_48dp = 2130837511; // aapt resource value: 0x7f020008 public const int Icon = 2130837512; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f090009 public const int context = 2131296265; // aapt resource value: 0x7f090001 public const int linearLayout2 = 2131296257; // aapt resource value: 0x7f09000b public const int menu_refresh = 2131296267; // aapt resource value: 0x7f09000d public const int menu_reset = 2131296269; // aapt resource value: 0x7f09000a public const int menu_search = 2131296266; // aapt resource value: 0x7f09000c public const int menu_settings = 2131296268; // aapt resource value: 0x7f090008 public const int preference_numberpicker = 2131296264; // aapt resource value: 0x7f090007 public const int preference_numberpicker_dialog = 2131296263; // aapt resource value: 0x7f090004 public const int scrollView1 = 2131296260; // aapt resource value: 0x7f090003 public const int spinner1 = 2131296259; // aapt resource value: 0x7f090005 public const int tableLayout1 = 2131296261; // aapt resource value: 0x7f090006 public const int tableRow1 = 2131296262; // aapt resource value: 0x7f090002 public const int textView1 = 2131296258; // aapt resource value: 0x7f090000 public const int toolbar = 2131296256; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int Main = 2130903040; // aapt resource value: 0x7f030001 public const int preference_numberpicker = 2130903041; // aapt resource value: 0x7f030002 public const int Settings = 2130903042; // aapt resource value: 0x7f030003 public const int toolbar = 2130903043; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class Menu { // aapt resource value: 0x7f080000 public const int actionbar_menu_main = 2131230720; // aapt resource value: 0x7f080001 public const int actionbar_menu_settings = 2131230721; static Menu() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Menu() { } } public partial class String { // aapt resource value: 0x7f050000 public const int ApplicationName = 2131034112; // aapt resource value: 0x7f050001 public const int ApplicationNameShort = 2131034113; // aapt resource value: 0x7f050002 public const int sorting_prompt = 2131034114; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } public partial class Style { // aapt resource value: 0x7f070000 public const int CustomThemes_TsumTsum = 2131165184; static Style() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Style() { } } public partial class Xml { // aapt resource value: 0x7f040000 public const int preferences = 2130968576; // aapt resource value: 0x7f040001 public const int searchable = 2130968577; static Xml() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Xml() { } } public partial class Styleable { public static int[] NumberPickerPreference = new int[] { 2130771968, 2130771969}; // aapt resource value: 1 public const int NumberPickerPreference_maxValue = 1; // aapt resource value: 0 public const int NumberPickerPreference_minValue = 0; static Styleable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Styleable() { } } } } #pragma warning restore 1591
23.233449
125
0.633323
[ "MIT" ]
KoffiePatje/TsumTsumHeartTracker
TsumTsumNotificationTracker/Resources/Resource.Designer.cs
6,668
C#
namespace RotaTable { partial class RotaTable { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tblRota = new System.Windows.Forms.TableLayoutPanel(); this.SuspendLayout(); // // tblRota // this.tblRota.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; this.tblRota.ColumnCount = 1; this.tblRota.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tblRota.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tblRota.Dock = System.Windows.Forms.DockStyle.Fill; this.tblRota.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize; this.tblRota.Location = new System.Drawing.Point(0, 0); this.tblRota.Name = "tblRota"; this.tblRota.RowCount = 1; this.tblRota.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tblRota.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tblRota.Size = new System.Drawing.Size(800, 450); this.tblRota.TabIndex = 6; // // RotaTable // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tblRota); this.Name = "RotaTable"; this.Size = new System.Drawing.Size(800, 450); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tblRota; } }
39.712121
124
0.602442
[ "MIT" ]
JackBattye91/Rota-Creator
RotaTable/RotaTable.Designer.cs
2,623
C#
using System; using Oogi2.Attributes; using Oogi2.Tokens; using Shushu.Attributes; namespace KotoriCore.Database.DocumentDb.Entities { /// <summary> /// Document. /// </summary> [EntityType("entity", Entity)] [ClassMapping(Shushu.Enums.IndexField.Entity, Entity)] public class Document : IEntity { internal const string Entity = "kotori/document"; /// <summary> /// Gets or sets the identifier (documentdb pk). /// </summary> /// <value>The identifier (documentdb pk).</value> [PropertyMapping(Shushu.Enums.IndexField.Id)] public string Id { get; set; } /// <summary> /// Gets or sets the instance. /// </summary> /// <value>The instance.</value> [PropertyMapping(Shushu.Enums.IndexField.Text0)] public string Instance { get; set; } /// <summary> /// Gets or sets the project identifier. /// </summary> /// <value>The project identifier.</value> [PropertyMapping(Shushu.Enums.IndexField.Text1)] public string ProjectId { get; set; } /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> [PropertyMapping(Shushu.Enums.IndexField.Text2)] public string Identifier { get; set; } /// <summary> /// Gets or sets the document type identifier. /// </summary> /// <value>The document type identifier.</value> [PropertyMapping(Shushu.Enums.IndexField.Text6)] public string DocumentTypeId { get; set; } /// <summary> /// Gets or sets the hash. /// </summary> /// <value>The hash.</value> public string Hash { get; set; } /// <summary> /// Gets or sets the slug. /// </summary> /// <value>The slug.</value> [PropertyMapping(Shushu.Enums.IndexField.Text3)] public string Slug { get; set; } /// <summary> /// Gets or sets the meta. /// </summary> /// <value>The meta.</value> public dynamic Meta { get; set; } /// <summary> /// Gets or sets the original meta. /// </summary> /// <value>The original meta.</value> public dynamic OriginalMeta { get; set; } /// <summary> /// Gets or sets the content. /// </summary> /// <value>The content.</value> [PropertyMapping(Shushu.Enums.IndexField.Text4)] public string Content { get; set; } /// <summary> /// Gets or sets the date. /// </summary> /// <value>The date.</value> [PropertyMapping(Shushu.Enums.IndexField.Date0)] public Stamp Date { get; set; } /// <summary> /// Gets or sets the modification. /// </summary> /// <value>The modification.</value> [PropertyMapping(Shushu.Enums.IndexField.Date1)] public Stamp Modified { get; set; } /// <summary> /// Gets or sets a value indicating whether this /// <see cref="T:KotoriCore.Database.DocumentDb.Entities.Document"/> is draft. /// </summary> /// <value><c>true</c> if draft; otherwise, <c>false</c>.</value> [PropertyMapping(Shushu.Enums.IndexField.Flag0)] public bool Draft { get; set; } /// <summary> /// Gets or sets the version. /// </summary> /// <value>The version.</value> public long Version { get; set; } /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Database.DocumentDb.Entities.Document"/> class. /// </summary> public Document() { } /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Database.DocumentDb.Entities.Document"/> class. /// </summary> /// <param name="instance">Instance.</param> /// <param name="projectId">Project identifier.</param> /// <param name="identifier">Identifier.</param> /// <param name="documentTypeId">Document type identifier.</param> /// <param name="hash">Hash.</param> /// <param name="slug">Slug.</param> /// <param name="originalMeta">Original meta.</param> /// <param name="meta">Meta.</param> /// <param name="content">Content.</param> /// <param name="date">Date.</param> /// <param name="draft">If set to <c>true</c> draft.</param> /// <param name="version">Version.</param> public Document(string instance, string projectId, string identifier, string documentTypeId, string hash, string slug, dynamic originalMeta, dynamic meta, string content, DateTime? date, bool draft, long version) { Instance = instance; ProjectId = projectId; Identifier = identifier; DocumentTypeId = documentTypeId; Hash = hash; Slug = slug; Meta = meta; OriginalMeta = originalMeta; Content = content; Date = date.HasValue ? new Stamp(date.Value) : null; Modified = new Stamp(); Draft = draft; Version = version; } } }
34.75
220
0.555661
[ "MIT" ]
kotorihq/kotori-core
KotoriCore/Database/DocumentDb/Entities/Document.cs
5,284
C#
using Drawmasters.Effects; using Spine; using Spine.Unity; using UnityEngine; using System; using Event = Spine.Event; namespace Drawmasters.Utils { public class AnimationEffectPlayerHandler : AnimationActionHandler { #region Fields private readonly string fxBoneName; private readonly string fxKey; private string stopEventName; private bool shouldAttachToTransform = true; private EffectHandler effectHandler; private GameObject fxRoot; #endregion #region Class lifecycle public AnimationEffectPlayerHandler(SkeletonGraphic _skeletonGraphic, string _eventName, string _fxBoneName, string _fxKey) : base(_skeletonGraphic, _eventName) { fxBoneName = _fxBoneName; fxKey = _fxKey; } #endregion #region Methods public override void Initialize() { base.Initialize(); if (skeletonGraphic != null) { if (fxRoot != null) { Content.Management.DestroyObject(fxRoot); fxRoot = null; } fxRoot = SpineUtility.InstantiateBoneFollower(skeletonGraphic, fxBoneName, skeletonGraphic.transform); } } public override void Deinitialize() { EffectManager.Instance.ReturnHandlerToPool(effectHandler); if (fxRoot != null) { Content.Management.DestroyObject(fxRoot); fxRoot = null; } base.Deinitialize(); } public void SetStopFxEvent(string _stopEventName) => stopEventName = _stopEventName; public void SetAttachToRoot(bool value) => shouldAttachToTransform = value; #endregion #region Events handlers protected override void OnMonitorEventHappened() { base.OnMonitorEventHappened(); Vector3 worldRotation = Vector3.zero; if (fxRoot.transform.rotation.z < 90) { worldRotation.z += 180.0f; } EffectManager.Instance.ReturnHandlerToPool(effectHandler); Transform parent = shouldAttachToTransform ? fxRoot.transform : null; effectHandler = EffectManager.Instance.PlaySystemOnce(fxKey, fxRoot.transform.position, Quaternion.Euler(worldRotation), parent); } protected override void AnimationState_Event(TrackEntry trackEntry, Event e) { base.AnimationState_Event(trackEntry, e); if (e.ToString().Equals(stopEventName, StringComparison.Ordinal)) { effectHandler.Stop(); } } #endregion } }
24.247863
141
0.589002
[ "Unlicense" ]
TheProxor/code-samples-from-pg
Assets/Scripts/GameFlow/Helpers/Spine/AnimationEffectPlayerHandler.cs
2,839
C#
using System.Collections; namespace System.Text.RegularExpressions { /// <summary> /// Returns the set of captured groups in a single match. /// </summary> [H5.Convention(Member = H5.ConventionMember.Field | H5.ConventionMember.Method, Notation = H5.Notation.CamelCase)] [H5.External] [H5.Reflectable] public class GroupCollection : ICollection { internal extern GroupCollection(); /// <summary> /// Gets an object that can be used to synchronize access to the GroupCollection. /// </summary> public extern object SyncRoot { [H5.Template("getSyncRoot()")] get; } /// <summary> /// Gets a value that indicates whether access to the GroupCollection is synchronized (thread-safe). /// </summary> public extern bool IsSynchronized { [H5.Template("getIsSynchronized()")] get; } /// <summary> /// Gets a value that indicates whether the collection is read-only. /// </summary> public extern bool IsReadOnly { [H5.Template("getIsReadOnly()")] get; } /// <summary> /// Returns the number of groups in the collection. /// </summary> public extern int Count { [H5.Template("getCount()")] get; } /// <summary> /// Enables access to a member of the collection by integer index. /// </summary> public extern Group this[int groupnum] { [H5.Template("get({0})")] get; } /// <summary> /// Enables access to a member of the collection by string index. /// </summary> public extern new Group this[string groupname] { [H5.Template("getByName({0})")] get; } /// <summary> /// Copies all the elements of the collection to the given array beginning at the given index. /// </summary> public extern void CopyTo(Array array, int arrayIndex); /// <summary> /// Provides an enumerator that iterates through the collection. /// </summary> [H5.Convention(H5.Notation.None)] public extern IEnumerator GetEnumerator(); } }
29.3625
118
0.550447
[ "Apache-2.0" ]
curiosity-ai/h5
H5/H5/System/Text/RegularExpressions/GroupCollection.cs
2,349
C#
using ConfigurationModel.Interfaces; namespace ConfigurationModel.Models { public record CognitoSetting : ICognitoSetting { public string RegionId { get; init; } = null!; public string UserPoolName { get; init; } = null!; public string UserPoolId { get; init; } = null!; public string AppClientId { get; init; } = null!; public string TokenValidIssuer { get; init; } = null!; public string HostingUiUri { get; init; } = null!; public string GetTokenValidIssuer() { return TokenValidIssuer.Replace("-REGIONID-", RegionId).Replace("-POOLID-", UserPoolId); } } }
34.631579
100
0.62766
[ "MIT" ]
returner/DummyDataFactory
DummyDataFactory/ConfigurationModel/Models/CognitoSetting.cs
660
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Interactivity; using System.Windows.Media; using WindowsSharp.DiskItems; namespace Everythingbar { public class TaskItemClickBehavior : Behavior<FrameworkElement> { bool _pressed = false; ListViewItem _item; new public ToggleButton Button { get => (ToggleButton)GetValue(ButtonProperty); set => SetValue(ButtonProperty, value); } new public static readonly DependencyProperty ButtonProperty = DependencyProperty.Register("Button", typeof(ToggleButton), typeof(TaskItemClickBehavior), new PropertyMetadata(OnButtonPropertyChanged)); protected override void OnAttached() { base.OnAttached(); _item = (AssociatedObject.TemplatedParent as FrameworkElement).TemplatedParent as ListViewItem; if (_item != null) { _item.PreviewMouseDown += _item_PreviewMouseDown; _item.PreviewMouseUp += _item_PreviewMouseUp; } } public static void OnButtonPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (e.NewValue as ToggleButton).Click += (d as TaskItemClickBehavior).Button_Click; } public void Button_Click(object sender, RoutedEventArgs e) { Panel visualOwner = VisualTreeHelper.GetParent(_item) as Panel; var app = ((Window.GetWindow(sender as DependencyObject) as MainWindow).OpenApplications[visualOwner.Children.IndexOf(_item)]); if (app.OpenWindows.Count == 0) app.DiskApplication.Open(); } private void _item_PreviewMouseUp(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Middle) _pressed = false; } private void _item_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if ((!_pressed) && (e.ChangedButton == MouseButton.Middle) && (e.MiddleButton == MouseButtonState.Pressed) && (Mouse.MiddleButton == MouseButtonState.Pressed)) { Debug.WriteLine("Opening app..."); Panel visualOwner = VisualTreeHelper.GetParent(_item) as Panel; ((Window.GetWindow(sender as DependencyObject) as MainWindow).OpenApplications[visualOwner.Children.IndexOf(_item)]).DiskApplication.Open(); _pressed = true; } } } class ToolBarClickBehavior : Behavior<FrameworkElement> { public Button TargetButton { get => (Button)GetValue(TargetButtonProperty); set => SetValue(TargetButtonProperty, value); } public static readonly DependencyProperty TargetButtonProperty = DependencyProperty.Register("TargetButton", typeof(Button), typeof(ToolBarClickBehavior), new PropertyMetadata(null, OnTargetButtonPropertyChangedCallback)); internal static void OnTargetButtonPropertyChangedCallback(object sender, DependencyPropertyChangedEventArgs e) { var sned = sender as ToolBarClickBehavior; sned.GetButton(); if (e.OldValue != null) (e.OldValue as Button).Click -= sned.Button_Click; } public DiskItem DiskFile { get => (DiskItem)GetValue(DiskFileProperty); set => SetValue(DiskFileProperty, value); } public static readonly DependencyProperty DiskFileProperty = DependencyProperty.Register("DiskFile", typeof(DiskItem), typeof(ToolBarClickBehavior), new PropertyMetadata(null)); Button _button; protected override void OnAttached() { base.OnAttached(); //_button = (AssociatedObject.TemplatedParent as FrameworkElement).TemplatedParent as Button; GetButton(); } void GetButton() { if (TargetButton != null) _button = TargetButton; else if (AssociatedObject.TemplatedParent != null) { if (AssociatedObject.TemplatedParent is FrameworkElement parent) { if (parent.TemplatedParent is Button button) _button = button; else _button = null; } else _button = null; if (_button != null) _button.Click += Button_Click; } else _button = null; } private void Button_Click(object sender, RoutedEventArgs e) { Debug.WriteLine("Opening file..."); /*Panel visualOwner = /*VisualTreeHelper.GetParent(_item)* / _button.TemplatedParent as Panel; var toolBar = visualOwner.TemplatedParent as SizableToolBar; (toolBar.ItemsSource as List<DiskItem>)[visualOwner.Children.IndexOf(_button)].Open();*/ if (DiskFile != null) DiskFile.Open(); } } }
36.753425
171
0.617406
[ "MIT" ]
StartNine/Superbar
Superbar/TaskItemClickBehavior.cs
5,368
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace OpenFeign.net { public class OpenFeign { public static T GenerateClient<T>() where T:class { return HttpProxy.Create<T>(); } public static object GenerateClientByType(Type type) { var method = typeof(OpenFeign).GetMethod(nameof(GenerateClient)); var generic = method.MakeGenericMethod(type); return generic.Invoke(null, null); } } }
23.73913
77
0.624542
[ "MIT" ]
yrc-cloud/OpenFeign.net
OpenFeign.net/OpenFeign.cs
548
C#
using IEXCloudClient.Common; using System.Collections.Generic; namespace IEXCloudClient.Quote { internal class QuoteMultiRequest : BaseRequest<Dictionary<string, RequestTypes>> { public QuoteMultiRequest(IEnumerable<string> symbols, string baseUrl, string token) : base(baseUrl, token) { SetEndpoint("stock", "market", "batch"); Parameters.Add("symbols", string.Join(",", symbols)); Parameters.Add("types", "quote"); } } }
31.0625
114
0.653924
[ "MIT" ]
sstrickley/IEXCloudClient
IEXCloudClient/Quote/QuoteMultiRequest.cs
499
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Adyen.Model.Checkout { /// <summary> /// LineItem /// </summary> [DataContract] public partial class LineItem : IEquatable<LineItem>, IValidatableObject { /// <summary> /// Tax category: High, Low, None, Zero /// </summary> /// <value>Tax category: High, Low, None, Zero</value> [JsonConverter(typeof(StringEnumConverter))] public enum TaxCategoryEnum { /// <summary> /// Enum High for value: High /// </summary> [EnumMember(Value = "High")] High = 1, /// <summary> /// Enum Low for value: Low /// </summary> [EnumMember(Value = "Low")] Low = 2, /// <summary> /// Enum None for value: None /// </summary> [EnumMember(Value = "None")] None = 3, /// <summary> /// Enum Zero for value: Zero /// </summary> [EnumMember(Value = "Zero")] Zero = 4 } /// <summary> /// Tax category: High, Low, None, Zero /// </summary> /// <value>Tax category: High, Low, None, Zero</value> [DataMember(Name="taxCategory", EmitDefaultValue=false)] public TaxCategoryEnum? TaxCategory { get; set; } /// <summary> /// Initializes a new instance of the <see cref="LineItem" /> class. /// </summary> /// <param name="AmountExcludingTax">Item amount excluding the tax, in minor units..</param> /// <param name="AmountIncludingTax">Item amount including the tax, in minor units..</param> /// <param name="Description">Description of the line item..</param> /// <param name="Id">ID of the line item..</param> /// <param name="Quantity">Number of items..</param> /// <param name="TaxAmount">Tax amount, in minor units..</param> /// <param name="TaxCategory">Tax category: High, Low, None, Zero.</param> /// <param name="TaxPercentage">Tax percentage, in minor units..</param> /// <param name="ProductUrl">Url to the item productpage.</param> /// <param name="ImageUrl">Url to an image of the item.</param> public LineItem(long? AmountExcludingTax = default(long?), long? AmountIncludingTax = default(long?), string Description = default(string), string Id = default(string), long? Quantity = default(long?), long? TaxAmount = default(long?), TaxCategoryEnum? TaxCategory = default(TaxCategoryEnum?), long? TaxPercentage = default(long?), string ProductUrl = default(string), string ImageUrl = default(string)) { this.AmountExcludingTax = AmountExcludingTax; this.AmountIncludingTax = AmountIncludingTax; this.Description = Description; this.Id = Id; this.Quantity = Quantity; this.TaxAmount = TaxAmount; this.TaxCategory = TaxCategory; this.TaxPercentage = TaxPercentage; this.ProductUrl = ProductUrl; this.ImageUrl = ImageUrl; } /// <summary> /// Item amount excluding the tax, in minor units. /// </summary> /// <value>Item amount excluding the tax, in minor units.</value> [DataMember(Name="amountExcludingTax", EmitDefaultValue=false)] public long? AmountExcludingTax { get; set; } /// <summary> /// Item amount including the tax, in minor units. /// </summary> /// <value>Item amount including the tax, in minor units.</value> [DataMember(Name="amountIncludingTax", EmitDefaultValue=false)] public long? AmountIncludingTax { get; set; } /// <summary> /// Description of the line item. /// </summary> /// <value>Description of the line item.</value> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// ID of the line item. /// </summary> /// <value>ID of the line item.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Number of items. /// </summary> /// <value>Number of items.</value> [DataMember(Name="quantity", EmitDefaultValue=false)] public long? Quantity { get; set; } /// <summary> /// Tax amount, in minor units. /// </summary> /// <value>Tax amount, in minor units.</value> [DataMember(Name="taxAmount", EmitDefaultValue=false)] public long? TaxAmount { get; set; } /// <summary> /// Tax percentage, in minor units. /// </summary> /// <value>Tax percentage, in minor units.</value> [DataMember(Name="taxPercentage", EmitDefaultValue=false)] public long? TaxPercentage { get; set; } /// <summary> /// Url to the productpage. /// </summary> /// <value>Description of the line item.</value> [DataMember(Name = "productUrl", EmitDefaultValue = false)] public string ProductUrl { get; set; } /// <summary> /// Url to an image of the item. /// </summary> /// <value>Description of the line item.</value> [DataMember(Name = "imageUrl", EmitDefaultValue = false)] public string ImageUrl { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LineItem {\n"); sb.Append(" AmountExcludingTax: ").Append(AmountExcludingTax).Append("\n"); sb.Append(" AmountIncludingTax: ").Append(AmountIncludingTax).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" TaxAmount: ").Append(TaxAmount).Append("\n"); sb.Append(" TaxCategory: ").Append(TaxCategory).Append("\n"); sb.Append(" TaxPercentage: ").Append(TaxPercentage).Append("\n"); sb.Append(" ProductUrl: ").Append(ProductUrl).Append("\n"); sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as LineItem); } /// <summary> /// Returns true if LineItem instances are equal /// </summary> /// <param name="input">Instance of LineItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(LineItem input) { if (input == null) return false; return ( this.AmountExcludingTax == input.AmountExcludingTax || (this.AmountExcludingTax != null && this.AmountExcludingTax.Equals(input.AmountExcludingTax)) ) && ( this.AmountIncludingTax == input.AmountIncludingTax || (this.AmountIncludingTax != null && this.AmountIncludingTax.Equals(input.AmountIncludingTax)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Quantity == input.Quantity || (this.Quantity != null && this.Quantity.Equals(input.Quantity)) ) && ( this.TaxAmount == input.TaxAmount || (this.TaxAmount != null && this.TaxAmount.Equals(input.TaxAmount)) ) && ( this.TaxCategory == input.TaxCategory || (this.TaxCategory != null && this.TaxCategory.Equals(input.TaxCategory)) ) && ( this.TaxPercentage == input.TaxPercentage || (this.TaxPercentage != null && this.TaxPercentage.Equals(input.TaxPercentage)) ) && ( this.ProductUrl == input.ProductUrl || (this.ProductUrl != null && this.ProductUrl.Equals(input.ProductUrl)) ) && ( this.ImageUrl == input.ImageUrl || (this.ImageUrl != null && this.ImageUrl.Equals(input.ImageUrl)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AmountExcludingTax != null) hashCode = hashCode * 59 + this.AmountExcludingTax.GetHashCode(); if (this.AmountIncludingTax != null) hashCode = hashCode * 59 + this.AmountIncludingTax.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Quantity != null) hashCode = hashCode * 59 + this.Quantity.GetHashCode(); if (this.TaxAmount != null) hashCode = hashCode * 59 + this.TaxAmount.GetHashCode(); if (this.TaxCategory != null) hashCode = hashCode * 59 + this.TaxCategory.GetHashCode(); if (this.TaxPercentage != null) hashCode = hashCode * 59 + this.TaxPercentage.GetHashCode(); if (this.ProductUrl != null) hashCode = hashCode * 59 + this.ProductUrl.GetHashCode(); if (this.ImageUrl != null) hashCode = hashCode * 59 + this.ImageUrl.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
40.296296
411
0.525819
[ "MIT" ]
Ganesh-Chavan/adyen-dotnet-api-library
Adyen/Model/Checkout/LineItem.cs
11,968
C#
using System; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Newtonsoft.Json; using Swashbuckle.AspNetCore.SwaggerUI; namespace ImCore.Chat { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = " API 文档", Description = "by bj eland" }); options.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OvOv.ImCore.Chat.xml")); }); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStaticFiles(); app.UseSwagger().UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); c.DocExpansion(DocExpansion.None); }); ImHelper.Initialization(new ImClientOptions { Redis = new CSRedis.CSRedisClient("127.0.0.1:6379,poolsize=5"), Servers = new[] { "127.0.0.1:6001" } }); ImHelper.Instance.OnSend += (s, e) => Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})"); ImHelper.EventBus( t => { Console.WriteLine(t.clientId + "上线了"); var onlineUids = ImHelper.GetClientListByOnline(); ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了"); }, t => Console.WriteLine(t.clientId + "下线了")); app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
33.637363
143
0.552107
[ "MIT" ]
2881099/dotnetcore-examples
aspnetcore-im/OvOv.ImCore.Chat/Startup.cs
3,089
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System.Runtime.InteropServices; using System; namespace MonoGame.Utilities { internal enum OS { Windows, Linux, MacOSX, Unknown } internal static class CurrentPlatform { private static bool init = false; private static OS os; [DllImport ("libc")] static extern int uname (IntPtr buf); private static void Init() { if (!init) { PlatformID pid = Environment.OSVersion.Platform; switch (pid) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: os = OS.Windows; break; case PlatformID.MacOSX: os = OS.MacOSX; break; case PlatformID.Unix: // Mac can return a value of Unix sometimes, We need to double check it. IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal (8192); if (uname (buf) == 0) { string sos = Marshal.PtrToStringAnsi (buf); if (sos == "Darwin") { os = OS.MacOSX; return; } } } catch { } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal (buf); } os = OS.Linux; break; default: os = OS.Unknown; break; } init = true; } } public static OS OS { get { Init(); return os; } } } public static class PlatformParameters { /// <summary> /// If true, MonoGame will detect the CPU architecture (x86 or x86-64) and add the "./x86" or "./x64" folder to the /// native DLL resolution paths. This allows MonoGame to work with Any CPU by loading the correct dependencies at runtime. /// If false, MonoGame will look for native DLLs in the executing folder, which typically is the .exe home. /// /// This parameter only works on Windows and doesn't affect other platforms. /// </summary> public static bool DetectWindowsArchitecture = (CurrentPlatform.OS == OS.Windows ? true : false); } internal static class NativeHelper { [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetDllDirectory(string lpPathName); private static bool _dllDirectorySet = false; public static void InitDllDirectory() { if (CurrentPlatform.OS == OS.Windows && !_dllDirectorySet) { string executingDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (Environment.Is64BitProcess) { NativeHelper.SetDllDirectory(System.IO.Path.Combine(executingDirectory, "x64")); } else { NativeHelper.SetDllDirectory(System.IO.Path.Combine(executingDirectory, "x86")); } _dllDirectorySet = true; } } } }
32.063492
136
0.459653
[ "MIT" ]
Adrriii/MonoGame
MonoGame.Framework/Utilities/CurrentPlatform.cs
4,042
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using XFile = Microsoft.Azure.Storage.File; using Microsoft.Azure.Storage.File; using System; using System.Collections.Concurrent; using System.Management.Automation; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Commands.Storage.File.Cmdlet { [Microsoft.Azure.PowerShell.Cmdlets.Storage.Profile("latest-2019-04-30")] [Cmdlet("Get", Azure.Commands.ResourceManager.Common.AzureRMConstants.AzurePrefix + "StorageFileCopyState!V2")] [OutputType(typeof(CloudFile))] public class GetAzureStorageFileCopyStateCommand : AzureStorageFileCmdletBase { [Parameter( Position = 0, HelpMessage = "Target share name", Mandatory = true, ParameterSetName = Constants.ShareNameParameterSetName)] [ValidateNotNullOrEmpty] public string ShareName { get; set; } [Parameter( Position = 1, HelpMessage = "Target file path", Mandatory = true, ParameterSetName = Constants.ShareNameParameterSetName)] [ValidateNotNullOrEmpty] public string FilePath { get; set; } [Parameter( Position = 0, HelpMessage = "Target file instance", Mandatory = true, ValueFromPipeline = true, ParameterSetName = Constants.FileParameterSetName)] [ValidateNotNull] public CloudFile File { get; set; } [Parameter(HelpMessage = "Indicates whether or not to wait util the copying finished.")] public SwitchParameter WaitForComplete { get; set; } /// <summary> /// CloudFile objects which need to mointor until copy complete /// </summary> private ConcurrentQueue<Tuple<long, CloudFile>> jobList = new ConcurrentQueue<Tuple<long, CloudFile>>(); private ConcurrentDictionary<long, bool> TaskStatus = new ConcurrentDictionary<long, bool>(); /// <summary> /// Is the specified task completed /// </summary> /// <param name="taskId">Task id</param> /// <returns>True if the specified task completed, otherwise false</returns> protected bool IsTaskCompleted(long taskId) { bool finished = false; bool existed = TaskStatus.TryGetValue(taskId, out finished); return existed && finished; } /// <summary> /// Copy task count /// </summary> private long InternalTotalTaskCount = 0; private long InternalFailedCount = 0; private long InternalFinishedCount = 0; /// <summary> /// Execute command /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { CloudFile file = null; if (null != this.File) { file = this.File; } else { string[] path = NamingUtil.ValidatePath(this.FilePath, true); file = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference().GetFileReferenceByPath(path); } long taskId = InternalTotalTaskCount; jobList.Enqueue(new Tuple<long, CloudFile>(taskId, file)); InternalTotalTaskCount++; } /// <summary> /// Write transmit summary status /// </summary> protected override void WriteTransmitSummaryStatus() { long localTotal = Interlocked.Read(ref InternalTotalTaskCount); long localFailed = Interlocked.Read(ref InternalFailedCount); long localFinished = Interlocked.Read(ref InternalFinishedCount); string summary = String.Format(ResourceV2.TransmitActiveSummary, localTotal, localFailed, localFinished, (localTotal - localFailed - localFinished)); summaryRecord.StatusDescription = summary; WriteProgress(summaryRecord); } /// <summary> /// Update failed/finished task count /// </summary> /// <param name="status">Copy status</param> private void UpdateTaskCount(XFile.CopyStatus status) { switch (status) { case XFile.CopyStatus.Invalid: case XFile.CopyStatus.Failed: case XFile.CopyStatus.Aborted: Interlocked.Increment(ref InternalFailedCount); break; case XFile.CopyStatus.Pending: break; case XFile.CopyStatus.Success: default: Interlocked.Increment(ref InternalFinishedCount); break; } } /// <summary> /// Write copy progress /// </summary> /// <param name="file">CloudFile instance</param> /// <param name="progress">Progress record</param> internal void WriteCopyProgress(CloudFile file, ProgressRecord progress) { if (file.CopyState == null) return; long bytesCopied = file.CopyState.BytesCopied ?? 0; long totalBytes = file.CopyState.TotalBytes ?? 0; int percent = 0; if (totalBytes != 0) { percent = (int)(bytesCopied * 100 / totalBytes); progress.PercentComplete = percent; } string activity = String.Format(ResourceV2.CopyFileStatus, file.CopyState.Status.ToString(), file.GetFullPath(), file.Share.Name, file.CopyState.Source.ToString()); progress.Activity = activity; string message = String.Format(ResourceV2.CopyPendingStatus, percent, file.CopyState.BytesCopied, file.CopyState.TotalBytes); progress.StatusDescription = message; OutputStream.WriteProgress(progress); } protected override void EndProcessing() { int currency = GetCmdletConcurrency(); OutputStream.TaskStatusQueryer = IsTaskCompleted; for (int i = 0; i < currency; i++) { Func<long, Task> taskGenerator = (taskId) => MonitorFileCopyStatusAsync(taskId); RunTask(taskGenerator); } base.EndProcessing(); } /// <summary> /// Cmdlet end processing /// </summary> protected async Task MonitorFileCopyStatusAsync(long taskId) { ProgressRecord records = new ProgressRecord(OutputStream.GetProgressId(taskId), ResourceV2.CopyFileActivity, ResourceV2.CopyFileActivity); Tuple<long, CloudFile> monitorRequest = null; FileRequestOptions requestOptions = RequestOptions; AccessCondition accessCondition = null; OperationContext context = OperationContext; while (!jobList.IsEmpty) { jobList.TryDequeue(out monitorRequest); if (monitorRequest != null) { long internalTaskId = monitorRequest.Item1; CloudFile file = monitorRequest.Item2; //Just use the last file management channel since the following operation is context insensitive await Channel.FetchFileAttributesAsync(file, accessCondition, requestOptions, context, CmdletCancellationToken).ConfigureAwait(false); bool taskDone = false; if (file.CopyState == null) { ArgumentException e = new ArgumentException(String.Format(ResourceV2.FileCopyTaskNotFound, file.SnapshotQualifiedUri.ToString())); OutputStream.WriteError(internalTaskId, e); Interlocked.Increment(ref InternalFailedCount); taskDone = true; } else { WriteCopyProgress(file, records); UpdateTaskCount(file.CopyState.Status); if (file.CopyState.Status == XFile.CopyStatus.Pending && this.WaitForComplete) { jobList.Enqueue(monitorRequest); } else { OutputStream.WriteObject(internalTaskId, file.CopyState); taskDone = true; } } if (taskDone) { SetInternalTaskDone(internalTaskId); } } if (ShouldForceQuit) { break; } } } private void SetInternalTaskDone(long taskId) { bool finishedTaskStatus = true; TaskStatus.TryAdd(taskId, finishedTaskStatus); } } }
40.2749
177
0.558809
[ "MIT" ]
bganapa/azure-powershell
src/Storage/custom/Dataplane.v2/File/Cmdlet/GetAzureStorageFileCopyState.cs
9,861
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tcb.V20180608.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CommonServiceAPIResponse : AbstractModel { /// <summary> /// json格式response /// </summary> [JsonProperty("JSONResp")] public string JSONResp{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "JSONResp", this.JSONResp); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.54902
81
0.6457
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Tcb/V20180608/Models/CommonServiceAPIResponse.cs
1,620
C#
using System.Collections.Generic; using Horizon.Payment.Alipay.Response; namespace Horizon.Payment.Alipay.Request { /// <summary> /// koubei.retail.wms.goodssafetyinventory.batchquery /// </summary> public class KoubeiRetailWmsGoodssafetyinventoryBatchqueryRequest : IAlipayRequest<KoubeiRetailWmsGoodssafetyinventoryBatchqueryResponse> { /// <summary> /// 安全库存批量查询接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "koubei.retail.wms.goodssafetyinventory.batchquery"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.048387
141
0.555283
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Request/KoubeiRetailWmsGoodssafetyinventoryBatchqueryRequest.cs
2,880
C#
using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using FirstFloor.ModernUI.Windows.Controls; using Microsoft.Win32; namespace Captura { public class TrimmerViewModel : NotifyPropertyChanged, IDisposable { MediaElement _player; Window _window; readonly DispatcherTimer _timer; public bool IsDragging { get; set; } public void AssignPlayer(MediaElement Player, Window Window) { _player = Player; _window = Window; _player.MediaOpened += (S, E) => { From = TimeSpan.Zero; if (_player.NaturalDuration.HasTimeSpan) { To = End = _player.NaturalDuration.TimeSpan; } else To = End = TimeSpan.Zero; PlayCommand.RaiseCanExecuteChanged(true); TrimCommand.RaiseCanExecuteChanged(true); }; _timer.Start(); } public TrimmerViewModel() { _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; _timer.Tick += (Sender, Args) => { if (IsDragging) return; RaisePropertyChanged(nameof(PlaybackPosition)); if (IsPlaying && _player.Position > To || _player.Position < From) { Stop(); } }; OpenCommand = new DelegateCommand(Open); PlayCommand = new DelegateCommand(Play, false); TrimCommand = new DelegateCommand(Trim, false); } TimeSpan _from, _to, _end; public TimeSpan From { get => _from; set { _from = value; if (IsPlaying && value + TimeSpan.FromSeconds(1) >= _player.Position) { Stop(); } OnPropertyChanged(); } } void Stop() { if (!_isPlaying) return; _player.Stop(); IsPlaying = false; } void Play() { if (IsPlaying) Stop(); else { _player.Position = From; _player.Play(); IsPlaying = true; } } public TimeSpan To { get => _to; set { _to = value; if (IsPlaying && _player.Position + TimeSpan.FromSeconds(1) >= value) { Stop(); } OnPropertyChanged(); } } public TimeSpan End { get => _end; set { _end = value; OnPropertyChanged(); } } string _fileName; public string FileName { get => _fileName; private set { _fileName = value; OnPropertyChanged(); } } string _filePath; public string FilePath { get => _filePath; set { _filePath = value; FileName = Path.GetFileNameWithoutExtension(value); OnPropertyChanged(); } } public DelegateCommand OpenCommand { get; } public DelegateCommand PlayCommand { get; } public DelegateCommand TrimCommand { get; } void Open() { var ofd = new OpenFileDialog { CheckPathExists = true, CheckFileExists = true }; if (ofd.ShowDialog().GetValueOrDefault()) { Open(ofd.FileName); } } public void Open(string Path) { PlayCommand.RaiseCanExecuteChanged(false); TrimCommand.RaiseCanExecuteChanged(false); _player.Source = new Uri(Path); var oldVol = _player.Volume; // Force Load _player.Play(); _player.Stop(); _player.Volume = oldVol; FilePath = Path; } bool _isPlaying; public bool IsPlaying { get => _isPlaying; set { _isPlaying = value; OnPropertyChanged(); } } public TimeSpan PlaybackPosition { get => _player?.Position ?? TimeSpan.Zero; set => _player.Position = value; } public void Dispose() { _player.Close(); _player.Source = null; } async void Trim() { if (!FFMpegService.FFMpegExists) { ModernDialog.ShowMessage("FFMpeg not Found", "FFMpeg not Found", MessageBoxButton.OK, _window); return; } var ext = Path.GetExtension(FilePath); var sfd = new SaveFileDialog { AddExtension = true, DefaultExt = ext, Filter = $"*{ext}|*{ext}", FileName = Path.GetFileName(FilePath), InitialDirectory = Path.GetDirectoryName(FilePath), CheckPathExists = true }; if (sfd.ShowDialog().GetValueOrDefault()) { _player.Close(); var command = $"-i \"{FilePath}\" -ss {From} -to {To} {(_player.HasAudio ? "-acodec copy" : "")} \"{sfd.FileName}\""; var process = new Process { StartInfo = { FileName = FFMpegService.FFMpegExePath, Arguments = command, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true }, EnableRaisingEvents = true }; var output = ""; process.ErrorDataReceived += (Sender, Args) => output += "\n" + Args.Data; OpenCommand.RaiseCanExecuteChanged(false); PlayCommand.RaiseCanExecuteChanged(false); TrimCommand.RaiseCanExecuteChanged(false); process.Start(); process.BeginErrorReadLine(); await Task.Run(() => process.WaitForExit()); if (process.ExitCode != 0) { ModernDialog.ShowMessage($"FFMpeg Output:\n{output}", "An Error Occured", MessageBoxButton.OK, _window); } OpenCommand.RaiseCanExecuteChanged(true); PlayCommand.RaiseCanExecuteChanged(true); TrimCommand.RaiseCanExecuteChanged(true); } } } }
24.786441
133
0.446663
[ "MIT" ]
anxgang/Captura
src/Captura/ViewModels/TrimmerViewModel.cs
7,314
C#
using Haengma.GS.Hubs; using Haengma.GS.Models; using Microsoft.AspNetCore.SignalR.Client; using Moq; using System; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Xunit; namespace Haengma.Tests { public static class HubExtensions { public static Mock<IGameClient> CreateGameClient(this HubConnection connection) { var client = new Mock<IGameClient>(); connection.On<JsonBoard>(nameof(IGameClient.BoardUpdated), v => client.Object.BoardUpdated(v)); connection.On<string>(nameof(IGameClient.CommentAdded), v => client.Object.CommentAdded(v)); connection.On<string>(nameof(IGameClient.GameCreated), v => client.Object.GameCreated(v)); connection.On<JsonGame>(nameof(IGameClient.GameStarted), v => client.Object.GameStarted(v)); connection.On<JsonColor>(nameof(IGameClient.PlayerPassed), v => client.Object.PlayerPassed(v)); return client; } public static Task CreateGameAsync(this HubConnection hubConnection, JsonGameSettings gameSettings) => hubConnection .InvokeAsync(nameof(GameHub.CreateGame), gameSettings); public static Task JoinGameAsync(this HubConnection hubConnection, string gameId) => hubConnection .InvokeAsync(nameof(GameHub.JoinGame), gameId); public static Task AddMoveAsync(this HubConnection hubConnection, string gameId, JsonPoint move) => hubConnection .InvokeAsync(nameof(GameHub.AddMove), gameId, move); public static Task PassAsync(this HubConnection hubConnection, string gameId) => hubConnection .InvokeAsync(nameof(GameHub.Pass), gameId); public static async Task<JsonColor> VerifyPlayerPassedAsync(this Mock<IGameClient> gameClient, Times times, string failMessage = "Couldn't verify that a player passed.") { await gameClient.VerifyWithTimeoutAsync(x => x.PlayerPassed(It.IsAny<JsonColor>()), times, failMessage: failMessage); var value = gameClient.GetValueFromInvocations<JsonColor>(nameof(IGameClient.PlayerPassed)); gameClient.Invocations.Clear(); return value; } public static async Task<JsonGame> VerifyGameStarted(this Mock<IGameClient> gameClient, Times times, string failMessage = "Couldn't verify that game started was triggered.") { await gameClient.VerifyWithTimeoutAsync(x => x.GameStarted(It.IsAny<JsonGame>()), times, failMessage: failMessage); var value = gameClient.GetValueFromInvocations<JsonGame>(nameof(IGameClient.GameStarted)); gameClient.Invocations.Clear(); return value; } public static async Task<JsonBoard> VerifyBoardUpdated(this Mock<IGameClient> gameClient, Times times, string failMessage = "Couldn't verify board update.") { await gameClient.VerifyWithTimeoutAsync(x => x.BoardUpdated(It.IsAny<JsonBoard>()), times, failMessage: failMessage); var value = gameClient.GetValueFromInvocations<JsonBoard>(nameof(IGameClient.BoardUpdated)); gameClient.Invocations.Clear(); return value; } public static async Task<string> VerifyGameCreated(this Mock<IGameClient> gameClient, Times times, string failMessage = "Couldn't verify game created.") { await gameClient.VerifyWithTimeoutAsync(x => x.GameCreated(It.IsAny<string>()), times, failMessage: failMessage); var value = gameClient.GetValueFromInvocations<string>(nameof(IGameClient.GameCreated)); gameClient.Invocations.Clear(); return value; } private static T GetValueFromInvocations<T>(this Mock<IGameClient> client, string methodName) => client .Invocations .Where(x => x.Method == typeof(IGameClient).GetMethod(methodName)) .SelectMany(x => x.Arguments) .OfType<T>() .LastOrDefault(); private static async Task VerifyWithTimeoutAsync(this Mock<IGameClient> gameClient, Expression<Func<IGameClient, Task>> method, Times times, int timeOutInMs = 100, int delayBetweenIterationInMs = 50, string failMessage = "Failed to verify") { bool hasBeenExecuted = false; bool hasTimedOut = false; var stopwatch = new Stopwatch(); stopwatch.Start(); while (!hasBeenExecuted && !hasTimedOut) { if (stopwatch.ElapsedMilliseconds > timeOutInMs) { hasTimedOut = true; } try { gameClient.Verify(method, times); hasBeenExecuted = true; } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } await Task.Delay(delayBetweenIterationInMs); } if (!hasBeenExecuted) { Assert.False(true, failMessage); } } } }
44.101695
181
0.640085
[ "MIT" ]
Ekenstein/Haengma
Haengma.Tests/HubExtensions.cs
5,206
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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, ValueSource<SolutionStateChecksums>> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } private void CheckInvariants() { // Run these quick checks all the time. We need to know immediately if we violate these. Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. #if DEBUG // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); #endif } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.UnionWithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; Contract.ThrowIfFalse(_projectIdToProjectStateMap.ContainsKey(projectId)); var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(_solutionServices, newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(_solutionServices, tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); Contract.ThrowIfFalse(_projectIdToProjectStateMap.ContainsKey(documentId.ProjectId)); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
46.184329
218
0.644579
[ "MIT" ]
bernd5/roslyn
src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs
91,955
C#
using AMaaS.Core.Sdk.Models; using System; using System.Collections.Generic; using System.Text; namespace AMaaS.Core.Sdk.Transactions.Models { public class Code : AMaaSModel { #region Properties public string CodeValue { get; set; } #endregion } }
17.882353
46
0.638158
[ "Apache-2.0" ]
amaas-fintech/amaas-core-sdk-dotnet
AMaaS.Core.Sdk.Transactions/Models/Code.cs
306
C#
using Dotmim.Sync; using Dotmim.Sync.Enumerations; using Dotmim.Sync.SqlServer; using System; using System.Threading.Tasks; namespace ProvisionDeprovision { class Program { private static string serverConnectionString = $"Data Source=(localdb)\\mssqllocaldb; Initial Catalog=AdventureWorks;Integrated Security=true;"; private static string clientConnectionString = $"Data Source=(localdb)\\mssqllocaldb; Initial Catalog=Client;Integrated Security=true;"; static async Task Main(string[] args) { await ProvisionServerManuallyAsync(); await ProvisionClientManuallyAsync(); await DeprovisionServerManuallyAsync(); await DeprovisionClientManuallyAsync(); Console.WriteLine("Hello World!"); } private static async Task ProvisionServerManuallyAsync() { // Create 2 Sql Sync providers var serverProvider = new SqlSyncProvider(serverConnectionString); // Create standard Setup and Options var setup = new SyncSetup(new string[] { "Address", "Customer", "CustomerAddress" }); var options = new SyncOptions(); // ----------------------------------------------------------------- // Server side // ----------------------------------------------------------------- // This method is useful if you want to provision by yourself the server database // You will need to : // - Create a remote orchestrator with the correct setup to proivision // - Get the server scope that will contains after provisioning, the serialized version of your scope / schema // - Provision everything // - Save the server scope information // Create a server orchestrator used to Deprovision and Provision only table Address var remoteOrchestrator = new RemoteOrchestrator(serverProvider, options, setup); // Get the server scope var serverScope = await remoteOrchestrator.GetServerScopeAsync(); // Server scope is created on the server side. // but Setup and Schema are both null, since nothing have been created so far // // serverScope.Setup = null; // serverScope.Schema = null; // // Provision everything needed (sp, triggers, tracking tables) // Internally provision will fectch the schema a will return it to the caller. var newSchema = await remoteOrchestrator.ProvisionAsync(SyncProvision.StoredProcedures | SyncProvision.Triggers | SyncProvision.TrackingTable); // affect good values serverScope.Setup = setup; serverScope.Schema = newSchema; // save the server scope await remoteOrchestrator.WriteServerScopeAsync(serverScope); } private static async Task DeprovisionServerManuallyAsync() { // Create server provider var serverProvider = new SqlSyncProvider(serverConnectionString); // Create standard Setup and Options var setup = new SyncSetup(new string[] { "Address", "Customer", "CustomerAddress" }); var options = new SyncOptions(); // Create a server orchestrator used to Deprovision everything on the server side var remoteOrchestrator = new RemoteOrchestrator(serverProvider, options, setup); // Get the server scope var serverScope = await remoteOrchestrator.GetServerScopeAsync(); // Deprovision everything await remoteOrchestrator.DeprovisionAsync(SyncProvision.StoredProcedures | SyncProvision.Triggers | SyncProvision.TrackingTable); // Affect good values serverScope.Setup = null; serverScope.Schema = null; // save the server scope await remoteOrchestrator.WriteServerScopeAsync(serverScope); } private static async Task DeprovisionClientManuallyAsync() { // Create client provider var clientProvider = new SqlSyncProvider(clientConnectionString); // Create standard Setup and Options var setup = new SyncSetup(new string[] { "Address", "Customer", "CustomerAddress" }); var options = new SyncOptions(); // Create a local orchestrator used to Deprovision everything var localOrchestrator = new LocalOrchestrator(clientProvider, options, setup); // Get the local scope var clientScope = await localOrchestrator.GetClientScopeAsync(); // Deprovision everything await localOrchestrator.DeprovisionAsync(SyncProvision.StoredProcedures | SyncProvision.Triggers | SyncProvision.TrackingTable | SyncProvision.Table); // affect good values clientScope.Setup = null; clientScope.Schema = null; // save the local scope await localOrchestrator.WriteClientScopeAsync(clientScope); } private static async Task ProvisionClientManuallyAsync() { // Create 2 Sql Sync providers var serverProvider = new SqlSyncProvider(serverConnectionString); var clientProvider = new SqlSyncProvider(clientConnectionString); // Create standard Setup and Options var setup = new SyncSetup(new string[] { "Address", "Customer", "CustomerAddress" }); var options = new SyncOptions(); // ----------------------------------------------------------------- // Client side // ----------------------------------------------------------------- // This method is useful if you want to provision by yourself the client database // You will need to : // - Create a local orchestrator with the correct setup to provision // - Get the local scope that will contains after provisioning, the serialized version of your scope / schema // - Get the schema from the server side using a RemoteOrchestrator or a WebClientOrchestrator // - Provision everything locally // - Save the local scope information // Create a local orchestrator used to provision everything locally var localOrchestrator = new LocalOrchestrator(clientProvider, options, setup); // Because we need the schema from remote side, create a remote orchestrator var remoteOrchestrator = new RemoteOrchestrator(serverProvider, options, setup); // Getting the schema from server side var serverSchema = await remoteOrchestrator.GetSchemaAsync(); // At this point, if you need the schema and you are not able to create a RemoteOrchestrator, // You can create a WebClientOrchestrator and get the schema as well // var proxyClientProvider = new WebClientOrchestrator("https://localhost:44369/api/Sync"); // var serverSchema = proxyClientProvider.GetSchemaAsync(); // get the local scope var clientScope = await localOrchestrator.GetClientScopeAsync(); // Provision everything needed (sp, triggers, tracking tables, AND TABLES) await localOrchestrator.ProvisionAsync(serverSchema, SyncProvision.StoredProcedures | SyncProvision.Triggers | SyncProvision.TrackingTable | SyncProvision.Table); // affect good values clientScope.Setup = setup; clientScope.Schema = serverSchema; // save the client scope await localOrchestrator.WriteClientScopeAsync(clientScope); } } }
43.899441
155
0.620769
[ "MIT" ]
NgoVoQuocAnh/Dotmim.Sync
Samples/ProvisionDeprovision/Program.cs
7,860
C#
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // -------------------------------------------------------------------------- using System.IO; namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Tests.Extractor.Abstractions { public class ExtractorMockerWithOutputTestsBase : ExtractorMockerTestsBase { protected const string TESTS_OUTPUT_DIRECTORY = "tests-output"; protected string OutputDirectory; protected ExtractorMockerWithOutputTestsBase(string outputDirectoryName) { this.OutputDirectory = Path.Combine(TESTS_OUTPUT_DIRECTORY, outputDirectoryName); // remember to clean up the output directory before each test if (Directory.Exists(this.OutputDirectory)) { Directory.Delete(this.OutputDirectory, true); } } } }
36.777778
93
0.588117
[ "MIT" ]
Azure/azure-api-management-devops-example
tests/ArmTemplates.Tests/Extractor/Abstractions/ExtractorMockerWithOutputTestsBase.cs
995
C#
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Sockets.BluetoothDeviceInfo // // Copyright (c) 2003-2020 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using InTheHand.Net.Bluetooth; using System; using System.Collections.Generic; namespace InTheHand.Net.Sockets { public sealed partial class BluetoothDeviceInfo : IEquatable<BluetoothDeviceInfo> { public void Refresh() { DoRefresh(); } public BluetoothAddress DeviceAddress { get { return GetDeviceAddress(); } } public string DeviceName { get { return GetDeviceName(); } } public ClassOfDevice ClassOfDevice { get { return GetClassOfDevice(); } } public IReadOnlyCollection<Guid> InstalledServices { get { return GetInstalledServices(); } } public bool Connected { get { return GetConnected(); } } public bool Authenticated { get { return GetAuthenticated(); } } public void SetServiceState(Guid service, bool state) { DoSetServiceState(service, state); } public bool Equals(BluetoothDeviceInfo other) { if (other is null) return false; return DeviceAddress == other.DeviceAddress; } } }
20.795181
85
0.495365
[ "MIT" ]
msalandro/32feet
InTheHand.Net.Bluetooth/BluetoothDeviceInfo.cs
1,728
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("Actor2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Actor2")] [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("a9077f31-cdab-4ff4-b435-7fc44a30ac60")] // 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")]
37.432432
84
0.74296
[ "MIT" ]
arturl/SFCluster
service/Actor2/Properties/AssemblyInfo.cs
1,388
C#
using Microsoft.AspNet.Mvc; using Microsoft.Framework.Configuration; using Microsoft.Framework.OptionsModel; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TKDemoMVC.Controllers { public class Data123Config { public int Value1 { get; set; } public string Value2 { get; set; } public DefaultConnectionClass DefaultConnection { get; set; } } public class DefaultConnectionClass { public string ConnectionString { get; set; } } public class OptionsController : Controller { AppSettingsConfig Options { get; } Data123Config Data { get; } SecretsConfig Secrets { get; } public OptionsController(IOptions<AppSettingsConfig> opt, IOptions<Data123Config> dat, IOptions<SecretsConfig> sec) { Options = opt.Options; Data = dat.Options; //user-secret.cmd set AzureKey ABC Secrets = sec.Options; } public IActionResult Index() { return View(); //Maybe using model? } } }
34.090909
126
0.640889
[ "MIT" ]
tkopacz/aspnet5-tkdemo-beta7
TKDemoMVC_beta7/src/TKDemoMVC/Controllers/OptionsController.cs
1,127
C#
using GameFramework; using GameFramework.ObjectPool; using UnityEngine; using UnityGameFramework.Runtime; namespace UGFExtensions.Texture { public class TextureItemObject : ObjectBase { private TextureLoad m_TextureLoad; private ResourceComponent m_ResourceComponent; public static TextureItemObject Create(string collectionPath, UnityEngine.Texture target,TextureLoad textureLoad,ResourceComponent resourceComponent = null) { TextureItemObject item = ReferencePool.Acquire<TextureItemObject>(); item.Initialize(collectionPath, target); item.m_TextureLoad = textureLoad; item.m_ResourceComponent = resourceComponent; return item; } protected override void Release(bool isShutdown) { UnityEngine.Texture texture = (UnityEngine.Texture)Target; if (texture == null) { return; } switch (m_TextureLoad) { case TextureLoad.FromResource: m_ResourceComponent.UnloadAsset(texture); m_ResourceComponent = null; break; case TextureLoad.FromNet: case TextureLoad.FromFileSystem: Object.Destroy(texture); break; } } } public enum TextureLoad { /// <summary> /// 从文件系统 /// </summary> FromFileSystem, /// <summary> /// 从网络 /// </summary> FromNet, /// <summary> /// 从资源包 /// </summary> FromResource } }
28.779661
164
0.557715
[ "MIT" ]
FingerCaster/UGFExtension
Assets/Scripts/TextureExtension/TextureItemObject.cs
1,722
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace IniParse { /// <summary> /// Represents a section in an ini file /// </summary> public class IniSection : Validateable, ICloneable { /// <summary> /// Gets or sets the name of the section /// </summary> /// <remarks>This can be null for an unnamed section</remarks> public string Name { get; set; } /// <summary> /// Gets the list of settings /// </summary> public List<IniSetting> Settings { get; private set; } /// <summary> /// Gets or sets the section header comments /// </summary> public string[] Comments { get; set; } /// <summary> /// Gets or sets the case sensitivity handling when searching for names /// </summary> public CaseSensitivity CaseHandling { get; set; } /// <summary> /// Gets the first setting with the given name /// </summary> /// <param name="name">Setting name</param> /// <returns>Setting</returns> public IniSetting this[string name] { get { return Settings.FirstOrDefault(m => SetEq(m.Name, name)); } } /// <summary> /// Gets the setting at the given position /// </summary> /// <param name="index">Setting position</param> /// <returns>Setting</returns> public IniSetting this[int index] { get { return Settings[index]; } } /// <summary> /// Initializes an empty section /// </summary> public IniSection() : this(null) { } /// <summary> /// Initializes a named section /// </summary> /// <param name="SectionName">Section name</param> public IniSection(string SectionName) { Name = SectionName; Settings = new List<IniSetting>(); } /// <summary> /// Gets all settings with the given name /// </summary> /// <param name="SettingName">Setting name</param> /// <returns>Found settings</returns> public IniSetting[] GetAll(string SettingName) { return Settings .Where(m => SetEq(m.Name, SettingName)) .ToArray(); } /// <summary> /// Gets all values with the given name /// </summary> /// <param name="SettingName">Setting name</param> /// <returns>Found Values</returns> public string[] GetValues(string SettingName) { return GetAll(SettingName) .Select(m => m.Value) .ToArray(); } /// <summary> /// Removes all settings with the given name according to /// </summary> /// <param name="SettingName"></param> public void RemoveSettings(string SettingName) { Settings.RemoveAll(m => SetEq(m.Name, SettingName)); } /// <summary> /// Exports this section /// </summary> /// <param name="SW">Location to write contents to</param> /// <param name="CommentChar">Character for comments</param> /// <returns>Task</returns> public async Task ExportSection(StreamWriter SW, char CommentChar) { if (Name != null) { if (!Tools.IsEmpty(Comments)) { foreach (var L in Comments) { await SW.WriteLineAsync($"{CommentChar}{L}"); } } await SW.WriteLineAsync($"[{Name}]"); } foreach (var S in Settings) { await S.ExportSetting(SW, CommentChar); } } /// <summary> /// Sorts the settings in this section /// </summary> /// <param name="ascending">Sort ascending</param> public void Sort(bool Ascending = true) { if (Ascending) { Settings.Sort((m, n) => m.Name.CompareTo(n.Name)); } else { Settings.Sort((n, m) => m.Name.CompareTo(n.Name)); } } /// <summary> /// Checks if two setting names are equal under the current <see cref="CaseHandling"/> flags /// </summary> /// <param name="A">Setting Name</param> /// <param name="B">Setting name</param> /// <returns>true, if considered identical</returns> private bool SetEq(string A, string B) { if (A == null && B == null) { return true; } else if (A == null || B == null) { return false; } if (CaseHandling.HasFlag(CaseSensitivity.CaseInsensitiveSetting)) { return A.ToLower() == B.ToLower(); } return A == B; } #region Overrides public object Clone() { var Copy = new IniSection(Name); Copy.CaseHandling = CaseHandling; if (Comments != null) { Copy.Comments = (string[])Comments.Clone(); } foreach (var Set in Settings) { Copy.Settings.Add((IniSetting)Set.Clone()); } return Copy; } /// <summary> /// Gets a string representation of this instance /// </summary> /// <returns>String representation</returns> public override string ToString() { return $"INI Section \"{Name}\" with {Settings.Count} settings"; } /// <summary> /// Validates this section /// </summary> /// <remarks> /// Sections are allowed to have duplicate settings by default. /// Check for duplicates yourself if you don't want them. /// </remarks> public override void Validate() { if (Name != null && Name.Any(m => Tools.ForbiddenHeaderChar.Contains(m))) { var ex = new ValidationException("Forbidden character in section name"); ex.Data.Add("Section", Name); throw ex; } foreach (var S in Settings) { try { S.Validate(); } catch (ValidationException ex) { ex.Data.Add("Section", Name); throw ex; } } } #endregion } }
29.508547
100
0.476466
[ "MIT" ]
AyrA/IniParse
IniParse/IniSection.cs
6,907
C#