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.Collections; using System.Collections.Generic; using UnityEngine; public enum ItemType { ShotTypeChange, BulletSupply, StageClear, } public class Item : MonoBehaviour { public ItemType m_itemType; private void OnCollisionEnter2D(Collision2D collision) { gameObject.SetActive(false); } }
16.190476
58
0.723529
[ "MIT" ]
world29/FlappyAzarashi
Assets/Scripts/Item.cs
342
C#
using UnityEngine; using System.Collections; using Sfs2X.Entities.Data; using YxFramwork.Common; using YxFramwork.Framework.Core; using YxFramwork.Manager; using System.Collections.Generic; using YxFramwork.View; namespace Assets.Scripts.Game.brtbsone { //棋牌控制 public class BrttzCardsCtrl : MonoBehaviour { public GameObject[] Target; public ISFSArray CardsValue = new SFSArray(); public UIGrid Grid; public GameObject CardClone; public DicePointsCtrl Dices; public CardPoint[] CardPoints; public HistoryCardsCtrl HistoryCardsCtrl; public int FirstCardsNum = 8; /// <summary> /// 从零开始在牌墙中第几排牌墙发牌,不能大于4 /// </summary> public int CutNum = 0; /// <summary> /// 每局游戏开始时是否需要洗牌,false为发完40张牌之后才洗牌,换庄自动洗牌.true为每局都洗牌 /// </summary> public bool IsNeedRefresh = false; //一共有多少张牌 public int MaxCardsNum = 40; /// <summary> /// 麻将缩放tween的两个值,索引0为初始值,索引1为目标值 /// </summary> public float[] CardsBgScaleNums; /// <summary> /// 已经给出了几张牌 /// </summary> protected int HasGiveNum; //保存牌堆上的牌 protected List<GameObject> Cards = new List<GameObject>(); /// <summary> /// 牌堆索引 /// </summary> protected int CardsArrindex; /// <summary> /// 庄家每门的输赢 /// </summary> internal int[] Bpg; /// <summary> /// 发牌状态 /// </summary> protected int GiveCardsStatus; /// <summary> /// 记录发了多少张牌 /// </summary> protected int Index; /// <summary> /// 发牌区域的索引 /// </summary> protected int Arrindex = -1; /// <summary> /// 翻牌时在牌墙里的索引 /// </summary> protected int ShowIndex; /// <summary> /// 发牌时在牌墙里的索引 /// </summary> protected int CardIndex; /// <summary> /// 骰子数组 /// </summary> protected int[] DicesNums; /// <summary> /// 骰子的值 /// </summary> protected int DicePoint; /// <summary> /// 打骰子从那家开始发牌 /// </summary> protected int StartNum; /// <summary> /// 记录已经出了哪些牌 /// </summary> protected Dictionary<int, int> HistoryCards = new Dictionary<int, int>(); /// <summary> /// 是否是重连 /// </summary> protected bool IsRejoin = false; public void GetHistoryCards(ISFSObject gameInfo) { var history = gameInfo.GetIntArray(Parameter.RCards); HasGiveNum = history.Length; if (history.Length == 0) return; for (int i = 0; i < history.Length; i++) { if (HistoryCards.ContainsKey(history[i])) HistoryCards[history[i]]++; } } //----------------发牌:---- public virtual void BeginGiveCards(ISFSObject responseData) { var gdata = App.GetGameData<BrttzGameData>(); if (responseData.ContainsKey(Parameter.Bpg)) { Bpg = responseData.GetIntArray(Parameter.Bpg); } if (responseData.ContainsKey(Parameter.Total)) { gdata.GetPlayerInfo().CoinA = responseData.GetLong(Parameter.Total); } gdata.ResultUserTotal = responseData.ContainsKey(Parameter.Win) ? responseData.GetInt(Parameter.Win) : 0; gdata.ResultBnakerTotal = responseData.ContainsKey(Parameter.Bwin) ? responseData.GetLong(Parameter.Bwin) : 0; CardsValue = responseData.GetSFSArray(Parameter.Cards); } public void GiveCardsOnFrist(ISFSObject gameInfo) { if (!gameInfo.ContainsKey(Parameter.RollResult)) return; var data = gameInfo.GetSFSObject(Parameter.RollResult); var cardsValueFrist = data.GetSFSArray(Parameter.Cards); int temp = 0; for (int i = 0; i < FirstCardsNum; i++) { var go = Cards[i]; go.transform.parent = Target[temp].GetComponent<BrttzCardPostion>().TargetPositions[i % 2]; go.transform.localScale = Vector3.one; go.transform.localPosition = Vector3.zero; var mj = go.GetComponent<MjCard>(); mj.Mahjong.spriteName = "card"; mj.Mahjong.MakePixelPerfect(); var values = cardsValueFrist.GetSFSObject(temp).GetIntArray(Parameter.Cards); mj.Target.spriteName = "A_" + values[i % 2]; mj.Target.gameObject.SetActive(true); if (i % 2 != 0) temp++; } for (int i = 0; i < 4; i++) { int type = cardsValueFrist.GetSFSObject(i).GetInt(Parameter.Type); int value = cardsValueFrist.GetSFSObject(i).GetInt(Parameter.Value); CardPoints[i].ShowPointValue(type, value); } IsRejoin = true; } public virtual void GetDicesPoints(int[] dices) { DicesNums = dices; var count = DicesNums.Length; for (int i = 0; i < count; i++) { DicePoint += DicesNums[i]; } GiveCardsStatus = 0; Invoke("BeginGiveCards", 1); } public virtual void GetDicesPoints(ISFSObject responseData) { if (responseData.ContainsKey(Parameter.Dices)) { DicesNums = responseData.GetIntArray(Parameter.Dices); } var count = DicesNums.Length; for (int i = 0; i < count; i++) { DicePoint += DicesNums[i]; } Dices.gameObject.SetActive(true); //播放摇骰子的音效 Facade.Instance<MusicManager>().Play("touzi"); Dices.Anim.enabled = true; for (int i = 0; i < Dices.Dices.Length; i++) { Dices.Dices[i].spriteName = "dice_" + DicesNums[i]; } } public virtual void BeginGiveCards() { BeginClone(); InvokeRepeating("ReadyGiveCards", 0, 0.1f); } protected void ReadyGiveCards() { if (GiveCardsStatus == 2) { OnGiveCardsOver(); CancelInvoke("ReadyGiveCards"); } } public virtual void OnGiveCardsOver() { ShowIndex = 0; StartNum = DicePoint == 0 ? 0 : ((DicePoint - 2) % 4); CardsArrindex = 2 * (StartNum + 1) + 2 * CutNum; InvokeRepeating("ShowCards", 0.5f, 0.5f); } protected int ShowNum = 0; protected int ShowTarget = 0; /// <summary> /// 翻牌 /// </summary> public virtual void ShowCards() { if (CardsValue == null) return; if (ShowIndex % 2 == 0 && ShowIndex != 0) { //显示牌值 ShowPoints(StartNum); StartNum++; StartNum = StartNum >= 4 ? StartNum % 4 : StartNum; } if (ShowIndex >= 8) { //发够多少张牌之后停止发牌 CancelInvoke("ShowCards"); return; } if (HasGiveNum > 32) CardsArrindex = CardsArrindex >= 8 ? CardsArrindex % 8 : CardsArrindex; else CardsArrindex = CardsArrindex >= (8 + 2 * CutNum) ? CardsArrindex % (8 + 2 * CutNum) + 2 * CutNum : CardsArrindex; var go = Cards[CardsArrindex]; var mj = go.GetComponent<MjCard>(); var value = CardsValue.GetSFSObject(StartNum).GetIntArray(Parameter.Cards); if (HistoryCards.ContainsKey(value[ShowIndex % 2])) { HistoryCards[value[ShowIndex % 2]]++; ShowNum = value[ShowIndex % 2] - 1; ShowTarget = HistoryCards[value[ShowIndex % 2]]; Invoke("ShowHistoryChange", 0.4f); } mj.CardValue = value[ShowIndex % 2]; mj.TurnCard(); ShowIndex++; CardsArrindex++; } private void ShowHistoryChange() { HistoryCardsCtrl.RefrshDataOnPlay(ShowNum, ShowTarget); } public virtual void ShowPoints(int index) { //显示牌值 int type = CardsValue.GetSFSObject(index).GetInt(Parameter.Type); int value = CardsValue.GetSFSObject(index).GetInt(Parameter.Value); CardPoints[index].ShowPointValue(type, value); } public void GetIsXiPai(ISFSObject data) { if ((data.ContainsKey(Parameter.XiPai) && data.GetBool(Parameter.XiPai)) || IsNeedRefresh) { HasGiveNum = 0; InitHistoryCards(); YxMessageTip.Show("开始洗牌"); } ShowAllCards(); RefreshHistoryCards(); } public void GetGameInfoOnCheck(ISFSObject data) { if (data.ContainsKey(Parameter.Dices)) { DicesNums = data.GetIntArray(Parameter.Dices); } var count = DicesNums.Length; for (int i = 0; i < count; i++) { DicePoint += DicesNums[i]; } } /// <summary> /// 显示牌堆,最多显示20张牌 /// </summary> public void ShowAllCards() { ClearCardsWall(); HasGiveNum = HasGiveNum > MaxCardsNum ? 0 : HasGiveNum; int count = MaxCardsNum - HasGiveNum >= 20 ? 20 : MaxCardsNum - HasGiveNum; count = count == MaxCardsNum % FirstCardsNum ? (MaxCardsNum % FirstCardsNum) + FirstCardsNum : count; if (Grid == null) return; for (int i = 0; i < count; i++) { var go = Instantiate(CardClone); Cards.Add(go); if (i % 2 == 0) { var temp = go.GetComponent<UISprite>(); if (temp != null) temp.depth++; } go.transform.parent = Grid.transform; go.name = "Card" + i; go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; go.SetActive(true); } Grid.repositionNow = true; Grid.Reposition(); } public void ReceiveResult(ISFSObject responseData) { if (responseData.ContainsKey(Parameter.Total)) { App.GameData.GetPlayer().Coin = responseData.GetLong(Parameter.Total); } if (responseData.ContainsKey(Parameter.BankerGold)) { App.GetGameData<BrttzGameData>().BankerPlayer.Coin = responseData.GetLong(Parameter.BankerGold); } if (responseData.ContainsKey(Parameter.Bpg)) { Bpg = new[] { 0, 0, 0, 0, 0, 0 }; Bpg = responseData.GetIntArray(Parameter.Bpg); } App.GetGameData<BrttzGameData>().ResultUserTotal = responseData.ContainsKey(Parameter.Win) ? responseData.GetInt(Parameter.Win) : 0; App.GetGameData<BrttzGameData>().ResultBnakerTotal = responseData.ContainsKey(Parameter.Bwin) ? responseData.GetLong(Parameter.Bwin) : 0; } /// <summary> /// 清理牌墙 /// </summary> protected void ClearCardsWall() { if (Cards.Count <= 0) return; while (Cards.Count != 0) { Destroy(Cards[0]); Cards.RemoveAt(0); } } protected virtual void InstantiateChip() { if (Index % 2 == 0 && Index != 0) { Arrindex++; if (Arrindex >= 4) Arrindex = Arrindex % 4; } if (Index >= 8) { //发够多少张牌之后停止发牌 CancelInvoke("GiveCards"); GiveCardsStatus = 2; return; } HasGiveNum++; if (HasGiveNum > 32) CardIndex = CardIndex >= 8 ? CardIndex % 8 : CardIndex; else CardIndex = CardIndex >= (8 + 2 * CutNum) ? CardIndex % (8 + 2 * CutNum) + 2 * CutNum : CardIndex; var go = Cards[CardIndex]; var target = Target[Arrindex].GetComponent<BrttzCardPostion>().TargetPositions[Index % 2]; go.transform.parent = target.transform; go.transform.localScale = Vector3.one; var sp = go.GetComponent<SpringPosition>(); sp.target = Vector3.zero; sp.enabled = true; var ts = go.GetComponent<TweenScale>(); //ts.from = Vector3.one * 0.8f; //ts.to = Vector3.one * 1.5f; if (CardsBgScaleNums != null && CardsBgScaleNums.Length == 2) { ts.from = Vector3.one * CardsBgScaleNums[0]; ts.to = Vector3.one * CardsBgScaleNums[1]; } ts.duration = 0.5f; ts.PlayForward(); Facade.Instance<MusicManager>().Play("card"); Index++; CardIndex++; //可以添加一些移动 } public virtual void BeginGiveMingCards(ISFSObject responseData) { } public virtual void SendMingCardFirst(ISFSObject gameInfo) { } //public int[] GetResultList() //{ // if (CardsValue.Count == 0) return null; // int[] results = { -1, -1, -1 }; // var bankerType = CardsValue.GetSFSObject(3).GetInt(Parameter.Type); // var bankerValue = CardsValue.GetSFSObject(3).GetInt(Parameter.Value); // for (int i = 0; i < 3; i++) // { // var type = CardsValue.GetSFSObject(i).GetInt(Parameter.Type); // var value = CardsValue.GetSFSObject(i).GetInt(Parameter.Value); // if (bankerType < type) results[i] = 1; // else if (bankerType == type && bankerValue < value) results[i] = 1; // } // return results; //} //protected int[] GetResultList(ISFSArray fristCardsValues) //{ // if (fristCardsValues.Count == 0) return null; // int[] results = { -1, -1, -1 }; // var bankerType = fristCardsValues.GetSFSObject(3).GetInt(Parameter.Type); // var bankerValue = fristCardsValues.GetSFSObject(3).GetInt(Parameter.Value); // for (int i = 0; i < 3; i++) // { // var type = fristCardsValues.GetSFSObject(i).GetInt(Parameter.Type); // var value = fristCardsValues.GetSFSObject(i).GetInt(Parameter.Value); // if (bankerType < type) results[i] = 1; // else if (bankerType == type && bankerValue < value) results[i] = 1; // } // return results; //} public void Reset() { ReSetGiveCardsStatus(); DicePoint = 0; DicesNums = new int[2]; CancelInvoke("ShowCards"); foreach (var point in CardPoints) { point.Init(); } CancelInvoke("GiveCards"); CancelInvoke("ReadyGiveCards"); Dices.Reset(); CancelInvoke(); IsRejoin = false; } public void ReSetGiveCardsStatus() { GiveCardsStatus = 0; CancelInvoke("GiveCards"); } protected void GiveCards() { InstantiateChip(); } public void BeginClone() { if (GiveCardsStatus == 0) { GiveCardsStatus = 1; Index = 0; Arrindex = DicePoint == 0 ? 0 : ((DicePoint - 2) % 4); CardIndex = 2 * (Arrindex + 1) + 2 * CutNum; InvokeRepeating("GiveCards", 0.5f, 0.3f); } } protected void RefreshHistoryCards() { int[] history = new int[HistoryCards.Count]; for (int i = 0; i < history.Length; i++) { history[i] = HistoryCardsCtrl.MaxMahjongNum - HistoryCards[i + 1]; } HistoryCardsCtrl.RefreshData(history); } public void InitHistoryCards() { HistoryCardsCtrl.InitMahjong(); HistoryCards.Clear(); HistoryCards.Add(1, 0); HistoryCards.Add(2, 0); HistoryCards.Add(3, 0); HistoryCards.Add(4, 0); HistoryCards.Add(5, 0); HistoryCards.Add(6, 0); HistoryCards.Add(7, 0); HistoryCards.Add(8, 0); HistoryCards.Add(9, 0); HistoryCards.Add(10, 0); } } }
33.658153
149
0.501109
[ "MIT" ]
GEngine-JP/chessgame
Assets/Scripts/Game/brtbsone/BrttzCardsCtrl.cs
17,638
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; namespace eIVOGo.Published { public partial class ContentPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { initializeData(); } protected override void OnInit(EventArgs e) { base.OnInit(e); } protected virtual void initializeData() { if (this.PreviousPage != null && this.PreviousPage.Items.Count > 0) { if (this.PreviousPage.Items["contentList"] is IEnumerable<Control>) { foreach (Control ctrl in (IEnumerable<Control>)this.PreviousPage.Items["contentList"]) { theForm.Controls.Add(ctrl); } } } } } }
25.789474
106
0.547959
[ "MIT" ]
uxb2bralph/IFS-EIVO03
eIVOGo/Published/ContentPage.aspx.cs
982
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.Buffers; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json { /// <summary> /// Provides functionality to serialize objects or value types to JSON and /// deserialize JSON into objects or value types. /// </summary> public static partial class JsonSerializer { /// <summary> /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="options">Options to control the behavior during parsing.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <typeparamref name="TValue" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize<TValue>(string json, JsonSerializerOptions? options = null) { if (json == null) { throw new ArgumentNullException(nameof(json)); } JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadFromSpan<TValue>(json.AsSpan(), jsonTypeInfo); } /// <summary> /// Parses the text representing a single JSON value into an instance of the type specified by a generic type parameter. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="json">The JSON text to parse.</param> /// <param name="options">Options to control the behavior during parsing.</param> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <typeparamref name="TValue" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the span beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> /// <remarks>Using a UTF-16 span is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize<TValue>(ReadOnlySpan<char> json, JsonSerializerOptions? options = null) { // default/null span is treated as empty JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadFromSpan<TValue>(json, jsonTypeInfo); } /// <summary> /// Parses the text representing a single JSON value into a <paramref name="returnType"/>. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during parsing.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <paramref name="returnType"/> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize(string json, Type returnType, JsonSerializerOptions? options = null) { if (json == null) { throw new ArgumentNullException(nameof(json)); } if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); } JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan<object?>(json.AsSpan(), jsonTypeInfo)!; } /// <summary> /// Parses the text representing a single JSON value into an instance of a specified type. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="json">The JSON text to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during parsing.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <paramref name="returnType"/> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the span beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <remarks>Using a UTF-16 span is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize(ReadOnlySpan<char> json, Type returnType, JsonSerializerOptions? options = null) { // default/null span is treated as empty if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); } if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); } JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan<object?>(json, jsonTypeInfo)!; } /// <summary> /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> is <see langword="null"/>. /// /// -or- /// /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <typeparamref name="TValue" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> public static TValue? Deserialize<TValue>(string json, JsonTypeInfo<TValue> jsonTypeInfo) { // default/null span is treated as empty if (json == null) { throw new ArgumentNullException(nameof(json)); } if (jsonTypeInfo == null) { throw new ArgumentNullException(nameof(jsonTypeInfo)); } return ReadFromSpan<TValue?>(json.AsSpan(), jsonTypeInfo); } /// <summary> /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> is <see langword="null"/>. /// /// -or- /// /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <typeparamref name="TValue" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> public static TValue? Deserialize<TValue>(ReadOnlySpan<char> json, JsonTypeInfo<TValue> jsonTypeInfo) { // default/null span is treated as empty if (jsonTypeInfo == null) { throw new ArgumentNullException(nameof(jsonTypeInfo)); } return ReadFromSpan<TValue?>(json, jsonTypeInfo); } /// <summary> /// Parses the text representing a single JSON value into a <paramref name="returnType"/>. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// /// -or- /// /// <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <paramref name="returnType" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided /// <paramref name="context"/> returns <see langword="null"/> for the type to convert. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> public static object? Deserialize(string json, Type returnType, JsonSerializerContext context) { if (json == null) { throw new ArgumentNullException(nameof(json)); } if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpan<object?>(json.AsSpan(), jsonTypeInfo); } /// <summary> /// Parses the text representing a single JSON value into a <paramref name="returnType"/>. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="json">JSON text to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// /// -or- /// /// <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid. /// /// -or- /// /// <paramref name="returnType" /> is not compatible with the JSON. /// /// -or- /// /// There is remaining data in the string beyond a single JSON value.</exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided /// <paramref name="context"/> returns <see langword="null"/> for the type to convert. /// </exception> /// <remarks>Using a <see cref="string"/> is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// </remarks> public static object? Deserialize(ReadOnlySpan<char> json, Type returnType, JsonSerializerContext context) { if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpan<object?>(json, jsonTypeInfo); } private static TValue? ReadFromSpan<TValue>(ReadOnlySpan<char> json, JsonTypeInfo jsonTypeInfo) { byte[]? tempArray = null; // For performance, avoid obtaining actual byte count unless memory usage is higher than the threshold. Span<byte> utf8 = json.Length <= (JsonConstants.ArrayPoolMaxSizeBeforeUsingNormalAlloc / JsonConstants.MaxExpansionFactorWhileTranscoding) ? // Use a pooled alloc. tempArray = ArrayPool<byte>.Shared.Rent(json.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) : // Use a normal alloc since the pool would create a normal alloc anyway based on the threshold (per current implementation) // and by using a normal alloc we can avoid the Clear(). new byte[JsonReaderHelper.GetUtf8ByteCount(json)]; try { int actualByteCount = JsonReaderHelper.GetUtf8FromText(json, utf8); utf8 = utf8.Slice(0, actualByteCount); return ReadFromSpan<TValue>(utf8, jsonTypeInfo, actualByteCount); } finally { if (tempArray != null) { utf8.Clear(); ArrayPool<byte>.Shared.Return(tempArray); } } } } }
44.630542
152
0.585706
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs
18,120
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs.Choices; using Microsoft.Bot.Schema; using Microsoft.BotBuilderSamples.FacebookModel; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.BotBuilderSamples.Bots { public class FacebookBot : ActivityHandler { // These are the options provided to the user when they message the bot const string FacebookPageIdOption = "Facebook Id"; const string QuickRepliesOption = "Quick Replies"; const string PostBackOption = "PostBack"; protected readonly ILogger Logger; public FacebookBot(ILogger<FacebookBot> logger) { Logger = logger; } protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken) { Logger.LogInformation("Processing a Message Activity."); // Show choices if the Facebook Payload from ChannelData is not handled if (!await ProcessFacebookPayload(turnContext, turnContext.Activity.ChannelData, cancellationToken)) await ShowChoices(turnContext, cancellationToken); } protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken) { Logger.LogInformation("Processing an Event Activity."); // Analyze Facebook payload from EventActivity.Value await ProcessFacebookPayload(turnContext, turnContext.Activity.Value, cancellationToken); } private static async Task ShowChoices(ITurnContext turnContext, CancellationToken cancellationToken) { // Create choices for the prompt var choices = new List<Choice>(); choices.Add(new Choice() { Value = QuickRepliesOption, Action = new CardAction() { Title = QuickRepliesOption, Type = ActionTypes.PostBack, Value = QuickRepliesOption } }); choices.Add(new Choice() { Value = FacebookPageIdOption, Action = new CardAction() { Title = FacebookPageIdOption, Type = ActionTypes.PostBack, Value = FacebookPageIdOption } }); choices.Add(new Choice() { Value = PostBackOption, Action = new CardAction() { Title = PostBackOption, Type = ActionTypes.PostBack, Value = PostBackOption } }); // Create the prompt message var message = ChoiceFactory.ForChannel(turnContext.Activity.ChannelId, choices, "What Facebook feature would you like to try? Here are some quick replies to choose from!"); await turnContext.SendActivityAsync(message, cancellationToken); } private async Task<bool> ProcessFacebookPayload(ITurnContext turnContext, object data, CancellationToken cancellationToken) { // At this point we know we are on Facebook channel, and can consume the Facebook custom payload // present in channelData. try { var facebookPayload = (data as JObject)?.ToObject<FacebookPayload>(); if (facebookPayload != null) { // PostBack if (facebookPayload.PostBack != null) { await OnFacebookPostBack(turnContext, facebookPayload.PostBack, cancellationToken); return true; } // Optin else if (facebookPayload.Optin != null) { await OnFacebookOptin(turnContext, facebookPayload.Optin, cancellationToken); return true; } // Quick reply else if (facebookPayload.Message?.QuickReply != null) { await OnFacebookQuickReply(turnContext, facebookPayload.Message.QuickReply, cancellationToken); return true; } // Echo else if (facebookPayload.Message?.IsEcho != null && facebookPayload.Message.IsEcho) { await OnFacebookEcho(turnContext, facebookPayload.Message, cancellationToken); return true; } // TODO: Handle other events that you're interested in... } } catch(JsonSerializationException) { if (turnContext.Activity.ChannelId != Bot.Connector.Channels.Facebook) { await turnContext.SendActivityAsync("This sample is intended to be used with a Facebook bot."); } else { throw; } } return false; } protected virtual async Task OnFacebookOptin(ITurnContext turnContext, FacebookOptin optin, CancellationToken cancellationToken) { Logger.LogInformation("Optin message received."); // TODO: Your optin event handling logic here... await Task.CompletedTask; } protected virtual async Task OnFacebookEcho(ITurnContext turnContext, FacebookMessage facebookMessage, CancellationToken cancellationToken) { Logger.LogInformation("Echo message received."); // TODO: Your echo event handling logic here... await Task.CompletedTask; } protected virtual async Task OnFacebookPostBack(ITurnContext turnContext, FacebookPostback postBack, CancellationToken cancellationToken) { Logger.LogInformation("PostBack message received."); // TODO: Your PostBack handling logic here... // Answer the postback, and show choices var reply = MessageFactory.Text("Are you sure?"); await turnContext.SendActivityAsync(reply, cancellationToken); await ShowChoices(turnContext, cancellationToken); } protected virtual async Task OnFacebookQuickReply(ITurnContext turnContext, FacebookQuickReply quickReply, CancellationToken cancellationToken) { Logger.LogInformation("QuickReply message received."); // TODO: Your quick reply event handling logic here... // Process the message by checking the Activity.Text. The FacebookQuickReply could also contain a json payload. // Initially the bot offers to showcase 3 Facebook features: Quick replies, PostBack and getting the Facebook Page Name. switch (turnContext.Activity.Text) { // Here we showcase how to obtain the Facebook page id. // This can be useful for the Facebook multi-page support provided by the Bot Framework. // The Facebook page id from which the message comes from is in turnContext.Activity.Recipient.Id. case FacebookPageIdOption: { var reply = MessageFactory.Text($"This message comes from the following Facebook Page: {turnContext.Activity.Recipient.Id}"); await turnContext.SendActivityAsync(reply, cancellationToken); await ShowChoices(turnContext, cancellationToken); break; } // Here we send a HeroCard with 2 options that will trigger a Facebook PostBack. case PostBackOption: { var card = new HeroCard { Text = "Is 42 the answer to the ultimate question of Life, the Universe, and Everything?", Buttons = new List<CardAction> { new CardAction() { Title = "Yes", Type = ActionTypes.PostBack, Value = "Yes" }, new CardAction() { Title = "No", Type = ActionTypes.PostBack, Value = "No" }, }, }; var reply = MessageFactory.Attachment(card.ToAttachment()); await turnContext.SendActivityAsync(reply, cancellationToken); break; } // By default we offer the users different actions that the bot supports, through quick replies. case QuickRepliesOption: default: { await ShowChoices(turnContext, cancellationToken); break; } } } } }
45.020101
190
0.592365
[ "MIT" ]
AdsTable/BotBuilder-Samples
samples/csharp_dotnetcore/23.facebook-events/Bots/FacebookBot.cs
8,961
C#
using FolkerKinzel.CsvTools.Helpers; using FolkerKinzel.CsvTools.Intls; using FolkerKinzel.CsvTools.Resources; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; namespace FolkerKinzel.CsvTools { /// <summary> /// Bietet schreibgeschützten Vorwärtszugriff auf die Datensätze einer CSV-Datei. (Das bedeutet, dass der <see cref="CsvReader"/> die Datei nur einmal vorwärts /// lesen kann.) /// </summary> /// <remarks> /// <para> /// Die Methode <see cref="Read"/> gibt einen <see cref="IEnumerator{T}">IEnumerator&lt;CsvRecord&gt;</see> zurück, mit dem Sie über die Datensätze der CSV-Datei iterieren /// können, die in Form von <see cref="CsvRecord"/>-Objekten zurückgegeben werden. /// </para> /// <para>Die Klasse <see cref="CsvRecordWrapper"/> bietet die /// Möglichkeit, die Reihenfolge der Datenspalten der <see cref="CsvRecord"/>-Objekte zur Laufzeit auf die Spaltenreihenfolge einer <see cref="DataTable"/> /// zu mappen und Typkonvertierungen durchzuführen. /// </para> /// <para>Beim Lesen einer unbekannten CSV-Datei können die geeigneten Parameter für den Konstruktor von <see cref="CsvReader"/> mit Hilfe der Klasse /// <see cref="CsvAnalyzer"/> ermittelt werden.</para> /// </remarks> /// <example> /// <note type="note">In den folgenden Code-Beispielen wurde - der leichteren Lesbarkeit wegen - auf Ausnahmebehandlung verzichtet.</note> /// <para>Linq-Abfrage auf einer CSV-Datei:</para> /// <code language="cs" source="..\Examples\LinqOnCsvFile.cs"/> /// <para>Speichern des Inhalts einer <see cref="DataTable"/> als CSV-Datei und Einlesen von Daten einer CSV-Datei in /// eine <see cref="DataTable"/>:</para> /// <code language="cs" source="..\Examples\CsvToDataTable.cs"/> /// <para>Deserialisieren beliebiger Objekte aus CSV-Dateien:</para> /// <code language="cs" source="..\Examples\DeserializingClassesFromCsv.cs"/> /// </example> public sealed class CsvReader : IDisposable { private readonly CsvStringReader _reader; private readonly CsvOptions _options; private readonly bool _hasHeaderRow; private bool _firstRun = true; #region ctors /// <summary> /// Initialisiert ein neues <see cref="CsvReader"/>-Objekt. /// </summary> /// <param name="fileName">Dateipfad der CSV-Datei.</param> /// <param name="hasHeaderRow"><c>true</c>, wenn die CSV-Datei eine Kopfzeile mit den Spaltennamen hat.</param> /// <param name="options">Optionen für das Lesen der CSV-Datei.</param> /// <param name="fieldSeparator">Das Feldtrennzeichen, das in der CSV-Datei Verwendung findet.</param> /// <param name="textEncoding">Die zum Einlesen der CSV-Datei zu verwendende Textenkodierung oder <c>null</c> für <see cref="Encoding.UTF8"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="fileName"/> ist <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="fileName"/> ist kein gültiger Dateipfad.</exception> /// <exception cref="IOException">Es kann nicht auf den Datenträger zugegriffen werden.</exception> public CsvReader( string fileName, bool hasHeaderRow = true, CsvOptions options = CsvOptions.Default, char fieldSeparator = ',', Encoding? textEncoding = null) { StreamReader streamReader = InitializeStreamReader(fileName, textEncoding); this._reader = new CsvStringReader(streamReader, fieldSeparator, (_options & CsvOptions.ThrowOnEmptyLines) != CsvOptions.ThrowOnEmptyLines); this._options = options; this._hasHeaderRow = hasHeaderRow; } /// <summary> /// Initialisiert ein neues <see cref="CsvReader"/>-Objekt. /// </summary> /// <param name="reader">Der <see cref="TextReader"/>, mit dem die CSV-Datei gelesen wird.</param> /// <param name="hasHeaderRow"><c>true</c>, wenn die CSV-Datei eine Kopfzeile mit den Spaltennamen hat.</param> /// <param name="options">Optionen für das Lesen der CSV-Datei.</param> /// <param name="fieldSeparator">Das Feldtrennzeichen.</param> /// <exception cref="ArgumentNullException"><paramref name="reader"/> ist <c>null</c>.</exception> public CsvReader( TextReader reader, bool hasHeaderRow = true, CsvOptions options = CsvOptions.Default, char fieldSeparator = ',') { if (reader is null) { throw new ArgumentNullException(nameof(reader)); } this._reader = new CsvStringReader(reader, fieldSeparator, (_options & CsvOptions.ThrowOnEmptyLines) != CsvOptions.ThrowOnEmptyLines); this._options = options; this._hasHeaderRow = hasHeaderRow; } #endregion #region public Methods /// <summary> /// Gibt ein <see cref="IEnumerable{T}">IEnumerable&lt;CsvRecord&gt;</see>-Objekt zurück, mit dem über die Datensätze der CSV-Datei /// iteriert werden kann. /// </summary> /// <returns>Ein <see cref="IEnumerable{T}">IEnumerable&lt;CsvRecord&gt;</see>, mit dem über die Datensätze der CSV-Datei /// iteriert werden kann.</returns> /// <exception cref="InvalidOperationException">Die Methode wurde mehr als einmal aufgerufen.</exception> /// <exception cref="ObjectDisposedException">Der <see cref="Stream"/> war bereits geschlossen.</exception> /// <exception cref="IOException">Fehler beim Zugriff auf den Datenträger.</exception> /// <exception cref="InvalidCsvException">Ungültige CSV-Datei. Die Interpretation ist abhängig vom <see cref="CsvOptions"/>-Wert, /// der im Konstruktor angegeben wurde.</exception> #if !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public IEnumerable<CsvRecord> Read() { if (!_firstRun) { ThrowInvalidOperationException(); } _firstRun = false; return new CsvRecordCollection(this); } /// <summary> /// Gibt die Resourcen frei. (Schließt den <see cref="TextReader"/>.) /// </summary> public void Dispose() => _reader.Dispose(); #endregion #region internal internal IEnumerator<CsvRecord> GetEnumerator() { CsvRecord? record = null; // Schablone für weitere CsvRecord-Objekte CsvRecord? clone = null; foreach (IEnumerable<string?> row in _reader) { if (record is null) { bool caseSensitiveColumns = (_options & CsvOptions.CaseSensitiveKeys) == CsvOptions.CaseSensitiveKeys; if (_hasHeaderRow) { record = new CsvRecord(row.ToArray(), caseSensitiveColumns, (_options & CsvOptions.TrimColumns) == CsvOptions.TrimColumns, false, false); continue; } else { string?[]? arr = row.ToArray(); if (arr.Length == 0) { continue; // Leerzeile am Anfang } record = new CsvRecord(arr.Length, caseSensitiveColumns, false); clone = new CsvRecord(record); Fill(clone, arr, _reader); } } else { if ((_options & CsvOptions.DisableCaching) == CsvOptions.DisableCaching) { clone ??= new CsvRecord(record); } else { clone = new CsvRecord(record); } Fill(clone, row, _reader); } yield return clone; } ///////////////////////////////////////////////////////////////////// void Fill(CsvRecord clone, IEnumerable<string?> data, CsvStringReader reader) { int dataIndex = 0; foreach (string? item in data) { if (dataIndex >= clone.Count) { if ((_options & CsvOptions.ThrowOnTooMuchFields) == CsvOptions.ThrowOnTooMuchFields) { throw new InvalidCsvException("Too much fields in a record.", reader.LineNumber, reader.LineIndex); } else { return; } } if (item != null && (_options & CsvOptions.TrimColumns) == CsvOptions.TrimColumns) { string? trimmed = item.Trim(); if (trimmed.Length == 0) { trimmed = null; } clone[dataIndex++] = trimmed; } else { clone[dataIndex++] = item; } } if (dataIndex < clone.Count) { if (dataIndex == 0 && (_options & CsvOptions.ThrowOnEmptyLines) == CsvOptions.ThrowOnEmptyLines) { throw new InvalidCsvException("Unmasked empty line.", reader.LineNumber, 0); } if ((_options & CsvOptions.ThrowOnTooFewFields) == CsvOptions.ThrowOnTooFewFields) { throw new InvalidCsvException("Too few fields in a record.", reader.LineNumber, reader.LineIndex); } if ((_options & CsvOptions.DisableCaching) == CsvOptions.DisableCaching) { for (int i = dataIndex; i < clone.Count; i++) { clone[i] = null; } } } }// Fill() }// GetEnumerator() /// <summary> /// Initialisiert einen <see cref="StreamReader"/>. /// </summary> /// <param name="fileName">Dateipfad.</param> /// <param name="textEncoding">Die zum Einlesen der CSV-Datei zu verwendende Textenkodierung oder <c>null</c> für <see cref="Encoding.UTF8"/>.</param> /// <returns>Ein <see cref="StreamReader"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="fileName"/> ist <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="fileName"/> ist kein gültiger Dateipfad.</exception> /// <exception cref="IOException">Es kann nicht auf den Datenträger zugegriffen werden.</exception> [ExcludeFromCodeCoverage] internal static StreamReader InitializeStreamReader(string fileName, Encoding? textEncoding) { try { return new StreamReader(fileName, textEncoding ?? Encoding.UTF8, true); } catch (ArgumentNullException) { throw new ArgumentNullException(nameof(fileName)); } catch (ArgumentException e) { throw new ArgumentException(e.Message, nameof(fileName), e); } catch (UnauthorizedAccessException e) { throw new IOException(e.Message, e); } catch (NotSupportedException e) { throw new ArgumentException(e.Message, nameof(fileName), e); } catch (System.Security.SecurityException e) { throw new IOException(e.Message, e); } catch (PathTooLongException e) { throw new ArgumentException(e.Message, nameof(fileName), e); } catch (Exception e) { throw new IOException(e.Message, e); } } #endregion #region private [DoesNotReturn] private static void ThrowInvalidOperationException() => throw new InvalidOperationException(Res.NotTwice); #endregion } }
41.298077
175
0.54707
[ "MIT" ]
FolkerKinzel/CsvTools
src/FolkerKinzel.CsvTools/CsvReader.cs
12,918
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.Compute.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Describes a virtual machine scale set storage profile. /// </summary> public partial class VirtualMachineScaleSetStorageProfile { /// <summary> /// Initializes a new instance of the /// VirtualMachineScaleSetStorageProfile class. /// </summary> public VirtualMachineScaleSetStorageProfile() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// VirtualMachineScaleSetStorageProfile class. /// </summary> /// <param name="imageReference">Specifies information about the image /// to use. You can specify information about platform images, /// marketplace images, or virtual machine images. This element is /// required when you want to use a platform image, marketplace image, /// or virtual machine image, but is not used in other creation /// operations.</param> /// <param name="osDisk">Specifies information about the operating /// system disk used by the virtual machines in the scale set. /// &lt;br&gt;&lt;br&gt; For more information about disks, see [About /// disks and VHDs for Azure virtual /// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).</param> /// <param name="dataDisks">Specifies the parameters that are used to /// add data disks to the virtual machines in the scale set. /// &lt;br&gt;&lt;br&gt; For more information about disks, see [About /// disks and VHDs for Azure virtual /// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).</param> public VirtualMachineScaleSetStorageProfile(ImageReference imageReference = default(ImageReference), VirtualMachineScaleSetOSDisk osDisk = default(VirtualMachineScaleSetOSDisk), IList<VirtualMachineScaleSetDataDisk> dataDisks = default(IList<VirtualMachineScaleSetDataDisk>)) { ImageReference = imageReference; OsDisk = osDisk; DataDisks = dataDisks; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets specifies information about the image to use. You can /// specify information about platform images, marketplace images, or /// virtual machine images. This element is required when you want to /// use a platform image, marketplace image, or virtual machine image, /// but is not used in other creation operations. /// </summary> [JsonProperty(PropertyName = "imageReference")] public ImageReference ImageReference { get; set; } /// <summary> /// Gets or sets specifies information about the operating system disk /// used by the virtual machines in the scale set. /// &amp;lt;br&amp;gt;&amp;lt;br&amp;gt; For more information about /// disks, see [About disks and VHDs for Azure virtual /// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). /// </summary> [JsonProperty(PropertyName = "osDisk")] public VirtualMachineScaleSetOSDisk OsDisk { get; set; } /// <summary> /// Gets or sets specifies the parameters that are used to add data /// disks to the virtual machines in the scale set. /// &amp;lt;br&amp;gt;&amp;lt;br&amp;gt; For more information about /// disks, see [About disks and VHDs for Azure virtual /// machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). /// </summary> [JsonProperty(PropertyName = "dataDisks")] public IList<VirtualMachineScaleSetDataDisk> DataDisks { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (OsDisk != null) { OsDisk.Validate(); } if (DataDisks != null) { foreach (var element in DataDisks) { if (element != null) { element.Validate(); } } } } } }
44.975
283
0.632203
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/Models/VirtualMachineScaleSetStorageProfile.cs
5,397
C#
namespace Sql2Json.Core.Engine { /// <summary> /// Prefix types for sql parameter. /// </summary> public enum CommandParameterPrefix { /// <summary> /// '@' Prefix for mssql-, sqlite-, postgres- parameters /// </summary> AtSign, /// <summary> /// ":" Prefix for oracle parameters /// </summary> Colon } /// <summary> /// Extension Methods for the enum <see cref="CommandParameterPrefix"/> /// </summary> public static class CommandParameterPrefixExtension { /// <summary> /// Return the matching prefix char. /// '@' or ':' /// </summary> /// <param name="prefix">prefix type</param> /// <returns>for AtSign='@' and Colon=':'</returns> public static string ToRealPrefix(this CommandParameterPrefix prefix) { switch (prefix) { case CommandParameterPrefix.AtSign: return "@"; case CommandParameterPrefix.Colon: return ":"; } return null; } } }
28
77
0.506098
[ "MIT" ]
mohzy83/Sql2Json
Sql2Json.Core/Engine/CommandParameterPrefix.cs
1,150
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Components { /// <summary> /// Configures options for binding specific element types. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class BindElementAttribute : Attribute { /// <summary> /// Constructs an instance of <see cref="BindElementAttribute"/>. /// </summary> /// <param name="element">The tag name of the element.</param> /// <param name="suffix">The suffix value. For example, set this to <c>value</c> for <c>bind-value</c>, or set this to <see langword="null" /> for <c>bind</c>.</param> /// <param name="valueAttribute">The name of the value attribute to be bound.</param> /// <param name="changeAttribute">The name of an attribute that will register an associated change event.</param> public BindElementAttribute(string element, string suffix, string valueAttribute, string changeAttribute) { if (element == null) { throw new ArgumentNullException(nameof(element)); } if (valueAttribute == null) { throw new ArgumentNullException(nameof(valueAttribute)); } if (changeAttribute == null) { throw new ArgumentNullException(nameof(changeAttribute)); } Element = element; ValueAttribute = valueAttribute; ChangeAttribute = changeAttribute; } /// <summary> /// Gets the tag name of the element. /// </summary> public string Element { get; } /// <summary> /// Gets the suffix value. /// For example, this will be <c>value</c> to mean <c>bind-value</c>, or <see langword="null" /> to mean <c>bind</c>. /// </summary> public string Suffix { get; } /// <summary> /// Gets the name of the value attribute to be bound. /// </summary> public string ValueAttribute { get; } /// <summary> /// Gets the name of an attribute that will register an associated change event. /// </summary> public string ChangeAttribute { get; } } }
37.784615
175
0.590798
[ "Apache-2.0" ]
AhmedKhalil777/aspnetcore
src/Components/Components/src/BindElementAttribute.cs
2,456
C#
using System; namespace Puffix.IoC { public interface IIoCContainer { ObjectT Resolve<ObjectT>(params IoCNamedParameter[] parameters); object Resolve(Type objectType, params IoCNamedParameter[] parameters); } }
20.166667
79
0.706612
[ "Apache-2.0" ]
EhRom/Puffix.IoC
Puffix.IoC/IIoCContainer.cs
244
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: IEntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The interface IGraphServiceAccessReviewsCollectionPage. /// </summary> [JsonConverter(typeof(InterfaceConverter<GraphServiceAccessReviewsCollectionPage>))] public interface IGraphServiceAccessReviewsCollectionPage : ICollectionPage<AccessReview> { /// <summary> /// Gets the next page <see cref="IGraphServiceAccessReviewsCollectionRequest"/> instance. /// </summary> IGraphServiceAccessReviewsCollectionRequest NextPageRequest { get; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString); } }
38
153
0.621212
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IGraphServiceAccessReviewsCollectionPage.cs
1,254
C#
namespace MingTransaction { using System.Threading.Tasks; internal class PutMessage : IMessage { public PutMessage(TaskCompletionSource<bool> tcs, Transaction transaction, string key, string value) { this.TaskCompletionSource = tcs; this.Transaction = transaction; this.Key = key; this.Value = value; } public TaskCompletionSource<bool> TaskCompletionSource { get; } public Transaction Transaction { get; } public string Key { get; } public string Value { get; } } }
25.73913
108
0.614865
[ "MIT" ]
cshung/MingTransaction
MingTransaction/MingTransaction/Messages/PutMessage.cs
594
C#
#pragma checksum "..\..\AboutPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "B1112D61CECEC44FCB81C4158902F752FD8ABCFF" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using InputSim; using MaterialDesignThemes.Wpf; using MaterialDesignThemes.Wpf.Converters; using MaterialDesignThemes.Wpf.Transitions; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace InputSim { /// <summary> /// AboutPage /// </summary> public partial class AboutPage : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector { #line 21 "..\..\AboutPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button BackBtn; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/InputSim;component/aboutpage.xaml", System.UriKind.Relative); #line 1 "..\..\AboutPage.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.BackBtn = ((System.Windows.Controls.Button)(target)); #line 21 "..\..\AboutPage.xaml" this.BackBtn.Click += new System.Windows.RoutedEventHandler(this.BackBtn_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
37.808081
141
0.650013
[ "MIT" ]
xFahim/InputSim
InputSim C# WPF/InputSim/obj/Debug/AboutPage.g.cs
3,745
C#
using Newtonsoft.Json.Linq; using System; using System.Text; using TRIPRO.BotFramework.Auth.AspNetCore.Models; namespace TRIPRO.BotFramework.Auth.AspNetCore.AADb2cProvider { public static class Extensions { public static AuthResult ToAuthResult(this JObject json) { string idTokenInfo = json.Value<string>("id_token").Split('.')[1]; idTokenInfo = Base64UrlEncoder.Decode(idTokenInfo); JObject idTokenJson = JObject.Parse(idTokenInfo); var result = new AuthResult { AccessToken = json.Value<string>("access_token"), UserName = idTokenJson.Value<string>("name"), UserUniqueId = idTokenJson.Value<string>("oid"), ExpiresOnUtcTicks = DateTime.UtcNow.AddSeconds(3600).Ticks, //HACK??? RefreshToken = json.Value<string>("refresh_token"), IdentityProvider = idTokenJson.Value<string>("idp") }; return result; } } public static class Base64UrlEncoder { public static Encoding TextEncoding = Encoding.UTF8; private static char Base64PadCharacter = '='; private static char Base64Character62 = '+'; private static char Base64Character63 = '/'; private static char Base64UrlCharacter62 = '-'; private static char Base64UrlCharacter63 = '_'; private static byte[] DecodeBytes(string arg) { if (String.IsNullOrEmpty(arg)) { throw new ApplicationException("String to decode cannot be null or empty."); } StringBuilder s = new StringBuilder(arg); s.Replace(Base64UrlCharacter62, Base64Character62); s.Replace(Base64UrlCharacter63, Base64Character63); int pad = s.Length % 4; s.Append(Base64PadCharacter, (pad == 0) ? 0 : 4 - pad); return Convert.FromBase64String(s.ToString()); } public static string Decode(string arg) { return TextEncoding.GetString(DecodeBytes(arg)); } } }
33.857143
92
0.60572
[ "MIT" ]
3-PRO/BotFramework.Auth
TRIPRO.BotFramework.Auth.AspNetCore.ProviderAADb2c/Extensions.cs
2,135
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Aggregates.Attributes; using Aggregates.Contracts; using Aggregates.Exceptions; using Aggregates.Extensions; using Aggregates.Logging; using Aggregates.Messages; namespace Aggregates.Internal { public class Repository<TEntity, TState, TParent> : Repository<TEntity, TState>, IRepository<TEntity, TParent> where TParent : IEntity where TEntity : Entity<TEntity, TState, TParent> where TState : class, IState, new() { private static readonly ILog Logger = LogProvider.GetLogger("Repository"); private readonly TParent _parent; public Repository(TParent parent, IStoreEntities store) : base(store) { _parent = parent; } public override async Task<TEntity> TryGet(Id id) { if (id == null) return default(TEntity); try { return await Get(id).ConfigureAwait(false); } catch (NotFoundException) { } return default(TEntity); } public override async Task<TEntity> Get(Id id) { var cacheId = $"{_parent.Bucket}.{_parent.Id}.{id}"; TEntity root; if (!Tracked.TryGetValue(cacheId, out root)) { root = await GetUntracked(_parent.Bucket, id, _parent).ConfigureAwait(false); if (!Tracked.TryAdd(cacheId, root)) throw new InvalidOperationException($"Could not add cache key [{cacheId}] to repo tracked"); } return root; } public override async Task<TEntity> New(Id id) { var cacheId = $"{_parent.Bucket}.{_parent.Id}.{id}"; TEntity root; if (!Tracked.TryGetValue(cacheId, out root)) { root = await NewUntracked(_parent.Bucket, id, _parent).ConfigureAwait(false); if (!Tracked.TryAdd(cacheId, root)) throw new InvalidOperationException($"Could not add cache key [{cacheId}] to repo tracked"); } return root; } protected override async Task<TEntity> GetUntracked(string bucket, Id id, IEntity parent) { var entity = await base.GetUntracked(bucket, id, parent).ConfigureAwait(false); entity.Parent = _parent; return entity; } protected override async Task<TEntity> NewUntracked(string bucket, Id id, IEntity parent) { var entity = await base.NewUntracked(bucket, id, parent).ConfigureAwait(false); entity.Parent = _parent; return entity; } } public class Repository<TEntity, TState> : IRepository<TEntity>, IRepositoryCommit where TEntity : Entity<TEntity, TState> where TState : class, IState, new() { private static readonly ILog Logger = LogProvider.GetLogger("Repository"); protected readonly ConcurrentDictionary<string, TEntity> Tracked = new ConcurrentDictionary<string, TEntity>(); private readonly IStoreEntities _store; private bool _disposed; public int ChangedStreams => Tracked.Count(x => x.Value.Dirty); // Todo: too many operations on this class, make a "EntityWriter" contract which does event, oob, and snapshot writing public Repository(IStoreEntities store) { _store = store; } Task IRepositoryCommit.Prepare(Guid commitId) { Logger.DebugEvent("Prepare", "{EntityType} prepare {CommitId}", typeof(TEntity).FullName, commitId); // Verify streams we read but didn't change are still save version return Tracked.Values .Where(x => !x.Dirty) .ToArray() .WhenAllAsync((x) => _store.Verify<TEntity, TState>(x)); } async Task IRepositoryCommit.Commit(Guid commitId, IDictionary<string, string> commitHeaders) { Logger.DebugEvent("Commit", "[{EntityType:l}] commit {CommitId}", typeof(TEntity).FullName, commitId); await Tracked.Values .ToArray() .Where(x => x.Dirty) .WhenAllAsync((tracked) => _store.Commit<TEntity, TState>(tracked, commitId, commitHeaders) ).ConfigureAwait(false); Logger.DebugEvent("FinishedCommit", "[{EntityType:l}] commit {CommitId}", typeof(TEntity).FullName, commitId); } void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (_disposed || !disposing) return; Tracked.Clear(); _disposed = true; } public virtual Task<TEntity> TryGet(Id id) { return TryGet(Defaults.Bucket, id); } public async Task<TEntity> TryGet(string bucket, Id id) { if (id == null) return default(TEntity); try { return await Get(bucket, id).ConfigureAwait(false); } catch (NotFoundException) { } return default(TEntity); } public virtual Task<TEntity> Get(Id id) { return Get(Defaults.Bucket, id); } public async Task<TEntity> Get(string bucket, Id id) { var cacheId = $"{bucket}.{id}"; TEntity root; if (!Tracked.TryGetValue(cacheId, out root)) { root = await GetUntracked(bucket, id).ConfigureAwait(false); if (!Tracked.TryAdd(cacheId, root)) throw new InvalidOperationException($"Could not add cache key [{cacheId}] to repo tracked"); } return root; } protected virtual Task<TEntity> GetUntracked(string bucket, Id id, IEntity parent = null) { return _store.Get<TEntity, TState>(bucket, id, parent); } public virtual Task<TEntity> New(Id id) { return New(Defaults.Bucket, id); } public async Task<TEntity> New(string bucket, Id id) { TEntity root; var cacheId = $"{bucket}.{id}"; if (!Tracked.TryGetValue(cacheId, out root)) { root = await NewUntracked(bucket, id).ConfigureAwait(false); if (!Tracked.TryAdd(cacheId, root)) throw new InvalidOperationException($"Could not add cache key [{cacheId}] to repo tracked"); } return root; } protected virtual Task<TEntity> NewUntracked(string bucket, Id id, IEntity parent = null) { return _store.New<TEntity, TState>(bucket, id, parent); } } }
32.776744
223
0.57528
[ "MIT" ]
WahidNET/Aggregates.NET
src/Aggregates.NET/Internal/Repository.cs
7,049
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("App12")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("App12")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("b6fa0888-cca2-4e37-835b-0d34950d165c")] // 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.243243
84
0.745283
[ "MIT" ]
dimitarminchev/ITCareer
03. Introduction to Object Oriented Programming/2018/2. Properties and Methods/App12/Properties/AssemblyInfo.cs
1,381
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("GeoJSON.Net.MsSqlSpatial.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GeoJSON.Net.MsSqlSpatial.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("2306d559-92de-420c-8fc6-93aeb33cb846")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou vous pouvez définir par défaut les numéros de build et de révision // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.72973
114
0.752591
[ "MIT" ]
xfischer/GeoJSON.Net
src/GeoJSON.Net.MsSqlSpatial.Tests/Properties/AssemblyInfo.cs
1,570
C#
using Abp.Notifications; using YoYoCms.AbpProjectTemplate.Dto; namespace YoYoCms.AbpProjectTemplate.Notifications.Dto { public class GetUserNotificationsInput : PagedInputDto { public UserNotificationState? State { get; set; } } }
25.2
58
0.757937
[ "Apache-2.0" ]
52ABP/YoYoCms.AbpProjectTemplate
src/YoYoCms.AbpProjectTemplate.Application/Notifications/Dto/GetUserNotificationsInput.cs
254
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Schneedetektion.OpenCV.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.888889
151
0.584958
[ "MIT" ]
uzapy/ch.bfh.bti7321.w2016.schneedetektion
Schneedetektion/Schneedetektion.OpenCV/Properties/Settings.Designer.cs
1,079
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Kiwaii : Character { public float catScore = 10; public Ability heartAbility; public override void BasicAction() { FixableDestructable fd = proximator.Prox; if (fd != null) fd.Fix(Game.Instance.KiwaiiHealAmount); } public override void ProjectileCollision(AbilityProjectile proj) { switch (proj.Type) { case AbilityProjectile.ProjecileType.CAT: Game.Instance.score += Game.Instance.KiwaiiCatchCatScore; heartAbility.DoAbility(); // DO ABILITY break; case AbilityProjectile.ProjecileType.DEBRIS: Game.Instance.score += Game.Instance.KiwaiiHitRubbleScore; // STUN, Backlash? break; case AbilityProjectile.ProjecileType.HEART: break; case AbilityProjectile.ProjecileType.STUN: //stun break; } Destroy(proj.gameObject); } }
27
74
0.590786
[ "MIT" ]
hexthedev/Jam-McGameJam20210115
Assets/Scripts/Characters/Kiwaii.cs
1,109
C#
using System.Linq; using DocumentFormat.OpenXml.Spreadsheet; using PoeParser.Common; using PoeParser.Filter.Tooltip; using Tornado.Common.Utility; using Tornado.Parser.Filter; namespace Tornado.Parser.Entities { public class JewelryItem : Item { public JewelryItem(string source, ItemRarity rarity, Core core, Tornado.Data.Data.BaseItem baseItem, string name, bool noCraft) : base(source, rarity, core, baseItem, name, noCraft) { Color = ToolTipColor.GeneralGroup; } public override NiceDictionary<string, string> GetPoeTradeAffixes(FilterResult filter) { var properties = Core.GetPoeTradeAffixes(filter); if (ItemTypes.RareBases.Contains(Core.BaseName) || Core.BaseName == "Rustic Sash") { properties.Add("base", Core.BaseName); } return properties; } public override string ToString() { return $"{EnumInfo<ItemType>.Current[Type].DisplayName}: {Name} - {Price}"; } } }
36.464286
191
0.667973
[ "MIT" ]
kiruxak/tornado
Tornado.Parser/Entities/Items/BaseItem/JewelryItem.cs
1,023
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.linkedmall.Transform; using Aliyun.Acs.linkedmall.Transform.V20180116; namespace Aliyun.Acs.linkedmall.Model.V20180116 { public class DeleteBizItemsRequest : RpcAcsRequest<DeleteBizItemsResponse> { public DeleteBizItemsRequest() : base("linkedmall", "2018-01-16", "DeleteBizItems", "linkedmall", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private string bizId; private List<long?> itemIdLists = new List<long?>(){ }; private string subBizId; public string BizId { get { return bizId; } set { bizId = value; DictionaryUtil.Add(QueryParameters, "BizId", value); } } public List<long?> ItemIdLists { get { return itemIdLists; } set { itemIdLists = value; for (int i = 0; i < itemIdLists.Count; i++) { DictionaryUtil.Add(QueryParameters,"ItemIdList." + (i + 1) , itemIdLists[i]); } } } public string SubBizId { get { return subBizId; } set { subBizId = value; DictionaryUtil.Add(QueryParameters, "SubBizId", value); } } public override DeleteBizItemsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DeleteBizItemsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
27.835052
134
0.667037
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-linkedmall/Linkedmall/Model/V20180116/DeleteBizItemsRequest.cs
2,700
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using ETicaret.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; namespace ETicaret.Areas.Identity.Pages.Account { [AllowAnonymous] public class ConfirmEmailChangeModel : PageModel { private readonly UserManager<AppUser> _userManager; private readonly SignInManager<AppUser> _signInManager; public ConfirmEmailChangeModel(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync(string userId, string email, string code) { if (userId == null || email == null || code == null) { return RedirectToPage("/Index"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return NotFound($"Unable to load user with ID '{userId}'."); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ChangeEmailAsync(user, email, code); if (!result.Succeeded) { StatusMessage = "Error changing email."; return Page(); } // In our UI email and user name are one and the same, so when we update the email // we need to update the user name. var setUserNameResult = await _userManager.SetUserNameAsync(user, email); if (!setUserNameResult.Succeeded) { StatusMessage = "Error changing user name."; return Page(); } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Thank you for confirming your email change."; return Page(); } } }
33.5
110
0.616915
[ "Apache-2.0" ]
Bilgisayar-Programciligi/Programlama
Programlama-3/10 - ETicaretSQLite_Identity_role/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs
2,211
C#
//============================================================== // Copyright (C) 2020 Inc. All rights reserved. // //============================================================== // Create by 种道洋 at 2020/8/17 9:33:19. // Version 1.0 // 种道洋 //============================================================== using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; namespace Cdy.Spider { /// <summary> /// /// </summary> public interface ICommChannelDevelop { #region ... Variables ... #endregion ...Variables... #region ... Events ... #endregion ...Events... #region ... Constructor... #endregion ...Constructor... #region ... Properties ... /// <summary> /// /// </summary> string Name { get; set; } /// <summary> /// /// </summary> ChannelData Data { get; set; } string TypeName { get; } #endregion ...Properties... #region ... Methods ... object Config(); /// <summary> /// /// </summary> /// <returns></returns> XElement Save(); /// <summary> /// /// </summary> /// <param name="xe"></param> void Load(XElement xe); #endregion ...Methods... #region ... Interfaces ... #endregion ...Interfaces... } public interface ICommChannelDevelopForFactory { #region ... Variables ... #endregion ...Variables... #region ... Events ... #endregion ...Events... #region ... Constructor... #endregion ...Constructor... #region ... Properties ... /// <summary> /// /// </summary> string TypeName { get; } #endregion ...Properties... #region ... Methods ... /// <summary> /// /// </summary> /// <returns></returns> ICommChannelDevelop NewChannel(); #endregion ...Methods... #region ... Interfaces ... #endregion ...Interfaces... } }
20
65
0.420183
[ "Apache-2.0" ]
bingwang12/Spider
Common/Cdy.Spider.Common/Interface/ICommChannelDevelop.cs
2,194
C#
using System.Reflection; 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("jQueryUploadTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("jQueryUploadTest")] [assembly: AssemblyCopyright("Copyright © 2011")] [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("3d5900ae-111a-45be-96b3-d9e4606ca793")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.885714
84
0.746606
[ "MIT" ]
slavapa/jQuery-File-Upload-master
Properties/AssemblyInfo.cs
1,329
C#
using PhoneContact.API.Client.Base; using PhoneContact.API.Client.Resources; using System.Net.Http; namespace PhoneContact.API.Client { public class PhoneContactClient : IPhoneContactClient { public PhoneContactClient(HttpClient client) { Item = new PhoneContactContactResource(new BaseClient(client, client.BaseAddress.ToString())); } public IPhoneContactContactResource Item { get; } } }
28.4375
106
0.703297
[ "Apache-2.0" ]
saimnasir/my-phone-contact
PhoneContact/PhoneContact.API.Client/PhoneContactClient.cs
457
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MySqlConnector; namespace MySqlBackupTestApp { public partial class FormTestEncryptDecrypt : Form { public FormTestEncryptDecrypt() { InitializeComponent(); } private void btSourceFile_Click(object sender, EventArgs e) { OpenFileDialog f = new OpenFileDialog(); if (DialogResult.OK == f.ShowDialog()) { txtSource.Text = f.FileName; } } private void btOutputFile_Click(object sender, EventArgs e) { SaveFileDialog f = new SaveFileDialog(); if (DialogResult.OK == f.ShowDialog()) { txtOutput.Text = f.FileName; } } private void btDecrypt_Click(object sender, EventArgs e) { MessageBox.Show("this function is dropped in V2.3"); //try //{ // using (MySqlBackup mb = new MySqlBackup()) // { // mb.DecryptDumpFile(txtSource.Text, txtOutput.Text, txtPwd.Text); // } // MessageBox.Show("Done"); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} } private void btEncrypt_Click(object sender, EventArgs e) { MessageBox.Show("this function is dropped in V2.3"); //try //{ // using (MySqlBackup mb = new MySqlBackup()) // { // mb.EncryptDumpFile(txtSource.Text, txtOutput.Text, txtPwd.Text); // } // MessageBox.Show("Done"); //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} } private void btSwitch_Click(object sender, EventArgs e) { string f1 = txtSource.Text; string f2 = txtOutput.Text; txtSource.Text = f2; txtOutput.Text = f1; } } }
27.9875
86
0.501117
[ "Unlicense" ]
MySqlBackupNET/MySqlBackup.Net
source code/Test_WinForm_MySqlConnector/FormTestEncryptDecrypt.cs
2,241
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; #if NETSTANDARD1_6 using System.Reflection; #endif namespace FluentdClient.Sharp { internal static class TypeAccessor { private static readonly ConcurrentDictionary<Type, IDictionary<string, Func<object, object>>> _valueGetter; static TypeAccessor() { _valueGetter = new ConcurrentDictionary<Type, IDictionary<string, Func<object, object>>>(); } internal static IDictionary<string, object> GetMessageAsDictionary<T>(T message) where T : class { var type = message.GetType(); var valueGetter = GetValueGetter(type); var dictionary = valueGetter.ToDictionary(x => x.Key, x => x.Value.Invoke(message)); return dictionary; } internal static IDictionary<string, Func<object, object>> GetValueGetter(Type type) { return _valueGetter.GetOrAdd( type, valueType => { var properties = valueType.GetProperties(); return properties.ToDictionary( x => x.Name, x => new Func<object, object>(obj => x.GetValue(obj))); }); } } }
29.173913
115
0.587183
[ "MIT" ]
ttakahari/FluentdClient.Sharp
src/FluentdClient.Sharp/TypeAccessor.cs
1,344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Erlin.Lib.Common.Misc { /// <summary> /// Mathematic calculation helper /// </summary> public static class MathHelper { /// <summary> /// Check if entered number is non-floating point number /// </summary> /// <param name="value">Number to check</param> /// <returns>False - value is floating point number</returns> public static bool IsWholeInteger(decimal value) { return Math.Abs(value % 1) <= 0.0000000000000000000000001m; } } }
27.5
71
0.625758
[ "Unlicense" ]
ErlinEmrys/Lib.Common
Erlin.Lib.Common/Misc/MathHelper.cs
662
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 Microsoft.Extensions.Http.Logging; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.Http { // Internal so we can change the requirements without breaking changes. internal sealed class LoggingHttpMessageHandlerBuilderFilter : IHttpMessageHandlerBuilderFilter { private readonly ILoggerFactory _loggerFactory; private readonly IOptionsMonitor<HttpClientFactoryOptions> _optionsMonitor; public LoggingHttpMessageHandlerBuilderFilter(ILoggerFactory loggerFactory, IOptionsMonitor<HttpClientFactoryOptions> optionsMonitor) { ThrowHelper.ThrowIfNull(loggerFactory); ThrowHelper.ThrowIfNull(optionsMonitor); _loggerFactory = loggerFactory; _optionsMonitor = optionsMonitor; } public Action<HttpMessageHandlerBuilder> Configure(Action<HttpMessageHandlerBuilder> next) { ThrowHelper.ThrowIfNull(next); return (builder) => { // Run other configuration first, we want to decorate. next(builder); string loggerName = !string.IsNullOrEmpty(builder.Name) ? builder.Name : "Default"; // We want all of our logging message to show up as-if they are coming from HttpClient, // but also to include the name of the client for more fine-grained control. ILogger outerLogger = _loggerFactory.CreateLogger($"System.Net.Http.HttpClient.{loggerName}.LogicalHandler"); ILogger innerLogger = _loggerFactory.CreateLogger($"System.Net.Http.HttpClient.{loggerName}.ClientHandler"); HttpClientFactoryOptions options = _optionsMonitor.Get(builder.Name); // The 'scope' handler goes first so it can surround everything. builder.AdditionalHandlers.Insert(0, new LoggingScopeHttpMessageHandler(outerLogger, options)); // We want this handler to be last so we can log details about the request after // service discovery and security happen. builder.AdditionalHandlers.Add(new LoggingHttpMessageHandler(innerLogger, options)); }; } } }
43.8
141
0.689083
[ "MIT" ]
Ali-YousefiTelori/runtime
src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs
2,409
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.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Text.RegularExpressions; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyWideningAndAddInt16() { var test = new SimpleTernaryOpTest__MultiplyWideningAndAddInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } else { Console.WriteLine("Avx Is Not Supported"); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); //TODO: this one does not work. Fix it. if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { Console.WriteLine("Test Is Not Supported"); // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyWideningAndAddInt16 { private struct DataTable { private byte[] inArray0; private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle0; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray0, Int16[] inArray1, Int16[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray0 = inArray0.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if((alignment != 32 && alignment != 16) || (alignment *2) < sizeOfinArray0 || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray0 = new byte[alignment * 2]; this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle0 = GCHandle.Alloc(this.inArray0, GCHandleType.Pinned); this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray0Ptr), ref Unsafe.As<Int32, byte>(ref inArray0[0]), (uint)sizeOfinArray0); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray0Ptr => Align((byte*)(inHandle0.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle0.Free(); inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlighment) { return (void*)(((ulong)buffer + expectedAlighment -1) & ~(expectedAlighment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld0; public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op0ElementCount; i++) { _data0[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld0), ref Unsafe.As<Int32, byte>(ref _data0[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyWideningAndAddInt16 testClass) { var result = AvxVnni.MultiplyWideningAndAdd(_fld0, _fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld0, _fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op0ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data0 = new Int32[Op0ElementCount]; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int32> _clsVar0; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int32> _fld0; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyWideningAndAddInt16() { for (var i = 0; i < Op0ElementCount; i++) { _data0[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar0), ref Unsafe.As<Int32, byte>(ref _data0[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleTernaryOpTest__MultiplyWideningAndAddInt16() { Succeeded = true; for (var i = 0; i < Op0ElementCount; i++) { _data0[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld0), ref Unsafe.As<Int32, byte>(ref _data0[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op0ElementCount; i++) { _data0[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data0, _data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AvxVnni.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AvxVnni.MultiplyWideningAndAdd( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray0Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AvxVnni.MultiplyWideningAndAdd( Avx.LoadVector256((Int32*)(_dataTable.inArray0Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = AvxVnni.MultiplyWideningAndAdd( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray0Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AvxVnni).GetMethod(nameof(AvxVnni.MultiplyWideningAndAdd), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray0Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AvxVnni).GetMethod(nameof(AvxVnni.MultiplyWideningAndAdd), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray0Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(AvxVnni).GetMethod(nameof(AvxVnni.MultiplyWideningAndAdd), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray0Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray0Ptr, _dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AvxVnni.MultiplyWideningAndAdd( _clsVar0, _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar0, _clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var first = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray0Ptr); var second = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var third = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = AvxVnni.MultiplyWideningAndAdd(first, second, third); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(first, second, third, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var first= Avx.LoadVector256((Int32*)(_dataTable.inArray0Ptr)); var second = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var third = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = AvxVnni.MultiplyWideningAndAdd(first, second, third); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(first, second, third, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var first = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray0Ptr)); var second = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var third = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = AvxVnni.MultiplyWideningAndAdd(first, second, third); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(first, second, third, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyWideningAndAddInt16(); var result = AvxVnni.MultiplyWideningAndAdd(test._fld0, test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld0, test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AvxVnni.MultiplyWideningAndAdd(_fld0, _fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld0, _fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AvxVnni.MultiplyWideningAndAdd(test._fld0, test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld0, test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> addend, Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray0 = new Int32[Op0ElementCount]; Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray0[0]), addend); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray0, inArray1, inArray2, outArray, method); } private void ValidateResult(void* addend, void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray0 = new Int32[Op0ElementCount]; Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray0[0]), ref Unsafe.AsRef<byte>(addend), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray0, inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] addend, Int16[] left, Int16[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; Int32[] outArray = new Int32[RetElementCount]; for (var i = 0; i < RetElementCount; i++) { outArray[i] = Math.Clamp((addend[i] + (right[i * 2 + 1] * left[i * 2 + 1] + right[i * 2] * left[i * 2])), int.MinValue, int.MaxValue); } for (var i = 0; i < RetElementCount; i++) { if (result[i] != outArray[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AvxVnni)}.{nameof(AvxVnni.MultiplyWideningAndAdd)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" addend: ({string.Join(", ", addend)})"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation($" valid: ({string.Join(", ", outArray)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
47.804391
207
0.609228
[ "MIT" ]
333fred/runtime
src/tests/JIT/HardwareIntrinsics/X86/AvxVnni/MultiplyWideningAndAdd.Int16.cs
23,950
C#
using System.Linq; using System.Collections; using System.Collections.Generic; using MongoDB; using MongoDB.Configuration; namespace System.Quality.EventSourcing { public class MongoEventStore : IEventStore { private readonly IMongoDatabase _database; private readonly Func<object, object, bool> _aggregateKeyEqualityComparer; public MongoEventStore(string connectionString, ITypeCatalog eventTypeCatalog, Func<object, object, bool> aggregateKeyEqualityComparer) { var connectionStringBuilder = new MongoConnectionStringBuilder(connectionString); var mongo = new Mongo(BuildMongoConfiguration(connectionString, eventTypeCatalog)); mongo.Connect(); _database = mongo.GetDatabase(connectionStringBuilder.Database); _aggregateKeyEqualityComparer = aggregateKeyEqualityComparer; } private static MongoConfiguration BuildMongoConfiguration(string connectionString, ITypeCatalog eventTypeCatalog) { var configurationBuilder = new MongoConfigurationBuilder(); configurationBuilder.ConnectionString(connectionString); configurationBuilder.Mapping(mapping => { mapping.DefaultProfile(profile => profile.SubClassesAre(type => type.IsSubclassOf(typeof(Event)))); eventTypeCatalog.GetDerivedTypes(typeof(Event), true) .Yield(type => MongoBuilder.MapType(type, mapping)); }); return configurationBuilder.BuildConfiguration(); } public IEnumerable<Event> GetEventsById(object aggregateId, int startSequence) { return _database.GetCollection<Event>("events") .Linq() .Where(e => _aggregateKeyEqualityComparer(e.AggregateId, aggregateId)) .Where(e => e.EventSequence > startSequence) .ToList(); } public IEnumerable<Event> GetEventsByEventTypes(IEnumerable<Type> eventTypes) { var document = new Document { { "_t", new Document { { "$in", eventTypes.Select(t => t.Name).ToArray() } } } }; var cursor = _database.GetCollection<Event>("events").Find(document); return cursor.Documents; } public void SaveEvents(object aggregateId, IEnumerable<Event> events) { var mogoEvents = _database.GetCollection<Event>("events"); mogoEvents.Insert(events); } } }
44.964912
144
0.646898
[ "Apache-2.0", "MIT" ]
Grimace1975/bclcontrib
Core/Quality/System.Core.Quality_Mongo/Quality+EventSourcing/EventSourcing/MongoEventStore.cs
2,565
C#
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Text; using Xamarin.Utils; namespace xharness { public class Jenkins { bool populating = true; public Harness Harness; public bool IncludeAll; public bool IncludeClassicMac = true; public bool IncludeBcl; public bool IncludeMac = true; public bool IncludeiOS = true; public bool IncludeiOSExtensions; public bool IncludetvOS = true; public bool IncludewatchOS = true; public bool IncludeMmpTest; public bool IncludeiOSMSBuild = true; public bool IncludeMtouch; public bool IncludeBtouch; public bool IncludeMacBindingProject; public bool IncludeSimulator = true; public bool IncludeDevice; public bool IncludeXtro; public Log MainLog; public Log SimulatorLoadLog; public Log DeviceLoadLog; public string LogDirectory { get { return Path.Combine (Harness.JENKINS_RESULTS_DIRECTORY, "tests"); } } Logs logs; public Logs Logs { get { return logs ?? (logs = new Logs (LogDirectory)); } } public Simulators Simulators = new Simulators (); public Devices Devices = new Devices (); List<TestTask> Tasks = new List<TestTask> (); internal static Resource DesktopResource = new Resource ("Desktop", Environment.ProcessorCount); static Dictionary<string, Resource> device_resources = new Dictionary<string, Resource> (); internal static Resources GetDeviceResources (IEnumerable<Device> devices) { List<Resource> resources = new List<Resource> (); lock (device_resources) { foreach (var device in devices) { Resource res; if (!device_resources.TryGetValue (device.UDID, out res)) device_resources.Add (device.UDID, res = new Resource (device.UDID, 1, device.Name)); resources.Add (res); } } return new Resources (resources); } // Loads both simulators and devices in parallel Task LoadSimulatorsAndDevicesAsync () { Simulators.Harness = Harness; Devices.Harness = Harness; if (SimulatorLoadLog == null) SimulatorLoadLog = Logs.Create ("simulator-list.log", "Simulator Listing"); var simulatorLoadTask = Task.Run (async () => { try { await Simulators.LoadAsync (SimulatorLoadLog); } catch (Exception e) { SimulatorLoadLog.WriteLine ("Failed to load simulators:"); SimulatorLoadLog.WriteLine (e); } }); if (DeviceLoadLog == null) DeviceLoadLog = Logs.Create ("device-list.log", "Device Listing"); var deviceLoadTask = Task.Run (async () => { try { await Devices.LoadAsync (DeviceLoadLog, removed_locked: true); } catch (Exception e) { DeviceLoadLog.WriteLine ("Failed to load devices:"); DeviceLoadLog.WriteLine (e); } }); return Task.CompletedTask; } IEnumerable<RunSimulatorTask> CreateRunSimulatorTaskAsync (XBuildTask buildTask) { var runtasks = new List<RunSimulatorTask> (); AppRunnerTarget [] targets; TestPlatform [] platforms; switch (buildTask.Platform) { case TestPlatform.tvOS: targets = new AppRunnerTarget [] { AppRunnerTarget.Simulator_tvOS }; platforms = new TestPlatform [] { TestPlatform.tvOS }; break; case TestPlatform.watchOS: targets = new AppRunnerTarget [] { AppRunnerTarget.Simulator_watchOS }; platforms = new TestPlatform [] { TestPlatform.watchOS }; break; case TestPlatform.iOS_Unified: targets = new AppRunnerTarget [] { AppRunnerTarget.Simulator_iOS32, AppRunnerTarget.Simulator_iOS64 }; platforms = new TestPlatform [] { TestPlatform.iOS_Unified32, TestPlatform.iOS_Unified64 }; break; default: throw new NotImplementedException (); } for (int i = 0; i < targets.Length; i++) runtasks.Add (new RunSimulatorTask (buildTask, Simulators.SelectDevices (targets [i], SimulatorLoadLog)) { Platform = platforms [i], Ignored = buildTask.Ignored }); return runtasks; } bool IsIncluded (TestProject project) { if (!project.IsExecutableProject) return false; if (!IncludeBcl && project.IsBclTest) return false; if (!Harness.IncludeSystemPermissionTests && project.Name == "introspection") return false; return true; } class TestData { public string Variation; public string MTouchExtraArgs; public string MonoBundlingExtraArgs; // mmp public bool Debug; public bool Profiling; public string LinkMode; public string Defines; public bool Ignored; } IEnumerable<TestData> GetTestData (RunTestTask test) { // This function returns additional test configurations (in addition to the default one) for the specific test switch (test.ProjectPlatform) { case "iPhone": /* we don't add --assembly-build-target=@all=staticobject because that's the default in all our test projects */ yield return new TestData { Variation = "AssemblyBuildTarget: dylib (debug)", MTouchExtraArgs = "--assembly-build-target=@all=dynamiclibrary", Debug = true, Profiling = false }; yield return new TestData { Variation = "AssemblyBuildTarget: SDK framework (debug)", MTouchExtraArgs = "--assembly-build-target=@sdk=framework=Xamarin.Sdk --assembly-build-target=@all=staticobject", Debug = true, Profiling = false }; yield return new TestData { Variation = "AssemblyBuildTarget: dylib (debug, profiling)", MTouchExtraArgs = "--assembly-build-target=@all=dynamiclibrary", Debug = true, Profiling = true }; yield return new TestData { Variation = "AssemblyBuildTarget: SDK framework (debug, profiling)", MTouchExtraArgs = "--assembly-build-target=@sdk=framework=Xamarin.Sdk --assembly-build-target=@all=staticobject", Debug = true, Profiling = true }; yield return new TestData { Variation = "Release", MTouchExtraArgs = "", Debug = false, Profiling = false }; yield return new TestData { Variation = "AssemblyBuildTarget: SDK framework (release)", MTouchExtraArgs = "--assembly-build-target=@sdk=framework=Xamarin.Sdk --assembly-build-target=@all=staticobject", Debug = false, Profiling = false }; switch (test.TestName) { case "monotouch-test": yield return new TestData { Variation = "Release (all optimizations)", MTouchExtraArgs = "--registrar:static --optimize:all", Debug = false, Profiling = false, Defines = "OPTIMIZEALL" }; yield return new TestData { Variation = "Debug (all optimizations)", MTouchExtraArgs = "--registrar:static --optimize:all", Debug = true, Profiling = false, Defines = "OPTIMIZEALL" }; break; } break; case "iPhoneSimulator": switch (test.TestName) { case "monotouch-test": // The default is to run monotouch-test with the dynamic registrar (in the simulator), so that's already covered yield return new TestData { Variation = "Debug (static registrar)", MTouchExtraArgs = "--registrar:static", Debug = true, Profiling = false }; yield return new TestData { Variation = "Release (all optimizations)", MTouchExtraArgs = "--registrar:static --optimize:all", Debug = false, Profiling = false, LinkMode = "Full", Defines = "LINKALL;OPTIMIZEALL" }; yield return new TestData { Variation = "Debug (all optimizations)", MTouchExtraArgs = "--registrar:static --optimize:all,-remove-uithread-checks", Debug = true, Profiling = false, LinkMode = "Full", Defines = "LINKALL;OPTIMIZEALL", Ignored = !IncludeAll }; break; } break; case "AnyCPU": case "x86": switch (test.TestName) { case "xammac tests": switch (test.ProjectConfiguration) { case "Release": yield return new TestData { Variation = "Release (all optimizations)", MonoBundlingExtraArgs = "--registrar:static --optimize:all", Debug = false, LinkMode = "Full", Defines = "LINKALL;OPTIMIZEALL"}; break; case "Debug": yield return new TestData { Variation = "Release (all optimizations)", MonoBundlingExtraArgs = "--registrar:static --optimize:all,-remove-uithread-checks", Debug = true, LinkMode = "Full", Defines = "LINKALL;OPTIMIZEALL", Ignored = !IncludeAll }; break; } break; } break; default: throw new NotImplementedException (test.ProjectPlatform); } } IEnumerable<T> CreateTestVariations<T> (IEnumerable<T> tests, Func<XBuildTask, T, T> creator) where T: RunTestTask { foreach (var task in tests) { if (string.IsNullOrEmpty (task.Variation)) task.Variation = "Debug"; } var rv = new List<T> (tests); foreach (var task in tests.ToArray ()) { foreach (var test_data in GetTestData (task)) { var variation = test_data.Variation; var mtouch_extra_args = test_data.MTouchExtraArgs; var bundling_extra_args = test_data.MonoBundlingExtraArgs; var configuration = test_data.Debug ? task.ProjectConfiguration : task.ProjectConfiguration.Replace ("Debug", "Release"); var debug = test_data.Debug; var profiling = test_data.Profiling; var link_mode = test_data.LinkMode; var defines = test_data.Defines; var ignored = test_data.Ignored; var clone = task.TestProject.Clone (); var clone_task = Task.Run (async () => { await task.BuildTask.InitialTask; // this is the project cloning above await clone.CreateCopyAsync (task); var isMac = false; switch (task.Platform) { case TestPlatform.Mac: case TestPlatform.Mac_Classic: case TestPlatform.Mac_Unified: case TestPlatform.Mac_Unified32: case TestPlatform.Mac_UnifiedXM45: case TestPlatform.Mac_UnifiedXM45_32: isMac = true; break; } if (!string.IsNullOrEmpty (mtouch_extra_args)) clone.Xml.AddExtraMtouchArgs (mtouch_extra_args, task.ProjectPlatform, configuration); if (!string.IsNullOrEmpty (bundling_extra_args)) clone.Xml.AddMonoBundlingExtraArgs (bundling_extra_args, task.ProjectPlatform, configuration); if (!string.IsNullOrEmpty (link_mode)) clone.Xml.SetNode (isMac ? "LinkMode" : "MtouchLink", link_mode, task.ProjectPlatform, configuration); if (!string.IsNullOrEmpty (defines)) { clone.Xml.AddAdditionalDefines (defines, task.ProjectPlatform, configuration); if (clone.ProjectReferences != null) { foreach (var pr in clone.ProjectReferences) { pr.Xml.AddAdditionalDefines (defines, task.ProjectPlatform, configuration); pr.Xml.Save (pr.Path); } } } clone.Xml.SetNode (isMac ? "Profiling" : "MTouchProfiling", profiling ? "True" : "False", task.ProjectPlatform, configuration); if (!debug && !isMac) clone.Xml.SetMtouchUseLlvm (true, task.ProjectPlatform, configuration); clone.Xml.Save (clone.Path); }); var build = new XBuildTask { Jenkins = this, TestProject = clone, ProjectConfiguration = configuration, ProjectPlatform = task.ProjectPlatform, Platform = task.Platform, InitialTask = clone_task, TestName = clone.Name, }; T newVariation = creator (build, task); newVariation.Variation = variation; newVariation.Ignored = task.Ignored || ignored; rv.Add (newVariation); } } return rv; } IEnumerable<TestTask> CreateRunSimulatorTasks () { var runSimulatorTasks = new List<RunSimulatorTask> (); foreach (var project in Harness.IOSTestProjects) { if (!project.IsExecutableProject) continue; bool ignored = !IncludeSimulator; if (!IsIncluded (project)) ignored = true; var ps = new List<Tuple<TestProject, TestPlatform, bool>> (); if (!project.SkipiOSVariation) ps.Add (new Tuple<TestProject, TestPlatform, bool> (project, TestPlatform.iOS_Unified, ignored || !IncludeiOS)); if (!project.SkiptvOSVariation) ps.Add (new Tuple<TestProject, TestPlatform, bool> (project.AsTvOSProject (), TestPlatform.tvOS, ignored || !IncludetvOS)); if (!project.SkipwatchOSVariation) ps.Add (new Tuple<TestProject, TestPlatform, bool> (project.AsWatchOSProject (), TestPlatform.watchOS, ignored || !IncludewatchOS)); var configurations = project.Configurations; if (configurations == null) configurations = new string [] { "Debug" }; foreach (var config in configurations) { foreach (var pair in ps) { var derived = new XBuildTask () { Jenkins = this, ProjectConfiguration = config, ProjectPlatform = "iPhoneSimulator", Platform = pair.Item2, Ignored = pair.Item3, TestName = project.Name, }; derived.CloneTestProject (pair.Item1); var simTasks = CreateRunSimulatorTaskAsync (derived); runSimulatorTasks.AddRange (simTasks); if (configurations.Length > 1) { foreach (var task in simTasks) task.Variation = config; } } } } var testVariations = CreateTestVariations (runSimulatorTasks, (buildTask, test) => new RunSimulatorTask (buildTask, test.Candidates)).ToList (); foreach (var taskGroup in testVariations.GroupBy ((RunSimulatorTask task) => task.Platform)) { yield return new AggregatedRunSimulatorTask (taskGroup) { Jenkins = this, TestName = $"Tests for {taskGroup.Key}", }; } } IEnumerable<TestTask> CreateRunDeviceTasks () { var rv = new List<RunDeviceTask> (); foreach (var project in Harness.IOSTestProjects) { if (!project.IsExecutableProject) continue; bool ignored = !IncludeDevice; if (!IsIncluded (project)) ignored = true; if (!project.SkipiOSVariation) { var build64 = new XBuildTask { Jenkins = this, ProjectConfiguration = "Debug64", ProjectPlatform = "iPhone", Platform = TestPlatform.iOS_Unified64, TestName = project.Name, }; build64.CloneTestProject (project); rv.Add (new RunDeviceTask (build64, Devices.ConnectedDevices.Where ((dev) => dev.DevicePlatform == DevicePlatform.iOS && dev.Supports64Bit)) { Ignored = ignored || !IncludeiOS }); var build32 = new XBuildTask { Jenkins = this, ProjectConfiguration = "Debug32", ProjectPlatform = "iPhone", Platform = TestPlatform.iOS_Unified32, TestName = project.Name, }; build32.CloneTestProject (project); rv.Add (new RunDeviceTask (build32, Devices.ConnectedDevices.Where ((dev) => dev.DevicePlatform == DevicePlatform.iOS && dev.Supports32Bit)) { Ignored = ignored || !IncludeiOS }); var todayProject = project.AsTodayExtensionProject (); var buildToday = new XBuildTask { Jenkins = this, ProjectConfiguration = "Debug64", ProjectPlatform = "iPhone", Platform = TestPlatform.iOS_TodayExtension64, TestName = project.Name, }; buildToday.CloneTestProject (todayProject); rv.Add (new RunDeviceTask (buildToday, Devices.ConnectedDevices.Where ((dev) => dev.DevicePlatform == DevicePlatform.iOS && dev.Supports64Bit)) { Ignored = ignored || !IncludeiOSExtensions }); } if (!project.SkiptvOSVariation) { var tvOSProject = project.AsTvOSProject (); var buildTV = new XBuildTask { Jenkins = this, ProjectConfiguration = "Debug", ProjectPlatform = "iPhone", Platform = TestPlatform.tvOS, TestName = project.Name, }; buildTV.CloneTestProject (tvOSProject); rv.Add (new RunDeviceTask (buildTV, Devices.ConnectedDevices.Where ((dev) => dev.DevicePlatform == DevicePlatform.tvOS)) { Ignored = ignored || !IncludetvOS }); } if (!project.SkipwatchOSVariation) { var watchOSProject = project.AsWatchOSProject (); var buildWatch = new XBuildTask { Jenkins = this, ProjectConfiguration = "Debug", ProjectPlatform = "iPhone", Platform = TestPlatform.watchOS, TestName = project.Name, }; buildWatch.CloneTestProject (watchOSProject); rv.Add (new RunDeviceTask (buildWatch, Devices.ConnectedDevices.Where ((dev) => dev.DevicePlatform == DevicePlatform.watchOS)) { Ignored = ignored || !IncludewatchOS }); } } return CreateTestVariations (rv, (buildTask, test) => new RunDeviceTask (buildTask, test.Candidates)); } static string AddSuffixToPath (string path, string suffix) { return Path.Combine (Path.GetDirectoryName (path), Path.GetFileNameWithoutExtension (path) + suffix + Path.GetExtension (path)); } void SelectTests () { int pull_request; if (!int.TryParse (Environment.GetEnvironmentVariable ("ghprbPullId"), out pull_request)) MainLog.WriteLine ("The environment variable 'ghprbPullId' was not found, so no pull requests will be checked for test selection."); // First check if can auto-select any tests based on which files were modified. // This will only enable additional tests, never disable tests. if (pull_request > 0) SelectTestsByModifiedFiles (pull_request); // Then we check for labels. Labels are manually set, so those override // whatever we did automatically. SelectTestsByLabel (pull_request); if (!Harness.INCLUDE_IOS) { MainLog.WriteLine ("The iOS build is diabled, so any iOS tests will be disabled as well."); IncludeiOS = false; } if (!Harness.INCLUDE_WATCH) { MainLog.WriteLine ("The watchOS build is disabled, so any watchOS tests will be disabled as well."); IncludewatchOS = false; } if (!Harness.INCLUDE_TVOS) { MainLog.WriteLine ("The tvOS build is disabled, so any tvOS tests will be disabled as well."); IncludetvOS = false; } if (!Harness.INCLUDE_MAC) { MainLog.WriteLine ("The macOS build is disabled, so any macOS tests will be disabled as well."); IncludeMac = false; } } void SelectTestsByModifiedFiles (int pull_request) { var files = GitHub.GetModifiedFiles (Harness, pull_request); MainLog.WriteLine ("Found {0} modified file(s) in the pull request #{1}.", files.Count (), pull_request); foreach (var f in files) MainLog.WriteLine (" {0}", f); // We select tests based on a prefix of the modified files. // Add entries here to check for more prefixes. var mtouch_prefixes = new string [] { "tests/mtouch", "tests/common", "tools/mtouch", "tools/common", "tools/linker", "src/ObjCRuntime/Registrar.cs", "external/mono", "external/llvm", "msbuild", }; var mmp_prefixes = new string [] { "tests/mmptest", "tests/common", "tools/mmp", "tools/common", "tools/linker", "src/ObjCRuntime/Registrar.cs", "external/mono", "msbuild", }; var bcl_prefixes = new string [] { "tests/bcl-test", "tests/common", "external/mono", "external/llvm", }; var btouch_prefixes = new string [] { "src/btouch.cs", "src/generator.cs", "src/generator-", "src/Makefile.generator", "tests/generator", "tests/common", }; var mac_binding_project = new string [] { "msbuild", "tests/mac-binding-project", "tests/common/mac", }.Intersect (btouch_prefixes).ToArray (); var xtro_prefixes = new string [] { "tests/xtro-sharpie", "src", }; SetEnabled (files, mtouch_prefixes, "mtouch", ref IncludeMtouch); SetEnabled (files, mmp_prefixes, "mmp", ref IncludeMmpTest); SetEnabled (files, bcl_prefixes, "bcl", ref IncludeBcl); SetEnabled (files, btouch_prefixes, "btouch", ref IncludeBtouch); SetEnabled (files, mac_binding_project, "mac-binding-project", ref IncludeMacBindingProject); SetEnabled (files, xtro_prefixes, "xtro", ref IncludeXtro); } void SetEnabled (IEnumerable<string> files, string [] prefixes, string testname, ref bool value) { foreach (var file in files) { foreach (var prefix in prefixes) { if (file.StartsWith (prefix, StringComparison.Ordinal)) { value = true; MainLog.WriteLine ("Enabled '{0}' tests because the modified file '{1}' matches prefix '{2}'", testname, file, prefix); return; } } } } void SelectTestsByLabel (int pull_request) { var labels = new HashSet<string> (); labels.UnionWith (Harness.Labels); if (pull_request > 0) labels.UnionWith (GitHub.GetLabels (Harness, pull_request)); MainLog.WriteLine ("Found {1} label(s) in the pull request #{2}: {0}", string.Join (", ", labels.ToArray ()), labels.Count (), pull_request); // disabled by default SetEnabled (labels, "mtouch", ref IncludeMtouch); SetEnabled (labels, "mmp", ref IncludeMmpTest); SetEnabled (labels, "bcl", ref IncludeBcl); SetEnabled (labels, "btouch", ref IncludeBtouch); SetEnabled (labels, "mac-binding-project", ref IncludeMacBindingProject); SetEnabled (labels, "ios-extensions", ref IncludeiOSExtensions); SetEnabled (labels, "ios-device", ref IncludeDevice); SetEnabled (labels, "xtro", ref IncludeXtro); SetEnabled (labels, "all", ref IncludeAll); // enabled by default SetEnabled (labels, "ios", ref IncludeiOS); SetEnabled (labels, "tvos", ref IncludetvOS); SetEnabled (labels, "watchos", ref IncludewatchOS); SetEnabled (labels, "mac", ref IncludeMac); SetEnabled (labels, "mac-classic", ref IncludeClassicMac); SetEnabled (labels, "ios-msbuild", ref IncludeiOSMSBuild); SetEnabled (labels, "ios-simulator", ref IncludeSimulator); bool inc_permission_tests = Harness.IncludeSystemPermissionTests; SetEnabled (labels, "system-permission", ref inc_permission_tests); Harness.IncludeSystemPermissionTests = inc_permission_tests; } void SetEnabled (HashSet<string> labels, string testname, ref bool value) { if (labels.Contains ("skip-" + testname + "-tests")) { MainLog.WriteLine ("Disabled '{0}' tests because the label 'skip-{0}-tests' is set.", testname); value = false; } else if (labels.Contains ("run-" + testname + "-tests")) { MainLog.WriteLine ("Enabled '{0}' tests because the label 'run-{0}-tests' is set.", testname); value = true; } else if (labels.Contains ("skip-all-tests")) { MainLog.WriteLine ("Disabled '{0}' tests because the label 'skip-all-tests' is set.", testname); value = false; } else if (labels.Contains ("run-all-tests")) { MainLog.WriteLine ("Enabled '{0}' tests because the label 'run-all-tests' is set.", testname); value = true; } // respect any default value } async Task PopulateTasksAsync () { // Missing: // api-diff SelectTests (); await LoadSimulatorsAndDevicesAsync (); Tasks.AddRange (CreateRunSimulatorTasks ()); var buildiOSMSBuild = new XBuildTask () { Jenkins = this, TestProject = new TestProject (Path.GetFullPath (Path.Combine (Harness.RootDirectory, "..", "msbuild", "Xamarin.MacDev.Tasks.sln"))), SpecifyPlatform = false, SpecifyConfiguration = false, Platform = TestPlatform.iOS, UseMSBuild = true, }; var nunitExecutioniOSMSBuild = new NUnitExecuteTask (buildiOSMSBuild) { TestLibrary = Path.Combine (Harness.RootDirectory, "..", "msbuild", "tests", "bin", "Xamarin.iOS.Tasks.Tests.dll"), TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.Runners.2.6.4", "tools", "nunit-console.exe"), WorkingDirectory = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.Runners.2.6.4", "tools", "lib"), Platform = TestPlatform.iOS, TestName = "MSBuild tests", Mode = "iOS", Timeout = TimeSpan.FromMinutes (60), Ignored = !IncludeiOSMSBuild, }; Tasks.Add (nunitExecutioniOSMSBuild); var buildInstallSources = new XBuildTask () { Jenkins = this, TestProject = new TestProject (Path.GetFullPath (Path.Combine (Harness.RootDirectory, "..", "tools", "install-source", "InstallSourcesTests", "InstallSourcesTests.csproj"))), SpecifyPlatform = false, SpecifyConfiguration = false, Platform = TestPlatform.iOS, }; buildInstallSources.SolutionPath = Path.GetFullPath (Path.Combine (Harness.RootDirectory, "..", "tools", "install-source", "install-source.sln")); // this is required for nuget restore to be executed var nunitExecutionInstallSource = new NUnitExecuteTask (buildInstallSources) { TestLibrary = Path.Combine (Harness.RootDirectory, "..", "tools", "install-source", "InstallSourcesTests", "bin", "Release", "InstallSourcesTests.dll"), TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.Runners.2.6.4", "tools", "nunit-console.exe"), WorkingDirectory = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.Runners.2.6.4", "tools", "lib"), Platform = TestPlatform.iOS, TestName = "Install Sources tests", Mode = "iOS", Timeout = TimeSpan.FromMinutes (60), Ignored = !IncludeMac && !IncludeSimulator, }; Tasks.Add (nunitExecutionInstallSource); foreach (var project in Harness.MacTestProjects) { bool ignored = !IncludeMac; if (!IncludeMmpTest && project.Path.Contains ("mmptest")) ignored = true; if (!IsIncluded (project)) ignored = true; var configurations = project.Configurations; if (configurations == null) configurations = new string [] { "Debug" }; foreach (var config in configurations) { BuildProjectTask build; if (project.GenerateVariations) { build = new MdtoolTask (); build.Platform = TestPlatform.Mac_Classic; build.TestProject = project; } else { build = new XBuildTask (); build.Platform = TestPlatform.Mac; build.CloneTestProject (project); } build.Jenkins = this; build.SolutionPath = project.SolutionPath; build.ProjectConfiguration = config; build.ProjectPlatform = project.Platform; build.SpecifyPlatform = false; build.SpecifyConfiguration = build.ProjectConfiguration != "Debug"; RunTestTask exec; IEnumerable<RunTestTask> execs; if (project.IsNUnitProject) { var dll = Path.Combine (Path.GetDirectoryName (build.TestProject.Path), project.Xml.GetOutputAssemblyPath (build.ProjectPlatform, build.ProjectConfiguration).Replace ('\\', '/')); exec = new NUnitExecuteTask (build) { Ignored = ignored || !IncludeClassicMac, TestLibrary = dll, TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.ConsoleRunner.3.5.0", "tools", "nunit3-console.exe"), WorkingDirectory = Path.GetDirectoryName (dll), Platform = build.Platform, TestName = project.Name, Timeout = TimeSpan.FromMinutes (120), }; execs = new [] { exec }; } else { exec = new MacExecuteTask (build) { Ignored = ignored || !IncludeClassicMac, BCLTest = project.IsBclTest, TestName = project.Name, IsUnitTest = true, }; execs = CreateTestVariations (new [] { exec }, (buildTask, test) => new MacExecuteTask (buildTask)); } exec.Variation = configurations.Length > 1 ? config : project.TargetFrameworkFlavor.ToString (); Tasks.AddRange (execs); foreach (var e in execs) { if (project.GenerateVariations) { Tasks.Add (CloneExecuteTask (e, project, TestPlatform.Mac_Unified, "-unified", ignored)); Tasks.Add (CloneExecuteTask (e, project, TestPlatform.Mac_Unified32, "-unified-32", ignored)); if (project.GenerateFull) { Tasks.Add (CloneExecuteTask (e, project, TestPlatform.Mac_UnifiedXM45, "-unifiedXM45", ignored)); Tasks.Add (CloneExecuteTask (e, project, TestPlatform.Mac_UnifiedXM45_32, "-unifiedXM45-32", ignored)); } } } } } var buildMTouch = new MakeTask () { Jenkins = this, TestProject = new TestProject (Path.GetFullPath (Path.Combine (Harness.RootDirectory, "mtouch", "mtouch.sln"))), SpecifyPlatform = false, SpecifyConfiguration = false, Platform = TestPlatform.iOS, Target = "dependencies", WorkingDirectory = Path.GetFullPath (Path.Combine (Harness.RootDirectory, "mtouch")), }; var nunitExecutionMTouch = new NUnitExecuteTask (buildMTouch) { TestLibrary = Path.Combine (Harness.RootDirectory, "mtouch", "bin", "Debug", "mtouch.dll"), TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.ConsoleRunner.3.5.0", "tools", "nunit3-console.exe"), WorkingDirectory = Path.Combine (Harness.RootDirectory, "mtouch", "bin", "Debug"), Platform = TestPlatform.iOS, TestName = "MTouch tests", Timeout = TimeSpan.FromMinutes (120), Ignored = !IncludeMtouch, }; Tasks.Add (nunitExecutionMTouch); var buildGenerator = new MakeTask { Jenkins = this, TestProject = new TestProject (Path.GetFullPath (Path.Combine (Harness.RootDirectory, "..", "src", "generator.sln"))), SpecifyPlatform = false, SpecifyConfiguration = false, Platform = TestPlatform.iOS, Target = "build-unit-tests", WorkingDirectory = Path.GetFullPath (Path.Combine (Harness.RootDirectory, "generator")), }; var runGenerator = new NUnitExecuteTask (buildGenerator) { TestLibrary = Path.Combine (Harness.RootDirectory, "generator", "bin", "Debug", "generator-tests.dll"), TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.ConsoleRunner.3.5.0", "tools", "nunit3-console.exe"), WorkingDirectory = Path.Combine (Harness.RootDirectory, "generator", "bin", "Debug"), Platform = TestPlatform.iOS, TestName = "Generator tests", Timeout = TimeSpan.FromMinutes (10), Ignored = !IncludeBtouch, }; Tasks.Add (runGenerator); var run_mmp = new MakeTask { Jenkins = this, Platform = TestPlatform.Mac, TestName = "MMP Regression Tests", Target = "all", // -j" + Environment.ProcessorCount, WorkingDirectory = Path.Combine (Harness.RootDirectory, "mmptest", "regression"), Ignored = !IncludeMmpTest || !IncludeMac, Timeout = TimeSpan.FromMinutes (30), SupportsParallelExecution = false, // Already doing parallel execution by running "make -jX" }; run_mmp.CompletedTask = new Task (() => { foreach (var log in Directory.GetFiles (Path.GetFullPath (run_mmp.WorkingDirectory), "*.log", SearchOption.AllDirectories)) run_mmp.Logs.AddFile (log, log.Substring (run_mmp.WorkingDirectory.Length + 1)); }); run_mmp.Environment.Add ("BUILD_REVISION", "jenkins"); // This will print "@MonkeyWrench: AddFile: <log path>" lines, which we can use to get the log filenames. Tasks.Add (run_mmp); var runMacBindingProject = new MakeTask { Jenkins = this, Platform = TestPlatform.Mac, TestName = "Mac Binding Projects", Target = "all", WorkingDirectory = Path.Combine (Harness.RootDirectory, "mac-binding-project"), Ignored = !IncludeMacBindingProject || !IncludeMac, }; Tasks.Add (runMacBindingProject); var buildXtroTests = new MakeTask { Jenkins = this, Platform = TestPlatform.All, TestName = "Xtro", Target = "wrench", WorkingDirectory = Path.Combine (Harness.RootDirectory, "xtro-sharpie"), Ignored = !IncludeXtro, Timeout = TimeSpan.FromMinutes (15), }; var runXtroReporter = new RunXtroTask (buildXtroTests) { Jenkins = this, Platform = TestPlatform.Mac, TestName = buildXtroTests.TestName, Ignored = buildXtroTests.Ignored, WorkingDirectory = buildXtroTests.WorkingDirectory, }; Tasks.Add (runXtroReporter); Tasks.AddRange (CreateRunDeviceTasks ()); } RunTestTask CloneExecuteTask (RunTestTask task, TestProject original_project, TestPlatform platform, string suffix, bool ignore) { var build = new XBuildTask () { Platform = platform, Jenkins = task.Jenkins, ProjectConfiguration = task.ProjectConfiguration, ProjectPlatform = task.ProjectPlatform, SpecifyPlatform = task.BuildTask.SpecifyPlatform, SpecifyConfiguration = task.BuildTask.SpecifyConfiguration, }; var tp = new TestProject (Path.ChangeExtension (AddSuffixToPath (original_project.Path, suffix), "csproj")); build.CloneTestProject (tp); var macExec = task as MacExecuteTask; if (macExec != null) { return new MacExecuteTask (build) { Ignored = ignore, TestName = task.TestName, IsUnitTest = macExec.IsUnitTest, }; } var nunit = task as NUnitExecuteTask; if (nunit != null) { var project = build.TestProject; var dll = Path.Combine (Path.GetDirectoryName (project.Path), project.Xml.GetOutputAssemblyPath (build.ProjectPlatform, build.ProjectConfiguration).Replace ('\\', '/')); return new NUnitExecuteTask (build) { Ignored = ignore, TestName = build.TestName, TestLibrary = dll, TestExecutable = Path.Combine (Harness.RootDirectory, "..", "packages", "NUnit.ConsoleRunner.3.5.0", "tools", "nunit3-console.exe"), WorkingDirectory = Path.GetDirectoryName (dll), Platform = build.Platform, Timeout = TimeSpan.FromMinutes (120), }; } throw new NotImplementedException (); } async Task ExecutePeriodicCommandAsync (Log periodic_loc) { //await Task.Delay (Harness.UploadInterval); periodic_loc.WriteLine ($"Starting periodic task with interval {Harness.PeriodicCommandInterval.TotalMinutes} minutes."); while (true) { var watch = Stopwatch.StartNew (); using (var process = new Process ()) { process.StartInfo.FileName = Harness.PeriodicCommand; process.StartInfo.Arguments = Harness.PeriodicCommandArguments; var rv = await process.RunAsync (periodic_loc, null); if (!rv.Succeeded) periodic_loc.WriteLine ($"Periodic command failed with exit code {rv.ExitCode} (Timed out: {rv.TimedOut})"); } var ticksLeft = watch.ElapsedTicks - Harness.PeriodicCommandInterval.Ticks; if (ticksLeft < 0) ticksLeft = Harness.PeriodicCommandInterval.Ticks; var wait = TimeSpan.FromTicks (ticksLeft); await Task.Delay (wait); } } public int Run () { try { Directory.CreateDirectory (LogDirectory); Log log = Logs.Create ("Harness.log", "Harness log"); if (Harness.InWrench) log = Log.CreateAggregatedLog (log, new ConsoleLog ()); Harness.HarnessLog = MainLog = log; Harness.HarnessLog.Timestamp = true; var tasks = new List<Task> (); if (IsServerMode) tasks.Add (RunTestServer ()); if (Harness.InJenkins) { Task.Factory.StartNew (async () => { while (true) { await Task.Delay (TimeSpan.FromMinutes (10)); Console.WriteLine ("Still running tests. Please be patient."); } }); } if (!string.IsNullOrEmpty (Harness.PeriodicCommand)) { var periodic_log = Logs.Create ("PeriodicCommand.log", "Periodic command log"); periodic_log.Timestamp = true; Task.Run (async () => await ExecutePeriodicCommandAsync (periodic_log)); } Task.Run (async () => { await SimDevice.KillEverythingAsync (MainLog); await PopulateTasksAsync (); populating = false; }).Wait (); GenerateReport (); BuildTestLibraries (); if (!IsServerMode) { foreach (var task in Tasks) tasks.Add (task.RunAsync ()); } Task.WaitAll (tasks.ToArray ()); GenerateReport (); return Tasks.Any ((v) => v.Failed || v.Skipped) ? 1 : 0; } catch (Exception ex) { MainLog.WriteLine ("Unexpected exception: {0}", ex); Console.WriteLine ("Unexpected exception: {0}", ex); return 2; } } public bool IsServerMode { get { return Harness.JenkinsConfiguration == "server"; } } void BuildTestLibraries () { ProcessHelper.ExecuteCommandAsync ("make", $"all -j{Environment.ProcessorCount} -C {StringUtils.Quote (Path.Combine (Harness.RootDirectory, "test-libraries"))}", MainLog, TimeSpan.FromMinutes (1)).Wait (); } Task RunTestServer () { var server = new HttpListener (); // Try and find an unused port int attemptsLeft = 50; int port = 51234; // Try this port first, to try to not vary between runs just because. Random r = new Random ((int) DateTime.Now.Ticks); while (attemptsLeft-- > 0) { var newPort = port != 0 ? port : r.Next (49152, 65535); // The suggested range for dynamic ports is 49152-65535 (IANA) server.Prefixes.Clear (); server.Prefixes.Add ("http://*:" + newPort + "/"); try { server.Start (); port = newPort; break; } catch (Exception ex) { MainLog.WriteLine ("Failed to listen on port {0}: {1}", newPort, ex.Message); port = 0; } } MainLog.WriteLine ($"Created server on localhost:{port}"); var tcs = new TaskCompletionSource<bool> (); var thread = new System.Threading.Thread (() => { while (server.IsListening) { var context = server.GetContext (); var request = context.Request; var response = context.Response; var arguments = System.Web.HttpUtility.ParseQueryString (request.Url.Query); try { var allTasks = Tasks.SelectMany ((v) => { var rv = new List<TestTask> (); var runsim = v as AggregatedRunSimulatorTask; if (runsim != null) rv.AddRange (runsim.Tasks); rv.Add (v); return rv; }); switch (request.Url.LocalPath) { case "/": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Html; GenerateReportImpl (response.OutputStream); break; case "/select": case "/deselect": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; using (var writer = new StreamWriter (response.OutputStream)) { foreach (var task in allTasks) { bool? is_match = null; if (!(task.Ignored || task.NotStarted)) continue; switch (request.Url.Query) { case "?all": is_match = true; break; case "?all-device": is_match = task is RunDeviceTask; break; case "?all-simulator": is_match = task is RunSimulatorTask; break; case "?all-ios": switch (task.Platform) { case TestPlatform.iOS: case TestPlatform.iOS_TodayExtension64: case TestPlatform.iOS_Unified: case TestPlatform.iOS_Unified32: case TestPlatform.iOS_Unified64: is_match = true; break; default: if (task.Platform.ToString ().StartsWith ("iOS", StringComparison.Ordinal)) throw new NotImplementedException (); break; } break; case "?all-tvos": switch (task.Platform) { case TestPlatform.tvOS: is_match = true; break; default: if (task.Platform.ToString ().StartsWith ("tvOS", StringComparison.Ordinal)) throw new NotImplementedException (); break; } break; case "?all-watchos": switch (task.Platform) { case TestPlatform.watchOS: is_match = true; break; default: if (task.Platform.ToString ().StartsWith ("watchOS", StringComparison.Ordinal)) throw new NotImplementedException (); break; } break; case "?all-mac": switch (task.Platform) { case TestPlatform.Mac: case TestPlatform.Mac_Classic: case TestPlatform.Mac_Unified: case TestPlatform.Mac_Unified32: case TestPlatform.Mac_UnifiedXM45: case TestPlatform.Mac_UnifiedXM45_32: is_match = true; break; default: if (task.Platform.ToString ().StartsWith ("Mac", StringComparison.Ordinal)) throw new NotImplementedException (); break; } break; default: writer.WriteLine ("unknown query: {0}", request.Url.Query); break; } if (request.Url.LocalPath == "/select") { if (is_match.HasValue && is_match.Value) task.Ignored = false; } else if (request.Url.LocalPath == "/deselect") { if (is_match.HasValue && is_match.Value) task.Ignored = true; } } writer.WriteLine ("OK"); } break; case "/runalltests": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; using (var writer = new StreamWriter (response.OutputStream)) { // We want to randomize the order the tests are added, so that we don't build first the test for one device, // then for another, since that would not take advantage of running tests on several devices in parallel. var rnd = new Random ((int) DateTime.Now.Ticks); foreach (var task in Tasks.OrderBy (v => rnd.Next ())) { if (task.InProgress || task.Waiting) { writer.WriteLine ($"Test '{task.TestName}' is already executing."); } else { task.Reset (); task.RunAsync (); } } writer.WriteLine ("OK"); } break; case "/runselected": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; using (var writer = new StreamWriter (response.OutputStream)) { // We want to randomize the order the tests are added, so that we don't build first the test for one device, // then for another, since that would not take advantage of running tests on several devices in parallel. var rnd = new Random ((int) DateTime.Now.Ticks); foreach (var task in allTasks.Where ((v) => !v.Ignored).OrderBy (v => rnd.Next ())) { if (task.InProgress || task.Waiting) { writer.WriteLine ($"Test '{task.TestName}' is already executing."); } else { task.Reset (); task.RunAsync (); writer.WriteLine ($"Started '{task.TestName}'."); } } } break; case "/runfailed": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; using (var writer = new StreamWriter (response.OutputStream)) { foreach (var task in allTasks.Where ((v) => v.Failed)) { if (task.InProgress || task.Waiting) { writer.WriteLine ($"Test '{task.TestName}' is already executing."); } else { task.Reset (); task.RunAsync (); writer.WriteLine ($"Started '{task.TestName}'."); } } } break; case "/runtest": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; using (var writer = new StreamWriter (response.OutputStream)) { int id; var id_inputs = arguments ["id"].Split (','); // We want to randomize the order the tests are added, so that we don't build first the test for one device, // then for another, since that would not take advantage of running tests on several devices in parallel. var rnd = new Random ((int) DateTime.Now.Ticks); id_inputs = id_inputs.OrderBy (v => rnd.Next ()).ToArray (); foreach (var id_input in id_inputs) { if (int.TryParse (id_input, out id)) { var task = Tasks.FirstOrDefault ((t) => t.ID == id); if (task == null) task = Tasks.Where ((v) => v is AggregatedRunSimulatorTask).Cast<AggregatedRunSimulatorTask> ().SelectMany ((v) => v.Tasks).FirstOrDefault ((t) => t.ID == id); if (task == null) { writer.WriteLine ($"Could not find test {id}"); } else if (task.InProgress || task.Waiting) { writer.WriteLine ($"Test '{task.TestName}' is already executing."); } else { task.Reset (); task.RunAsync (); writer.WriteLine ("OK"); } } else { writer.WriteLine ($"Could not parse {arguments ["id"]}"); } } } break; case "/reload-devices": GC.KeepAlive (Devices.LoadAsync (DeviceLoadLog, force: true)); break; case "/reload-simulators": GC.KeepAlive (Simulators.LoadAsync (SimulatorLoadLog, force: true)); break; case "/quit": using (var writer = new StreamWriter (response.OutputStream)) { writer.WriteLine ("<!DOCTYPE html>"); writer.WriteLine ("<html>"); writer.WriteLine ("<body onload='close ();'>Closing web page...</body>"); writer.WriteLine ("</html>"); } server.Stop (); break; case "/favicon.ico": var favicon = File.ReadAllBytes (Path.Combine (Harness.RootDirectory, "xharness", "favicon.ico")); response.OutputStream.Write (favicon, 0, favicon.Length); response.OutputStream.Close (); break; default: var path = Path.Combine (LogDirectory, request.Url.LocalPath.Substring (1)); if (File.Exists (path)) { var buffer = new byte [4096]; using (var fs = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { int read; response.ContentLength64 = fs.Length; response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain; while ((read = fs.Read (buffer, 0, buffer.Length)) > 0) response.OutputStream.Write (buffer, 0, read); } } else { response.StatusCode = 404; response.OutputStream.WriteByte ((byte) '?'); } break; } } catch (IOException ioe) { Console.WriteLine (ioe.Message); } catch (Exception e) { Console.WriteLine (e); } response.Close (); } tcs.SetResult (true); }) { IsBackground = true, }; thread.Start (); var url = $"http://localhost:{port}/"; Console.WriteLine ($"Launching {url} in the system's default browser."); Process.Start ("open", url); return tcs.Task; } string GetTestColor (IEnumerable<TestTask> tests) { if (!tests.Any ()) return "black"; var first = tests.First (); if (tests.All ((v) => v.ExecutionResult == first.ExecutionResult)) return GetTestColor (first); if (tests.Any ((v) => v.Crashed)) return "maroon"; else if (tests.Any ((v) => v.TimedOut)) return "purple"; else if (tests.Any ((v) => v.BuildFailure)) return "darkred"; else if (tests.Any ((v) => v.Failed)) return "red"; else if (tests.Any ((v) => v.NotStarted)) return "black"; else if (tests.Any ((v) => v.Ignored)) return "gray"; else if (tests.Any ((v) => v.Skipped)) return "orangered"; else return "black"; } string GetTestColor (TestTask test) { if (test.NotStarted) { return "black"; } else if (test.InProgress) { if (test.Building) { return "darkblue"; } else if (test.Running) { return "lightblue"; } else { return "blue"; } } else { if (test.Crashed) { return "maroon"; } else if (test.HarnessException) { return "orange"; } else if (test.TimedOut) { return "purple"; } else if (test.BuildFailure) { return "darkred"; } else if (test.Failed) { return "red"; } else if (test.Succeeded) { return "green"; } else if (test.Ignored) { return "gray"; } else if (test.Waiting) { return "darkgray"; } else if (test.Skipped) { return "orangered"; } else { return "pink"; } } } object report_lock = new object (); public void GenerateReport (bool only_if_ci = false) { if (only_if_ci && IsServerMode) return; try { lock (report_lock) { var report = Path.Combine (LogDirectory, "index.html"); using (var stream = new MemoryStream ()) { MemoryStream markdown_summary = null; StreamWriter markdown_writer = null; if (!string.IsNullOrEmpty (Harness.MarkdownSummaryPath)) { markdown_summary = new MemoryStream (); markdown_writer = new StreamWriter (markdown_summary); } GenerateReportImpl (stream, markdown_writer); if (File.Exists (report)) File.Delete (report); File.WriteAllBytes (report, stream.ToArray ()); if (!string.IsNullOrEmpty (Harness.MarkdownSummaryPath)) { markdown_writer.Flush (); if (File.Exists (Harness.MarkdownSummaryPath)) File.Delete (Harness.MarkdownSummaryPath); File.WriteAllBytes (Harness.MarkdownSummaryPath, markdown_summary.ToArray ()); markdown_writer.Close (); } } } } catch (Exception e) { this.MainLog.WriteLine ("Failed to write log: {0}", e); } } void GenerateReportImpl (Stream stream, StreamWriter markdown_summary = null) { var id_counter = 0; var allSimulatorTasks = new List<RunSimulatorTask> (); var allExecuteTasks = new List<MacExecuteTask> (); var allNUnitTasks = new List<NUnitExecuteTask> (); var allMakeTasks = new List<MakeTask> (); var allDeviceTasks = new List<RunDeviceTask> (); foreach (var task in Tasks) { var aggregated = task as AggregatedRunSimulatorTask; if (aggregated != null) { allSimulatorTasks.AddRange (aggregated.Tasks); continue; } var execute = task as MacExecuteTask; if (execute != null) { allExecuteTasks.Add (execute); continue; } var nunit = task as NUnitExecuteTask; if (nunit != null) { allNUnitTasks.Add (nunit); continue; } var make = task as MakeTask; if (make != null) { allMakeTasks.Add (make); continue; } var run_device = task as RunDeviceTask; if (run_device != null) { allDeviceTasks.Add (run_device); continue; } throw new NotImplementedException (); } var allTasks = new List<TestTask> (); if (!populating) { allTasks.AddRange (allExecuteTasks); allTasks.AddRange (allSimulatorTasks); allTasks.AddRange (allNUnitTasks); allTasks.AddRange (allMakeTasks); allTasks.AddRange (allDeviceTasks); } var failedTests = allTasks.Where ((v) => v.Failed); var skippedTests = allTasks.Where ((v) => v.Skipped); var unfinishedTests = allTasks.Where ((v) => !v.Finished); var passedTests = allTasks.Where ((v) => v.Succeeded); var runningTests = allTasks.Where ((v) => v.Running && !v.Waiting); var buildingTests = allTasks.Where ((v) => v.Building && !v.Waiting); var runningQueuedTests = allTasks.Where ((v) => v.Running && v.Waiting); var buildingQueuedTests = allTasks.Where ((v) => v.Building && v.Waiting); if (markdown_summary != null) { markdown_summary.WriteLine ("# Test results"); markdown_summary.WriteLine (); if (allTasks.Count == 0) { markdown_summary.WriteLine ($"Loading tests..."); } else if (unfinishedTests.Any ()) { var list = new List<string> (); var grouped = allTasks.GroupBy ((v) => v.ExecutionResult).OrderBy ((v) => (int) v.Key); foreach (var @group in grouped) list.Add ($"{@group.Key.ToString ()}: {@group.Count ()}"); markdown_summary.Write ($"# Test run in progress: "); markdown_summary.Write (string.Join (", ", list)); markdown_summary.WriteLine (); } else if (failedTests.Any ()) { markdown_summary.WriteLine ($"{failedTests.Count ()} tests failed, {skippedTests.Count ()} tests skipped, {passedTests.Count ()} tests passed."); } else if (skippedTests.Any ()) { markdown_summary.WriteLine ($"{skippedTests.Count ()} tests skipped, {passedTests.Count ()} tests passed."); } else if (passedTests.Any ()) { markdown_summary.WriteLine ($"# All {passedTests.Count ()} tests passed"); } else { markdown_summary.WriteLine ($"# No tests selected."); } markdown_summary.WriteLine (); if (failedTests.Any ()) { markdown_summary.WriteLine ("## Failed tests"); markdown_summary.WriteLine (); foreach (var t in failedTests) { markdown_summary.Write ($" * {t.TestName}"); if (!string.IsNullOrEmpty (t.Mode)) markdown_summary.Write ($"/{t.Mode}"); if (!string.IsNullOrEmpty (t.Variation)) markdown_summary.Write ($"/{t.Variation}"); markdown_summary.Write ($": {t.ExecutionResult}"); if (!string.IsNullOrEmpty (t.FailureMessage)) markdown_summary.Write ($" ({t.FailureMessage})"); markdown_summary.WriteLine (); } } } using (var writer = new StreamWriter (stream)) { writer.WriteLine ("<!DOCTYPE html>"); writer.WriteLine ("<html onkeypress='keyhandler(event)' lang='en'>"); if (IsServerMode && populating) writer.WriteLine ("<meta http-equiv=\"refresh\" content=\"1\">"); writer.WriteLine (@"<head> <style> .pdiv { display: table; padding-top: 10px; } .p1 { } .p2 { } .p3 { } .expander { display: table-cell; height: 100%; padding-right: 6px; text-align: center; vertical-align: middle; min-width: 10px; } .runall { font-size: 75%; margin-left: 3px; } .logs { padding-bottom: 10px; padding-top: 10px; padding-left: 30px; } #nav { display: inline-block; width: 350px; } #nav > * { display: inline; width: 300px; } #nav ul { background: #ffffff; list-style: none; position: absolute; left: -9999px; padding: 10px; z-index: 2; width: 200px; border-style: ridge; border-width: thin; } #nav li { margin-right: 10px; position: relative; } #nav a { display: block; padding: 5px; text-decoration: none; } #nav a:hover { text-decoration: underline; } #nav ul li { padding-top: 0; padding-bottom: 0; padding-left: 0; } #nav ul a { white-space: nowrap; } #nav li:hover ul { left: 0; } #nav li:hover a { text-decoration: underline; } #nav li:hover ul a { text-decoration:none; } #nav li:hover ul li a:hover { text-decoration: underline; } </style>"); writer.WriteLine ("<title>Test results</title>"); writer.WriteLine (@"<script type='text/javascript'> var ajax_log = null; function addlog (msg) { if (ajax_log == null) ajax_log = document.getElementById ('ajax-log'); if (ajax_log == null) return; var newText = msg + ""\n"" + ajax_log.innerText; if (newText.length > 1024) newText = newText.substring (0, 1024); ajax_log.innerText = newText; } function toggleLogVisibility (logName) { var button = document.getElementById ('button_' + logName); var logs = document.getElementById ('logs_' + logName); if (logs.style.display == 'none' && logs.innerText.trim () != '') { logs.style.display = 'block'; button.innerText = '-'; } else { logs.style.display = 'none'; button.innerText = '+'; } } function toggleContainerVisibility2 (containerName) { var button = document.getElementById ('button_container2_' + containerName); var div = document.getElementById ('test_container2_' + containerName); if (div.style.display == 'none') { div.style.display = 'block'; button.innerText = '-'; } else { div.style.display = 'none'; button.innerText = '+'; } } function quit () { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { window.close (); } }; xhttp.open(""GET"", ""quit"", true); xhttp.send(); } function toggleAjaxLogVisibility() { if (ajax_log == null) ajax_log = document.getElementById ('ajax-log'); var button = document.getElementById ('ajax-log-button'); if (ajax_log.style.display == 'none') { ajax_log.style.display = 'block'; button.innerText = 'Hide log'; } else { ajax_log.style.display = 'none'; button.innerText = 'Show log'; } } function toggleVisibility (css_class) { var objs = document.getElementsByClassName (css_class); for (var i = 0; i < objs.length; i++) { var obj = objs [i]; var pname = 'original-' + css_class + '-display'; if (obj.hasOwnProperty (pname)) { obj.style.display = obj [pname]; delete obj [pname]; } else { obj [pname] = obj.style.display; obj.style.display = 'none'; } } } function keyhandler(event) { switch (String.fromCharCode (event.keyCode)) { case ""q"": case ""Q"": quit (); break; } } function runalltests() { sendrequest (""runalltests""); } function runtest(id) { sendrequest (""runtest?id="" + id); } function sendrequest(url, callback) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { addlog (""Loaded url: "" + url + "" with status code: "" + this.status + ""\nResponse: "" + this.responseText); if (callback) callback (this.responseText); } }; xhttp.open(""GET"", url, true); xhttp.send(); addlog (""Loading url: "" + url); } function autorefresh() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { addlog (""Reloaded.""); var parser = new DOMParser (); var r = parser.parseFromString (this.responseText, 'text/html'); var ar_objs = document.getElementsByClassName (""autorefreshable""); for (var i = 0; i < ar_objs.length; i++) { var ar_obj = ar_objs [i]; if (!ar_obj.id || ar_obj.id.length == 0) { console.log (""Found object without id""); continue; } var new_obj = r.getElementById (ar_obj.id); if (new_obj) { if (ar_obj.innerHTML != new_obj.innerHTML) ar_obj.innerHTML = new_obj.innerHTML; if (ar_obj.style.cssText != new_obj.style.cssText) { ar_obj.style = new_obj.style; } var evt = ar_obj.getAttribute ('data-onautorefresh'); if (evt != '') { autoshowdetailsmessage (evt); } } else { console.log (""Could not find id "" + ar_obj.id + "" in updated page.""); } } setTimeout (autorefresh, 1000); } }; xhttp.open(""GET"", window.location.href, true); xhttp.send(); } function autoshowdetailsmessage (id) { var input_id = 'logs_' + id; var message_id = 'button_' + id; var input_div = document.getElementById (input_id); if (input_div == null) return; var message_div = document.getElementById (message_id); var txt = input_div.innerText.trim (); if (txt == '') { message_div.style.opacity = 0; } else { message_div.style.opacity = 1; if (input_div.style.display == 'block') { message_div.innerText = '-'; } else { message_div.innerText = '+'; } } } function oninitialload () { var autorefreshable = document.getElementsByClassName (""autorefreshable""); for (var i = 0; i < autorefreshable.length; i++) { var evt = autorefreshable [i].getAttribute (""data-onautorefresh""); if (evt != '') autoshowdetailsmessage (evt); } } function toggleAll (show) { var expandable = document.getElementsByClassName ('expander'); var counter = 0; var value = show ? '-' : '+'; for (var i = 0; i < expandable.length; i++) { var div = expandable [i]; if (div.textContent != value) div.textContent = value; counter++; } var togglable = document.getElementsByClassName ('togglable'); counter = 0; value = show ? 'block' : 'none'; for (var i = 0; i < togglable.length; i++) { var div = togglable [i]; if (div.style.display != value) { if (show && div.innerText.trim () == '') { // don't show nothing } else { div.style.display = value; } } counter++; } } "); if (IsServerMode) writer.WriteLine ("setTimeout (autorefresh, 1000);"); writer.WriteLine ("</script>"); writer.WriteLine ("</head>"); writer.WriteLine ("<body onload='oninitialload ();'>"); if (IsServerMode) { writer.WriteLine ("<div id='quit' style='position:absolute; top: 20px; right: 20px;'><a href='javascript:quit()'>Quit</a><br/><a id='ajax-log-button' href='javascript:toggleAjaxLogVisibility ();'>Show log</a></div>"); writer.WriteLine ("<div id='ajax-log' style='position:absolute; top: 200px; right: 20px; max-width: 100px; display: none;'></div>"); } writer.WriteLine ("<h1>Test results</h1>"); foreach (var log in Logs) writer.WriteLine ("<a href='{0}' type='text/plain'>{1}</a><br />", log.FullPath.Substring (LogDirectory.Length + 1), log.Description); var headerColor = "black"; if (unfinishedTests.Any ()) { ; // default } else if (failedTests.Any ()) { headerColor = "red"; } else if (skippedTests.Any ()) { headerColor = "orange"; } else if (passedTests.Any ()) { headerColor = "green"; } else { headerColor = "gray"; } writer.Write ($"<h2 style='color: {headerColor}'>"); writer.Write ($"<span id='x{id_counter++}' class='autorefreshable'>"); if (allTasks.Count == 0) { writer.Write ($"Loading tests..."); } else if (unfinishedTests.Any ()) { writer.Write ($"Test run in progress ("); var list = new List<string> (); var grouped = allTasks.GroupBy ((v) => v.ExecutionResult).OrderBy ((v) => (int) v.Key); foreach (var @group in grouped) list.Add ($"<span style='color: {GetTestColor (@group)}'>{@group.Key.ToString ()}: {@group.Count ()}</span>"); writer.Write (string.Join (", ", list)); writer.Write (")"); } else if (failedTests.Any ()) { writer.Write ($"{failedTests.Count ()} tests failed, {skippedTests.Count ()} tests skipped, {passedTests.Count ()} tests passed"); } else if (skippedTests.Any ()) { writer.Write ($"{skippedTests.Count ()} tests skipped, {passedTests.Count ()} tests passed"); } else if (passedTests.Any ()) { writer.Write ($"All {passedTests.Count ()} tests passed"); } else { writer.Write ($"No tests selected."); } writer.WriteLine ("</span>"); writer.WriteLine ("</h2>"); if (allTasks.Count > 0) { writer.WriteLine ($"<ul id='nav'>"); if (IsServerMode) { writer.WriteLine (@" <li>Select <ul> <li class=""adminitem""><a href='javascript:sendrequest (""select?all"");'>All tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-device"");'>All device tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-simulator"");'>All simulator tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-ios"");'>All iOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-tvos"");'>All tvOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-watchos"");'>All watchOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""select?all-mac"");'>All Mac tests</a></li> </ul> </li> <li>Deselect <ul> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all"");'>All tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-device"");'>All device tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-simulator"");'>All simulator tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-ios"");'>All iOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-tvos"");'>All tvOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-watchos"");'>All watchOS tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""deselect?all-mac"");'>All Mac tests</a></li> </ul> </li> <li>Run <ul> <li class=""adminitem""><a href='javascript:runalltests ();'>All tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""runselected"");'>All selected tests</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""runfailed"");'>All failed tests</a></li> </ul> </li>"); } writer.WriteLine (@" <li>Toggle visibility <ul> <li class=""adminitem""><a href='javascript:toggleAll (true);'>Expand all</a></li> <li class=""adminitem""><a href='javascript:toggleAll (false);'>Collapse all</a></li> <li class=""adminitem""><a href='javascript:toggleVisibility (""toggleable-ignored"");'>Hide/Show ignored tests</a></li> </ul> </li>"); if (IsServerMode) { writer.WriteLine (@" <li>Reload <ul> <li class=""adminitem""><a href='javascript:sendrequest (""reload-devices"");'>Devices</a></li> <li class=""adminitem""><a href='javascript:sendrequest (""reload-simulators"");'>Simulators</a></li> </ul> </li>"); } writer.WriteLine ("</ul>"); } writer.WriteLine ("<div id='test-table' style='width: 100%'>"); if (IsServerMode) { writer.WriteLine ("<div id='test-status' style='display: inline-block; margin-left: 100px;' class='autorefreshable'>"); if (failedTests.Count () == 0) { foreach (var group in failedTests.GroupBy ((v) => v.TestName)) { var enumerableGroup = group as IEnumerable<TestTask>; if (enumerableGroup != null) { writer.WriteLine ("<a href='#test_{2}'>{0}</a> ({1})<br />", group.Key, string.Join (", ", enumerableGroup.Select ((v) => string.Format ("<span style='color: {0}'>{1}</span>", GetTestColor (v), string.IsNullOrEmpty (v.Mode) ? v.ExecutionResult.ToString () : v.Mode)).ToArray ()), group.Key.Replace (' ', '-')); continue; } throw new NotImplementedException (); } } if (buildingTests.Any ()) { writer.WriteLine ($"<h3>{buildingTests.Count ()} building tests:</h3>"); foreach (var test in buildingTests) { var runTask = test as RunTestTask; var buildDuration = string.Empty; if (runTask != null) buildDuration = runTask.BuildTask.Duration.ToString (); writer.WriteLine ($"<a href='#test_{test.TestName}'>{test.TestName} ({test.Mode})</a> {buildDuration}<br />"); } } if (runningTests.Any ()) { writer.WriteLine ($"<h3>{runningTests.Count ()} running tests:</h3>"); foreach (var test in runningTests) { writer.WriteLine ($"<a href='#test_{test.TestName}'>{test.TestName} ({test.Mode})</a> {test.Duration.ToString ()} {test.ProgressMessage}<br />"); } } if (buildingQueuedTests.Any ()) { writer.WriteLine ($"<h3>{buildingQueuedTests.Count ()} tests in build queue:</h3>"); foreach (var test in buildingQueuedTests) { writer.WriteLine ($"<a href='#test_{test.TestName}'>{test.TestName} ({test.Mode})</a><br />"); } } if (runningQueuedTests.Any ()) { writer.WriteLine ($"<h3>{runningQueuedTests.Count ()} tests in run queue:</h3>"); foreach (var test in runningQueuedTests) { writer.WriteLine ($"<a href='#test_{test.TestName}'>{test.TestName} ({test.Mode})</a><br />"); } } var resources = device_resources.Values.Concat (new Resource [] { DesktopResource }); if (resources.Any ()) { writer.WriteLine ($"<h3>Devices:</h3>"); foreach (var dr in resources.OrderBy ((v) => v.Description, StringComparer.OrdinalIgnoreCase)) { writer.WriteLine ($"{dr.Description} - {dr.Users}/{dr.MaxConcurrentUsers} users - {dr.QueuedUsers} in queue<br />"); } } } writer.WriteLine ("</div>"); writer.WriteLine ("<div id='test-list' style='float:left'>"); var orderedTasks = allTasks.GroupBy ((TestTask v) => v.TestName); if (IsServerMode) { // In server mode don't take into account anything that can change during a test run // when ordering, since it's confusing to have the tests reorder by themselves while // you're looking at the web page. orderedTasks = orderedTasks.OrderBy ((v) => v.Key, StringComparer.OrdinalIgnoreCase); } else { // Put failed tests at the top and ignored tests at the end. // Then order alphabetically. orderedTasks = orderedTasks.OrderBy ((v) => { if (v.Any ((t) => t.Failed)) return -1; if (v.All ((t) => t.Ignored)) return 1; return 0; }). ThenBy ((v) => v.Key, StringComparer.OrdinalIgnoreCase); } foreach (var group in orderedTasks) { var singleTask = group.Count () == 1; var groupId = group.Key.Replace (' ', '-'); // Test header for multiple tests if (!singleTask) { var autoExpand = !IsServerMode && group.Any ((v) => v.Failed); var ignoredClass = group.All ((v) => v.Ignored) ? "toggleable-ignored" : string.Empty; var defaultExpander = autoExpand ? "-" : "+"; var defaultDisplay = autoExpand ? "block" : "none"; writer.Write ($"<div class='pdiv {ignoredClass}'>"); writer.Write ($"<span id='button_container2_{groupId}' class='expander' onclick='javascript: toggleContainerVisibility2 (\"{groupId}\");'>{defaultExpander}</span>"); writer.Write ($"<span id='x{id_counter++}' class='p1 autorefreshable' onclick='javascript: toggleContainerVisibility2 (\"{groupId}\");'>{group.Key}{RenderTextStates (group)}</span>"); if (IsServerMode) writer.Write ($" <span><a class='runall' href='javascript: runtest (\"{string.Join (",", group.Select ((v) => v.ID.ToString ()))}\");'>Run all</a></span>"); writer.WriteLine ("</div>"); writer.WriteLine ($"<div id='test_container2_{groupId}' class='togglable' style='display: {defaultDisplay}; margin-left: 20px;'>"); } // Test data var groupedByMode = group.GroupBy ((v) => v.Mode); foreach (var modeGroup in groupedByMode) { var multipleModes = modeGroup.Count () > 1; if (multipleModes) { var modeGroupId = id_counter++.ToString (); var autoExpand = !IsServerMode && modeGroup.Any ((v) => v.Failed); var ignoredClass = modeGroup.All ((v) => v.Ignored) ? "toggleable-ignored" : string.Empty; var defaultExpander = autoExpand ? "-" : "+"; var defaultDisplay = autoExpand ? "block" : "none"; writer.Write ($"<div class='pdiv {ignoredClass}'>"); writer.Write ($"<span id='button_container2_{modeGroupId}' class='expander' onclick='javascript: toggleContainerVisibility2 (\"{modeGroupId}\");'>{defaultExpander}</span>"); writer.Write ($"<span id='x{id_counter++}' class='p2 autorefreshable' onclick='javascript: toggleContainerVisibility2 (\"{modeGroupId}\");'>{modeGroup.Key}{RenderTextStates (modeGroup)}</span>"); if (IsServerMode) writer.Write ($" <span><a class='runall' href='javascript: runtest (\"{string.Join (",", modeGroup.Select ((v) => v.ID.ToString ()))}\");'>Run all</a></span>"); writer.WriteLine ("</div>"); writer.WriteLine ($"<div id='test_container2_{modeGroupId}' class='togglable' style='display: {defaultDisplay}; margin-left: 20px;'>"); } foreach (var test in modeGroup.OrderBy ((v) => v.Variation, StringComparer.OrdinalIgnoreCase)) { var runTest = test as RunTestTask; string state; state = test.ExecutionResult.ToString (); var log_id = id_counter++; var logs = test.AggregatedLogs.ToList (); string title; if (multipleModes) { title = test.Variation ?? "Default"; } else if (singleTask) { title = test.TestName; } else { title = test.Mode; } var autoExpand = !IsServerMode && test.Failed; var ignoredClass = test.Ignored ? "toggleable-ignored" : string.Empty; var defaultExpander = autoExpand ? "&nbsp;" : "+"; var defaultDisplay = autoExpand ? "block" : "none"; writer.Write ($"<div class='pdiv {ignoredClass}'>"); writer.Write ($"<span id='button_{log_id}' class='expander' onclick='javascript: toggleLogVisibility (\"{log_id}\");'>{defaultExpander}</span>"); writer.Write ($"<span id='x{id_counter++}' class='p3 autorefreshable' onclick='javascript: toggleLogVisibility (\"{log_id}\");'>{title} (<span style='color: {GetTestColor (test)}'>{state}</span>) </span>"); if (IsServerMode && !test.InProgress && !test.Waiting) writer.Write ($" <span><a class='runall' href='javascript:runtest ({test.ID})'>Run</a></span> "); writer.WriteLine ("</div>"); writer.WriteLine ($"<div id='logs_{log_id}' class='autorefreshable logs togglable' data-onautorefresh='{log_id}' style='display: {defaultDisplay};'>"); if (!string.IsNullOrEmpty (test.FailureMessage)) { var msg = System.Web.HttpUtility.HtmlEncode (test.FailureMessage).Replace ("\n", "<br />"); if (test.FailureMessage.Contains ('\n')) { writer.WriteLine ($"Failure:<br /> <div style='margin-left: 20px;'>{msg}</div>"); } else { writer.WriteLine ($"Failure: {msg} <br />"); } } var progressMessage = test.ProgressMessage; if (!string.IsNullOrEmpty (progressMessage)) writer.WriteLine (progressMessage + "<br />"); if (runTest != null) { if (runTest.BuildTask.Duration.Ticks > 0) { writer.WriteLine ($"Project file: {runTest.BuildTask.ProjectFile} <br />"); writer.WriteLine ($"Platform: {runTest.BuildTask.ProjectPlatform} Configuration: {runTest.BuildTask.ProjectConfiguration} <br />"); IEnumerable<IDevice> candidates = (runTest as RunDeviceTask)?.Candidates; if (candidates == null) candidates = (runTest as RunSimulatorTask)?.Candidates; if (candidates != null) writer.WriteLine ($"Candidate devices: {string.Join (", ", candidates.Select ((v) => v.Name))} <br />"); writer.WriteLine ($"Build duration: {runTest.BuildTask.Duration} <br />"); } if (test.Duration.Ticks > 0) writer.WriteLine ($"Run duration: {test.Duration} <br />"); var runDeviceTest = runTest as RunDeviceTask; if (runDeviceTest?.Device != null) { if (runDeviceTest.CompanionDevice != null) { writer.WriteLine ($"Device: {runDeviceTest.Device.Name} ({runDeviceTest.CompanionDevice.Name}) <br />"); } else { writer.WriteLine ($"Device: {runDeviceTest.Device.Name} <br />"); } } } else { if (test.Duration.Ticks > 0) writer.WriteLine ($"Duration: {test.Duration} <br />"); } if (logs.Count () > 0) { foreach (var log in logs) { log.Flush (); string log_type = System.Web.MimeMapping.GetMimeMapping (log.FullPath); string log_target; switch (log_type) { case "text/xml": log_target = "_top"; break; default: log_target = "_self"; break; } writer.WriteLine ("<a href='{0}' type='{2}' target='{3}'>{1}</a><br />", LinkEncode (log.FullPath.Substring (LogDirectory.Length + 1)), log.Description, log_type, log_target); if (log.Description == "Test log" || log.Description == "Execution log") { string summary; List<string> fails; try { using (var reader = log.GetReader ()) { Tuple<long, object> data; if (!log_data.TryGetValue (log, out data) || data.Item1 != reader.BaseStream.Length) { summary = string.Empty; fails = new List<string> (); while (!reader.EndOfStream) { string line = reader.ReadLine ()?.Trim (); if (line == null) continue; if (line.StartsWith ("Tests run:", StringComparison.Ordinal)) { summary = line; } else if (line.StartsWith ("[FAIL]", StringComparison.Ordinal)) { fails.Add (line); } } } else { var data_tuple = (Tuple<string, List<string>>) data.Item2; summary = data_tuple.Item1; fails = data_tuple.Item2; } } if (fails.Count > 0) { writer.WriteLine ("<div style='padding-left: 15px;'>"); foreach (var fail in fails) writer.WriteLine ("{0} <br />", System.Web.HttpUtility.HtmlEncode (fail)); writer.WriteLine ("</div>"); } if (!string.IsNullOrEmpty (summary)) writer.WriteLine ("<span style='padding-left: 15px;'>{0}</span><br />", summary); } catch (Exception ex) { writer.WriteLine ("<span style='padding-left: 15px;'>Could not parse log file: {0}</span><br />", System.Web.HttpUtility.HtmlEncode (ex.Message)); } } else if (log.Description == "Build log") { HashSet<string> errors; try { using (var reader = log.GetReader ()) { Tuple<long, object> data; if (!log_data.TryGetValue (log, out data) || data.Item1 != reader.BaseStream.Length) { errors = new HashSet<string> (); while (!reader.EndOfStream) { string line = reader.ReadLine ()?.Trim (); if (line == null) continue; // Sometimes we put error messages in pull request descriptions // Then Jenkins create environment variables containing the pull request descriptions (and other pull request data) // So exclude any lines matching 'ghprbPull', to avoid reporting those environment variables as build errors. if (line.Contains (": error") && !line.Contains ("ghprbPull")) errors.Add (line); } log_data [log] = new Tuple<long, object> (reader.BaseStream.Length, errors); } else { errors = (HashSet<string>) data.Item2; } } if (errors.Count > 0) { writer.WriteLine ("<div style='padding-left: 15px;'>"); foreach (var error in errors) writer.WriteLine ("{0} <br />", System.Web.HttpUtility.HtmlEncode (error)); writer.WriteLine ("</div>"); } } catch (Exception ex) { writer.WriteLine ("<span style='padding-left: 15px;'>Could not parse log file: {0}</span><br />", System.Web.HttpUtility.HtmlEncode (ex.Message)); } } else if (log.Description == "NUnit results" || log.Description == "XML log") { try { if (File.Exists (log.FullPath) && new FileInfo (log.FullPath).Length > 0) { var doc = new System.Xml.XmlDocument (); doc.LoadWithoutNetworkAccess (log.FullPath); var failures = doc.SelectNodes ("//test-case[@result='Error' or @result='Failure']").Cast<System.Xml.XmlNode> ().ToArray (); if (failures.Length > 0) { writer.WriteLine ("<div style='padding-left: 15px;'>"); writer.WriteLine ("<ul>"); foreach (var failure in failures) { writer.WriteLine ("<li>"); var test_name = failure.Attributes ["name"]?.Value; var message = failure.SelectSingleNode ("failure/message")?.InnerText; writer.Write (System.Web.HttpUtility.HtmlEncode (test_name)); if (!string.IsNullOrEmpty (message)) { writer.Write (": "); writer.Write (HtmlFormat (message)); } writer.WriteLine ("<br />"); writer.WriteLine ("</li>"); } writer.WriteLine ("</ul>"); writer.WriteLine ("</div>"); } } } catch (Exception ex) { writer.WriteLine ($"<span style='padding-left: 15px;'>Could not parse {log.Description}: {HtmlFormat (ex.Message)}</span><br />"); } } } } writer.WriteLine ("</div>"); } if (multipleModes) writer.WriteLine ("</div>"); } if (!singleTask) writer.WriteLine ("</div>"); } writer.WriteLine ("</div>"); writer.WriteLine ("</div>"); writer.WriteLine ("</body>"); writer.WriteLine ("</html>"); } } Dictionary<Log, Tuple<long, object>> log_data = new Dictionary<Log, Tuple<long, object>> (); static string HtmlFormat (string value) { var rv = System.Web.HttpUtility.HtmlEncode (value); return rv.Replace ("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").Replace ("\n", "<br/>\n"); } static string LinkEncode (string path) { return System.Web.HttpUtility.UrlEncode (path).Replace ("%2f", "/").Replace ("+", "%20"); } string RenderTextStates (IEnumerable<TestTask> tests) { // Create a collection of all non-ignored tests in the group (unless all tests were ignored). var allIgnored = tests.All ((v) => v.ExecutionResult == TestExecutingResult.Ignored); IEnumerable<TestTask> relevantGroup; if (allIgnored) { relevantGroup = tests; } else { relevantGroup = tests.Where ((v) => v.ExecutionResult != TestExecutingResult.NotStarted); } if (!relevantGroup.Any ()) return string.Empty; var results = relevantGroup .GroupBy ((v) => v.ExecutionResult) .Select ((v) => v.First ()) // GroupBy + Select = Distinct (lambda) .OrderBy ((v) => v.ID) .Select ((v) => $"<span style='color: {GetTestColor (v)}'>{v.ExecutionResult.ToString ()}</span>") .ToArray (); return " (" + string.Join ("; ", results) + ")"; } } abstract class TestTask { static int counter; public readonly int ID = counter++; bool? supports_parallel_execution; public Jenkins Jenkins; public Harness Harness { get { return Jenkins.Harness; } } public TestProject TestProject; public string ProjectFile { get { return TestProject?.Path; } } public string ProjectConfiguration; public string ProjectPlatform; public Dictionary<string, string> Environment = new Dictionary<string, string> (); public Task InitialTask; // a task that's executed before this task's ExecuteAsync method. public Task CompletedTask; // a task that's executed after this task's ExecuteAsync method. public void CloneTestProject (TestProject project) { // Don't build in the original project directory // We can build multiple projects in parallel, and if some of those // projects have the same project dependencies, then we may end up // building the same (dependent) project simultaneously (and they can // stomp on eachother). // So we clone the project file to a separate directory and build there instead. // This is done asynchronously to speed to the initial test load. TestProject = project.Clone (); InitialTask = TestProject.CreateCopyAsync (); } protected Stopwatch duration = new Stopwatch (); public TimeSpan Duration { get { return duration.Elapsed; } } TestExecutingResult execution_result; public virtual TestExecutingResult ExecutionResult { get { return execution_result; } set { execution_result = value; } } string failure_message; public string FailureMessage { get { return failure_message; } protected set { failure_message = value; MainLog.WriteLine (failure_message); } } public virtual string ProgressMessage { get; } public bool NotStarted { get { return (ExecutionResult & TestExecutingResult.StateMask) == TestExecutingResult.NotStarted; } } public bool InProgress { get { return (ExecutionResult & TestExecutingResult.InProgress) == TestExecutingResult.InProgress; } } public bool Waiting { get { return (ExecutionResult & TestExecutingResult.Waiting) == TestExecutingResult.Waiting; } } public bool Finished { get { return (ExecutionResult & TestExecutingResult.Finished) == TestExecutingResult.Finished; } } public bool Building { get { return (ExecutionResult & TestExecutingResult.Building) == TestExecutingResult.Building; } } public bool Built { get { return (ExecutionResult & TestExecutingResult.Built) == TestExecutingResult.Built; } } public bool Running { get { return (ExecutionResult & TestExecutingResult.Running) == TestExecutingResult.Running; } } public bool Succeeded { get { return (ExecutionResult & TestExecutingResult.Succeeded) == TestExecutingResult.Succeeded; } } public bool Failed { get { return (ExecutionResult & TestExecutingResult.Failed) == TestExecutingResult.Failed; } } public bool Ignored { get { return ExecutionResult == TestExecutingResult.Ignored; } set { if (ExecutionResult != TestExecutingResult.NotStarted && ExecutionResult != TestExecutingResult.Ignored) throw new InvalidOperationException (); ExecutionResult = value ? TestExecutingResult.Ignored : TestExecutingResult.NotStarted; } } public bool Skipped { get { return ExecutionResult == TestExecutingResult.Skipped; } } public bool Crashed { get { return (ExecutionResult & TestExecutingResult.Crashed) == TestExecutingResult.Crashed; } } public bool TimedOut { get { return (ExecutionResult & TestExecutingResult.TimedOut) == TestExecutingResult.TimedOut; } } public bool BuildFailure { get { return (ExecutionResult & TestExecutingResult.BuildFailure) == TestExecutingResult.BuildFailure; } } public bool HarnessException { get { return (ExecutionResult & TestExecutingResult.HarnessException) == TestExecutingResult.HarnessException; } } public virtual string Mode { get; set; } public virtual string Variation { get; set; } protected static string Timestamp { get { return Harness.Timestamp; } } public bool HasCustomTestName { get { return test_name != null; } } string test_name; public virtual string TestName { get { if (test_name != null) return test_name; var rv = Path.GetFileNameWithoutExtension (ProjectFile); if (rv == null) return $"unknown test name ({GetType ().Name}"; switch (Platform) { case TestPlatform.Mac: case TestPlatform.Mac_Classic: return rv; case TestPlatform.Mac_Unified: return rv.Substring (0, rv.Length - "-unified".Length); case TestPlatform.Mac_Unified32: return rv.Substring (0, rv.Length - "-unified-32".Length); case TestPlatform.Mac_UnifiedXM45: return rv.Substring (0, rv.Length - "-unifiedXM45".Length); case TestPlatform.Mac_UnifiedXM45_32: return rv.Substring (0, rv.Length - "-unifiedXM45-32".Length); default: if (rv.EndsWith ("-watchos", StringComparison.Ordinal)) { return rv.Substring (0, rv.Length - 8); } else if (rv.EndsWith ("-tvos", StringComparison.Ordinal)) { return rv.Substring (0, rv.Length - 5); } else if (rv.EndsWith ("-unified", StringComparison.Ordinal)) { return rv.Substring (0, rv.Length - 8); } else if (rv.EndsWith ("-today", StringComparison.Ordinal)) { return rv.Substring (0, rv.Length - 6); } else { return rv; } } } set { test_name = value; } } public TestPlatform Platform { get; set; } public List<Resource> Resources = new List<Resource> (); Log test_log; public Log MainLog { get { if (test_log == null) test_log = Logs.Create ($"main-{Timestamp}.log", "Main log"); return test_log; } } public virtual IEnumerable<Log> AggregatedLogs { get { return Logs; } } public string LogDirectory { get { var rv = Path.Combine (Jenkins.LogDirectory, $"{TestName}_{ID}"); Directory.CreateDirectory (rv); return rv; } } Logs logs; public Logs Logs { get { return logs ?? (logs = new Logs (LogDirectory)); } } Task execute_task; async Task RunInternalAsync () { if (Finished) return; ExecutionResult = (ExecutionResult & ~TestExecutingResult.StateMask) | TestExecutingResult.InProgress; try { if (InitialTask != null) await InitialTask; duration.Start (); execute_task = ExecuteAsync (); await execute_task; if (CompletedTask != null) { if (CompletedTask.Status == TaskStatus.Created) CompletedTask.Start (); await CompletedTask; } ExecutionResult = (ExecutionResult & ~TestExecutingResult.StateMask) | TestExecutingResult.Finished; if ((ExecutionResult & ~TestExecutingResult.StateMask) == 0) throw new Exception ("Result not set!"); } catch (Exception e) { using (var log = Logs.Create ($"execution-failure-{Timestamp}.log", "Execution failure")) { ExecutionResult = TestExecutingResult.HarnessException; FailureMessage = $"Harness exception for '{TestName}': {e}"; log.WriteLine (FailureMessage); } } finally { logs?.Dispose (); duration.Stop (); } Jenkins.GenerateReport (true); } public virtual void Reset () { test_log = null; failure_message = null; logs = null; duration.Reset (); execution_result = TestExecutingResult.NotStarted; execute_task = null; } public Task RunAsync () { if (execute_task == null) execute_task = RunInternalAsync (); return execute_task; } protected abstract Task ExecuteAsync (); public override string ToString () { return ExecutionResult.ToString (); } protected void SetEnvironmentVariables (Process process) { switch (Platform) { case TestPlatform.iOS: case TestPlatform.iOS_Unified: case TestPlatform.iOS_Unified32: case TestPlatform.iOS_Unified64: case TestPlatform.iOS_TodayExtension64: case TestPlatform.tvOS: case TestPlatform.watchOS: process.StartInfo.EnvironmentVariables ["MD_APPLE_SDK_ROOT"] = Harness.XcodeRoot; process.StartInfo.EnvironmentVariables ["MD_MTOUCH_SDK_ROOT"] = Path.Combine (Harness.IOS_DESTDIR, "Library", "Frameworks", "Xamarin.iOS.framework", "Versions", "Current"); process.StartInfo.EnvironmentVariables ["XBUILD_FRAMEWORK_FOLDERS_PATH"] = Path.Combine (Harness.IOS_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild-frameworks"); process.StartInfo.EnvironmentVariables ["MSBuildExtensionsPath"] = Path.Combine (Harness.IOS_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild"); break; case TestPlatform.Mac: case TestPlatform.Mac_Classic: case TestPlatform.Mac_Unified: case TestPlatform.Mac_Unified32: case TestPlatform.Mac_UnifiedXM45: case TestPlatform.Mac_UnifiedXM45_32: process.StartInfo.EnvironmentVariables ["MD_APPLE_SDK_ROOT"] = Harness.XcodeRoot; process.StartInfo.EnvironmentVariables ["XBUILD_FRAMEWORK_FOLDERS_PATH"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild-frameworks"); process.StartInfo.EnvironmentVariables ["MSBuildExtensionsPath"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild"); process.StartInfo.EnvironmentVariables ["XamarinMacFrameworkRoot"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current"); process.StartInfo.EnvironmentVariables ["XAMMAC_FRAMEWORK_PATH"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current"); break; case TestPlatform.All: // Don't set: // MSBuildExtensionsPath // XBUILD_FRAMEWORK_FOLDERS_PATH // because these values used by both XM and XI and we can't set it to two different values at the same time. // Any test that depends on these values should not be using 'TestPlatform.All' process.StartInfo.EnvironmentVariables ["MD_APPLE_SDK_ROOT"] = Harness.XcodeRoot; process.StartInfo.EnvironmentVariables ["MD_MTOUCH_SDK_ROOT"] = Path.Combine (Harness.IOS_DESTDIR, "Library", "Frameworks", "Xamarin.iOS.framework", "Versions", "Current"); process.StartInfo.EnvironmentVariables ["XamarinMacFrameworkRoot"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current"); process.StartInfo.EnvironmentVariables ["XAMMAC_FRAMEWORK_PATH"] = Path.Combine (Harness.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current"); break; default: throw new NotImplementedException (); } foreach (var kvp in Environment) process.StartInfo.EnvironmentVariables [kvp.Key] = kvp.Value; } protected void AddWrenchLogFiles (StreamReader stream) { string line; while ((line = stream.ReadLine ()) != null) { if (!line.StartsWith ("@MonkeyWrench: ", StringComparison.Ordinal)) continue; var cmd = line.Substring ("@MonkeyWrench:".Length).TrimStart (); var colon = cmd.IndexOf (':'); if (colon <= 0) continue; var name = cmd.Substring (0, colon); switch (name) { case "AddFile": var src = cmd.Substring (name.Length + 1).Trim (); Logs.AddFile (src); break; default: Harness.HarnessLog.WriteLine ("Unknown @MonkeyWrench command in {0}: {1}", TestName, name); break; } } } protected void LogProcessExecution (Log log, Process process, string text, params object[] args) { Jenkins.MainLog.WriteLine (text, args); log.WriteLine (text, args); foreach (string key in process.StartInfo.EnvironmentVariables.Keys) log.WriteLine ("{0}={1}", key, process.StartInfo.EnvironmentVariables [key]); log.WriteLine ("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); } public string GuessFailureReason (Log log) { try { using (var reader = log.GetReader ()) { string line; var error_msg = new System.Text.RegularExpressions.Regex ("([A-Z][A-Z][0-9][0-9][0-9][0-9]:.*)"); while ((line = reader.ReadLine ()) != null) { var match = error_msg.Match (line); if (match.Success) return match.Groups [1].Captures [0].Value; } } } catch (Exception e) { Harness.Log ("Failed to guess failure reason: {0}", e.Message); } return null; } // This method will set (and clear) the Waiting flag correctly while waiting on a resource // It will also pause the duration. public async Task<IAcquiredResource> NotifyBlockingWaitAsync (Task<IAcquiredResource> task) { var rv = new BlockingWait (); // Stop the timer while we're waiting for a resource duration.Stop (); ExecutionResult = ExecutionResult | TestExecutingResult.Waiting; rv.Wrapped = await task; ExecutionResult = ExecutionResult & ~TestExecutingResult.Waiting; duration.Start (); rv.OnDispose = duration.Stop; return rv; } public virtual bool SupportsParallelExecution { get { return supports_parallel_execution ?? true; } set { supports_parallel_execution = value; } } protected Task<IAcquiredResource> NotifyAndAcquireDesktopResourceAsync () { return NotifyBlockingWaitAsync ((SupportsParallelExecution ? Jenkins.DesktopResource.AcquireConcurrentAsync () : Jenkins.DesktopResource.AcquireExclusiveAsync ())); } class BlockingWait : IAcquiredResource, IDisposable { public IAcquiredResource Wrapped; public Action OnDispose; public Resource Resource { get { return Wrapped.Resource; } } public void Dispose () { OnDispose (); Wrapped.Dispose (); } } } abstract class BuildToolTask : TestTask { public bool SpecifyPlatform = true; public bool SpecifyConfiguration = true; public override string Mode { get { return Platform.ToString (); } set { throw new NotSupportedException (); } } public virtual Task CleanAsync () { Console.WriteLine ("Clean is not implemented for {0}", GetType ().Name); return Task.CompletedTask; } } abstract class BuildProjectTask : BuildToolTask { public string SolutionPath; public bool RestoreNugets { get { return !string.IsNullOrEmpty (SolutionPath); } } public override bool SupportsParallelExecution { get { return Platform.ToString ().StartsWith ("Mac", StringComparison.Ordinal); } } // This method must be called with the desktop resource acquired // (which is why it takes an IAcquiredResources as a parameter without using it in the function itself). protected async Task RestoreNugetsAsync (Log log, IAcquiredResource resource) { if (!RestoreNugets) return; if (!File.Exists (SolutionPath)) throw new FileNotFoundException ("Could not find the solution whose nugets to restore.", SolutionPath); using (var nuget = new Process ()) { nuget.StartInfo.FileName = "/Library/Frameworks/Mono.framework/Versions/Current/Commands/nuget"; var args = new StringBuilder (); args.Append ("restore "); args.Append (StringUtils.Quote (SolutionPath)); nuget.StartInfo.Arguments = args.ToString (); SetEnvironmentVariables (nuget); LogProcessExecution (log, nuget, "Restoring nugets for {0} ({1})", TestName, Mode); var timeout = TimeSpan.FromMinutes (15); var result = await nuget.RunAsync (log, true, timeout); if (result.TimedOut) { ExecutionResult = TestExecutingResult.TimedOut; log.WriteLine ("Nuget restore timed out after {0} seconds.", timeout.TotalSeconds); return; } else if (!result.Succeeded) { ExecutionResult = TestExecutingResult.Failed; return; } } } } class MdtoolTask : BuildProjectTask { protected override async Task ExecuteAsync () { ExecutionResult = TestExecutingResult.Building; using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { var log = Logs.Create ($"build-{Platform}-{Timestamp}.txt", "Build log"); await RestoreNugetsAsync (log, resource); using (var xbuild = new Process ()) { xbuild.StartInfo.FileName = "/Applications/Visual Studio.app/Contents/MacOS/vstool"; var args = new StringBuilder (); args.Append ("build "); var sln = Path.ChangeExtension (ProjectFile, "sln"); args.Append (StringUtils.Quote (File.Exists (sln) ? sln : ProjectFile)); xbuild.StartInfo.Arguments = args.ToString (); SetEnvironmentVariables (xbuild); LogProcessExecution (log, xbuild, "Building {0} ({1})", TestName, Mode); if (!Harness.DryRun) { var timeout = TimeSpan.FromMinutes (5); var result = await xbuild.RunAsync (log, true, timeout); if (result.TimedOut) { ExecutionResult = TestExecutingResult.TimedOut; log.WriteLine ("Build timed out after {0} seconds.", timeout.TotalSeconds); } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; } } Jenkins.MainLog.WriteLine ("Built {0} ({1})", TestName, Mode); } log.Dispose (); } } } class MakeTask : BuildToolTask { public string Target; public string WorkingDirectory; public TimeSpan Timeout = TimeSpan.FromMinutes (5); protected override async Task ExecuteAsync () { using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { using (var make = new Process ()) { make.StartInfo.FileName = "make"; make.StartInfo.WorkingDirectory = WorkingDirectory; make.StartInfo.Arguments = Target; SetEnvironmentVariables (make); var log = Logs.Create ($"make-{Platform}-{Timestamp}.txt", "Build log"); log.Timestamp = true; LogProcessExecution (log, make, "Making {0} in {1}", Target, WorkingDirectory); if (!Harness.DryRun) { var timeout = Timeout; var result = await make.RunAsync (log, true, timeout); if (result.TimedOut) { ExecutionResult = TestExecutingResult.TimedOut; log.WriteLine ("Make timed out after {0} seconds.", timeout.TotalSeconds); } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; } } using (var reader = log.GetReader ()) AddWrenchLogFiles (reader); Jenkins.MainLog.WriteLine ("Made {0} ({1})", TestName, Mode); } } } } class XBuildTask : BuildProjectTask { public bool UseMSBuild; protected override async Task ExecuteAsync () { using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { var log = Logs.Create ($"build-{Platform}-{Timestamp}.txt", "Build log"); await RestoreNugetsAsync (log, resource); using (var xbuild = new Process ()) { xbuild.StartInfo.FileName = UseMSBuild ? "msbuild" : "xbuild"; var args = new StringBuilder (); args.Append ("/verbosity:diagnostic "); if (SpecifyPlatform) args.Append ($"/p:Platform={ProjectPlatform} "); if (SpecifyConfiguration) args.Append ($"/p:Configuration={ProjectConfiguration} "); args.Append (StringUtils.Quote (ProjectFile)); xbuild.StartInfo.Arguments = args.ToString (); SetEnvironmentVariables (xbuild); if (UseMSBuild) xbuild.StartInfo.EnvironmentVariables ["MSBuildExtensionsPath"] = null; LogProcessExecution (log, xbuild, "Building {0} ({1})", TestName, Mode); if (!Harness.DryRun) { var timeout = TimeSpan.FromMinutes (15); var result = await xbuild.RunAsync (log, true, timeout); if (result.TimedOut) { ExecutionResult = TestExecutingResult.TimedOut; log.WriteLine ("Build timed out after {0} seconds.", timeout.TotalSeconds); } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; } } Jenkins.MainLog.WriteLine ("Built {0} ({1})", TestName, Mode); } log.Dispose (); } } async Task CleanProjectAsync (Log log, string project_file, string project_platform, string project_configuration) { // Don't require the desktop resource here, this shouldn't be that resource sensitive using (var xbuild = new Process ()) { xbuild.StartInfo.FileName = "xbuild"; var args = new StringBuilder (); args.Append ("/verbosity:diagnostic "); if (project_platform != null) args.Append ($"/p:Platform={project_platform} "); if (project_configuration != null) args.Append ($"/p:Configuration={project_configuration} "); args.Append (StringUtils.Quote (project_file)).Append (" "); args.Append ("/t:Clean "); xbuild.StartInfo.Arguments = args.ToString (); SetEnvironmentVariables (xbuild); LogProcessExecution (log, xbuild, "Cleaning {0} ({1}) - {2}", TestName, Mode, project_file); var timeout = TimeSpan.FromMinutes (1); await xbuild.RunAsync (log, true, timeout); log.WriteLine ("Clean timed out after {0} seconds.", timeout.TotalSeconds); Jenkins.MainLog.WriteLine ("Cleaned {0} ({1})", TestName, Mode); } } public async override Task CleanAsync () { var log = Logs.Create ($"clean-{Platform}-{Timestamp}.txt", "Clean log"); await CleanProjectAsync (log, ProjectFile, SpecifyPlatform ? ProjectPlatform : null, SpecifyConfiguration ? ProjectConfiguration : null); // Iterate over all the project references as well. var doc = new System.Xml.XmlDocument (); doc.LoadWithoutNetworkAccess (ProjectFile); foreach (var pr in doc.GetProjectReferences ()) { var path = pr.Replace ('\\', '/'); await CleanProjectAsync (log, path, SpecifyPlatform ? ProjectPlatform : null, SpecifyConfiguration ? ProjectConfiguration : null); } } } class NUnitExecuteTask : RunTestTask { public string TestLibrary; public string TestExecutable; public string WorkingDirectory; public bool ProduceHtmlReport = true; public TimeSpan Timeout = TimeSpan.FromMinutes (10); public NUnitExecuteTask (BuildToolTask build_task) : base (build_task) { } public bool IsNUnit3 { get { return Path.GetFileName (TestExecutable) == "nunit3-console.exe"; } } public override IEnumerable<Log> AggregatedLogs { get { return base.AggregatedLogs.Union (BuildTask.Logs); } } public override string Mode { get { return base.Mode ?? "NUnit"; } set { base.Mode = value; } } protected override async Task RunTestAsync () { using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { var xmlLog = Logs.CreateFile ($"log-{Timestamp}.xml", "XML log"); var log = Logs.Create ($"execute-{Timestamp}.txt", "Execution log"); log.Timestamp = true; using (var proc = new Process ()) { proc.StartInfo.WorkingDirectory = WorkingDirectory; proc.StartInfo.FileName = "/Library/Frameworks/Mono.framework/Commands/mono"; var args = new StringBuilder (); args.Append (StringUtils.Quote (Path.GetFullPath (TestExecutable))).Append (' '); args.Append (StringUtils.Quote (Path.GetFullPath (TestLibrary))).Append (' '); if (IsNUnit3) { args.Append ("-result=").Append (StringUtils.Quote (xmlLog)).Append (";format=nunit2 "); args.Append ("--labels=All "); } else { args.Append ("-xml=" + StringUtils.Quote (xmlLog)).Append (' '); args.Append ("-labels "); } proc.StartInfo.Arguments = args.ToString (); SetEnvironmentVariables (proc); Jenkins.MainLog.WriteLine ("Executing {0} ({1})", TestName, Mode); if (!Harness.DryRun) { ExecutionResult = TestExecutingResult.Running; var result = await proc.RunAsync (log, true, Timeout); if (result.TimedOut) { FailureMessage = $"Execution timed out after {Timeout.Minutes} minutes."; log.WriteLine (FailureMessage); ExecutionResult = TestExecutingResult.TimedOut; } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; FailureMessage = $"Execution failed with exit code {result.ExitCode}"; } } Jenkins.MainLog.WriteLine ("Executed {0} ({1})", TestName, Mode); } if (ProduceHtmlReport) { try { var output = Logs.Create ($"Log-{Timestamp}.html", "HTML log"); using (var srt = new StringReader (File.ReadAllText (Path.Combine (Harness.RootDirectory, "HtmlTransform.xslt")))) { using (var sri = File.OpenRead (xmlLog)) { using (var xrt = System.Xml.XmlReader.Create (srt)) { using (var xri = System.Xml.XmlReader.Create (sri)) { var xslt = new System.Xml.Xsl.XslCompiledTransform (); xslt.Load (xrt); using (var xwo = System.Xml.XmlWriter.Create (output, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML { xslt.Transform (xri, xwo); } } } } } } catch (Exception e) { log.WriteLine ("Failed to produce HTML report: {0}", e); } } } } public override void Reset () { base.Reset (); BuildTask?.Reset (); } } abstract class MacTask : RunTestTask { public MacTask (BuildToolTask build_task) : base (build_task) { } public override string Mode { get { switch (Platform) { case TestPlatform.Mac: return "Mac"; case TestPlatform.Mac_Classic: return "Mac Classic"; case TestPlatform.Mac_Unified: return "Mac Unified"; case TestPlatform.Mac_Unified32: return "Mac Unified 32-bit"; case TestPlatform.Mac_UnifiedXM45: return "Mac Unified XM45"; case TestPlatform.Mac_UnifiedXM45_32: return "Mac Unified XM45 32-bit"; default: throw new NotImplementedException (); } } set { throw new NotSupportedException (); } } } class MacExecuteTask : MacTask { public string Path; public bool BCLTest; public bool IsUnitTest; public MacExecuteTask (BuildToolTask build_task) : base (build_task) { } public override bool SupportsParallelExecution { get { if (TestName.Contains ("xammac")) { // We run the xammac tests in both Debug and Release configurations. // These tests are not written to support parallel execution // (there are hard coded paths used for instance), so disable // parallel execution for these tests. return false; } if (BCLTest) { // We run the BCL tests in multiple flavors (Full/Modern), // and the BCL tests are not written to support parallel execution, // so disable parallel execution for these tests. return false; } return base.SupportsParallelExecution; } } public override IEnumerable<Log> AggregatedLogs { get { return base.AggregatedLogs.Union (BuildTask.Logs); } } protected override async Task RunTestAsync () { var projectDir = System.IO.Path.GetDirectoryName (ProjectFile); var name = System.IO.Path.GetFileName (projectDir); if (string.Equals ("mac", name, StringComparison.OrdinalIgnoreCase)) name = System.IO.Path.GetFileName (System.IO.Path.GetDirectoryName (projectDir)); var suffix = string.Empty; switch (Platform) { case TestPlatform.Mac_Unified: suffix = "-unified"; break; case TestPlatform.Mac_Unified32: suffix = "-unified-32"; break; case TestPlatform.Mac_UnifiedXM45: suffix = "-unifiedXM45"; break; case TestPlatform.Mac_UnifiedXM45_32: suffix = "-unifiedXM45-32"; break; } if (ProjectFile.EndsWith (".sln", StringComparison.Ordinal)) { Path = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (ProjectFile), "bin", BuildTask.ProjectPlatform, BuildTask.ProjectConfiguration + suffix, name + ".app", "Contents", "MacOS", name); } else { var project = new System.Xml.XmlDocument (); project.LoadWithoutNetworkAccess (ProjectFile); var outputPath = project.GetOutputPath (BuildTask.ProjectPlatform, BuildTask.ProjectConfiguration).Replace ('\\', '/'); var assemblyName = project.GetAssemblyName (); Path = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (ProjectFile), outputPath, assemblyName + ".app", "Contents", "MacOS", assemblyName); } using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { using (var proc = new Process ()) { proc.StartInfo.FileName = Path; if (IsUnitTest) { var xml = Logs.CreateFile ($"test-{Platform}-{Timestamp}.xml", "NUnit results"); proc.StartInfo.Arguments = $"-result={StringUtils.Quote (xml)}"; } proc.StartInfo.EnvironmentVariables ["MONO_DEBUG"] = "no-gdb-backtrace"; Jenkins.MainLog.WriteLine ("Executing {0} ({1})", TestName, Mode); var log = Logs.Create ($"execute-{Platform}-{Timestamp}.txt", "Execution log"); log.Timestamp = true; log.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments); if (!Harness.DryRun) { ExecutionResult = TestExecutingResult.Running; var snapshot = new CrashReportSnapshot () { Device = false, Harness = Harness, Log = log, Logs = Logs, LogDirectory = LogDirectory }; await snapshot.StartCaptureAsync (); ProcessExecutionResult result = null; try { var timeout = TimeSpan.FromMinutes (20); result = await proc.RunAsync (log, true, timeout); if (result.TimedOut) { FailureMessage = $"Execution timed out after {timeout.TotalSeconds} seconds."; log.WriteLine (FailureMessage); ExecutionResult = TestExecutingResult.TimedOut; } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; FailureMessage = result.ExitCode != 1 ? $"Test run crashed (exit code: {result.ExitCode})." : "Test run failed."; log.WriteLine (FailureMessage); } } finally { await snapshot.EndCaptureAsync (TimeSpan.FromSeconds (Succeeded ? 0 : (result?.ExitCode > 1 ? 120 : 5))); } } Jenkins.MainLog.WriteLine ("Executed {0} ({1})", TestName, Mode); } } } } class RunXtroTask : MacExecuteTask { public string WorkingDirectory; public RunXtroTask (BuildToolTask build_task) : base (build_task) { } protected override async Task RunTestAsync () { var projectDir = System.IO.Path.GetDirectoryName (ProjectFile); var name = System.IO.Path.GetFileName (projectDir); using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { using (var proc = new Process ()) { proc.StartInfo.FileName = "/Library/Frameworks/Mono.framework/Commands/mono"; var reporter = System.IO.Path.Combine (WorkingDirectory, "xtro-report/bin/Debug/xtro-report.exe"); var results = System.IO.Path.GetFullPath (System.IO.Path.Combine (Jenkins.LogDirectory, "..", "xtro")); proc.StartInfo.Arguments = $"--debug {reporter} {WorkingDirectory} {results}"; Jenkins.MainLog.WriteLine ("Executing {0} ({1})", TestName, Mode); var log = Logs.Create ($"execute-xtro-{Timestamp}.txt", "Execution log"); log.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments); if (!Harness.DryRun) { ExecutionResult = TestExecutingResult.Running; var snapshot = new CrashReportSnapshot () { Device = false, Harness = Harness, Log = log, Logs = Logs, LogDirectory = LogDirectory }; await snapshot.StartCaptureAsync (); try { var timeout = TimeSpan.FromMinutes (20); var result = await proc.RunAsync (log, true, timeout); if (result.TimedOut) { FailureMessage = $"Execution timed out after {timeout.TotalSeconds} seconds."; log.WriteLine (FailureMessage); ExecutionResult = TestExecutingResult.TimedOut; } else if (result.Succeeded) { ExecutionResult = TestExecutingResult.Succeeded; } else { ExecutionResult = TestExecutingResult.Failed; FailureMessage = result.ExitCode != 1 ? $"Test run crashed (exit code: {result.ExitCode})." : "Test run failed."; log.WriteLine (FailureMessage); } } finally { await snapshot.EndCaptureAsync (TimeSpan.FromSeconds (Succeeded ? 0 : 5)); } } Jenkins.MainLog.WriteLine ("Executed {0} ({1})", TestName, Mode); var output = Logs.Create ($"Report-{Timestamp}.html", "HTML Report"); var report = System.IO.Path.GetFullPath (System.IO.Path.Combine (results, "index.html")); output.WriteLine ($"<html><head><meta http-equiv=\"refresh\" content=\"0; url={report}\" /></head></html>"); } } } } abstract class RunTestTask : TestTask { public readonly BuildToolTask BuildTask; public RunTestTask (BuildToolTask build_task) { this.BuildTask = build_task; Jenkins = build_task.Jenkins; TestProject = build_task.TestProject; Platform = build_task.Platform; ProjectPlatform = build_task.ProjectPlatform; ProjectConfiguration = build_task.ProjectConfiguration; if (build_task.HasCustomTestName) TestName = build_task.TestName; } public override IEnumerable<Log> AggregatedLogs { get { var rv = base.AggregatedLogs; if (BuildTask != null) rv = rv.Union (BuildTask.AggregatedLogs); return rv; } } public override TestExecutingResult ExecutionResult { get { // When building, the result is the build result. if ((BuildTask.ExecutionResult & (TestExecutingResult.InProgress | TestExecutingResult.Waiting)) != 0) return (BuildTask.ExecutionResult & ~TestExecutingResult.InProgressMask) | TestExecutingResult.Building; return base.ExecutionResult; } set { base.ExecutionResult = value; } } public async Task<bool> BuildAsync () { if (Finished) return true; ExecutionResult = TestExecutingResult.Building; await BuildTask.RunAsync (); if (!BuildTask.Succeeded) { if (BuildTask.TimedOut) { ExecutionResult = TestExecutingResult.TimedOut; } else { ExecutionResult = TestExecutingResult.BuildFailure; } FailureMessage = BuildTask.FailureMessage; } else { ExecutionResult = TestExecutingResult.Built; } return BuildTask.Succeeded; } protected override async Task ExecuteAsync () { if (Finished) return; VerifyRun (); if (Finished) return; if (!await BuildAsync ()) return; ExecutionResult = TestExecutingResult.Running; duration.Restart (); // don't count the build time. await RunTestAsync (); } protected abstract Task RunTestAsync (); protected virtual void VerifyRun () { } public override void Reset () { base.Reset (); BuildTask.Reset (); } } abstract class RunXITask<TDevice> : RunTestTask where TDevice: class, IDevice { IEnumerable<TDevice> candidates; TDevice device; TDevice companion_device; public AppRunnerTarget AppRunnerTarget; protected AppRunner runner; protected AppRunner additional_runner; public IEnumerable<TDevice> Candidates => candidates; public TDevice Device { get { return device; } protected set { device = value; } } public TDevice CompanionDevice { get { return companion_device; } protected set { companion_device = value; } } public string BundleIdentifier { get { return runner.BundleIdentifier; } } public RunXITask (BuildToolTask build_task, IEnumerable<TDevice> candidates) : base (build_task) { this.candidates = candidates; } public override IEnumerable<Log> AggregatedLogs { get { var rv = base.AggregatedLogs; if (runner != null) rv = rv.Union (runner.Logs); if (additional_runner != null) rv = rv.Union (additional_runner.Logs); return rv; } } public override string Mode { get { switch (Platform) { case TestPlatform.tvOS: case TestPlatform.watchOS: return Platform.ToString () + " - " + XIMode; case TestPlatform.iOS_Unified32: return "iOS Unified 32-bits - " + XIMode; case TestPlatform.iOS_Unified64: return "iOS Unified 64-bits - " + XIMode; case TestPlatform.iOS_TodayExtension64: return "iOS Unified Today Extension 64-bits - " + XIMode; case TestPlatform.iOS_Unified: return "iOS Unified - " + XIMode; default: throw new NotImplementedException (); } } set { throw new NotImplementedException (); } } protected override void VerifyRun () { base.VerifyRun (); if (!candidates.Any ()) { ExecutionResult = TestExecutingResult.Skipped; FailureMessage = "No applicable devices found."; } } protected abstract string XIMode { get; } public override void Reset () { base.Reset (); runner = null; additional_runner = null; } } class RunDeviceTask : RunXITask<Device> { object lock_obj = new object (); Log install_log; public override string ProgressMessage { get { StreamReader reader; lock (lock_obj) reader = install_log?.GetReader (); if (reader == null) return base.ProgressMessage; using (reader) { var lines = reader.ReadToEnd ().Split ('\n'); for (int i = lines.Length - 1; i >= 0; i--) { var idx = lines [i].IndexOf ("PercentComplete:", StringComparison.Ordinal); if (idx == -1) continue; return "Install: " + lines [i].Substring (idx + "PercentComplete:".Length + 1) + "%"; } } return base.ProgressMessage; } } public RunDeviceTask (XBuildTask build_task, IEnumerable<Device> candidates) : base (build_task, candidates.OrderBy ((v) => v.DebugSpeed)) { switch (build_task.Platform) { case TestPlatform.iOS: case TestPlatform.iOS_Unified: case TestPlatform.iOS_Unified32: case TestPlatform.iOS_Unified64: AppRunnerTarget = AppRunnerTarget.Device_iOS; break; case TestPlatform.iOS_TodayExtension64: AppRunnerTarget = AppRunnerTarget.Device_iOS; break; case TestPlatform.tvOS: AppRunnerTarget = AppRunnerTarget.Device_tvOS; break; case TestPlatform.watchOS: AppRunnerTarget = AppRunnerTarget.Device_watchOS; break; default: throw new NotImplementedException (); } } protected override async Task RunTestAsync () { Jenkins.MainLog.WriteLine ("Running '{0}' on device (candidates: '{1}')", ProjectFile, string.Join ("', '", Candidates.Select ((v) => v.Name).ToArray ())); var install_log = Logs.Create ($"install-{Timestamp}.log", "Install log"); install_log.Timestamp = true; var uninstall_log = Logs.Create ($"uninstall-{Timestamp}.log", "Uninstall log"); using (var device_resource = await NotifyBlockingWaitAsync (Jenkins.GetDeviceResources (Candidates).AcquireAnyConcurrentAsync ())) { try { // Set the device we acquired. Device = Candidates.First ((d) => d.UDID == device_resource.Resource.Name); if (Platform == TestPlatform.watchOS) CompanionDevice = Jenkins.Devices.FindCompanionDevice (Jenkins.DeviceLoadLog, Device); Jenkins.MainLog.WriteLine ("Acquired device '{0}' for '{1}'", Device.Name, ProjectFile); runner = new AppRunner { Harness = Harness, ProjectFile = ProjectFile, Target = AppRunnerTarget, LogDirectory = LogDirectory, MainLog = install_log, DeviceName = Device.Name, CompanionDeviceName = CompanionDevice?.Name, Configuration = ProjectConfiguration, }; // Sometimes devices can't upgrade (depending on what has changed), so make sure to uninstall any existing apps first. runner.MainLog = uninstall_log; var uninstall_result = await runner.UninstallAsync (); if (!uninstall_result.Succeeded) MainLog.WriteLine ($"Pre-run uninstall failed, exit code: {uninstall_result.ExitCode} (this hopefully won't affect the test result)"); if (!Failed) { // Install the app lock (lock_obj) this.install_log = install_log; try { runner.MainLog = install_log; var install_result = await runner.InstallAsync (); if (!install_result.Succeeded) { FailureMessage = $"Install failed, exit code: {install_result.ExitCode}."; ExecutionResult = TestExecutingResult.Failed; } } finally { lock (lock_obj) this.install_log = null; } } if (!Failed) { // Run the app runner.MainLog = Logs.Create ($"run-{Device.UDID}-{Timestamp}.log", "Run log"); await runner.RunAsync (); if (!string.IsNullOrEmpty (runner.FailureMessage)) FailureMessage = runner.FailureMessage; else if (runner.Result != TestExecutingResult.Succeeded) FailureMessage = GuessFailureReason (runner.MainLog); if (runner.Result == TestExecutingResult.Succeeded && Platform == TestPlatform.iOS_TodayExtension64) { // For the today extension, the main app is just a single test. // This is because running the today extension will not wake up the device, // nor will it close & reopen the today app (but launching the main app // will do both of these things, preparing the device for launching the today extension). AppRunner todayRunner = new AppRunner { Harness = Harness, ProjectFile = TestProject.GetTodayExtension ().Path, Target = AppRunnerTarget, LogDirectory = LogDirectory, MainLog = Logs.Create ($"extension-run-{Device.UDID}-{Timestamp}.log", "Extension run log"), DeviceName = Device.Name, CompanionDeviceName = CompanionDevice?.Name, Configuration = ProjectConfiguration, }; additional_runner = todayRunner; await todayRunner.RunAsync (); foreach (var log in todayRunner.Logs.Where ((v) => !v.Description.StartsWith ("Extension ", StringComparison.Ordinal))) log.Description = "Extension " + log.Description [0].ToString ().ToLower () + log.Description.Substring (1); ExecutionResult = todayRunner.Result; if (!string.IsNullOrEmpty (todayRunner.FailureMessage)) FailureMessage = todayRunner.FailureMessage; } else { ExecutionResult = runner.Result; } } } finally { // Uninstall again, so that we don't leave junk behind and fill up the device. runner.MainLog = uninstall_log; var uninstall_result = await runner.UninstallAsync (); if (!uninstall_result.Succeeded) MainLog.WriteLine ($"Post-run uninstall failed, exit code: {uninstall_result.ExitCode} (this won't affect the test result)"); // Also clean up after us locally. if (Harness.InJenkins || Harness.InWrench || Succeeded) await BuildTask.CleanAsync (); } } } protected override string XIMode { get { return "device"; } } } class RunSimulatorTask : RunXITask<SimDevice> { public IAcquiredResource AcquiredResource; public SimDevice [] Simulators { get { if (Device == null) { return new SimDevice [] { }; } else if (CompanionDevice == null) { return new SimDevice [] { Device }; } else { return new SimDevice [] { Device, CompanionDevice }; } } } public RunSimulatorTask (XBuildTask build_task, IEnumerable<SimDevice> candidates = null) : base (build_task, candidates) { var project = Path.GetFileNameWithoutExtension (ProjectFile); if (project.EndsWith ("-tvos", StringComparison.Ordinal)) { AppRunnerTarget = AppRunnerTarget.Simulator_tvOS; } else if (project.EndsWith ("-watchos", StringComparison.Ordinal)) { AppRunnerTarget = AppRunnerTarget.Simulator_watchOS; } else { AppRunnerTarget = AppRunnerTarget.Simulator_iOS; } } public Task SelectSimulatorAsync () { if (Finished) return Task.FromResult (true); if (!BuildTask.Succeeded) { ExecutionResult = TestExecutingResult.BuildFailure; return Task.FromResult (true); } Device = Candidates.First (); if (Platform == TestPlatform.watchOS) CompanionDevice = Jenkins.Simulators.FindCompanionDevice (Jenkins.SimulatorLoadLog, Device); var clean_state = false;//Platform == TestPlatform.watchOS; runner = new AppRunner () { Harness = Harness, ProjectFile = ProjectFile, EnsureCleanSimulatorState = clean_state, Target = AppRunnerTarget, LogDirectory = LogDirectory, MainLog = Logs.Create ($"run-{Device.UDID}-{Timestamp}.log", "Run log"), Configuration = ProjectConfiguration, }; runner.Simulators = Simulators; runner.Initialize (); return Task.FromResult (true); } class NondisposedResource : IAcquiredResource { public IAcquiredResource Wrapped; public Resource Resource { get { return Wrapped.Resource; } } public void Dispose () { // Nope, no disposing here. } } Task<IAcquiredResource> AcquireResourceAsync () { if (AcquiredResource != null) { // We don't own the acquired resource, so wrap it in a class that won't dispose it. return Task.FromResult<IAcquiredResource> (new NondisposedResource () { Wrapped = AcquiredResource }); } else { return Jenkins.DesktopResource.AcquireExclusiveAsync (); } } protected override async Task RunTestAsync () { Jenkins.MainLog.WriteLine ("Running XI on '{0}' ({2}) for {1}", Device?.Name, ProjectFile, Device?.UDID); ExecutionResult = (ExecutionResult & ~TestExecutingResult.InProgressMask) | TestExecutingResult.Running; if (BuildTask.NotStarted) await BuildTask.RunAsync (); if (!BuildTask.Succeeded) { ExecutionResult = TestExecutingResult.BuildFailure; return; } using (var resource = await NotifyBlockingWaitAsync (AcquireResourceAsync ())) { if (runner == null) await SelectSimulatorAsync (); await runner.RunAsync (); } ExecutionResult = runner.Result; } protected override string XIMode { get { return "simulator"; } } } // This class groups simulator run tasks according to the // simulator they'll run from, so that we minimize switching // between different simulators (which is slow). class AggregatedRunSimulatorTask : TestTask { public IEnumerable<RunSimulatorTask> Tasks; // Due to parallelization this isn't the same as the sum of the duration for all the build tasks. Stopwatch build_timer = new Stopwatch (); public TimeSpan BuildDuration { get { return build_timer.Elapsed; } } Stopwatch run_timer = new Stopwatch (); public TimeSpan RunDuration { get { return run_timer.Elapsed; } } public AggregatedRunSimulatorTask (IEnumerable<RunSimulatorTask> tasks) { this.Tasks = tasks; } protected override async Task ExecuteAsync () { if (Tasks.All ((v) => v.Ignored)) { ExecutionResult = TestExecutingResult.Ignored; return; } // First build everything. This is required for the run simulator // task to properly configure the simulator. build_timer.Start (); await Task.WhenAll (Tasks.Select ((v) => v.BuildAsync ()).Distinct ()); build_timer.Stop (); using (var desktop = await NotifyBlockingWaitAsync (Jenkins.DesktopResource.AcquireExclusiveAsync ())) { run_timer.Start (); // We need to set the dialog permissions for all the apps // before launching the simulator, because once launched // the simulator caches the values in-memory. var executingTasks = Tasks.Where ((v) => !v.Ignored && !v.Failed); foreach (var task in executingTasks) await task.SelectSimulatorAsync (); var devices = executingTasks.First ().Simulators; Jenkins.MainLog.WriteLine ("Selected simulator: {0}", devices.Length > 0 ? devices [0].Name : "none"); foreach (var dev in devices) await dev.PrepareSimulatorAsync (Jenkins.MainLog, executingTasks.Select ((v) => v.BundleIdentifier).ToArray ()); foreach (var task in executingTasks) { task.AcquiredResource = desktop; try { await task.RunAsync (); } finally { task.AcquiredResource = null; } } foreach (var dev in devices) await dev.ShutdownAsync (Jenkins.MainLog); await SimDevice.KillEverythingAsync (Jenkins.MainLog); run_timer.Stop (); } if (Tasks.All ((v) => v.Ignored)) { ExecutionResult = TestExecutingResult.Ignored; } else { ExecutionResult = Tasks.Any ((v) => v.Failed) ? TestExecutingResult.Failed : TestExecutingResult.Succeeded; } } } // This is a very simple class to manage the general concept of 'resource'. // Performance isn't important, so this is very simple. // Currently it's only used to make sure everything that happens on the desktop // is serialized (Jenkins.DesktopResource), but in the future the idea is to // make each connected device a separate resource, which will make it possible // to run tests in parallel across devices (and at the same time use the desktop // to build the next test project). class Resource { public string Name; public string Description; ConcurrentQueue<TaskCompletionSource<IAcquiredResource>> queue = new ConcurrentQueue<TaskCompletionSource<IAcquiredResource>> (); ConcurrentQueue<TaskCompletionSource<IAcquiredResource>> exclusive_queue = new ConcurrentQueue<TaskCompletionSource<IAcquiredResource>> (); int users; int max_concurrent_users = 1; bool exclusive; public int Users => users; public int QueuedUsers => queue.Count + exclusive_queue.Count; public int MaxConcurrentUsers { get { return max_concurrent_users; } set { max_concurrent_users = value; } } public Resource (string name, int max_concurrent_users = 1, string description = null) { this.Name = name; this.max_concurrent_users = max_concurrent_users; this.Description = description ?? name; } public Task<IAcquiredResource> AcquireConcurrentAsync () { lock (queue) { if (!exclusive && users < max_concurrent_users) { users++; return Task.FromResult<IAcquiredResource> (new AcquiredResource (this)); } else { var tcs = new TaskCompletionSource<IAcquiredResource> (new AcquiredResource (this)); queue.Enqueue (tcs); return tcs.Task; } } } public Task<IAcquiredResource> AcquireExclusiveAsync () { lock (queue) { if (users == 0) { users++; exclusive = true; return Task.FromResult<IAcquiredResource> (new AcquiredResource (this)); } else { var tcs = new TaskCompletionSource<IAcquiredResource> (new AcquiredResource (this)); exclusive_queue.Enqueue (tcs); return tcs.Task; } } } void Release () { TaskCompletionSource<IAcquiredResource> tcs; lock (queue) { users--; exclusive = false; if (queue.TryDequeue (out tcs)) { users++; tcs.SetResult ((IAcquiredResource) tcs.Task.AsyncState); } else if (users == 0 && exclusive_queue.TryDequeue (out tcs)) { users++; exclusive = true; tcs.SetResult ((IAcquiredResource) tcs.Task.AsyncState); } } } class AcquiredResource : IAcquiredResource { Resource resource; public AcquiredResource (Resource resource) { this.resource = resource; } void IDisposable.Dispose () { resource.Release (); } public Resource Resource { get { return resource; } } } } interface IAcquiredResource : IDisposable { Resource Resource { get; } } class Resources { readonly Resource [] resources; public Resources (IEnumerable<Resource> resources) { this.resources = resources.ToArray (); } public Task<IAcquiredResource> AcquireAnyConcurrentAsync () { if (resources.Length == 0) throw new Exception ("No resources"); if (resources.Length == 1) return resources [0].AcquireConcurrentAsync (); // We try to acquire every resource // When the first one succeeds, we set the result to true // We immediately release any other resources we acquire. var tcs = new TaskCompletionSource<IAcquiredResource> (); for (int i = 0; i < resources.Length; i++) { resources [i].AcquireConcurrentAsync ().ContinueWith ((v) => { var ar = v.Result; if (!tcs.TrySetResult (ar)) ar.Dispose (); }); } return tcs.Task; } } public enum TestPlatform { None, All, iOS, iOS_Unified, iOS_Unified32, iOS_Unified64, iOS_TodayExtension64, tvOS, watchOS, Mac, Mac_Classic, Mac_Unified, Mac_UnifiedXM45, Mac_Unified32, Mac_UnifiedXM45_32, } [Flags] public enum TestExecutingResult { NotStarted = 0, InProgress = 0x1, Finished = 0x2, Waiting = 0x4, StateMask = NotStarted + InProgress + Waiting + Finished, // In progress state Building = 0x10 + InProgress, BuildQueued = 0x10 + InProgress + Waiting, Built = 0x20 + InProgress, Running = 0x40 + InProgress, RunQueued = 0x40 + InProgress + Waiting, InProgressMask = 0x10 + 0x20 + 0x40, // Finished results Succeeded = 0x100 + Finished, Failed = 0x200 + Finished, Ignored = 0x400 + Finished, Skipped = 0x800 + Finished, // Finished & Failed results Crashed = 0x1000 + Failed, TimedOut = 0x2000 + Failed, HarnessException = 0x4000 + Failed, BuildFailure = 0x8000 + Failed, } }
35.709246
318
0.654927
[ "BSD-3-Clause" ]
filipnavara/xamarin-macios
tests/xharness/Jenkins.cs
133,626
C#
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; namespace SisoDb.Serialization.Common { internal static class WriteListsOfElements<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); static Dictionary<Type, WriteObjectDelegate> ListCacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetListWriteFn(Type elementType) { WriteObjectDelegate writeFn; if (ListCacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteList", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = ListCacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(ListCacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ListCacheFns, newCache, snapshot), snapshot)); return writeFn; } static Dictionary<Type, WriteObjectDelegate> IListCacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetIListWriteFn(Type elementType) { WriteObjectDelegate writeFn; if (IListCacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteIList", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = IListCacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(IListCacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref IListCacheFns, newCache, snapshot), snapshot)); return writeFn; } static Dictionary<Type, WriteObjectDelegate> CacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetGenericWriteArray(Type elementType) { WriteObjectDelegate writeFn; if (CacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteArray", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = CacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(CacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref CacheFns, newCache, snapshot), snapshot)); return writeFn; } static Dictionary<Type, WriteObjectDelegate> EnumerableCacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetGenericWriteEnumerable(Type elementType) { WriteObjectDelegate writeFn; if (EnumerableCacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteEnumerable", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = EnumerableCacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(EnumerableCacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref EnumerableCacheFns, newCache, snapshot), snapshot)); return writeFn; } static Dictionary<Type, WriteObjectDelegate> ListValueTypeCacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetWriteListValueType(Type elementType) { WriteObjectDelegate writeFn; if (ListValueTypeCacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteListValueType", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = ListValueTypeCacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(ListValueTypeCacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ListValueTypeCacheFns, newCache, snapshot), snapshot)); return writeFn; } static Dictionary<Type, WriteObjectDelegate> IListValueTypeCacheFns = new Dictionary<Type, WriteObjectDelegate>(); public static WriteObjectDelegate GetWriteIListValueType(Type elementType) { WriteObjectDelegate writeFn; if (IListValueTypeCacheFns.TryGetValue(elementType, out writeFn)) return writeFn; var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteIListValueType", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = IListValueTypeCacheFns; newCache = new Dictionary<Type, WriteObjectDelegate>(IListValueTypeCacheFns); newCache[elementType] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref IListValueTypeCacheFns, newCache, snapshot), snapshot)); return writeFn; } public static void WriteIEnumerable(TextWriter writer, object oValueCollection) { WriteObjectDelegate toStringFn = null; writer.Write(JsWriter.ListStartChar); var valueCollection = (IEnumerable)oValueCollection; var ranOnce = false; foreach (var valueItem in valueCollection) { if (toStringFn == null) toStringFn = Serializer.GetWriteFn(valueItem.GetType()); JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); toStringFn(writer, valueItem); } writer.Write(JsWriter.ListEndChar); } } internal static class WriteListsOfElements<T, TSerializer> where TSerializer : ITypeSerializer { private static readonly WriteObjectDelegate ElementWriteFn; static WriteListsOfElements() { ElementWriteFn = JsWriter.GetTypeSerializer<TSerializer>().GetWriteFn<T>(); } public static void WriteList(TextWriter writer, object oList) { if (oList == null) return; WriteGenericIList(writer, (IList<T>)oList); } public static void WriteGenericList(TextWriter writer, List<T> list) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; var listLength = list.Count; for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, list[i]); } writer.Write(JsWriter.ListEndChar); } public static void WriteListValueType(TextWriter writer, object list) { WriteGenericListValueType(writer, (List<T>)list); } public static void WriteGenericListValueType(TextWriter writer, List<T> list) { if (list == null) return; //AOT writer.Write(JsWriter.ListStartChar); var ranOnce = false; var listLength = list.Count; for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, list[i]); } writer.Write(JsWriter.ListEndChar); } public static void WriteIList(TextWriter writer, object oList) { if (oList == null) return; WriteGenericIList(writer, (IList<T>)oList); } public static void WriteGenericIList(TextWriter writer, IList<T> list) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; var listLength = list.Count; try { for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, list[i]); } } catch (Exception ex) { Tracer.Instance.WriteError(ex); throw; } writer.Write(JsWriter.ListEndChar); } public static void WriteIListValueType(TextWriter writer, object list) { WriteGenericIListValueType(writer, (IList<T>)list); } public static void WriteGenericIListValueType(TextWriter writer, IList<T> list) { if (list == null) return; //AOT writer.Write(JsWriter.ListStartChar); var ranOnce = false; var listLength = list.Count; for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, list[i]); } writer.Write(JsWriter.ListEndChar); } public static void WriteArray(TextWriter writer, object oArrayValue) { if (oArrayValue == null) return; WriteGenericArray(writer, (Array)oArrayValue); } public static void WriteGenericArrayValueType(TextWriter writer, object oArray) { writer.Write(JsWriter.ListStartChar); var array = (T[])oArray; var ranOnce = false; var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, array[i]); } writer.Write(JsWriter.ListEndChar); } private static void WriteGenericArrayMultiDimension(TextWriter writer, Array array, int rank, int[] indices) { var ranOnce = false; writer.Write(JsWriter.ListStartChar); for (int i = 0; i < array.GetLength(rank); i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); indices[rank] = i; if (rank < (array.Rank - 1)) WriteGenericArrayMultiDimension(writer, array, rank + 1, indices); else ElementWriteFn(writer, array.GetValue(indices)); } writer.Write(JsWriter.ListEndChar); } public static void WriteGenericArray(TextWriter writer, Array array) { WriteGenericArrayMultiDimension(writer, array, 0, new int[array.Rank]); } public static void WriteEnumerable(TextWriter writer, object oEnumerable) { if (oEnumerable == null) return; WriteGenericEnumerable(writer, (IEnumerable<T>)oEnumerable); } public static void WriteGenericEnumerable(TextWriter writer, IEnumerable<T> enumerable) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; foreach (var value in enumerable) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, value); } writer.Write(JsWriter.ListEndChar); } public static void WriteGenericEnumerableValueType(TextWriter writer, IEnumerable<T> enumerable) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; foreach (var value in enumerable) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); ElementWriteFn(writer, value); } writer.Write(JsWriter.ListEndChar); } } internal static class WriteLists { public static void WriteListString(ITypeSerializer serializer, TextWriter writer, object list) { WriteListString(serializer, writer, (List<string>)list); } public static void WriteListString(ITypeSerializer serializer, TextWriter writer, List<string> list) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; list.ForEach(x => { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); serializer.WriteString(writer, x); }); writer.Write(JsWriter.ListEndChar); } public static void WriteIListString(ITypeSerializer serializer, TextWriter writer, object list) { WriteIListString(serializer, writer, (IList<string>)list); } public static void WriteIListString(ITypeSerializer serializer, TextWriter writer, IList<string> list) { writer.Write(JsWriter.ListStartChar); var ranOnce = false; var listLength = list.Count; for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); serializer.WriteString(writer, list[i]); } writer.Write(JsWriter.ListEndChar); } public static void WriteBytes(ITypeSerializer serializer, TextWriter writer, object byteValue) { if (byteValue == null) return; serializer.WriteBytes(writer, byteValue); } public static void WriteStringArray(ITypeSerializer serializer, TextWriter writer, object oList) { writer.Write(JsWriter.ListStartChar); var list = (string[])oList; var ranOnce = false; var listLength = list.Length; for (var i = 0; i < listLength; i++) { JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); serializer.WriteString(writer, list[i]); } writer.Write(JsWriter.ListEndChar); } } internal static class WriteLists<T, TSerializer> where TSerializer : ITypeSerializer { private static readonly WriteObjectDelegate CacheFn; private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); static WriteLists() { CacheFn = GetWriteFn(); } public static WriteObjectDelegate Write { get { return CacheFn; } } public static WriteObjectDelegate GetWriteFn() { var type = typeof(T); var listInterface = type.GetTypeWithGenericTypeDefinitionOf(typeof(IList<>)); if (listInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type IList<>", type.FullName)); //optimized access for regularly used types if (type == typeof(List<string>)) return (w, x) => WriteLists.WriteListString(Serializer, w, x); if (type == typeof(IList<string>)) return (w, x) => WriteLists.WriteIListString(Serializer, w, x); if (type == typeof(List<int>)) return WriteListsOfElements<int, TSerializer>.WriteListValueType; if (type == typeof(IList<int>)) return WriteListsOfElements<int, TSerializer>.WriteIListValueType; if (type == typeof(List<long>)) return WriteListsOfElements<long, TSerializer>.WriteListValueType; if (type == typeof(IList<long>)) return WriteListsOfElements<long, TSerializer>.WriteIListValueType; var elementType = listInterface.GetGenericArguments()[0]; var isGenericList = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>); if (elementType.IsValueType && JsWriter.ShouldUseDefaultToStringMethod(elementType)) { if (isGenericList) return WriteListsOfElements<TSerializer>.GetWriteListValueType(elementType); return WriteListsOfElements<TSerializer>.GetWriteIListValueType(elementType); } return isGenericList ? WriteListsOfElements<TSerializer>.GetListWriteFn(elementType) : WriteListsOfElements<TSerializer>.GetIListWriteFn(elementType); } } }
33.592814
117
0.6776
[ "MIT" ]
eric-swann-q2/SisoDb-Provider
Source/Projects/SisoDb.Serialization/Common/WriteLists.cs
16,830
C#
using RefactoringToPatterns.Strategy.Common.Enum; namespace RefactoringToPatterns.Strategy.Step4.Strategy { internal class ConferenceCostCalculationStrategy : WishListItemCostCalculationStrategy { internal override decimal CalculateCost(WishListItem item) { var totalCost = item.BaseItemCost; if (item.Location == LocationType.Foreign) { totalCost *= 0.7m; } if (item.SideCosts.IncludeAccommodationCost) { totalCost += item.SideCosts.AccommodationCost; } if (item.SideCosts.IncludeDailyAllowanceCost) { totalCost += item.SideCosts.DailyAllowanceCost; } if (item.SideCosts.IncludeTransportCost) { totalCost += item.SideCosts.TransportCost; } return totalCost; } } }
27.617647
90
0.57934
[ "MIT" ]
wojciech-dabrowski/RefactoringToPatterns
RefactoringToPatterns/RefactoringToPatterns.Strategy/Step4/Strategy/ConferenceCostCalculationStrategy.cs
941
C#
// // Tests for System.Drawing.Drawing2D.Matrix.cs // // Authors: // Jordi Mas i Hernandez <[email protected]> // Sebastien Pouliot <[email protected]> // // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Security.Permissions; namespace MonoTests.System.Drawing.Drawing2D { [TestFixture] [SecurityPermission (SecurityAction.Deny, UnmanagedCode = true)] public class MatrixTest { private Matrix default_matrix; private Rectangle rect; private RectangleF rectf; [TestFixtureSetUp] public void FixtureSetUp () { default_matrix = new Matrix (); } [Test] public void Constructor_Default () { Matrix matrix = new Matrix (); Assert.AreEqual (6, matrix.Elements.Length, "C#1"); } [Test] public void Constructor_SixFloats () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); Assert.AreEqual (6, matrix.Elements.Length, "C#2"); Assert.AreEqual (10, matrix.Elements[0], "C#3"); Assert.AreEqual (20, matrix.Elements[1], "C#4"); Assert.AreEqual (30, matrix.Elements[2], "C#5"); Assert.AreEqual (40, matrix.Elements[3], "C#6"); Assert.AreEqual (50, matrix.Elements[4], "C#7"); Assert.AreEqual (60, matrix.Elements[5], "C#8"); } [Test] public void Constructor_Float () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); Assert.AreEqual (6, matrix.Elements.Length, "C#2"); Assert.AreEqual (10, matrix.Elements[0], "C#3"); Assert.AreEqual (20, matrix.Elements[1], "C#4"); Assert.AreEqual (30, matrix.Elements[2], "C#5"); Assert.AreEqual (40, matrix.Elements[3], "C#6"); Assert.AreEqual (50, matrix.Elements[4], "C#7"); Assert.AreEqual (60, matrix.Elements[5], "C#8"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Constructor_Int_Null () { new Matrix (rect, null); } [Test] [ExpectedException (typeof (ArgumentException))] public void Constructor_Int_Empty () { new Matrix (rect, new Point[0]); } [Test] [ExpectedException (typeof (ArgumentException))] public void Constructor_Int_4Point () { new Matrix (rect, new Point[4]); } [Test] public void Constructor_Rect_Point () { Rectangle r = new Rectangle (100, 200, 300, 400); Matrix m = new Matrix (r, new Point[3] { new Point (10, 20), new Point (30, 40), new Point (50, 60) }); float[] elements = m.Elements; Assert.AreEqual (0.06666666, elements[0], 0.00001, "0"); Assert.AreEqual (0.06666666, elements[1], 0.00001, "1"); Assert.AreEqual (0.09999999, elements[2], 0.00001, "2"); Assert.AreEqual (0.09999999, elements[3], 0.00001, "3"); Assert.AreEqual (-16.6666679, elements[4], 0.00001, "4"); Assert.AreEqual (-6.666667, elements[5], 0.00001, "5"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Constructor_Float_Null () { new Matrix (rectf, null); } [Test] [ExpectedException (typeof (ArgumentException))] public void Constructor_Float_Empty () { new Matrix (rectf, new PointF[0]); } [Test] [ExpectedException (typeof (ArgumentException))] public void Constructor_Float_2PointF () { new Matrix (rectf, new PointF[2]); } [Test] public void Constructor_RectF_PointF () { RectangleF r = new RectangleF (100, 200, 300, 400); Matrix m = new Matrix (r, new PointF[3] { new PointF (10, 20), new PointF (30, 40), new PointF (50, 60) }); float[] elements = m.Elements; Assert.AreEqual (0.06666666, elements[0], 0.00001, "0"); Assert.AreEqual (0.06666666, elements[1], 0.00001, "1"); Assert.AreEqual (0.09999999, elements[2], 0.00001, "2"); Assert.AreEqual (0.09999999, elements[3], 0.00001, "3"); Assert.AreEqual (-16.6666679, elements[4], 0.00001, "4"); Assert.AreEqual (-6.666667, elements[5], 0.00001, "5"); } // Properties [Test] public void Invertible () { Matrix matrix = new Matrix (123, 24, 82, 16, 47, 30); Assert.AreEqual (false, matrix.IsInvertible, "I#1"); matrix = new Matrix (156, 46, 0, 0, 106, 19); Assert.AreEqual (false, matrix.IsInvertible, "I#2"); matrix = new Matrix (146, 66, 158, 104, 42, 150); Assert.AreEqual (true, matrix.IsInvertible, "I#3"); matrix = new Matrix (119, 140, 145, 74, 102, 58); Assert.AreEqual (true, matrix.IsInvertible, "I#4"); } [Test] public void IsIdentity () { Matrix identity = new Matrix (); Matrix matrix = new Matrix (123, 24, 82, 16, 47, 30); Assert.AreEqual (false, matrix.IsIdentity, "N#1-identity"); Assert.IsTrue (!identity.Equals (matrix), "N#1-equals"); matrix = new Matrix (1, 0, 0, 1, 0, 0); Assert.AreEqual (true, matrix.IsIdentity, "N#2-identity"); Assert.IsTrue (identity.Equals (matrix), "N#2-equals"); // so what's the required precision ? matrix = new Matrix (1.1f, 0.1f, -0.1f, 0.9f, 0, 0); Assert.IsTrue (!matrix.IsIdentity, "N#3-identity"); Assert.IsTrue (!identity.Equals (matrix), "N#3-equals"); matrix = new Matrix (1.01f, 0.01f, -0.01f, 0.99f, 0, 0); Assert.IsTrue (!matrix.IsIdentity, "N#4-identity"); Assert.IsTrue (!identity.Equals (matrix), "N#4-equals"); matrix = new Matrix (1.001f, 0.001f, -0.001f, 0.999f, 0, 0); Assert.IsTrue (!matrix.IsIdentity, "N#5-identity"); Assert.IsTrue (!identity.Equals (matrix), "N#5-equals"); matrix = new Matrix (1.0001f, 0.0001f, -0.0001f, 0.9999f, 0, 0); Assert.IsTrue (matrix.IsIdentity, "N#6-identity"); // note: NOT equal Assert.IsTrue (!identity.Equals (matrix), "N#6-equals"); matrix = new Matrix (1.0009f, 0.0009f, -0.0009f, 0.99995f, 0, 0); Assert.IsTrue (!matrix.IsIdentity, "N#7-identity"); Assert.IsTrue (!identity.Equals (matrix), "N#7-equals"); } [Test] public void IsOffsetX () { Matrix matrix = new Matrix (123, 24, 82, 16, 47, 30); Assert.AreEqual (47, matrix.OffsetX, "X#1"); } [Test] public void IsOffsetY () { Matrix matrix = new Matrix (123, 24, 82, 16, 47, 30); Assert.AreEqual (30, matrix.OffsetY, "Y#1"); } // Elements Property is checked implicity in other test // // Methods // [Test] public void Clone () { Matrix matsrc = new Matrix (10, 20, 30, 40, 50, 60); Matrix matrix = matsrc.Clone (); Assert.AreEqual (6, matrix.Elements.Length, "D#1"); Assert.AreEqual (10, matrix.Elements[0], "D#2"); Assert.AreEqual (20, matrix.Elements[1], "D#3"); Assert.AreEqual (30, matrix.Elements[2], "D#4"); Assert.AreEqual (40, matrix.Elements[3], "D#5"); Assert.AreEqual (50, matrix.Elements[4], "D#6"); Assert.AreEqual (60, matrix.Elements[5], "D#7"); } [Test] public void HashCode () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); Matrix clone = matrix.Clone (); Assert.IsTrue (matrix.GetHashCode () != clone.GetHashCode (), "HashCode/Clone"); Matrix matrix2 = new Matrix (10, 20, 30, 40, 50, 60); Assert.IsTrue (matrix.GetHashCode () != matrix2.GetHashCode (), "HashCode/Identical"); } [Test] public void Reset () { Matrix matrix = new Matrix (51, 52, 53, 54, 55, 56); matrix.Reset (); Assert.AreEqual (6, matrix.Elements.Length, "F#1"); Assert.AreEqual (1, matrix.Elements[0], "F#2"); Assert.AreEqual (0, matrix.Elements[1], "F#3"); Assert.AreEqual (0, matrix.Elements[2], "F#4"); Assert.AreEqual (1, matrix.Elements[3], "F#5"); Assert.AreEqual (0, matrix.Elements[4], "F#6"); Assert.AreEqual (0, matrix.Elements[5], "F#7"); } [Test] public void Rotate () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Rotate (180); Assert.AreEqual (-10.0f, matrix.Elements[0], 0.0001, "H#1"); Assert.AreEqual (-20, matrix.Elements[1], 0.0001, "H#2"); Assert.AreEqual (-30.0000019f, matrix.Elements[2], 0.0001, "H#3"); Assert.AreEqual (-40.0000038f, matrix.Elements[3], 0.0001, "H#4"); Assert.AreEqual (50, matrix.Elements[4], "H#5"); Assert.AreEqual (60, matrix.Elements[5], "H#6"); } [Test] public void Rotate_45_135 () { Matrix matrix = new Matrix (); Assert.IsTrue (matrix.IsIdentity, "original.IsIdentity"); matrix.Rotate (45); Assert.IsTrue (!matrix.IsIdentity, "+45.!IsIdentity"); float[] elements = matrix.Elements; Assert.AreEqual (0.707106769f, elements[0], 0.0001, "45#1"); Assert.AreEqual (0.707106769f, elements[1], 0.0001, "45#2"); Assert.AreEqual (-0.707106829f, elements[2], 0.0001, "45#3"); Assert.AreEqual (0.707106769f, elements[3], 0.0001, "45#4"); Assert.AreEqual (0, elements[4], 0.001f, "45#5"); Assert.AreEqual (0, elements[5], 0.001f, "45#6"); matrix.Rotate (135); Assert.IsTrue (!matrix.IsIdentity, "+135.!IsIdentity"); elements = matrix.Elements; Assert.AreEqual (-1, elements[0], 0.0001, "180#1"); Assert.AreEqual (0, elements[1], 0.0001, "180#2"); Assert.AreEqual (0, elements[2], 0.0001, "180#3"); Assert.AreEqual (-1, elements[3], 0.0001, "180#4"); Assert.AreEqual (0, elements[4], "180#5"); Assert.AreEqual (0, elements[5], "180#6"); } [Test] public void Rotate_90_270_Matrix () { Matrix matrix = new Matrix (); Assert.IsTrue (matrix.IsIdentity, "original.IsIdentity"); matrix.Rotate (90); Assert.IsTrue (!matrix.IsIdentity, "+90.!IsIdentity"); float[] elements = matrix.Elements; Assert.AreEqual (0, elements[0], 0.0001, "90#1"); Assert.AreEqual (1, elements[1], 0.0001, "90#2"); Assert.AreEqual (-1, elements[2], 0.0001, "90#3"); Assert.AreEqual (0, elements[3], 0.0001, "90#4"); Assert.AreEqual (0, elements[4], "90#5"); Assert.AreEqual (0, elements[5], "90#6"); matrix.Rotate (270); // this isn't a perfect 1, 0, 0, 1, 0, 0 matrix - but close enough Assert.IsTrue (matrix.IsIdentity, "360.IsIdentity"); Assert.IsTrue (!new Matrix ().Equals (matrix), "360.Equals"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Rotate_InvalidOrder () { new Matrix ().Rotate (180, (MatrixOrder) Int32.MinValue); } [Test] public void RotateAt () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.RotateAt (180, new PointF (10, 10)); Assert.AreEqual (-10, matrix.Elements[0], 0.01, "I#1"); Assert.AreEqual (-20, matrix.Elements[1], 0.01, "I#2"); Assert.AreEqual (-30, matrix.Elements[2], 0.01, "I#3"); Assert.AreEqual (-40, matrix.Elements[3], 0.01, "I#4"); Assert.AreEqual (850, matrix.Elements[4], 0.01, "I#5"); Assert.AreEqual (1260, matrix.Elements[5], 0.01, "I#6"); } [Test] [ExpectedException (typeof (ArgumentException))] public void RotateAt_InvalidOrder () { new Matrix ().RotateAt (180, new PointF (10, 10), (MatrixOrder) Int32.MinValue); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Multiply_Null () { new Matrix (10, 20, 30, 40, 50, 60).Multiply (null); } [Test] public void Multiply () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Multiply (new Matrix (10, 20, 30, 40, 50, 60)); Assert.AreEqual (700, matrix.Elements[0], "J#1"); Assert.AreEqual (1000, matrix.Elements[1], "J#2"); Assert.AreEqual (1500, matrix.Elements[2], "J#3"); Assert.AreEqual (2200, matrix.Elements[3], "J#4"); Assert.AreEqual (2350, matrix.Elements[4], "J#5"); Assert.AreEqual (3460, matrix.Elements[5], "J#6"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Multiply_Null_Order () { new Matrix (10, 20, 30, 40, 50, 60).Multiply (null, MatrixOrder.Append); } [Test] public void Multiply_Append () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Multiply (new Matrix (10, 20, 30, 40, 50, 60), MatrixOrder.Append); Assert.AreEqual (700, matrix.Elements[0], "J#1"); Assert.AreEqual (1000, matrix.Elements[1], "J#2"); Assert.AreEqual (1500, matrix.Elements[2], "J#3"); Assert.AreEqual (2200, matrix.Elements[3], "J#4"); Assert.AreEqual (2350, matrix.Elements[4], "J#5"); Assert.AreEqual (3460, matrix.Elements[5], "J#6"); } [Test] public void Multiply_Prepend () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Multiply (new Matrix (10, 20, 30, 40, 50, 60), MatrixOrder.Prepend); Assert.AreEqual (700, matrix.Elements[0], "J#1"); Assert.AreEqual (1000, matrix.Elements[1], "J#2"); Assert.AreEqual (1500, matrix.Elements[2], "J#3"); Assert.AreEqual (2200, matrix.Elements[3], "J#4"); Assert.AreEqual (2350, matrix.Elements[4], "J#5"); Assert.AreEqual (3460, matrix.Elements[5], "J#6"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Multiply_InvalidOrder () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Multiply (new Matrix (10, 20, 30, 40, 50, 60), (MatrixOrder)Int32.MinValue); } [Test] public void Equals () { Matrix mat1 = new Matrix (10, 20, 30, 40, 50, 60); Matrix mat2 = new Matrix (10, 20, 30, 40, 50, 60); Matrix mat3 = new Matrix (10, 20, 30, 40, 50, 10); Assert.AreEqual (true, mat1.Equals (mat2), "E#1"); Assert.AreEqual (false, mat2.Equals (mat3), "E#2"); Assert.AreEqual (false, mat1.Equals (mat3), "E#3"); } [Test] public void Invert () { Matrix matrix = new Matrix (1, 2, 3, 4, 5, 6); matrix.Invert (); Assert.AreEqual (-2, matrix.Elements[0], "V#1"); Assert.AreEqual (1, matrix.Elements[1], "V#2"); Assert.AreEqual (1.5, matrix.Elements[2], "V#3"); Assert.AreEqual (-0.5, matrix.Elements[3], "V#4"); Assert.AreEqual (1, matrix.Elements[4], "V#5"); Assert.AreEqual (-2, matrix.Elements[5], "V#6"); } [Test] public void Invert_Translation () { Matrix matrix = new Matrix (1, 0, 0, 1, 8, 8); matrix.Invert (); float[] elements = matrix.Elements; Assert.AreEqual (1, elements[0], "#1"); Assert.AreEqual (0, elements[1], "#2"); Assert.AreEqual (0, elements[2], "#3"); Assert.AreEqual (1, elements[3], "#4"); Assert.AreEqual (-8, elements[4], "#5"); Assert.AreEqual (-8, elements[5], "#6"); } [Test] public void Invert_Identity () { Matrix matrix = new Matrix (); Assert.IsTrue (matrix.IsIdentity, "IsIdentity"); Assert.IsTrue (matrix.IsInvertible, "IsInvertible"); matrix.Invert (); Assert.IsTrue (matrix.IsIdentity, "IsIdentity-2"); Assert.IsTrue (matrix.IsInvertible, "IsInvertible-2"); } [Test] public void Scale () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Scale (2, 4); Assert.AreEqual (20, matrix.Elements[0], "S#1"); Assert.AreEqual (40, matrix.Elements[1], "S#2"); Assert.AreEqual (120, matrix.Elements[2], "S#3"); Assert.AreEqual (160, matrix.Elements[3], "S#4"); Assert.AreEqual (50, matrix.Elements[4], "S#5"); Assert.AreEqual (60, matrix.Elements[5], "S#6"); matrix.Scale (0.5f, 0.25f); Assert.AreEqual (10, matrix.Elements[0], "SB#1"); Assert.AreEqual (20, matrix.Elements[1], "SB#2"); Assert.AreEqual (30, matrix.Elements[2], "SB#3"); Assert.AreEqual (40, matrix.Elements[3], "SB#4"); Assert.AreEqual (50, matrix.Elements[4], "SB#5"); Assert.AreEqual (60, matrix.Elements[5], "SB#6"); } [Test] public void Scale_Negative () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Scale (-2, -4); Assert.AreEqual (-20, matrix.Elements[0], "S#1"); Assert.AreEqual (-40, matrix.Elements[1], "S#2"); Assert.AreEqual (-120, matrix.Elements[2], "S#3"); Assert.AreEqual (-160, matrix.Elements[3], "S#4"); Assert.AreEqual (50, matrix.Elements[4], "S#5"); Assert.AreEqual (60, matrix.Elements[5], "S#6"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Scale_InvalidOrder () { new Matrix ().Scale (2, 1, (MatrixOrder) Int32.MinValue); } [Test] public void Shear () { Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60); matrix.Shear (2, 4); Assert.AreEqual (130, matrix.Elements[0], "H#1"); Assert.AreEqual (180, matrix.Elements[1], "H#2"); Assert.AreEqual (50, matrix.Elements[2], "H#3"); Assert.AreEqual (80, matrix.Elements[3], "H#4"); Assert.AreEqual (50, matrix.Elements[4], "H#5"); Assert.AreEqual (60, matrix.Elements[5], "H#6"); matrix = new Matrix (5, 3, 9, 2, 2, 1); matrix.Shear (10, 20); Assert.AreEqual (185, matrix.Elements[0], "H#7"); Assert.AreEqual (43, matrix.Elements[1], "H#8"); Assert.AreEqual (59, matrix.Elements[2], "H#9"); Assert.AreEqual (32, matrix.Elements[3], "H#10"); Assert.AreEqual (2, matrix.Elements[4], "H#11"); Assert.AreEqual (1, matrix.Elements[5], "H#12"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Shear_InvalidOrder () { new Matrix ().Shear (-1, 1, (MatrixOrder) Int32.MinValue); } [Test] public void TransformPoints () { Matrix matrix = new Matrix (2, 4, 6, 8, 10, 12); PointF [] pointsF = new PointF [] {new PointF (2, 4), new PointF (4, 8)}; matrix.TransformPoints (pointsF); Assert.AreEqual (38, pointsF[0].X, "K#1"); Assert.AreEqual (52, pointsF[0].Y, "K#2"); Assert.AreEqual (66, pointsF[1].X, "K#3"); Assert.AreEqual (92, pointsF[1].Y, "K#4"); Point [] points = new Point [] {new Point (2, 4), new Point (4, 8)}; matrix.TransformPoints (points); Assert.AreEqual (38, pointsF[0].X, "K#5"); Assert.AreEqual (52, pointsF[0].Y, "K#6"); Assert.AreEqual (66, pointsF[1].X, "K#7"); Assert.AreEqual (92, pointsF[1].Y, "K#8"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void TransformPoints_Point_Null () { new Matrix ().TransformPoints ((Point[]) null); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void TransformPoints_PointF_Null () { new Matrix ().TransformPoints ((PointF[]) null); } [Test] [ExpectedException (typeof (ArgumentException))] public void TransformPoints_Point_Empty () { new Matrix ().TransformPoints (new Point[0]); } [Test] [ExpectedException (typeof (ArgumentException))] public void TransformPoints_PointF_Empty () { new Matrix ().TransformPoints (new PointF[0]); } [Test] public void TransformVectors () { Matrix matrix = new Matrix (2, 4, 6, 8, 10, 12); PointF [] pointsF = new PointF [] {new PointF (2, 4), new PointF (4, 8)}; matrix.TransformVectors (pointsF); Assert.AreEqual (28, pointsF[0].X, "N#1"); Assert.AreEqual (40, pointsF[0].Y, "N#2"); Assert.AreEqual (56, pointsF[1].X, "N#3"); Assert.AreEqual (80, pointsF[1].Y, "N#4"); Point [] points = new Point [] {new Point (2, 4), new Point (4, 8)}; matrix.TransformVectors (points); Assert.AreEqual (28, pointsF[0].X, "N#5"); Assert.AreEqual (40, pointsF[0].Y, "N#6"); Assert.AreEqual (56, pointsF[1].X, "N#7"); Assert.AreEqual (80, pointsF[1].Y, "N#8"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void TransformVectors_Point_Null () { new Matrix ().TransformVectors ((Point[]) null); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void TransformVectors_PointF_Null () { new Matrix ().TransformVectors ((PointF[]) null); } [Test] [ExpectedException (typeof (ArgumentException))] public void TransformVectors_Point_Empty () { new Matrix ().TransformVectors (new Point[0]); } [Test] [ExpectedException (typeof (ArgumentException))] public void TransformVectors_PointF_Empty () { new Matrix ().TransformVectors (new PointF[0]); } [Test] public void Translate () { Matrix matrix = new Matrix (2, 4, 6, 8, 10, 12); matrix.Translate (5, 10); Assert.AreEqual (2, matrix.Elements[0], "Y#1"); Assert.AreEqual (4, matrix.Elements[1], "Y#2"); Assert.AreEqual (6, matrix.Elements[2], "Y#3"); Assert.AreEqual (8, matrix.Elements[3], "Y#4"); Assert.AreEqual (80, matrix.Elements[4], "Y#5"); Assert.AreEqual (112, matrix.Elements[5], "Y#6"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Translate_InvalidOrder () { new Matrix ().Translate (-1, 1, (MatrixOrder) Int32.MinValue); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void VectorTransformPoints_Null () { new Matrix ().VectorTransformPoints ((Point[]) null); } [Test] [ExpectedException (typeof (ArgumentException))] public void VectorTransformPoints_Empty () { new Matrix ().VectorTransformPoints (new Point[0]); } } }
31.50073
110
0.642367
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Drawing/Test/System.Drawing.Drawing2D/TestMatrix.cs
21,578
C#
#pragma checksum "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\MyNotification\MyNotificaton.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e894d2893fe49cdd4b4ed1fc8c4bc34e994be0b9" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_MyNotification_MyNotificaton), @"mvc.1.0.view", @"/Views/MyNotification/MyNotificaton.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\_ViewImports.cshtml" using DotNetNote; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\_ViewImports.cshtml" using DotNetNote.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e894d2893fe49cdd4b4ed1fc8c4bc34e994be0b9", @"/Views/MyNotification/MyNotificaton.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"0daafac8a85ee43e3c34bc74f0c87c74269b2818", @"/Views/_ViewImports.cshtml")] public class Views_MyNotification_MyNotificaton : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\MyNotification\MyNotificaton.cshtml" ViewData["Title"] = "알림이 있으면 출력"; #line default #line hidden #nullable disable WriteLiteral("<h2>"); #nullable restore #line 4 "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\MyNotification\MyNotificaton.cshtml" Write(ViewData["Title"]); #line default #line hidden #nullable disable WriteLiteral("</h2>\r\n"); WriteLiteral("<hr />\r\n<div>\r\n <input type=\"button\" id=\"btnCheck\" value=\"알림이있는지 확인\" />\r\n <input type=\"hidden\" id=\"hdnUserId\""); BeginWriteAttribute("value", " value=\"", 332, "\"", 355, 1); #nullable restore #line 11 "D:\VsTest2\ASPNETCoreFundPart3\DotNetNote\Views\MyNotification\MyNotificaton.cshtml" WriteAttributeValue("", 340, ViewBag.UserId, 340, 15, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(" />\r\n</div>\r\n"); DefineSection("Scripts", async() => { WriteLiteral(@" <script> $(function () { $(""#btnCheck"").click(function () { var userId = parseInt($(""#hdnUserId"").val(), 10); // 웹 API 호출 $.get(""/api/IsNotification?userId="" + userId).done(function (data) { if (data) { alert(""알림이 있습니다.""); } else { alert(""알림이 없습니다.""); } }); }); }); </script> "); } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
42.51
200
0.68478
[ "MIT" ]
banminseok/ASPNETCoreFundPart3
DotNetNote/obj/Debug/net5.0/Razor/Views/MyNotification/MyNotificaton.cshtml.g.cs
4,317
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("RSAPPK")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RSAPPK")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("0df226fc-83b4-417b-9991-b10298ec3eda")] // 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.297297
84
0.745652
[ "MIT" ]
AaronAmberman/RSAPPK
RSAPPK/RSAPPK/Properties/AssemblyInfo.cs
1,383
C#
namespace Iracle { public class Identity { public Identity(string userString) { var split = userString.Split('!', '@'); Nick = split[0]; User = split[1]; Host = split[2]; } public string Nick { get; } public string User { get; } public string Host { get; } } }
18.65
51
0.466488
[ "MIT" ]
connellw/Iracle
src/Iracle/Irc/Identity.cs
375
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.Threading; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class PoolBlockPeriodTest { private const string AzureEndpointSample = "nonexistent.database.windows.net"; private const string AzureChinaEnpointSample = "nonexistent.database.chinacloudapi.cn"; private const string AzureUSGovernmentEndpointSample = "nonexistent.database.usgovcloudapi.net"; private const string AzureGermanEndpointSample = "nonexistent.database.cloudapi.de"; private const string AzureEndpointMixedCaseSample = "nonexistent.database.WINDOWS.net"; private const string NonExistentServer = "nonexistentserver"; private const string PolicyKeyword = "PoolBlockingPeriod"; private const string PortNumber = "1234"; private const string InstanceName = "InstanceName"; private const int ConnectionTimeout = 15; private const int CompareMargin = 2; [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), /* [ActiveIssue(33930)] */ nameof(DataTestUtility.IsUsingNativeSNI))] [InlineData("Azure with Default Policy must Disable blocking (*.database.windows.net)", new object[] { AzureEndpointSample })] [InlineData("Azure with Default Policy must Disable blocking (*.database.chinacloudapi.cn)", new object[] { AzureChinaEnpointSample })] [InlineData("Azure with Default Policy must Disable blocking (*.database.usgovcloudapi.net)", new object[] { AzureUSGovernmentEndpointSample })] [InlineData("Azure with Default Policy must Disable blocking (*.database.cloudapi.de)", new object[] { AzureGermanEndpointSample })] [InlineData("Azure with Default Policy must Disable blocking (MIXED CASES) (*.database.WINDOWS.net)", new object[] { AzureEndpointMixedCaseSample })] [InlineData("Azure with Default Policy must Disable blocking (PORT) (*.database.WINDOWS.net,1234)", new object[] { AzureEndpointMixedCaseSample + "," + PortNumber })] [InlineData("Azure with Default Policy must Disable blocking (INSTANCE NAME) (*.database.WINDOWS.net,1234\\InstanceName)", new object[] { AzureEndpointMixedCaseSample + "," + PortNumber + "\\" + InstanceName })] [InlineData("Azure with Auto Policy must Disable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.Auto })] [InlineData("Azure with Always Policy must Enable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.AlwaysBlock })] [InlineData("Azure with Never Policy must Disable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.NeverBlock })] public void TestAzureBlockingPeriod(string description, object[] Params) { _ = description; string serverName = Params[0] as string; PoolBlockingPeriod? policy = null; if (Params.Length > 1) { policy = (PoolBlockingPeriod)Params[1]; } string connString = CreateConnectionString(serverName, policy); PoolBlockingPeriodAzureTest(connString, policy); } [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), /* [ActiveIssue(33930)] */ nameof(DataTestUtility.IsUsingNativeSNI))] [InlineData("NonAzure with Default Policy must Enable blocking", new object[] { NonExistentServer })] [InlineData("NonAzure with Auto Policy must Enable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.Auto })] [InlineData("NonAzure with Always Policy must Enable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.AlwaysBlock })] [InlineData("NonAzure with Never Policy must Disable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.NeverBlock })] [InlineData("NonAzure (which contains azure endpoint - nonexistent.WINDOWS.net) with Default Policy must Enable Blocking", new object[] { "nonexistent.windows.net" })] [InlineData("NonAzure (which contains azure endpoint - nonexistent.database.windows.net.else) with Default Policy must Enable Blocking", new object[] { "nonexistent.database.windows.net.else" })] public void TestNonAzureBlockingPeriod(string description, object[] Params) { _ = description; string serverName = Params[0] as string; PoolBlockingPeriod? policy = null; if (Params.Length > 1) { policy = (PoolBlockingPeriod)Params[1]; } string connString = CreateConnectionString(serverName, policy); PoolBlockingPeriodNonAzureTest(connString, policy); } [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), /* [ActiveIssue(33930)] */ nameof(DataTestUtility.IsUsingNativeSNI))] [InlineData("Test policy with Auto (lowercase)", "auto")] [InlineData("Test policy with Auto (PascalCase)", "Auto")] [InlineData("Test policy with Always (lowercase)", "alwaysblock")] [InlineData("Test policy with Always (PascalCase)", "AlwaysBlock")] [InlineData("Test policy with Never (lowercase)", "neverblock")] [InlineData("Test policy with Never (PascalCase)", "NeverBlock")] public void TestSetPolicyWithVariations(string description, string policyString) { _ = description; PoolBlockingPeriod? policy = null; if (policyString.ToLower().Contains("auto")) { policy = PoolBlockingPeriod.Auto; } else if (policyString.ToLower().Contains("always")) { policy = PoolBlockingPeriod.AlwaysBlock; } else { policy = PoolBlockingPeriod.NeverBlock; } string connString = $"{CreateConnectionString(AzureEndpointSample, null)};{PolicyKeyword}={policyString}"; PoolBlockingPeriodAzureTest(connString, policy); } private void PoolBlockingPeriodNonAzureTest(string connStr, PoolBlockingPeriod? policy) { int firstErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr); int secondErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr); switch (policy) { case PoolBlockingPeriod.Auto: case PoolBlockingPeriod.AlwaysBlock: Assert.InRange(secondErrorTimeInSecs, 0, firstErrorTimeInSecs + CompareMargin); break; case PoolBlockingPeriod.NeverBlock: Assert.InRange(secondErrorTimeInSecs, 1, 2 * ConnectionTimeout); break; } } private void PoolBlockingPeriodAzureTest(string connStr, PoolBlockingPeriod? policy) { int firstErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr); int secondErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr); switch (policy) { case PoolBlockingPeriod.AlwaysBlock: Assert.InRange(secondErrorTimeInSecs, 0, firstErrorTimeInSecs + CompareMargin); break; case PoolBlockingPeriod.Auto: case PoolBlockingPeriod.NeverBlock: Assert.InRange(secondErrorTimeInSecs, 1, 2 * ConnectionTimeout); break; } } private int GetConnectionOpenTimeInSeconds(string connString) { using (SqlConnection conn = new SqlConnection(connString)) { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); try { stopwatch.Start(); conn.Open(); throw new Exception("Connection Open must expect an exception"); } catch (Exception) { stopwatch.Stop(); } return stopwatch.Elapsed.Seconds; } } public string CreateConnectionString(string serverName, PoolBlockingPeriod? policy) { SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder(); connBuilder.DataSource = serverName; connBuilder.UserID = "user"; connBuilder.Password = "password"; connBuilder.InitialCatalog = "test"; connBuilder.PersistSecurityInfo = true; if (policy != null) { connBuilder.PoolBlockingPeriod = policy.Value; } return connBuilder.ToString(); } } }
54.4
219
0.650735
[ "MIT" ]
AntonLandor/corefx
src/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/PoolBlockPeriodTest.netcoreapp.cs
8,978
C#
/* * The MIT License (MIT) * * Copyright (c) 2014 Andrew B. Johnson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Linq; namespace DataSwallow.Utilities { /// <summary> /// An extension class for IEnumerable{T}'s /// </summary> public static class EnumerableExtensions { #region public methods /// <summary> /// Calculates the sequence's hash code /// </summary> /// <typeparam name="TElement">The type of the element.</typeparam> /// <param name="this">The IEnumerable{TElement}</param> /// <returns>The hash code of this sequence</returns> public static int GetSequenceHashCode<TElement>(this IEnumerable<TElement> @this) { return @this.Aggregate<TElement, int>(0, HashCodeFolder<TElement>); } /// <summary> /// Returns an object as an IEnumerable of one element (itself) /// </summary> /// <typeparam name="T">The type of this</typeparam> /// <param name="t">This reference</param> /// <returns>An IEnumerable with this as its only element</returns> public static IEnumerable<T> AsEnumerable<T>(this T t) { yield return t; } #endregion #region private methods private static int HashCodeFolder<TElement>(int accumulate, TElement element) { return accumulate ^ element.GetHashCode(); } #endregion } }
39.104478
90
0.65229
[ "MIT" ]
helios2k6/Data-Swallow
Data Swallow/Utilities/EnumerableExtensions.cs
2,622
C#
/* Copyright 2018 Alexandre Pires - [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using PDFOnlineSignature.Models; namespace PDFOnlineSignature.Core { public static class FileManager { static IConfiguration Configuration { get; set; } public static string DocumentRoot { get { return Configuration.GetValue<string> ("FileManager:DocumentRoot", "DOCUMENT_ROOT"); } } public static void Init (IConfiguration configuration) { Configuration = configuration; if (!Directory.Exists (DocumentRoot)) Directory.CreateDirectory (DocumentRoot); } public async static Task<Document> StoreFile (IFormFile file) { Document document = new Document (); document.Uuid = Guid.NewGuid ().ToString (); document.Name = file.FileName; document.Size = file.Length; document.CreationdDate = DateTime.UtcNow; document.MimeType = "application/pdf"; using (var stream = new FileStream (DocumentRoot + "/" + document.Uuid, FileMode.Create)) { await file.CopyToAsync (stream); } return document; } public static async Task<MemoryStream> GetFile (Document document) { var path = DocumentRoot + "/" + document.Uuid; if (document.Signed == true) { path += "-signed"; } var memory = new MemoryStream (); using (var stream = new FileStream (path, FileMode.Open)) { await stream.CopyToAsync (memory); } memory.Position = 0; return memory; } } }
36.8125
103
0.652292
[ "MIT" ]
a13labs/pdf-online-signature
Core/FileManager.cs
2,945
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more information) /// </summary> internal partial class JobOperations : IServiceOperations<AutomationManagementClient>, IJobOperations { /// <summary> /// Initializes a new instance of the JobOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal JobOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a job of the runbook. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create job operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create job operation. /// </returns> public async Task<JobCreateResponse> CreateAsync(string resourceGroupName, string automationAccount, JobCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.Runbook == null) { throw new ArgumentNullException("parameters.Properties.Runbook"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobs/"; url = url + Guid.NewGuid().ToString(); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject jobCreateParametersValue = new JObject(); requestDoc = jobCreateParametersValue; JObject propertiesValue = new JObject(); jobCreateParametersValue["properties"] = propertiesValue; JObject runbookValue = new JObject(); propertiesValue["runbook"] = runbookValue; if (parameters.Properties.Runbook.Name != null) { runbookValue["name"] = parameters.Properties.Runbook.Name; } if (parameters.Properties.Parameters != null) { if (parameters.Properties.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Parameters).IsInitialized) { JObject parametersDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.Parameters) { string parametersKey = pair.Key; string parametersValue = pair.Value; parametersDictionary[parametersKey] = parametersValue; } propertiesValue["parameters"] = parametersDictionary; } } if (parameters.Properties.RunOn != null) { propertiesValue["runOn"] = parameters.Properties.RunOn; } if (parameters.Name != null) { jobCreateParametersValue["name"] = parameters.Name; } if (parameters.Location != null) { jobCreateParametersValue["location"] = parameters.Location; } if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair2 in parameters.Tags) { string tagsKey = pair2.Key; string tagsValue = pair2.Value; tagsDictionary[tagsKey] = tagsValue; } jobCreateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Job jobInstance = new Job(); result.Job = jobInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JobProperties propertiesInstance = new JobProperties(); jobInstance.Properties = propertiesInstance; JToken runbookValue2 = propertiesValue2["runbook"]; if (runbookValue2 != null && runbookValue2.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue = runbookValue2["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); runbookInstance.Name = nameInstance; } } JToken startedByValue = propertiesValue2["startedBy"]; if (startedByValue != null && startedByValue.Type != JTokenType.Null) { string startedByInstance = ((string)startedByValue); propertiesInstance.StartedBy = startedByInstance; } JToken runOnValue = propertiesValue2["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); propertiesInstance.RunOn = runOnInstance; } JToken jobIdValue = propertiesValue2["jobId"]; if (jobIdValue != null && jobIdValue.Type != JTokenType.Null) { Guid jobIdInstance = Guid.Parse(((string)jobIdValue)); propertiesInstance.JobId = jobIdInstance; } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken statusValue = propertiesValue2["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken statusDetailsValue = propertiesValue2["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); propertiesInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = propertiesValue2["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken endTimeValue = propertiesValue2["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); propertiesInstance.EndTime = endTimeInstance; } JToken exceptionValue = propertiesValue2["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); propertiesInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = propertiesValue2["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); propertiesInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)propertiesValue2["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey2 = ((string)property.Name); string parametersValue2 = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey2, parametersValue2); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get job operation. /// </returns> public async Task<JobGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/Jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Job jobInstance = new Job(); result.Job = jobInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobProperties propertiesInstance = new JobProperties(); jobInstance.Properties = propertiesInstance; JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue = runbookValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); runbookInstance.Name = nameInstance; } } JToken startedByValue = propertiesValue["startedBy"]; if (startedByValue != null && startedByValue.Type != JTokenType.Null) { string startedByInstance = ((string)startedByValue); propertiesInstance.StartedBy = startedByInstance; } JToken runOnValue = propertiesValue["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); propertiesInstance.RunOn = runOnInstance; } JToken jobIdValue = propertiesValue["jobId"]; if (jobIdValue != null && jobIdValue.Type != JTokenType.Null) { Guid jobIdInstance = Guid.Parse(((string)jobIdValue)); propertiesInstance.JobId = jobIdInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken statusDetailsValue = propertiesValue["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); propertiesInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken endTimeValue = propertiesValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); propertiesInstance.EndTime = endTimeInstance; } JToken exceptionValue = propertiesValue["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); propertiesInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = propertiesValue["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); propertiesInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the job output identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get job output operation. /// </returns> public async Task<JobGetOutputResponse> GetOutputAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "GetOutputAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/Jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); url = url + "/output"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobGetOutputResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobGetOutputResponse(); result.Output = responseContent; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the runbook content of the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get runbook content of the job operation. /// </returns> public async Task<JobGetRunbookContentResponse> GetRunbookContentAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "GetRunbookContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/Jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); url = url + "/runbookContent"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobGetRunbookContentResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobGetRunbookContentResponse(); result.Content = responseContent; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<JobListResponse> ListAsync(string resourceGroupName, string automationAccount, JobListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobs"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.StartTime != null) { odataFilter.Add("properties/startTime ge " + Uri.EscapeDataString(parameters.StartTime)); } if (parameters != null && parameters.EndTime != null) { odataFilter.Add("properties/endTime le " + Uri.EscapeDataString(parameters.EndTime)); } if (parameters != null && parameters.Status != null) { odataFilter.Add("properties/status eq '" + Uri.EscapeDataString(parameters.Status) + "'"); } if (parameters != null && parameters.RunbookName != null) { odataFilter.Add("properties/runbook/name eq '" + Uri.EscapeDataString(parameters.RunbookName) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(" and ", odataFilter)); } queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Job jobInstance = new Job(); result.Jobs.Add(jobInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobProperties propertiesInstance = new JobProperties(); jobInstance.Properties = propertiesInstance; JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue = runbookValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); runbookInstance.Name = nameInstance; } } JToken startedByValue = propertiesValue["startedBy"]; if (startedByValue != null && startedByValue.Type != JTokenType.Null) { string startedByInstance = ((string)startedByValue); propertiesInstance.StartedBy = startedByInstance; } JToken runOnValue = propertiesValue["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); propertiesInstance.RunOn = runOnInstance; } JToken jobIdValue = propertiesValue["jobId"]; if (jobIdValue != null && jobIdValue.Type != JTokenType.Null) { Guid jobIdInstance = Guid.Parse(((string)jobIdValue)); propertiesInstance.JobId = jobIdInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken statusDetailsValue = propertiesValue["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); propertiesInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken endTimeValue = propertiesValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); propertiesInstance.EndTime = endTimeInstance; } JToken exceptionValue = propertiesValue["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); propertiesInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = propertiesValue["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); propertiesInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<JobListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Job jobInstance = new Job(); result.Jobs.Add(jobInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobProperties propertiesInstance = new JobProperties(); jobInstance.Properties = propertiesInstance; JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue = runbookValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); runbookInstance.Name = nameInstance; } } JToken startedByValue = propertiesValue["startedBy"]; if (startedByValue != null && startedByValue.Type != JTokenType.Null) { string startedByInstance = ((string)startedByValue); propertiesInstance.StartedBy = startedByInstance; } JToken runOnValue = propertiesValue["runOn"]; if (runOnValue != null && runOnValue.Type != JTokenType.Null) { string runOnInstance = ((string)runOnValue); propertiesInstance.RunOn = runOnInstance; } JToken jobIdValue = propertiesValue["jobId"]; if (jobIdValue != null && jobIdValue.Type != JTokenType.Null) { Guid jobIdInstance = Guid.Parse(((string)jobIdValue)); propertiesInstance.JobId = jobIdInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken statusDetailsValue = propertiesValue["statusDetails"]; if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null) { string statusDetailsInstance = ((string)statusDetailsValue); propertiesInstance.StatusDetails = statusDetailsInstance; } JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken endTimeValue = propertiesValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue); propertiesInstance.EndTime = endTimeInstance; } JToken exceptionValue = propertiesValue["exception"]; if (exceptionValue != null && exceptionValue.Type != JTokenType.Null) { string exceptionInstance = ((string)exceptionValue); propertiesInstance.Exception = exceptionInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken lastStatusModifiedTimeValue = propertiesValue["lastStatusModifiedTime"]; if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue); propertiesInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Resume the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> ResumeAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "ResumeAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); url = url + "/resume"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Stop the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> StopAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "StopAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); url = url + "/stop"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Suspend the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SuspendAsync(string resourceGroupName, string automationAccount, Guid jobId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobId", jobId); TracingAdapter.Enter(invocationId, this, "SuspendAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobs/"; url = url + Uri.EscapeDataString(jobId.ToString()); url = url + "/suspend"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
48.836042
179
0.45267
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Automation/AutomationManagement/Generated/JobOperations.cs
102,165
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace webjob_webapp.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
19.333333
67
0.565517
[ "MIT" ]
firehouse/azure-camp-dec
demo/webjob-demo/webjob-cs-with-webapp/webjob-webapp/Controllers/HomeController.cs
582
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bohc.Parsing.Statements { public class ForeachStatement : BodyStatement { public VarDeclaration vardecl; public Expression expr; public ForeachStatement(VarDeclaration vardecl, Expression expr, Body body) : this(vardecl, expr, new Scope(body)) { } public ForeachStatement(VarDeclaration vardecl, Expression expr, Statement body) : base(body) { this.vardecl = vardecl; ++vardecl.refersto.usageCount; this.expr = expr; } } }
22.958333
82
0.747731
[ "MIT" ]
antonijn/bohc-intermediate
bohc/parsing/statements/ForeachStatement.cs
551
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Jeeves.DocsAgent.Models { /// <summary> /// Contains information about sections. /// </summary> /// <seealso cref="Jeeves.DocsAgent.Models.DocModelBase" /> [DataContract] public class Sections { /// <summary> /// Gets or sets the description. /// </summary> [DataMember(Order = 0)] public string Description { get; set; } /// <summary> /// Gets or sets the sections. /// </summary> [DataMember(Order = 1)] public List<Section> SectionCollection { get; set; } = new List<Section>(); } }
22.961538
77
0.668342
[ "MIT" ]
rajeshaz09/BlazorAOTDemo
src/Jeeves.Docs/Jeeves.DocsAgent.Models/Sections.cs
599
C#
using System; using System.Windows.Forms; using static Vanara.PInvoke.User32; namespace Vanara.Extensions { /// <summary>Extension methods for <see cref="ButtonBase"/>.</summary> public static partial class ButtonExtension { /// <summary>Sets a value that determines if the shield icon is shown on the button to indicate that elevation is required.</summary> /// <param name="btn">The <see cref="ButtonBase"/> instance.</param> /// <param name="required"> /// If set to <see langword="true"/>, the shield icon will be shown on the button. If <see langword="false"/>, the button will /// display normally. /// </param> /// <exception cref="PlatformNotSupportedException">This method is only support on Windows Vista and later.</exception> public static void SetElevationRequiredState(this ButtonBase btn, bool required = true) { if (Environment.OSVersion.Version.Major >= 6) { if (!btn.IsHandleCreated) return; if (required) btn.FlatStyle = FlatStyle.System; SendMessage(btn.Handle, (uint)ButtonMessage.BCM_SETSHIELD, IntPtr.Zero, required ? new IntPtr(1) : IntPtr.Zero); btn.Invalidate(); } else throw new PlatformNotSupportedException(); } } }
40.066667
135
0.717138
[ "MIT" ]
AndreGleichner/Vanara
Windows.Forms/Extensions/ButtonExtension.cs
1,204
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.WindowsAzure.Management.Network.Models; using Microsoft.WindowsAzure.Commands.ServiceManagement.Network.Gateway.Model; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Network.Gateway { [Cmdlet(VerbsCommon.Set, "AzureVirtualNetworkGatewayIPsecParameters"), OutputType(typeof(GatewayGetOperationStatusResponse))] public class SetAzureVirtualNetworkGatewayIPsecParameters : NetworkCmdletBase { [Parameter(Position = 0, Mandatory = true, HelpMessage = "The virtual network gateway id.")] [ValidateGuid] [ValidateNotNullOrEmpty] public string GatewayId { get; set; } [Parameter(Position = 1, Mandatory = true, HelpMessage = "The virtual network gateway connected entityId.")] [ValidateGuid] [ValidateNotNullOrEmpty] public string ConnectedEntityId { get; set; } [Parameter(Position = 2, Mandatory = false, HelpMessage = "The type of encryption that will " + "be used for the connection between the virtual network gateway and the local network. " + "Valid values are RequireEncryption/NoEncryption/AES256/AES128/DES3.")] public string EncryptionType { get; set; } [Parameter(Position = 3, Mandatory = false, HelpMessage = "The PFS gruop that will be used " + "for the connection between the virtual network gateway and the local network. Valid " + "values are PFS1 and None.")] public string PfsGroup { get; set; } [Parameter(Position = 4, Mandatory = false, HelpMessage = "The SA Data Size Kilobytes value " + "is used to determine how many kilobytes of traffic can be sent before the SA for the" + "connection will be renegotiated.")] public int SADataSizeKilobytes { get; set; } [Parameter(Position = 5, Mandatory = false, HelpMessage = "The SA Lifetime Seconds value " + "is used to determine how long (in seconds) this connection's SA will be valid before " + "a new SA will be negotiated.")] public int SALifetimeSeconds { get; set; } public override void ExecuteCmdlet() { WriteObject(Client.SetIPsecParametersV2(GatewayId, ConnectedEntityId, EncryptionType, PfsGroup, SADataSizeKilobytes, SALifetimeSeconds)); } } }
41.02381
150
0.604759
[ "MIT" ]
Andrean/azure-powershell
src/ServiceManagement/Network/Commands.Network/Gateway/SetAzureVirtualNetworkGatewayIPsecParameters.cs
3,365
C#
using System; using System.Collections.Generic; using System.Reactive.Threading.Tasks; using System.Threading.Tasks; using Android.App; using Android.Database; using Android.Provider; using static Android.Manifest; [assembly: UsesPermission("android.permission.ACCESS_MEDIA_LOCATION")] [assembly: UsesPermission(Permission.ReadExternalStorage)] namespace Shiny.MediaSync.Infrastructure { public class MediaGalleryScannerImpl : IMediaGalleryScanner { readonly AndroidContext context; public MediaGalleryScannerImpl(AndroidContext context) => this.context = context; public Task<IEnumerable<MediaAsset>> Query(MediaTypes mediaTypes, DateTimeOffset date) { var tcs = new TaskCompletionSource<IEnumerable<MediaAsset>>(); Task.Run(() => { var uri = MediaStore.Files.GetContentUri("external"); var cursor = this.context.AppContext.ContentResolver.Query( uri, new [] { MediaStore.Files.FileColumns.Id, MediaStore.Files.FileColumns.Data, MediaStore.Files.FileColumns.DateAdded, MediaStore.Files.FileColumns.MediaType, MediaStore.Files.FileColumns.MimeType, MediaStore.Files.FileColumns.Title, MediaStore.Files.FileColumns.Parent, MediaStore.Files.FileColumns.DisplayName, MediaStore.Files.FileColumns.Size }, ToWhereClause(mediaTypes, date), null, $"{MediaStore.Files.FileColumns.DateAdded} DESC" ); var list = new List<MediaAsset>(); while (cursor.MoveToNext()) list.Add(ToAsset(cursor)); tcs.SetResult(list); }); return tcs.Task; } public Task<AccessState> RequestAccess() => this.context .RequestAccess( Permission.ReadExternalStorage, "android.permission.ACCESS_MEDIA_LOCATION" ) .ToTask(); static string ToWhereClause(MediaTypes mediaTypes, DateTimeOffset date) { var filters = new List<string>(4); if (mediaTypes.HasFlag(MediaTypes.Image)) filters.Add($"{MediaStore.Files.FileColumns.MediaType} = {(int)MediaType.Image}"); if (mediaTypes.HasFlag(MediaTypes.Video)) filters.Add($"{MediaStore.Files.FileColumns.MediaType} = {(int)MediaType.Video}"); if (mediaTypes.HasFlag(MediaTypes.Audio)) filters.Add($"{MediaStore.Files.FileColumns.MediaType} = {(int)MediaType.Audio}"); var filter = String.Join(" OR ", filters.ToArray()); return filter; } static MediaAsset ToAsset(ICursor cursor) { var id = cursor.GetInt(cursor.GetColumnIndex(MediaStore.Files.FileColumns.Id)); var type = cursor.GetInt(cursor.GetColumnIndex(MediaStore.Files.FileColumns.MediaType)); var path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Files.FileColumns.Data)); var mediaType = MediaTypes.None; switch (type) { case (int)MediaType.Audio: mediaType = MediaTypes.Audio; break; case (int)MediaType.Image: mediaType = MediaTypes.Image; break; case (int)MediaType.Video: mediaType = MediaTypes.Video; break; } return new MediaAsset( id.ToString(), path, mediaType ); } } }
34.243478
100
0.556374
[ "MIT" ]
DigitalNut/shiny
src/Shiny.MediaSync/Platforms/Android/MediaGalleryScannerImpl.cs
3,940
C#
namespace FastFood.DataProcessor.Dto.Import { using System.ComponentModel.DataAnnotations; public class EmployeeDto { [Required] [StringLength(30), MinLength(3)] public string Name { get; set; } [Required] [Range(15, 80)] public int Age { get; set; } [Required] [StringLength(30), MinLength(3)] public string Position { get; set; } } }
22.473684
48
0.580796
[ "MIT" ]
mayapeneva/DATABASE-Advanced-Entity-Framework
EXAMS/Exam_2017.12.10_FastFood/FastFood.DataProcessor/Dto/Import/EmployeeDto.cs
429
C#
using NBTExplorer.Controllers; using NBTExplorer.Model; using NBTExplorer.Properties; using NBTModel.Interop; using Substrate.Nbt; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Threading; using System.Windows.Forms; namespace NBTExplorer.Windows { public partial class MainForm : Form { private static readonly Dictionary<TagType, int> _tagIconIndex; private readonly NodeTreeController _controller; private IconRegistry _iconRegistry; private string _openFolderPath; private CancelSearchForm _searchForm; private SearchStateWin _searchState; static MainForm() { try { _tagIconIndex = new Dictionary<TagType, int>(); _tagIconIndex[TagType.TAG_BYTE] = 0; _tagIconIndex[TagType.TAG_SHORT] = 1; _tagIconIndex[TagType.TAG_INT] = 2; _tagIconIndex[TagType.TAG_LONG] = 3; _tagIconIndex[TagType.TAG_FLOAT] = 4; _tagIconIndex[TagType.TAG_DOUBLE] = 5; _tagIconIndex[TagType.TAG_BYTE_ARRAY] = 6; _tagIconIndex[TagType.TAG_STRING] = 7; _tagIconIndex[TagType.TAG_LIST] = 8; _tagIconIndex[TagType.TAG_COMPOUND] = 9; _tagIconIndex[TagType.TAG_INT_ARRAY] = 14; _tagIconIndex[TagType.TAG_SHORT_ARRAY] = 16; _tagIconIndex[TagType.TAG_LONG_ARRAY] = 17; } catch (Exception e) { Program.StaticInitFailure(e); } } public MainForm() { InitializeComponent(); InitializeIconRegistry(); FormHandlers.Register(); NbtClipboardController.Initialize(new NbtClipboardControllerWin()); _controller = new NodeTreeController(_nodeTree); _controller.ConfirmAction += _controller_ConfirmAction; _controller.SelectionInvalidated += _controller_SelectionInvalidated; FormClosing += MainForm_Closing; _nodeTree.BeforeExpand += _nodeTree_BeforeExpand; _nodeTree.AfterCollapse += _nodeTree_AfterCollapse; _nodeTree.AfterSelect += _nodeTree_AfterSelect; _nodeTree.NodeMouseDoubleClick += _nodeTree_NodeMouseDoubleClick; _nodeTree.NodeMouseClick += _nodeTree_NodeMouseClick; _nodeTree.DragEnter += _nodeTree_DragEnter; _nodeTree.DragDrop += _nodeTree_DragDrop; _buttonOpen.Click += _buttonOpen_Click; _buttonOpenFolder.Click += _buttonOpenFolder_Click; _buttonSave.Click += _buttonSave_Click; _buttonEdit.Click += _buttonEdit_Click; _buttonRename.Click += _buttonRename_Click; _buttonDelete.Click += _buttonDelete_Click; _buttonCopy.Click += _buttonCopy_Click; _buttonCut.Click += _buttonCut_Click; _buttonPaste.Click += _buttonPaste_Click; _buttonAddTagByte.Click += _buttonAddTagByte_Click; _buttonAddTagByteArray.Click += _buttonAddTagByteArray_Click; _buttonAddTagCompound.Click += _buttonAddTagCompound_Click; _buttonAddTagDouble.Click += _buttonAddTagDouble_Click; _buttonAddTagFloat.Click += _buttonAddTagFloat_Click; _buttonAddTagInt.Click += _buttonAddTagInt_Click; _buttonAddTagIntArray.Click += _buttonAddTagIntArray_Click; _buttonAddTagList.Click += _buttonAddTagList_Click; _buttonAddTagLong.Click += _buttonAddTagLong_Click; _buttonAddTagLongArray.Click += _buttonAddTagLongArray_Click; _buttonAddTagShort.Click += _buttonAddTagShort_Click; _buttonAddTagString.Click += _buttonAddTagString_Click; _buttonFindNext.Click += _buttonFindNext_Click; _menuItemOpen.Click += _menuItemOpen_Click; _menuItemOpenFolder.Click += _menuItemOpenFolder_Click; _menuItemOpenMinecraftSaveFolder.Click += _menuItemOpenMinecraftSaveFolder_Click; _menuItemSave.Click += _menuItemSave_Click; _menuItemExit.Click += _menuItemExit_Click; _menuItemEditValue.Click += _menuItemEditValue_Click; _menuItemRename.Click += _menuItemRename_Click; _menuItemDelete.Click += _menuItemDelete_Click; _menuItemCopy.Click += _menuItemCopy_Click; _menuItemCut.Click += _menuItemCut_Click; _menuItemPaste.Click += _menuItemPaste_Click; _menuItemFind.Click += _menuItemFind_Click; _menuItemFindNext.Click += _menuItemFindNext_Click; _menuItemAbout.Click += _menuItemAbout_Click; _menuItemOpenInExplorer.Click += _menuItemOpenInExplorer_Click; var args = Environment.GetCommandLineArgs(); if (args.Length > 1) { var paths = new string[args.Length - 1]; Array.Copy(args, 1, paths, 0, paths.Length); OpenPaths(paths); } else { OpenMinecraftDirectory(); } UpdateOpenMenu(); } private void _menuItemOpenInExplorer_Click(object sender, EventArgs e) { if (_nodeTree.SelectedNode.Tag is DirectoryDataNode) { var ddNode = _nodeTree.SelectedNode.Tag as DirectoryDataNode; try { var path = (!Interop.IsWindows ? "file://" : "") + ddNode.NodeDirPath; Process.Start(path); } catch (Win32Exception ex) { MessageBox.Show(ex.Message, "Can't open directory", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void InitializeIconRegistry() { _iconRegistry = new IconRegistry(); _iconRegistry.DefaultIcon = 15; _iconRegistry.Register(typeof(TagByteDataNode), 0); _iconRegistry.Register(typeof(TagShortDataNode), 1); _iconRegistry.Register(typeof(TagIntDataNode), 2); _iconRegistry.Register(typeof(TagLongDataNode), 3); _iconRegistry.Register(typeof(TagFloatDataNode), 4); _iconRegistry.Register(typeof(TagDoubleDataNode), 5); _iconRegistry.Register(typeof(TagByteArrayDataNode), 6); _iconRegistry.Register(typeof(TagStringDataNode), 7); _iconRegistry.Register(typeof(TagListDataNode), 8); _iconRegistry.Register(typeof(TagCompoundDataNode), 9); _iconRegistry.Register(typeof(RegionChunkDataNode), 9); _iconRegistry.Register(typeof(DirectoryDataNode), 10); _iconRegistry.Register(typeof(RegionFileDataNode), 11); _iconRegistry.Register(typeof(CubicRegionDataNode), 11); _iconRegistry.Register(typeof(NbtFileDataNode), 12); _iconRegistry.Register(typeof(TagIntArrayDataNode), 14); _iconRegistry.Register(typeof(TagShortArrayDataNode), 16); } private void OpenFile() { if (!ConfirmAction("Open new file anyway?")) return; using (var ofd = new OpenFileDialog { RestoreDirectory = true, Multiselect = true, Filter = "All Files|*|NBT Files (*.dat, *.schematic)|*.dat;*.nbt;*.schematic;*.schem|Region Files (*.mca, *.mcr)|*.mca;*.mcr", FilterIndex = 0, }) { if (ofd.ShowDialog() == DialogResult.OK) { OpenPaths(ofd.FileNames); } } UpdateUI(); } private void OpenFolder() { if (!ConfirmAction("Open new folder anyway?")) return; if ((ModifierKeys & Keys.Control) > 0 && (ModifierKeys & Keys.Shift) == 0) using (var ofd = new OpenFileDialog()) { ofd.Title = "Select any file in the directory to open"; ofd.Filter = "All files (*.*)|*.*"; if (_openFolderPath != null) ofd.InitialDirectory = _openFolderPath; if (ofd.ShowDialog() == DialogResult.OK) { _openFolderPath = Path.GetDirectoryName(ofd.FileName); OpenPaths(new[] { _openFolderPath }); } } else using (var ofd = new FolderBrowserDialog()) { if (_openFolderPath != null) ofd.SelectedPath = _openFolderPath; if (ofd.ShowDialog() == DialogResult.OK) { _openFolderPath = ofd.SelectedPath; OpenPaths(new[] { ofd.SelectedPath }); } } UpdateUI(); } private void OpenPaths(string[] paths) { var failCount = _controller.OpenPaths(paths); foreach (var path in paths) if (Directory.Exists(path)) AddPathToHistory(GetRecentDirectories(), path); else if (File.Exists(path)) AddPathToHistory(GetRecentFiles(), path); UpdateUI(); UpdateOpenMenu(); if (failCount > 0) MessageBox.Show("One or more selected files failed to open."); } private StringCollection GetRecentFiles() { try { return Settings.Default.RecentFiles; } catch { return null; } } private StringCollection GetRecentDirectories() { try { return Settings.Default.RecentDirectories; } catch { return null; } } private void OpenMinecraftDirectory() { if (!ConfirmAction("Open Minecraft save folder anyway?")) return; try { var path = Environment.ExpandEnvironmentVariables("%APPDATA%"); if (!Directory.Exists(path)) path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); path = Path.Combine(path, ".minecraft"); path = Path.Combine(path, "saves"); if (!Directory.Exists(path)) path = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); OpenPaths(new[] { path }); } catch (Exception e) { MessageBox.Show("Could not open default Minecraft save directory"); Console.WriteLine(e.Message); try { OpenPaths(new[] { Directory.GetCurrentDirectory() }); } catch (Exception) { MessageBox.Show( "Could not open current directory, this tool is probably not compatible with your platform."); Console.WriteLine(e.Message); Application.Exit(); } } UpdateUI(); } private TreeNode CreateUnexpandedNode(DataNode node) { var frontNode = new TreeNode(node.NodeDisplay); frontNode.ImageIndex = _iconRegistry.Lookup(node.GetType()); frontNode.SelectedImageIndex = frontNode.ImageIndex; frontNode.Tag = node; //frontNode.ContextMenuStrip = BuildNodeContextMenu(node); if (node.HasUnexpandedChildren || node.Nodes.Count > 0) frontNode.Nodes.Add(new TreeNode()); return frontNode; } private void ExpandNode(TreeNode node) { _controller.ExpandNode(node); UpdateUI(node.Tag as DataNode); } private void CollapseNode(TreeNode node) { _controller.CollapseNode(node); UpdateUI(node.Tag as DataNode); } private bool ConfirmExit() { if (_controller.CheckModifications()) if (MessageBox.Show("You currently have unsaved changes. Close anyway?", "Unsaved Changes", MessageBoxButtons.OKCancel) != DialogResult.OK) return false; return true; } private bool ConfirmAction(string actionMessage) { if (_controller.CheckModifications()) if (MessageBox.Show("You currently have unsaved changes. " + actionMessage, "Unsaved Changes", MessageBoxButtons.OKCancel) != DialogResult.OK) return false; return true; } private void _controller_ConfirmAction(object sender, MessageBoxEventArgs e) { if (_controller.CheckModifications()) if (MessageBox.Show("You currently have unsaved changes. " + e.Message, "Unsaved Changes", MessageBoxButtons.OKCancel) != DialogResult.OK) e.Cancel = true; } private void SearchNode(TreeNode node) { if (node == null || !(node.Tag is DataNode)) return; var dataNode = node.Tag as DataNode; if (!dataNode.CanSearchNode) return; var form = new Find(); if (form.ShowDialog() != DialogResult.OK) return; _searchState = new SearchStateWin(this) { RootNode = dataNode, SearchName = form.NameToken, SearchValue = form.ValueToken, DiscoverCallback = SearchDiscoveryCallback, CollapseCallback = SearchCollapseCallback, EndCallback = SearchEndCallback }; SearchNextNode(); } private void SearchNextNode() { if (_searchState == null) return; var worker = new SearchWorker(_searchState); var t = new Thread(worker.Run); t.IsBackground = true; t.Start(); _searchForm = new CancelSearchForm(); if (_searchForm.ShowDialog(this) == DialogResult.Cancel) { worker.Cancel(); _searchState = null; UpdateUI(); } t.Join(); } public void SearchDiscoveryCallback(DataNode node) { _controller.SelectNode(node); if (_searchForm != null) { _searchForm.DialogResult = DialogResult.OK; _searchForm = null; } } public void SearchCollapseCallback(DataNode node) { _controller.CollapseBelow(node); } public void SearchEndCallback(DataNode node) { if (_searchForm != null) { _searchForm.DialogResult = DialogResult.OK; _searchForm = null; } _searchState = null; UpdateUI(); MessageBox.Show("End of results"); } private void UpdateUI() { var selected = _nodeTree.SelectedNode; if (_nodeTree.SelectedNodes.Count > 1) { UpdateUI(_nodeTree.SelectedNodes); } else if (selected != null && selected.Tag is DataNode) { UpdateUI(selected.Tag as DataNode); } else { DisableButtons(_buttonAddTagByte, _buttonAddTagByteArray, _buttonAddTagCompound, _buttonAddTagDouble, _buttonAddTagFloat, _buttonAddTagInt, _buttonAddTagIntArray, _buttonAddTagList, _buttonAddTagLong, _buttonAddTagLongArray, _buttonAddTagShort, _buttonAddTagString, _buttonCopy, _buttonCut, _buttonDelete, _buttonEdit, _buttonPaste, _buttonRefresh, _buttonRename); _buttonSave.Enabled = _controller.CheckModifications(); _buttonFindNext.Enabled = false; DisableMenuItems(_menuItemCopy, _menuItemCut, _menuItemDelete, _menuItemEditValue, _menuItemPaste, _menuItemRefresh, _menuItemRename, _menuItemMoveUp, _menuItemMoveDown); _menuItemSave.Enabled = _buttonSave.Enabled; _menuItemFind.Enabled = false; _menuItemFindNext.Enabled = _searchState != null; } } private void DisableButtons(params ToolStripButton[] buttons) { foreach (var button in buttons) button.Enabled = false; } private void DisableMenuItems(params ToolStripMenuItem[] buttons) { foreach (var button in buttons) button.Enabled = false; } private void UpdateUI(DataNode node) { if (node == null) return; _buttonAddTagByte.Enabled = node.CanCreateTag(TagType.TAG_BYTE); _buttonAddTagByteArray.Enabled = node.CanCreateTag(TagType.TAG_BYTE_ARRAY); _buttonAddTagCompound.Enabled = node.CanCreateTag(TagType.TAG_COMPOUND); _buttonAddTagDouble.Enabled = node.CanCreateTag(TagType.TAG_DOUBLE); _buttonAddTagFloat.Enabled = node.CanCreateTag(TagType.TAG_FLOAT); _buttonAddTagInt.Enabled = node.CanCreateTag(TagType.TAG_INT); _buttonAddTagIntArray.Enabled = node.CanCreateTag(TagType.TAG_INT_ARRAY); _buttonAddTagList.Enabled = node.CanCreateTag(TagType.TAG_LIST); _buttonAddTagLong.Enabled = node.CanCreateTag(TagType.TAG_LONG); _buttonAddTagLongArray.Enabled = node.CanCreateTag(TagType.TAG_LONG_ARRAY); _buttonAddTagShort.Enabled = node.CanCreateTag(TagType.TAG_SHORT); _buttonAddTagString.Enabled = node.CanCreateTag(TagType.TAG_STRING); _buttonSave.Enabled = _controller.CheckModifications(); _buttonCopy.Enabled = node.CanCopyNode && NbtClipboardController.IsInitialized; _buttonCut.Enabled = node.CanCutNode && NbtClipboardController.IsInitialized; _buttonDelete.Enabled = node.CanDeleteNode; _buttonEdit.Enabled = node.CanEditNode; _buttonFindNext.Enabled = node.CanSearchNode || _searchState != null; _buttonPaste.Enabled = node.CanPasteIntoNode && NbtClipboardController.IsInitialized; _buttonRename.Enabled = node.CanRenameNode; _buttonRefresh.Enabled = node.CanRefreshNode; _menuItemSave.Enabled = _buttonSave.Enabled; _menuItemCopy.Enabled = node.CanCopyNode && NbtClipboardController.IsInitialized; _menuItemCut.Enabled = node.CanCutNode && NbtClipboardController.IsInitialized; _menuItemDelete.Enabled = node.CanDeleteNode; _menuItemEditValue.Enabled = node.CanEditNode; _menuItemFind.Enabled = node.CanSearchNode; _menuItemPaste.Enabled = node.CanPasteIntoNode && NbtClipboardController.IsInitialized; _menuItemRename.Enabled = node.CanRenameNode; _menuItemRefresh.Enabled = node.CanRefreshNode; _menuItemFind.Enabled = node.CanSearchNode; _menuItemFindNext.Enabled = _searchState != null; _menuItemMoveUp.Enabled = node.CanMoveNodeUp; _menuItemMoveDown.Enabled = node.CanMoveNodeDown; _menuItemOpenInExplorer.Enabled = node is DirectoryDataNode; UpdateUI(_nodeTree.SelectedNodes); } private void UpdateUI(IList<TreeNode> nodes) { if (nodes == null) return; _buttonAddTagByte.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateByteNodePred); _buttonAddTagShort.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateShortNodePred); _buttonAddTagInt.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateIntNodePred); _buttonAddTagLong.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateLongNodePred); _buttonAddTagFloat.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateFloatNodePred); _buttonAddTagDouble.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateDoubleNodePred); _buttonAddTagByteArray.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateByteArrayNodePred); _buttonAddTagIntArray.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateIntArrayNodePred); _buttonAddTagLongArray.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateLongArrayNodePred); _buttonAddTagString.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateStringNodePred); _buttonAddTagList.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateListNodePred); _buttonAddTagCompound.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CreateCompoundNodePred); _buttonSave.Enabled = _controller.CheckModifications(); _buttonRename.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.RenameNodePred); _buttonEdit.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.EditNodePred); _buttonDelete.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.DeleteNodePred); _buttonCut.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CutNodePred) && NbtClipboardController.IsInitialized; ; _buttonCopy.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.CopyNodePred) && NbtClipboardController.IsInitialized; ; _buttonPaste.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.PasteIntoNodePred) && NbtClipboardController.IsInitialized; ; _buttonFindNext.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.SearchNodePred) || _searchState != null; _buttonRefresh.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.RefreshNodePred); _menuItemSave.Enabled = _buttonSave.Enabled; _menuItemRename.Enabled = _buttonRename.Enabled; _menuItemEditValue.Enabled = _buttonEdit.Enabled; _menuItemDelete.Enabled = _buttonDelete.Enabled; _menuItemMoveUp.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.MoveNodeUpPred); _menuItemMoveDown.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.MoveNodeDownPred); _menuItemCut.Enabled = _buttonCut.Enabled; _menuItemCopy.Enabled = _buttonCopy.Enabled; _menuItemPaste.Enabled = _buttonPaste.Enabled; _menuItemFind.Enabled = _controller.CanOperateOnSelection(NodeTreeController.Predicates.SearchNodePred); _menuItemRefresh.Enabled = _buttonRefresh.Enabled; _menuItemFindNext.Enabled = _searchState != null; } private void UpdateOpenMenu() { try { if (Settings.Default.RecentDirectories == null) Settings.Default.RecentDirectories = new StringCollection(); if (Settings.Default.RecentFiles == null) Settings.Default.RecentFiles = new StringCollection(); } catch { return; } _menuItemRecentFolders.DropDown = BuildRecentEntriesDropDown(Settings.Default.RecentDirectories); _menuItemRecentFiles.DropDown = BuildRecentEntriesDropDown(Settings.Default.RecentFiles); } private void _controller_SelectionInvalidated(object sender, EventArgs e) { UpdateUI(); } private ToolStripDropDown BuildRecentEntriesDropDown(StringCollection list) { if (list == null || list.Count == 0) return new ToolStripDropDown(); var menu = new ToolStripDropDown(); foreach (var entry in list) { var item = new ToolStripMenuItem("&" + (menu.Items.Count + 1) + " " + entry); item.Tag = entry; item.Click += _menuItemRecentPaths_Click; menu.Items.Add(item); } return menu; } private void AddPathToHistory(StringCollection list, string entry) { if (list == null) return; foreach (var item in list) if (item == entry) { list.Remove(item); break; } while (list.Count >= 5) list.RemoveAt(list.Count - 1); list.Insert(0, entry); } private GroupCapabilities CommonCapabilities(IEnumerable<GroupCapabilities> capabilities) { var caps = GroupCapabilities.All; foreach (var cap in capabilities) caps &= cap; return caps; } #region Event Handlers private void MainForm_Closing(object sender, CancelEventArgs e) { Settings.Default.RecentFiles = Settings.Default.RecentFiles; Settings.Default.Save(); if (!ConfirmExit()) e.Cancel = true; } #region TreeView Event Handlers private void _nodeTree_BeforeExpand(object sender, TreeViewCancelEventArgs e) { ExpandNode(e.Node); } private void _nodeTree_AfterCollapse(object sender, TreeViewEventArgs e) { CollapseNode(e.Node); } private void _nodeTree_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node != null) UpdateUI(e.Node.Tag as DataNode); } private void _nodeTree_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { _controller.EditNode(e.Node); } private void _nodeTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) { e.Node.ContextMenuStrip = _controller.BuildNodeContextMenu(e.Node, e.Node.Tag as DataNode); _nodeTree.SelectedNode = e.Node; } } private void _nodeTree_DragDrop(object sender, DragEventArgs e) { OpenPaths((string[])e.Data.GetData(DataFormats.FileDrop)); } private void _nodeTree_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } #endregion TreeView Event Handlers #region Toolstrip Event Handlers private void _buttonOpen_Click(object sender, EventArgs e) { OpenFile(); } private void _buttonOpenFolder_Click(object sender, EventArgs e) { OpenFolder(); } private void _buttonSave_Click(object sender, EventArgs e) { _controller.Save(); } private void _buttonEdit_Click(object sender, EventArgs e) { _controller.EditSelection(); } private void _buttonRename_Click(object sender, EventArgs e) { _controller.RenameSelection(); } private void _buttonDelete_Click(object sender, EventArgs e) { _controller.DeleteSelection(); } private void _buttonCopy_Click(object sernder, EventArgs e) { _controller.CopySelection(); } private void _buttonCut_Click(object sernder, EventArgs e) { _controller.CutSelection(); } private void _buttonPaste_Click(object sernder, EventArgs e) { _controller.PasteIntoSelection(); } private void _buttonAddTagByteArray_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_BYTE_ARRAY); } private void _buttonAddTagByte_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_BYTE); } private void _buttonAddTagCompound_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_COMPOUND); } private void _buttonAddTagDouble_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_DOUBLE); } private void _buttonAddTagFloat_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_FLOAT); } private void _buttonAddTagInt_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_INT); } private void _buttonAddTagIntArray_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_INT_ARRAY); } private void _buttonAddTagList_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_LIST); } private void _buttonAddTagLong_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_LONG); } private void _buttonAddTagLongArray_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_LONG_ARRAY); } private void _buttonAddTagShort_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_SHORT); } private void _buttonAddTagString_Click(object sender, EventArgs e) { _controller.CreateNode(TagType.TAG_STRING); } private void _buttonFindNext_Click(object sender, EventArgs e) { if (_searchState != null) SearchNextNode(); else SearchNode(_nodeTree.SelectedNode); } private void _buttonRefresh_Click(object sender, EventArgs e) { _controller.RefreshSelection(); } #endregion Toolstrip Event Handlers #region Menu Event Handlers private void _menuItemOpen_Click(object sender, EventArgs e) { OpenFile(); } private void _menuItemOpenFolder_Click(object sender, EventArgs e) { OpenFolder(); } private void _menuItemOpenMinecraftSaveFolder_Click(object sender, EventArgs e) { OpenMinecraftDirectory(); } private void _menuItemSave_Click(object sender, EventArgs e) { _controller.Save(); } private void _menuItemExit_Click(object sender, EventArgs e) { Settings.Default.Save(); Close(); } private void _menuItemEditValue_Click(object sender, EventArgs e) { _controller.EditSelection(); } private void _menuItemRename_Click(object sender, EventArgs e) { _controller.RenameSelection(); } private void _menuItemDelete_Click(object sender, EventArgs e) { _controller.DeleteSelection(); } private void _menuItemCopy_Click(object sender, EventArgs e) { _controller.CopySelection(); } private void _menuItemCut_Click(object sender, EventArgs e) { _controller.CutSelection(); } private void _menuItemPaste_Click(object sender, EventArgs e) { _controller.PasteIntoSelection(); } private void _menuItemFind_Click(object sender, EventArgs e) { SearchNode(_nodeTree.SelectedNode); } private void _menuItemFindNext_Click(object sender, EventArgs e) { SearchNextNode(); } private void _menuItemAbout_Click(object sender, EventArgs e) { new About().ShowDialog(); } private void _menuItemRecentPaths_Click(object sender, EventArgs e) { var item = sender as ToolStripMenuItem; if (item == null || !(item.Tag is string)) return; OpenPaths(new[] { item.Tag as string }); } private void refreshToolStripMenuItem_Click(object sender, EventArgs e) { _controller.RefreshSelection(); } private void replaceToolStripMenuItem_Click(object sender, EventArgs e) { Form form = new FindReplace(this, _controller, _nodeTree.SelectedNode.Tag as DataNode); form.Show(); } private void _menuItemMoveUp_Click(object sender, EventArgs e) { _controller.MoveSelectionUp(); } private void _menuItemMoveDown_Click(object sender, EventArgs e) { _controller.MoveSelectionDown(); } private void findBlockToolStripMenuItem_Click(object sender, EventArgs e) { var form = new FindBlock(_nodeTree.SelectedNode.Tag as DataNode); if (form.ShowDialog() == DialogResult.OK) if (form.Result != null) { _controller.SelectNode(form.Result); _controller.ExpandSelectedNode(); _controller.ScrollNode(form.Result); } else { MessageBox.Show("Chunk not found."); } } #endregion Menu Event Handlers #endregion Event Handlers } }
36.471324
142
0.589347
[ "MIT" ]
DalekCraft2/NBTExplorer
NBTExplorer/Windows/MainForm.cs
34,978
C#
using System.Threading.Tasks; using NbaStats.Application.Abstractions; using NbaStats.Application.DTO; using NbaStats.Domain.Repositories; namespace NbaStats.Application.Queries.Handlers { public class GetTeamHandler : IQueryHandler<GetTeam,TeamDto> { private readonly ITeamRepository _teamRepository; public GetTeamHandler(ITeamRepository teamRepository) { _teamRepository = teamRepository; } public async Task<TeamDto> HandleAsync(GetTeam query) { var team = await _teamRepository.GetAsync(query.TeamId); return team.AsDto(); } } }
28
68
0.687888
[ "MIT" ]
Pietrzaaq/nba-stats-app
src/NbaStats.Application/Queries/Handlers/GetTeamHandler.cs
646
C#
using System.Collections.Generic; using System.ServiceModel; using System.Threading.Tasks; namespace IdeaStatiCa.Plugin { public enum RequestedItemsType { Connections, Substructure, SingleConnection, } /// <summary> /// Abstraction of a FE application which provides data to Idea StatiCa /// </summary> [ServiceContract] public interface IApplicationBIM { [OperationContract] List<BIMItemId> GetActiveSelection(); [OperationContract] string GetActiveSelectionModelXML(IdeaRS.OpenModel.CountryCode countryCode, RequestedItemsType requestedType); [OperationContract] string GetApplicationName(); /// <summary> /// Returns a xml string representing a list of BIM models for requested sequence of given <paramref name="items"/> - groups. /// Each group in the list of <paramref name="items"/> represents designed item such as connection or member and is defined by the id, type and items belonging to the group. /// The item can also has id = -1, which means, that items (members or nodes typically) in this group doesn't belong to any design item (connection or member). /// </summary> /// <param name="countryCode">The standard that will match the imported models.</param> /// <param name="items">The sequence of items, for which the BIM model is required.</param> /// <returns>A xml string representing a list of BIM models for requested <paramref name="items"/>.</returns> [OperationContract] string GetModelForSelectionXML(IdeaRS.OpenModel.CountryCode countryCode, List<BIMItemsGroup> items); [OperationContract] bool IsCAD(); [OperationContract] Task SelectAsync(List<BIMItemId> items); } }
36
175
0.752415
[ "MIT" ]
idea-statica/ideastatica-public
src/IdeaStatiCa.Plugin/IApplicationBIM.cs
1,658
C#
using MetalUp.FunctionalLibrary; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FunctionalLibraryTest { [TestClass] public class Prepend : TestBase { [TestMethod] public void Prepend1() { var list = FList.New(1, 2, 3); var actual = FList.Prepend(4, list); var expected = FList.New(4, 1, 2, 3); Assert.AreEqual(expected, actual); } [TestMethod] public void Prepend2() { var list = FList.New(1); var actual = FList.Prepend(4, list); var expected = FList.New(4, 1); Assert.AreEqual(expected, actual); } [TestMethod] public void Prepend3() { var list = FList.Empty<int>(); var actual = FList.Prepend(4, list); var expected = FList.New(4); Assert.AreEqual(expected, actual); } [TestMethod] public void Prepend1String() { var list = "123"; var actual = FList.Prepend('4', list); var expected = "4123"; Assert.AreEqual(expected, actual.ToString()); } } }
25.638298
57
0.518672
[ "MIT" ]
MetalUp/FunctionalLibrary
FunctionalLibraryTest/Prepend.cs
1,207
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. namespace System { public static partial class Console { public static System.ConsoleColor BackgroundColor { get { return default(System.ConsoleColor); } set { } } public static void Beep() { } public static int BufferHeight { get { return default(int); } set { } } public static int BufferWidth { get { return default(int); } set { } } public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } } public static void Clear() { } public static int CursorLeft { get { return default(int); } set { } } public static int CursorTop { get { return default(int); } set { } } public static bool CursorVisible { get { return default(bool); } set { } } public static System.IO.TextWriter Error { get { return default(System.IO.TextWriter); } } public static System.ConsoleColor ForegroundColor { get { return default(System.ConsoleColor); } set { } } public static bool IsErrorRedirected { get { return false; } } public static bool IsInputRedirected { get { return false; } } public static bool IsOutputRedirected { get { return false; } } public static System.IO.TextReader In { get { return default(System.IO.TextReader); } } public static bool KeyAvailable { get { return default(bool); }} public static int LargestWindowWidth { get { return default(int); } } public static int LargestWindowHeight { get { return default(int); }} public static System.IO.Stream OpenStandardError() { return default(System.IO.Stream); } public static System.IO.Stream OpenStandardInput() { return default(System.IO.Stream); } public static System.IO.Stream OpenStandardOutput() { return default(System.IO.Stream); } public static System.IO.TextWriter Out { get { return default(System.IO.TextWriter); } } public static int Read() { return default(int); } public static ConsoleKeyInfo ReadKey() { return default(ConsoleKeyInfo); } public static ConsoleKeyInfo ReadKey(bool intercept) { return default(ConsoleKeyInfo); } public static string ReadLine() { return default(string); } public static void ResetColor() { } public static void SetBufferSize(int width, int height) { } public static void SetCursorPosition(int left, int top) { } public static void SetError(System.IO.TextWriter newError) { } public static void SetIn(System.IO.TextReader newIn) { } public static void SetOut(System.IO.TextWriter newOut) { } public static string Title { get { return default(string); } set { } } public static int WindowHeight { get { return default(int); } set { } } public static int WindowWidth { get { return default(int); } set { } } public static int WindowLeft { get { return default(int); } set { } } public static int WindowTop { get { return default(int); } set { } } public static void Write(bool value) { } public static void Write(char value) { } public static void Write(char[] buffer) { } public static void Write(char[] buffer, int index, int count) { } public static void Write(decimal value) { } public static void Write(double value) { } public static void Write(int value) { } public static void Write(long value) { } public static void Write(object value) { } public static void Write(float value) { } public static void Write(string value) { } public static void Write(string format, object arg0) { } public static void Write(string format, object arg0, object arg1) { } public static void Write(string format, object arg0, object arg1, object arg2) { } public static void Write(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void Write(uint value) { } [System.CLSCompliantAttribute(false)] public static void Write(ulong value) { } public static void WriteLine() { } public static void WriteLine(bool value) { } public static void WriteLine(char value) { } public static void WriteLine(char[] buffer) { } public static void WriteLine(char[] buffer, int index, int count) { } public static void WriteLine(decimal value) { } public static void WriteLine(double value) { } public static void WriteLine(int value) { } public static void WriteLine(long value) { } public static void WriteLine(object value) { } public static void WriteLine(float value) { } public static void WriteLine(string value) { } public static void WriteLine(string format, object arg0) { } public static void WriteLine(string format, object arg0, object arg1) { } public static void WriteLine(string format, object arg0, object arg1, object arg2) { } public static void WriteLine(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(uint value) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(ulong value) { } } public sealed partial class ConsoleCancelEventArgs : System.EventArgs { internal ConsoleCancelEventArgs() { } public bool Cancel { get { return default(bool); } set { } } public System.ConsoleSpecialKey SpecialKey { get { return default(System.ConsoleSpecialKey); } } } public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e); public enum ConsoleColor { Black = 0, Blue = 9, Cyan = 11, DarkBlue = 1, DarkCyan = 3, DarkGray = 8, DarkGreen = 2, DarkMagenta = 5, DarkRed = 4, DarkYellow = 6, Gray = 7, Green = 10, Magenta = 13, Red = 12, White = 15, Yellow = 14, } public partial struct ConsoleKeyInfo { public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { } public char KeyChar { get { return default(char); } } public ConsoleKey Key { get { return default(ConsoleKey); } } public ConsoleModifiers Modifiers { get { return default(ConsoleModifiers); ; } } } public enum ConsoleKey { Backspace = 0x8, Tab = 0x9, Clear = 0xC, Enter = 0xD, Pause = 0x13, Escape = 0x1B, Spacebar = 0x20, PageUp = 0x21, PageDown = 0x22, End = 0x23, Home = 0x24, LeftArrow = 0x25, UpArrow = 0x26, RightArrow = 0x27, DownArrow = 0x28, Select = 0x29, Print = 0x2A, Execute = 0x2B, PrintScreen = 0x2C, Insert = 0x2D, Delete = 0x2E, Help = 0x2F, D0 = 0x30, // 0 through 9 D1 = 0x31, D2 = 0x32, D3 = 0x33, D4 = 0x34, D5 = 0x35, D6 = 0x36, D7 = 0x37, D8 = 0x38, D9 = 0x39, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5A, Sleep = 0x5F, NumPad0 = 0x60, NumPad1 = 0x61, NumPad2 = 0x62, NumPad3 = 0x63, NumPad4 = 0x64, NumPad5 = 0x65, NumPad6 = 0x66, NumPad7 = 0x67, NumPad8 = 0x68, NumPad9 = 0x69, Multiply = 0x6A, Add = 0x6B, Separator = 0x6C, Subtract = 0x6D, Decimal = 0x6E, Divide = 0x6F, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7A, F12 = 0x7B, F13 = 0x7C, F14 = 0x7D, F15 = 0x7E, F16 = 0x7F, F17 = 0x80, F18 = 0x81, F19 = 0x82, F20 = 0x83, F21 = 0x84, F22 = 0x85, F23 = 0x86, F24 = 0x87, Oem1 = 0xBA, OemPlus = 0xBB, OemComma = 0xBC, OemMinus = 0xBD, OemPeriod = 0xBE, Oem2 = 0xBF, Oem3 = 0xC0, Oem4 = 0xDB, Oem5 = 0xDC, Oem6 = 0xDD, Oem7 = 0xDE, Oem8 = 0xDF, OemClear = 0xFE, } [Flags] public enum ConsoleModifiers { Alt = 1, Shift = 2, Control = 4 } public enum ConsoleSpecialKey { ControlBreak = 1, ControlC = 0, } }
37.120968
114
0.576472
[ "MIT" ]
er0dr1guez/corefx
src/System.Console/ref/System.Console.cs
9,206
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.Pokemon_Trainer { public class Pokemon { public string name; public string element; public int health; public Pokemon(string name, string element, int health) { this.name = name; this.element = element; this.health = health; } } }
20
63
0.61087
[ "MIT" ]
MikeHitrov/SoftUni
C# Basics OOP/1. Defining Classes Exercises/08. Pokemon Trainer/Pokemon.cs
462
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace ShopifySharp { /// <summary> /// An object representing a Shopify fulfillment service. /// </summary> public class FulfillmentServiceEntity : ShopifyObject { /// <summary> /// The name of the fulfillment service as seen by merchants and their customers. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// States the URL endpoint that Shopify needs to retrieve inventory and tracking updates. /// This field is necessary if either inventory_management or tracking_support is set to "true". /// </summary> [JsonProperty("callback_url")] public string CallbackUrl { get; set; } /// <summary> /// Specifies the format of the API output. Valid values are "json" and "xml". /// </summary> [JsonProperty("format")] public string Format { get; set; } /// <summary> /// A human-friendly unique string for the fulfillment service generated from its title. /// </summary> [JsonProperty("handle")] public string Handle { get; set; } /// <summary> /// States if the fulfillment service tracks product inventory and provides updates to Shopify. /// </summary> [JsonProperty("inventory_management")] public bool? InventoryManagement { get; set; } /// <summary> /// The unique identifier of the location tied to the fulfillment service /// </summary> [JsonProperty("location_id")] public long? LocationId { get; set; } /// <summary> /// A unique identifier for the fulfillment service provider. /// </summary> [JsonProperty("provider_id")] public string ProviderId { get; set; } /// <summary> /// States if the fulfillment service requires products to be physically shipped. /// </summary> [JsonProperty("requires_shipping_method")] public bool? RequiresShippingMethod { get; set; } /// <summary> /// States if the fulfillment service provides tracking numbers for packages. /// </summary> [JsonProperty("tracking_support")] public bool? TrackingSupport { get; set; } /// <summary> /// This property is undocumented by Shopify. /// </summary> [JsonProperty("email")] public string Email { get; set; } /// <summary> /// This property is undocumented by Shopify. /// </summary> [JsonProperty("include_pending_stock")] public bool? IncludePendingStock { get; set; } /// <summary> /// This property is undocumented by Shopify. /// </summary> [JsonProperty("service_name")] public string ServiceName { get; set; } } }
33.431818
104
0.595853
[ "MIT" ]
9001-Solutions/ShopifySharp
ShopifySharp/Entities/FulfillmentServiceEntity.cs
2,942
C#
using System; using Sora.OnebotModel.OnebotEvent.NoticeEvent; using Sora.Entities; using Sora.Entities.Info; namespace Sora.EventArgs.SoraEvent { /// <summary> /// 群文件上传事件参数 /// </summary> public sealed class FileUploadEventArgs : BaseSoraEventArgs { #region 属性 /// <summary> /// 消息源群 /// </summary> public Group SourceGroup { get; private set; } /// <summary> /// 上传者 /// </summary> public User Sender { get; private set; } /// <summary> /// 上传文件的信息 /// </summary> public UploadFileInfo FileInfo { get; private set; } #endregion #region 构造函数 /// <summary> /// 初始化 /// </summary> /// <param name="serviceId">服务ID</param> /// <param name="connectionId">服务器链接标识</param> /// <param name="eventName">事件名</param> /// <param name="fileUploadArgs">文件上传事件参数</param> internal FileUploadEventArgs(Guid serviceId, Guid connectionId, string eventName, ApiFileUploadEventArgs fileUploadArgs) : base(serviceId, connectionId, eventName, fileUploadArgs.SelfID, fileUploadArgs.Time) { SourceGroup = new Group(serviceId, connectionId, fileUploadArgs.GroupId); Sender = new User(serviceId, connectionId, fileUploadArgs.UserId); FileInfo = fileUploadArgs.Upload; } #endregion } }
28.692308
96
0.573727
[ "Apache-2.0" ]
traceless0929/Sora
Sora/EventArgs/SoraEvent/FileUploadEventArgs.cs
1,596
C#
using CoreAudio; using System; using System.Diagnostics; namespace CoreAudioConsole.Framework.Sample { class Program { static void Main(string[] args) { MMDeviceEnumerator DevEnum = new MMDeviceEnumerator(); MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia); // Note the AudioSession manager did not have a method to enumerate all sessions in windows Vista // this will only work on Win7 and newer. foreach(var session in device.AudioSessionManager2.Sessions) { if(session.State == AudioSessionState.AudioSessionStateActive) { Console.WriteLine("DisplayName: {0}", session.DisplayName); Console.WriteLine("State: {0}", session.State); Console.WriteLine("IconPath: {0}", session.IconPath); Console.WriteLine("SessionIdentifier: {0}", session.GetSessionIdentifier); Console.WriteLine("SessionInstanceIdentifier: {0}", session.GetSessionInstanceIdentifier); Console.WriteLine("ProcessID: {0}", session.GetProcessID); Console.WriteLine("IsSystemIsSystemSoundsSession: {0}", session.IsSystemSoundsSession); Process p = Process.GetProcessById((int)session.GetProcessID); Console.WriteLine("MainWindowTitle: {0}", p.MainWindowTitle); AudioMeterInformation mi = session.AudioMeterInformation; SimpleAudioVolume vol = session.SimpleAudioVolume; Console.WriteLine("---[Hotkeys]---"); Console.WriteLine("M Toggle Mute"); Console.WriteLine(", Lower volume"); Console.WriteLine(", Raise volume"); Console.WriteLine("Q Quit"); Console.CursorVisible = false; int start = Console.CursorTop; while(true) { //Draw a VU meter int len = (int)(mi.MasterPeakValue * 79); Console.SetCursorPosition(0, start); for(int j = 0; j < len; j++) Console.Write("*"); for(int j = 0; j < 79 - len; j++) Console.Write(" "); Console.SetCursorPosition(0, start + 1); Console.WriteLine("Mute : {0} ", vol.Mute); Console.WriteLine("Master : {0:0.00} ", vol.MasterVolume * 100); if(Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch(key.Key) { case ConsoleKey.M: vol.Mute = !vol.Mute; break; case ConsoleKey.Q: Console.CursorVisible = true; return; case ConsoleKey.OemComma: float curvol = vol.MasterVolume - 0.1f; if(curvol < 0) curvol = 0; vol.MasterVolume = curvol; break; case ConsoleKey.OemPeriod: float curvold = vol.MasterVolume + 0.1f; if(curvold > 1) curvold = 1; vol.MasterVolume = curvold; break; } } } } } //If we end up here there where no open audio sessions to monitor. Console.WriteLine("No Audio sessions found"); } } }
51.831169
110
0.467552
[ "MIT" ]
j-zero/CoreAudio
samples/CoreAudioConsole.Framework.Sample/Program.cs
3,993
C#
using System; using NetTopologySuite.Geometries; using NetTopologySuite.IO; using NetTopologySuite.Operation.Valid; using NUnit.Framework; namespace NetTopologySuite.Tests.NUnit.Operation.Valid { ///<summary> ///Tests allowing IsValidOp to validate polygons with ///Self-Touching Rings forming holes. ///Mainly tests that configuring <see cref="IsValidOp"/> to allow validating ///the STR validates polygons with this condition, and does not validate ///polygons with other kinds of self-intersection (such as ones with Disconnected Interiors). ///Includes some basic tests to confirm that other invalid cases remain detected correctly, ///but most of this testing is left to the existing XML validation tests. ///</summary> ///<author>Martin Davis</author> ///<version>1.7</version> [TestFixture] public class ValidSelfTouchingRingFormingHoleTest { private static WKTReader rdr = new WKTReader(); ///<summary> ///Tests a geometry with both a shell self-touch and a hole self-touch. ///This is valid if STR is allowed, but invalid in OGC ///</summary> [Test] public void TestShellAndHoleSelfTouch() { string wkt = "POLYGON ((0 0, 0 340, 320 340, 320 0, 120 0, 180 100, 60 100, 120 0, 0 0), (80 300, 80 180, 200 180, 200 240, 280 200, 280 280, 200 240, 200 300, 80 300))"; CheckIsValidSTR(wkt, true); CheckIsValidDefault(wkt, false); } ///<summary> ///Tests a geometry representing the same area as in <see cref="TestShellAndHoleSelfTouch"/> ///but using a shell-hole touch and a hole-hole touch. ///This is valid in OGC. ///</summary> [Test] public void TestShellHoleAndHoleHoleTouch() { string wkt = "POLYGON ((0 0, 0 340, 320 340, 320 0, 120 0, 0 0), (120 0, 180 100, 60 100, 120 0), (80 300, 80 180, 200 180, 200 240, 200 300, 80 300), (200 240, 280 200, 280 280, 200 240))"; CheckIsValidSTR(wkt, true); CheckIsValidDefault(wkt, true); } ///<summary> ///Tests an overlapping hole condition, where one of the holes is created by a shell self-touch. ///This is never valid. ///</summary> [Test] public void TestShellSelfTouchHoleOverlappingHole() { string wkt = "POLYGON ((0 0, 220 0, 220 200, 120 200, 140 100, 80 100, 120 200, 0 200, 0 0), (200 80, 20 80, 120 200, 200 80))"; CheckIsValidSTR(wkt, false); CheckIsValidDefault(wkt, false); } ///<summary> ///Ensure that the Disconnected Interior condition is not validated ///</summary> [Test] public void TestDisconnectedInteriorShellSelfTouchAtNonVertex() { string wkt = "POLYGON ((40 180, 40 60, 240 60, 240 180, 140 60, 40 180))"; CheckIsValidSTR(wkt, false); CheckIsValidDefault(wkt, false); } ///<summary> ///Ensure that the Disconnected Interior condition is not validated ///</summary> [Test] public void TestDisconnectedInteriorShellSelfTouchAtVertex() { string wkt = "POLYGON ((20 20, 20 100, 140 100, 140 180, 260 180, 260 100, 140 100, 140 20, 20 20))"; CheckIsValidSTR(wkt, false); CheckIsValidDefault(wkt, false); } [Test] public void TestShellCross() { string wkt = "POLYGON ((20 20, 120 20, 120 220, 240 220, 240 120, 20 120, 20 20))"; CheckIsValidSTR(wkt, false); CheckIsValidDefault(wkt, false); } [Test] public void TestShellCrossAndSTR() { string wkt = "POLYGON ((20 20, 120 20, 120 220, 180 220, 140 160, 200 160, 180 220, 240 220, 240 120, 20 120, 20 20))"; CheckIsValidSTR(wkt, false); CheckIsValidDefault(wkt, false); } private void CheckIsValidDefault(string wkt, bool expected) { var geom = FromWKT(wkt); var validator = new IsValidOp(geom); bool isValid = validator.IsValid; Assert.IsTrue(isValid == expected); } private void CheckIsValidSTR(string wkt, bool expected) { var geom = FromWKT(wkt); var validator = new IsValidOp(geom); validator.IsSelfTouchingRingFormingHoleValid = true; bool isValid = validator.IsValid; Assert.IsTrue(isValid == expected); } Geometry FromWKT(string wkt) { Geometry geom = null; try { geom = rdr.Read(wkt); } catch (Exception ex) { TestContext.WriteLine(ex.StackTrace); } return geom; } } }
37.318182
207
0.581608
[ "EPL-1.0" ]
CobeLapierre/NetTopologySuite
test/NetTopologySuite.Tests.NUnit/Operation/Valid/ValidSelfTouchingRingFormingHoleTest.cs
4,926
C#
// ----- // GNU General Public License // The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. // The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. // See the GNU Lesser General Public License for more details. // ----- using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Reflection; namespace fxpa { public partial class FxpaBaseComponentControl : FxpaCommonControl { FxpaBaseComponent _component; protected new FxpaBaseComponent Component { get { return _component; } } /// <summary> /// /// </summary> public FxpaBaseComponentControl() { InitializeComponent(); } /// <summary> /// /// </summary> public FxpaBaseComponentControl(FxpaBaseComponent component) { InitializeComponent(); _component = component; //SystemMonitor.CheckWarning(_component.IsInitialized); } private void PlatformComponentControl_Load(object sender, EventArgs e) { // SystemMonitor.CheckThrow(Tag == _component, "Tag is expected to be component."); } //void _component_ComponentInitializedEvent(ActivePlatformComponent component, bool initialized) //{ // if (this.IsHandleCreated) // { // this.Invoke(new GeneralHelper.GenericDelegate<bool>(ComponentInitialized), initialized); // } // else // { // SystemMonitor.Warning("Component initialized before UI."); // } //} //protected virtual void ComponentInitialized(bool initialized) //{ //} } }
31.884058
269
0.635909
[ "MIT" ]
harryho/fx-trading-platform-prototype
fxpa/fxpa/FxpaBase/FxpaBaseComponentControl.cs
2,200
C#
using System.IO; using System.Text; namespace Cake.AddinDiscoverer.Utilities { internal sealed class StringWriterWithEncoding : StringWriter { private readonly Encoding encoding; public StringWriterWithEncoding() : this(Encoding.UTF8) { } public StringWriterWithEncoding(Encoding encoding) { this.encoding = encoding; } public override Encoding Encoding { get { return encoding; } } } }
16.88
62
0.734597
[ "MIT" ]
augustoproiete-forks/cake-contrib--Cake.AddinDiscoverer
Source/Cake.AddinDiscoverer/Utilities/StringWriterWithEncoding.cs
424
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel; using System.Web.WebPages.Razor; namespace Microsoft.Web.WebPages.OAuth { /// <summary> /// Defines Start() method that gets executed when this assembly is loaded by ASP.NET /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class PreApplicationStartCode { /// <summary> /// Register global namepace imports for this assembly /// </summary> public static void Start() { WebPageRazorHost.AddGlobalImport("DotNetOpenAuth.AspNet"); WebPageRazorHost.AddGlobalImport("Microsoft.Web.WebPages.OAuth"); // Disable the "calls home" feature of DNOA DotNetOpenAuth.Reporting.Enabled = false; } } }
34.62963
111
0.670588
[ "Apache-2.0" ]
1508553303/AspNetWebStack
src/Microsoft.Web.WebPages.OAuth/PreApplicationStartCode.cs
937
C#
using System.Runtime.CompilerServices; #if SIGNED_ASSEMBLIES [assembly: InternalsVisibleTo("Microsoft.Diagnostics.Runtime.Native, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("Microsoft.Diagnostics.Runtime.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.Diagnostics.Runtime.Native")] [assembly: InternalsVisibleTo("Microsoft.Diagnostics.Runtime.Tests")] #endif
102.2
402
0.933464
[ "MIT" ]
TylerAP/clrmd
src/Microsoft.Diagnostics.Runtime/AssemblyProperties.cs
1,024
C#
using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using Ufangx.Xss; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; namespace Ufangx.Xss { /// <summary> /// /// </summary> public class RichTextBinderProvider : IModelBinderProvider { /// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Metadata.ModelType == typeof(RichText)) { return new BinderTypeModelBinder(typeof(RichTextBinder)); } return null; } } }
23.6
73
0.55569
[ "MIT" ]
JacksonBruce/AntiXssUF
AntiXssUF/RichTextBinderProvider.netcoreapp.cs
828
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace mszcoolPoDCommandApi.Controllers { [Route("api/[controller]/{environmentName}")] public class DevicePowerController : Controller { [HttpGet] public Dictionary<string, string> GetDeviceStatus(string environmentName) { return null; } [HttpGet("{agentName}")] public Dictionary<string, string> GetDeviceStatus(string environmentName, string agentName) { return null; } [HttpGet("{agentName}/{deviceName}")] public string GetDeviceStatus(string environmentName, string agentName, string deviceName) { return null; } [HttpPost("{agentName}/{deviceName}/on")] public void PowerOnDevice(string environmentName, string agentName, string deviceName) { } [HttpPost("{agentName}/{deviceName}/off")] public void PowerOffDevice(string environmentName, string agentName, string deviceName) { } } }
28.022222
116
0.654243
[ "Apache-2.0" ]
mszcool/mszcoolPowerOnDemand
mszcoolPoDCommandApi/Controllers/DevicePowerController.cs
1,263
C#
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_TargetInstances_AggregatedList_async] using Google.Api.Gax; using Google.Cloud.Compute.V1; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedTargetInstancesClientSnippets { /// <summary>Snippet for AggregatedListAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task AggregatedListRequestObjectAsync() { // Create client TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync(); // Initialize request argument(s) AggregatedListTargetInstancesRequest request = new AggregatedListTargetInstancesRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, TargetInstancesScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetInstanceAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, TargetInstancesScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END compute_v1_generated_TargetInstances_AggregatedList_async] }
43.694118
174
0.642165
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/TargetInstancesClient.AggregatedListRequestObjectAsyncSnippet.g.cs
3,714
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CognitoIdentityProvider.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AdminUpdateUserAttributes operation /// </summary> public class AdminUpdateUserAttributesResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { AdminUpdateUserAttributesResponse response = new AdminUpdateUserAttributesResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AliasExistsException")) { return AliasExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalErrorException")) { return InternalErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidEmailRoleAccessPolicyException")) { return InvalidEmailRoleAccessPolicyExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidLambdaResponseException")) { return InvalidLambdaResponseExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException")) { return InvalidParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidSmsRoleAccessPolicyException")) { return InvalidSmsRoleAccessPolicyExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidSmsRoleTrustRelationshipException")) { return InvalidSmsRoleTrustRelationshipExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotAuthorizedException")) { return NotAuthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException")) { return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnexpectedLambdaException")) { return UnexpectedLambdaExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UserLambdaValidationException")) { return UserLambdaValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UserNotFoundException")) { return UserNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonCognitoIdentityProviderException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static AdminUpdateUserAttributesResponseUnmarshaller _instance = new AdminUpdateUserAttributesResponseUnmarshaller(); internal static AdminUpdateUserAttributesResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static AdminUpdateUserAttributesResponseUnmarshaller Instance { get { return _instance; } } } }
47.557823
207
0.638249
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/Internal/MarshallTransformations/AdminUpdateUserAttributesResponseUnmarshaller.cs
6,991
C#
using ETModel; using System.Collections.Generic; namespace ET { [ObjectSystem] public class CoroutineLockQueueAwakeSystem : AwakeSystem<CoroutineLockQueue> { public override void Awake(CoroutineLockQueue self) { self.queue.Clear(); } } [ObjectSystem] public class CoroutineLockQueueDestroySystem : DestroySystem<CoroutineLockQueue> { public override void Destroy(CoroutineLockQueue self) { self.queue.Clear(); } } public struct CoroutineLockInfo { public ETTask<CoroutineLock> Tcs; public int Time; } public class CoroutineLockQueue : Entity { public Queue<CoroutineLockInfo> queue = new Queue<CoroutineLockInfo>(); public void Add(ETTask<CoroutineLock> tcs, int time) { this.queue.Enqueue(new CoroutineLockInfo() { Tcs = tcs, Time = time }); } public int Count { get { return this.queue.Count; } } public CoroutineLockInfo Dequeue() { return this.queue.Dequeue(); } } }
22.634615
84
0.579439
[ "MIT" ]
dayfox5317/et_ilruntime
Unity/Assets/Script/Model/Module/CoroutineLock/CoroutineLockQueue.cs
1,177
C#
namespace NetFlow.Services.Blog { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using Microsoft.EntityFrameworkCore; using NetFlow.Data; using NetFlow.Data.Models; using NetFlow.Services.Blog.Interface; using NetFlow.Services.Blog.Models; public class CommentService : ICommentService { private readonly NetFlowDbContext context; public CommentService(NetFlowDbContext context) { this.context = context; } public async Task CreateCommentAsync(string userId, int postId, string description) { var comment = new Comment { Content = description, UserId = userId, PostId = postId, CreatedOn = DateTime.UtcNow }; await this.context.Comments.AddAsync(comment); await this.context.SaveChangesAsync(); } public async Task<IEnumerable<CommentsPostDetailsServiceModel>> GetAllCommentsAsync(int id) { var comments = await this.context .Comments .Where(a => a.PostId == id) .ProjectTo<CommentsPostDetailsServiceModel>() .ToListAsync(); return comments; } } }
28.88
99
0.580332
[ "MIT" ]
MihailTanev/NetFlow
Services/NetFlow.Services/Blog/CommentService.cs
1,446
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Swr.V2.Model { /// <summary> /// Request Object /// </summary> public class ListImageAutoSyncReposDetailsRequest { /// <summary> /// 组织名称 /// </summary> [SDKProperty("namespace", IsPath = true)] [JsonProperty("namespace", NullValueHandling = NullValueHandling.Ignore)] public string Namespace { get; set; } /// <summary> /// 镜像仓库名称 /// </summary> [SDKProperty("repository", IsPath = true)] [JsonProperty("repository", NullValueHandling = NullValueHandling.Ignore)] public string Repository { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ListImageAutoSyncReposDetailsRequest {\n"); sb.Append(" Namespace: ").Append(Namespace).Append("\n"); sb.Append(" repository: ").Append(Repository).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ListImageAutoSyncReposDetailsRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ListImageAutoSyncReposDetailsRequest input) { if (input == null) return false; return ( this.Namespace == input.Namespace || (this.Namespace != null && this.Namespace.Equals(input.Namespace)) ) && ( this.Repository == input.Repository || (this.Repository != null && this.Repository.Equals(input.Repository)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Namespace != null) hashCode = hashCode * 59 + this.Namespace.GetHashCode(); if (this.Repository != null) hashCode = hashCode * 59 + this.Repository.GetHashCode(); return hashCode; } } } }
30.076087
82
0.521503
[ "Apache-2.0" ]
mawenbo-huawei/huaweicloud-sdk-net-v3
Services/Swr/V2/Model/ListImageAutoSyncReposDetailsRequest.cs
2,787
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace CoreApi.Areas.HelpPage.ModelDescriptions { public class ParameterDescription { public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); } public Collection<ParameterAnnotation> Annotations { get; private set; } public string Documentation { get; set; } public string Name { get; set; } public ModelDescription TypeDescription { get; set; } } }
25.619048
80
0.674721
[ "ISC" ]
ThorHuno/CoreSystems
CoreApi/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
538
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information namespace Microsoft.Azure.Devices.Client.Test { using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Devices.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class ConnectionPoolTests { [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void DeviceScopeMuxConnection_PoolingOffReleaseTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings.Pooling = false; var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); // Pooling is off - pass null for ConnectionPoolCache var iotHubConnection = new IotHubDeviceMuxConnection(null, 1, iotHubConnectionString, amqpTransportSettings); connectionCache.Setup(cache => cache.GetConnection(It.IsAny<IotHubConnectionString>(), It.IsAny<AmqpTransportSettings>())).Returns(iotHubConnection); // Act var connection = connectionCache.Object.GetConnection(iotHubConnectionString, amqpTransportSettings); connection.Release("device"); // does not match "device1" above, However pooling is off. Thus, this iothubconnection object is closed // Success } [ExpectedException(typeof(InvalidOperationException))] [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void DeviceScopeMuxConnection_PoolingOnNegativeReleaseTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); connectionCache.Setup(cache => cache.GetConnection(It.IsAny<IotHubConnectionString>(), It.IsAny<AmqpTransportSettings>())).Returns(connectionPool.GetConnection("device1")); // Act var connection = connectionCache.Object.GetConnection(iotHubConnectionString, amqpTransportSettings); // throw exception if you release a device that is not in the pool connection.Release("device2"); } [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void DeviceScopeMuxConnection_PoolingOnPositiveReleaseTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); connectionCache.Setup( cache => cache.GetConnection(It.IsAny<IotHubConnectionString>(), It.IsAny<AmqpTransportSettings>())).Returns(connectionPool.GetConnection("device1")); // Act var connection = connectionCache.Object.GetConnection(iotHubConnectionString, amqpTransportSettings); connection.Release("device1"); // Success - Device1 was in the pool and released } [ExpectedException(typeof(InvalidOperationException))] [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void DeviceScopeMuxConnection_MaxDevicesPerConnectionTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); // Reduce poolsize to 1. This will mux all devices onto one connection amqpConnectionPoolSettings.MaxPoolSize = 1; var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act // Create 995 Muxed Device Connections for (int i = 0; i < AmqpConnectionPoolSettings.MaxDevicesPerConnection; i++) { connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString()); } // try one more. This should throw invalid operation exception var connection = connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString()); } [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void DeviceScopeMuxConnection_NumberOfPoolsTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act // Create 10 Muxed Device Connections - these should hash into different mux connections for (int i = 0; i < 10; i++) { var connection = connectionPool.GetConnection(i.ToString()); } // Assert Assert.IsTrue(connectionPool.GetCount() == 10, "Did not create 10 different Connection objects"); } [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public async Task DeviceScopeMuxConnection_ConnectionIdleTimeoutTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act var connections = new IotHubDeviceMuxConnection[10]; // Create 10 Muxed Device Connections - these should hash into different mux connections for (int i = 0; i < 10; i++) { connections[i] = (IotHubDeviceMuxConnection)connectionPool.GetConnection(i.ToString()); } for (int j = 0; j < 10; j++) { connectionPool.RemoveDeviceFromConnection(connections[j], j.ToString()); } await Task.Delay(TimeSpan.FromSeconds(6)).ConfigureAwait(false); // Assert Assert.IsTrue(connectionPool.GetCount() == 0, "Did not cleanup all Connection objects"); } [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] [ExpectedException(typeof(ObjectDisposedException))] public async Task HubScopeMuxConnection_ConnectionIdleTimeoutTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock<IotHubConnectionCache>(); connectionCache.Setup(cache => cache.RemoveHubScopeConnectionPool(It.IsAny<IotHubConnectionString>())).Returns(true); var hubscopeConnectionPool = new IotHubScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act for (int i = 0; i < 10; i++) { hubscopeConnectionPool.TryAddRef(); } // Assert Assert.IsTrue(hubscopeConnectionPool.GetCount() == 10, "Reference count should be ten"); for (int i = 0; i < 10; i++) { hubscopeConnectionPool.RemoveRef(); } // Assert Assert.IsTrue(hubscopeConnectionPool.GetCount() == 0, "Reference count should be zero"); await Task.Delay(TimeSpan.FromSeconds(6)).ConfigureAwait(false); // Hacky way to verify that the SingleTokenConnection object has been closed. var singleConnection = (IotHubSingleTokenConnection)hubscopeConnectionPool.Connection; await singleConnection.CreateSendingLinkAsync("test", iotHubConnectionString, "device", IotHubConnection.SendingLinkType.TelemetryEvents, TimeSpan.FromMinutes(2), new ProductInfo(), CancellationToken.None).ConfigureAwait(false); } [TestMethod] [TestCategory("CIT")] [TestCategory("ConnectionPool")] public void AmqpConnectionPoolSettingsComparisonTests() { var amqpConnectionPoolSettings1 = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings1.Pooling = true; amqpConnectionPoolSettings1.MaxPoolSize = 10; amqpConnectionPoolSettings1.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); Assert.IsTrue(amqpConnectionPoolSettings1.Equals(amqpConnectionPoolSettings1)); Assert.IsFalse(amqpConnectionPoolSettings1.Equals(null)); Assert.IsFalse(amqpConnectionPoolSettings1.Equals(new AmqpConnectionPoolSettings())); var amqpConnectionPoolSettings2 = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings2.Pooling = false; amqpConnectionPoolSettings2.MaxPoolSize = 10; amqpConnectionPoolSettings2.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); Assert.IsFalse(amqpConnectionPoolSettings1.Equals(amqpConnectionPoolSettings2)); var amqpConnectionPoolSettings3 = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings3.Pooling = true; amqpConnectionPoolSettings3.MaxPoolSize = 9; amqpConnectionPoolSettings3.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); Assert.IsFalse(amqpConnectionPoolSettings1.Equals(amqpConnectionPoolSettings3)); var amqpConnectionPoolSettings4 = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings4.Pooling = true; amqpConnectionPoolSettings4.MaxPoolSize = 10; amqpConnectionPoolSettings4.ConnectionIdleTimeout = TimeSpan.FromSeconds(6); Assert.IsFalse(amqpConnectionPoolSettings1.Equals(amqpConnectionPoolSettings4)); var amqpConnectionPoolSettings5 = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings5.Pooling = true; amqpConnectionPoolSettings5.MaxPoolSize = 10; amqpConnectionPoolSettings5.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); Assert.IsTrue(amqpConnectionPoolSettings1.Equals(amqpConnectionPoolSettings5)); } } }
54.102362
240
0.698661
[ "MIT" ]
StannieV/IoTHubDeviceExplorer
iothub/device/tests/ConnectionPoolTests.cs
13,744
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.Extensions.DependencyInjection; namespace OrdersApp.Api.Core { public static class ApiConfiguration { public static IServiceCollection AddOrdersAppApiServices(this IServiceCollection services) { services .AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); options.ApiVersionReader = new HeaderApiVersionReader("x-apiversion"); }); return services; } } }
32.608696
98
0.62
[ "Apache-2.0" ]
acnagrellos/NetCoreDemo
Soluciones/9.FinalProject/OrdersApp/src/2.Api/OrdersApp.Api.Core/ApiConfiguration.cs
752
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SpeechSynthesizerService.Service.Worker { using System; using System.Collections.Generic; public partial class TTSMessage { public System.Guid TTSMessageId { get; set; } public System.DateTime CreatedDate { get; set; } public Nullable<System.DateTime> ProcessedDate { get; set; } public int VoiceGenderId { get; set; } public string Message { get; set; } public string Filename { get; set; } public virtual VoiceGender VoiceGender { get; set; } } }
35.888889
85
0.556244
[ "MIT" ]
calloncampbell/Blog-Samples
src/SpeechSynthesizerService.Service.Worker/TTSMessage.cs
969
C#
using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI; namespace HT.Framework { /// <summary> /// 可绑定的String类型 /// </summary> public sealed class BindableString : BindableType<string> { public static implicit operator string(BindableString bString) { return bString.Value; } private UnityAction<string> _callback; /// <summary> /// 数据值 /// </summary> public override string Value { get { return base.Value; } set { if (_value == value) return; _value = value; OnValueChanged?.Invoke(_value); } } public BindableString() { _callback = (v) => { Value = v; }; Value = null; } public BindableString(string value) { _callback = (v) => { Value = v; }; Value = value; } /// <summary> /// 绑定控件 /// </summary> /// <param name="control">绑定的目标控件</param> protected override void Binding(UIBehaviour control) { base.Binding(control); if (_bindedControls.Contains(control)) return; if (control is InputField) { InputField inputField = control as InputField; inputField.text = Value; inputField.onValueChanged.AddListener(_callback); OnValueChanged += (value) => { if (inputField) inputField.text = value; }; _bindedControls.Add(control); } else if (control is Text) { Text text = control as Text; text.text = Value; OnValueChanged += (value) => { if (text) text.text = value; }; _bindedControls.Add(control); } else { Log.Warning(string.Format("自动化任务:数据绑定失败,当前不支持控件 {0} 与 BindableString 类型的数据绑定!", control.GetType().FullName)); } } /// <summary> /// 解除所有控件的绑定 /// </summary> protected override void Unbind() { base.Unbind(); foreach (var control in _bindedControls) { if (control == null) continue; if (control is InputField) { InputField inputField = control as InputField; inputField.onValueChanged.RemoveListener(_callback); } } OnValueChanged = null; _bindedControls.Clear(); } } }
27.284314
125
0.467481
[ "MIT" ]
LZhenHong/HTFramework
RunTime/Utility/AutomaticTask/DataBinding/BindableString.cs
2,901
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ActivitiesTest.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Workflow.Model.Tests.Models.ActivitiesModel { using System.Linq; using System.Threading.Tasks; using Kephas.Model; using Kephas.Runtime; using Kephas.Security.Authorization; using Kephas.Services; using Kephas.Testing.Model; using Kephas.Workflow.Application; using Kephas.Workflow.Model.Elements; using NSubstitute; using NUnit.Framework; [TestFixture] public class ActivitiesTest : WorkflowModelTestBase { [Test] public async Task InitializeAsync_activityinfo_support() { var typeRegistry = new RuntimeTypeRegistry(); var behavior = new WorkflowAppLifecycleBehavior(typeRegistry); await behavior.BeforeAppInitializeAsync(Substitute.For<IContext>()); var container = this.CreateInjectorForModel( new AmbientServices(typeRegistry: typeRegistry), typeof(ILaughActivity), typeof(IEnjoyActivity)); var provider = container.Resolve<IModelSpaceProvider>(); await provider.InitializeAsync(); var modelSpace = provider.GetModelSpace(); var laughActivity = (ActivityType)modelSpace.Classifiers.Single(c => c.Name == "Laugh"); var enjoyActivity = (ActivityType)modelSpace.Classifiers.Single(c => c.Name == "Enjoy"); Assert.AreEqual(1, laughActivity.Parts.Count()); Assert.AreEqual(0, laughActivity.Parameters.Count()); Assert.AreEqual(1, enjoyActivity.Parts.Count()); Assert.AreEqual(1, enjoyActivity.Parameters.Count()); } } }
40.980769
120
0.595495
[ "MIT" ]
kephas-software/kephas
src/Tests/Kephas.Workflow.Model.Tests/Models/ActivitiesModel/ActivitiesTest.cs
2,133
C#
using System; using System.ComponentModel; using System.Reflection; /** Enumeration values for CompanyBatteryTroop * The enumeration values are generated from the SISO DIS XML EBV document (R35), which was * obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31<p> * * Note that this has two ways to look up an enumerated instance from a value: a fast * but brittle array lookup, and a slower and more garbage-intensive, but safer, method. * if you want to minimize memory use, get rid of one or the other.<p> * * Copyright 2008-2009. This work is licensed under the BSD license, available at * http://www.movesinstitute.org/licenses<p> * * @author DMcG, Jason Nelson * Modified for use with C#: * Peter Smith (Naval Air Warfare Center - Training Systems Division) */ namespace DISnet { public partial class DISEnumerations { public enum CompanyBatteryTroop { [Description("A-M")] A_M = 66, [Description("HQ")] HQ = 113, [Description("HHB")] HHB = 98, [Description("HHC")] HHC = 99, [Description("HHD")] HHD = 100, [Description("HHT")] HHT = 116 } } //End Parial Class } //End Namespace
23.188679
91
0.666395
[ "BSD-2-Clause" ]
Updownquark/DISEnumerations
src/main/Csharp/disenum/CompanyBatteryTroop.cs
1,229
C#
using System; using System.Text; using System.Runtime.Serialization; using Microsoft.Practices.RecipeFramework.VisualStudio.Templates; using EnvDTE; namespace BizTalkSoftwareFactory.References { /// <summary> /// Reference that makes sure an item only /// applies to the BizTalk Maps project /// </summary> [Serializable] public class MapsProjectReference : UnboundTemplateReference { public MapsProjectReference(string template) : base(template) { } /// <summary> /// This method makes sure this item can only be added to a BizTalk Maps project /// </summary> /// <param name="target">Project the user clicked on</param> /// <returns>True if the item can be added here, otherwise false</returns> public override bool IsEnabledFor(object target) { // Check if this is a multi project or single project solution if (target is Project) { return ((Project)target).Kind == BusinessComponents.Constants.BizTalkProjectType && ((Project)target).Name.EndsWith(".Maps"); } else if (target is ProjectItem) { return ((ProjectItem)target).Name.EndsWith("Maps"); } else { return false; } } public override string AppliesTo { get { return "The Maps Project in the BizTalk Solution"; } } #region ISerializable Members /// <summary> /// Required constructor for deserialization. /// </summary> protected MapsProjectReference(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion ISerializable Members } }
30.813559
141
0.59791
[ "MIT" ]
Geronius/BizTalk-Software-Factory
BizTalkSoftwareFactory for BizTalk Server 2006/BizTalkSoftwareFactory/References/MapsProjectReference.cs
1,818
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.Migrations { /// <summary> /// <para> /// A base class inherited by database providers that gives access to annotations used by EF Core Migrations /// when generating removal operations for various elements of the <see cref="IRelationalModel" />. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Singleton" />. This means a single instance /// is used by many <see cref="DbContext" /> instances. The implementation must be thread-safe. /// This service cannot depend on services registered as <see cref="ServiceLifetime.Scoped" />. /// </para> /// </summary> public class MigrationsAnnotationProvider : IMigrationsAnnotationProvider { /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dependencies"> Parameter object containing dependencies for this service. </param> public MigrationsAnnotationProvider(MigrationsAnnotationProviderDependencies dependencies) { Check.NotNull(dependencies, nameof(dependencies)); } /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IRelationalModel model) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(ITable table) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IColumn column) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IView view) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IViewColumn column) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IUniqueConstraint constraint) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(ITableIndex index) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(IForeignKeyConstraint foreignKey) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(ISequence sequence) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRemove(ICheckConstraint checkConstraint) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRename(ITable table) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRename(IColumn column) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRename(ITableIndex index) => Enumerable.Empty<IAnnotation>(); /// <inheritdoc /> public virtual IEnumerable<IAnnotation> ForRename(ISequence sequence) => Enumerable.Empty<IAnnotation>(); } }
41.26087
120
0.657534
[ "Apache-2.0" ]
0x0309/efcore
src/EFCore.Relational/Migrations/MigrationsAnnotationProvider.cs
3,796
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Pipelines; using System.Net; using System.Net.Http; using System.Runtime.InteropServices; using System.Security.Claims; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.HttpSys.Internal; using Microsoft.AspNetCore.Server.IIS.Core.IO; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Server.IIS.Core { using BadHttpRequestException = Microsoft.AspNetCore.Http.BadHttpRequestException; internal abstract partial class IISHttpContext : NativeRequestContext, IThreadPoolWorkItem, IDisposable { private const int MinAllocBufferSize = 2048; protected readonly NativeSafeHandle _requestNativeHandle; private readonly IISServerOptions _options; protected Streams _streams = default!; private volatile bool _hasResponseStarted; private int _statusCode; private string? _reasonPhrase; // Used to synchronize callback registration and native method calls internal readonly object _contextLock = new object(); protected Stack<KeyValuePair<Func<object, Task>, object>>? _onStarting; protected Stack<KeyValuePair<Func<object, Task>, object>>? _onCompleted; protected Exception? _applicationException; protected BadHttpRequestException? _requestRejectedException; private readonly MemoryPool<byte> _memoryPool; private readonly IISHttpServer _server; private readonly ILogger _logger; private GCHandle _thisHandle = default!; protected Task? _readBodyTask; protected Task? _writeBodyTask; private bool _wasUpgraded; protected Pipe? _bodyInputPipe; protected OutputProducer _bodyOutput = default!; private HeaderCollection? _trailers; private const string NtlmString = "NTLM"; private const string NegotiateString = "Negotiate"; private const string BasicString = "Basic"; private const string ConnectionClose = "close"; internal unsafe IISHttpContext( MemoryPool<byte> memoryPool, NativeSafeHandle pInProcessHandler, IISServerOptions options, IISHttpServer server, ILogger logger, bool useLatin1) : base((HttpApiTypes.HTTP_REQUEST*)NativeMethods.HttpGetRawRequest(pInProcessHandler), useLatin1: useLatin1) { _memoryPool = memoryPool; _requestNativeHandle = pInProcessHandler; _options = options; _server = server; _logger = logger; ((IHttpBodyControlFeature)this).AllowSynchronousIO = _options.AllowSynchronousIO; } private int PauseWriterThreshold => _options.MaxRequestBodyBufferSize; private int ResumeWriterTheshold => PauseWriterThreshold / 2; public Version HttpVersion { get; set; } = default!; public string Scheme { get; set; } = default!; public string Method { get; set; } = default!; public string PathBase { get; set; } = default!; public string Path { get; set; } = default!; public string QueryString { get; set; } = default!; public string RawTarget { get; set; } = default!; public bool HasResponseStarted => _hasResponseStarted; public IPAddress? RemoteIpAddress { get; set; } public int RemotePort { get; set; } public IPAddress? LocalIpAddress { get; set; } public int LocalPort { get; set; } public string? RequestConnectionId { get; set; } public string? TraceIdentifier { get; set; } public ClaimsPrincipal? User { get; set; } internal WindowsPrincipal? WindowsUser { get; set; } internal bool RequestCanHaveBody { get; private set; } public Stream RequestBody { get; set; } = default!; public Stream ResponseBody { get; set; } = default!; public PipeWriter? ResponsePipeWrapper { get; set; } protected IAsyncIOEngine? AsyncIO { get; set; } public IHeaderDictionary RequestHeaders { get; set; } = default!; public IHeaderDictionary ResponseHeaders { get; set; } = default!; public IHeaderDictionary? ResponseTrailers { get; set; } private HeaderCollection HttpResponseHeaders { get; set; } = default!; private HeaderCollection HttpResponseTrailers => _trailers ??= new HeaderCollection(checkTrailers: true); internal bool HasTrailers => _trailers?.Count > 0; internal HttpApiTypes.HTTP_VERB KnownMethod { get; private set; } private bool HasStartedConsumingRequestBody { get; set; } public long? MaxRequestBodySize { get; set; } protected void InitializeContext() { // create a memory barrier between initialize and disconnect to prevent a possible // NullRef with disconnect being called before these fields have been written // disconnect aquires this lock as well lock (_abortLock) { _thisHandle = GCHandle.Alloc(this); Method = GetVerb() ?? string.Empty; RawTarget = GetRawUrl() ?? string.Empty; // TODO version is slow. HttpVersion = GetVersion(); Scheme = SslStatus != SslStatus.Insecure ? Constants.HttpsScheme : Constants.HttpScheme; KnownMethod = VerbId; StatusCode = 200; var originalPath = GetOriginalPath(); if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawTarget, "*", StringComparison.Ordinal)) { PathBase = string.Empty; Path = string.Empty; } else { // Path and pathbase are unescaped by RequestUriBuilder // The UsePathBase middleware will modify the pathbase and path correctly PathBase = string.Empty; Path = originalPath ?? string.Empty; } var cookedUrl = GetCookedUrl(); QueryString = cookedUrl.GetQueryString() ?? string.Empty; RequestHeaders = new RequestHeaders(this); HttpResponseHeaders = new HeaderCollection(); ResponseHeaders = HttpResponseHeaders; // Request headers can be modified by the app, read these first. RequestCanHaveBody = CheckRequestCanHaveBody(); if (_options.ForwardWindowsAuthentication) { WindowsUser = GetWindowsPrincipal(); if (_options.AutomaticAuthentication) { User = WindowsUser; } } MaxRequestBodySize = _options.MaxRequestBodySize; ResetFeatureCollection(); if (!_server.IsWebSocketAvailable(_requestNativeHandle)) { _currentIHttpUpgradeFeature = null; } _streams = new Streams(this); (RequestBody, ResponseBody) = _streams.Start(); var pipe = new Pipe( new PipeOptions( _memoryPool, readerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: PauseWriterThreshold, resumeWriterThreshold: ResumeWriterTheshold, minimumSegmentSize: MinAllocBufferSize)); _bodyOutput = new OutputProducer(pipe); } NativeMethods.HttpSetManagedContext(_requestNativeHandle, (IntPtr)_thisHandle); } private string? GetOriginalPath() { var rawUrlInBytes = GetRawUrlInBytes(); // Pre Windows 10 RS2 applicationInitialization request might not have pRawUrl set, fallback to cocked url if (rawUrlInBytes.Length == 0) { return GetCookedUrl().GetAbsPath(); } // ApplicationInitialization request might have trailing \0 character included in the length // check and skip it if (rawUrlInBytes.Length > 0 && rawUrlInBytes[^1] == 0) { rawUrlInBytes = rawUrlInBytes[0..^1]; } var originalPath = RequestUriBuilder.DecodeAndUnescapePath(rawUrlInBytes); return originalPath; } public int StatusCode { get { return _statusCode; } set { if (HasResponseStarted) { ThrowResponseAlreadyStartedException(nameof(StatusCode)); } _statusCode = (ushort)value; } } public string? ReasonPhrase { get { return _reasonPhrase; } set { if (HasResponseStarted) { ThrowResponseAlreadyStartedException(nameof(ReasonPhrase)); } _reasonPhrase = value; } } internal IISHttpServer Server => _server; private bool CheckRequestCanHaveBody() { // Http/1.x requests with bodies require either a Content-Length or Transfer-Encoding header. // Note Http.Sys adds the Transfer-Encoding: chunked header to HTTP/2 requests with bodies for back compat. // Transfer-Encoding takes priority over Content-Length. string transferEncoding = RequestHeaders[HeaderNames.TransferEncoding]; if (string.Equals("chunked", transferEncoding?.Trim(), StringComparison.OrdinalIgnoreCase)) { return true; } return RequestHeaders.ContentLength.GetValueOrDefault() > 0; } private async Task InitializeResponse(bool flushHeaders) { await FireOnStarting(); if (_applicationException != null) { ThrowResponseAbortedException(); } await ProduceStart(flushHeaders); } private async Task ProduceStart(bool flushHeaders) { Debug.Assert(_hasResponseStarted == false); _hasResponseStarted = true; SetResponseHeaders(); EnsureIOInitialized(); var canHaveNonEmptyBody = StatusCodeCanHaveBody(); if (flushHeaders) { try { await AsyncIO.FlushAsync(canHaveNonEmptyBody); } // Client might be disconnected at this point // don't leak the exception catch (ConnectionResetException) { AbortIO(clientDisconnect: true); } } if (!canHaveNonEmptyBody) { _bodyOutput.Complete(); } else { _writeBodyTask = WriteBody(!flushHeaders); } } private bool StatusCodeCanHaveBody() { return StatusCode != 204 && StatusCode != 304; } private void InitializeRequestIO() { Debug.Assert(!HasStartedConsumingRequestBody); if (RequestHeaders.ContentLength > MaxRequestBodySize) { IISBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge); } HasStartedConsumingRequestBody = true; EnsureIOInitialized(); _bodyInputPipe = new Pipe(new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.ThreadPool, minimumSegmentSize: MinAllocBufferSize)); _readBodyTask = ReadBody(); } [MemberNotNull(nameof(AsyncIO))] private void EnsureIOInitialized() { // If at this point request was not upgraded just start a normal IO engine if (AsyncIO == null) { AsyncIO = new AsyncIOEngine(this, _requestNativeHandle); } } private void ThrowResponseAbortedException() { throw new ObjectDisposedException(CoreStrings.UnhandledApplicationException, _applicationException); } protected Task ProduceEnd() { if (_requestRejectedException != null || _applicationException != null) { if (HasResponseStarted) { // We can no longer change the response, so we simply close the connection. return Task.CompletedTask; } // If the request was rejected, the error state has already been set by SetBadRequestState and // that should take precedence. if (_requestRejectedException != null) { SetErrorResponseException(_requestRejectedException); } else { // 500 Internal Server Error SetErrorResponseHeaders(statusCode: StatusCodes.Status500InternalServerError); } } if (!HasResponseStarted) { return ProduceEndAwaited(); } return Task.CompletedTask; } private void SetErrorResponseHeaders(int statusCode) { StatusCode = statusCode; ReasonPhrase = string.Empty; HttpResponseHeaders.Clear(); } private async Task ProduceEndAwaited() { await ProduceStart(flushHeaders: true); await _bodyOutput.FlushAsync(default); } public unsafe void SetResponseHeaders() { // Verifies we have sent the statuscode before writing a header var reasonPhrase = string.IsNullOrEmpty(ReasonPhrase) ? ReasonPhrases.GetReasonPhrase(StatusCode) : ReasonPhrase; // This copies data into the underlying buffer NativeMethods.HttpSetResponseStatusCode(_requestNativeHandle, (ushort)StatusCode, reasonPhrase); if (HttpVersion >= System.Net.HttpVersion.Version20 && NativeMethods.HttpHasResponse4(_requestNativeHandle)) { // Check if connection close is set, if so setting goaway if (string.Equals(ConnectionClose, HttpResponseHeaders[HeaderNames.Connection], StringComparison.OrdinalIgnoreCase)) { NativeMethods.HttpSetNeedGoAway(_requestNativeHandle); } } HttpResponseHeaders.IsReadOnly = true; foreach (var headerPair in HttpResponseHeaders) { var headerValues = headerPair.Value; if (headerPair.Value.Count == 0) { continue; } var knownHeaderIndex = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerPair.Key); for (var i = 0; i < headerValues.Count; i++) { if (string.IsNullOrEmpty(headerValues[i])) { continue; } var isFirst = i == 0; var headerValueBytes = Encoding.UTF8.GetBytes(headerValues[i]); fixed (byte* pHeaderValue = headerValueBytes) { if (knownHeaderIndex == -1) { var headerNameBytes = Encoding.UTF8.GetBytes(headerPair.Key); fixed (byte* pHeaderName = headerNameBytes) { NativeMethods.HttpResponseSetUnknownHeader(_requestNativeHandle, pHeaderName, pHeaderValue, (ushort)headerValueBytes.Length, fReplace: isFirst); } } else { NativeMethods.HttpResponseSetKnownHeader(_requestNativeHandle, knownHeaderIndex, pHeaderValue, (ushort)headerValueBytes.Length, fReplace: isFirst); } } } } } public unsafe void SetResponseTrailers() { HttpResponseTrailers.IsReadOnly = true; foreach (var headerPair in HttpResponseTrailers) { var headerValues = headerPair.Value; if (headerValues.Count == 0) { continue; } var headerNameBytes = Encoding.ASCII.GetBytes(headerPair.Key); fixed (byte* pHeaderName = headerNameBytes) { var isFirst = true; for (var i = 0; i < headerValues.Count; i++) { var headerValue = headerValues[i]; if (string.IsNullOrEmpty(headerValue)) { continue; } var headerValueBytes = Encoding.UTF8.GetBytes(headerValue); fixed (byte* pHeaderValue = headerValueBytes) { NativeMethods.HttpResponseSetTrailer(_requestNativeHandle, pHeaderName, pHeaderValue, (ushort)headerValueBytes.Length, replace: isFirst); } isFirst = false; } } } } public abstract Task<bool> ProcessRequestAsync(); public void OnStarting(Func<object, Task> callback, object state) { lock (_contextLock) { if (HasResponseStarted) { throw new InvalidOperationException("Response already started"); } if (_onStarting == null) { _onStarting = new Stack<KeyValuePair<Func<object, Task>, object>>(); } _onStarting.Push(new KeyValuePair<Func<object, Task>, object>(callback, state)); } } public void OnCompleted(Func<object, Task> callback, object state) { lock (_contextLock) { if (_onCompleted == null) { _onCompleted = new Stack<KeyValuePair<Func<object, Task>, object>>(); } _onCompleted.Push(new KeyValuePair<Func<object, Task>, object>(callback, state)); } } protected async Task FireOnStarting() { Stack<KeyValuePair<Func<object, Task>, object>>? onStarting = null; lock (_contextLock) { onStarting = _onStarting; _onStarting = null; } if (onStarting != null) { try { foreach (var entry in onStarting) { await entry.Key.Invoke(entry.Value); } } catch (Exception ex) { ReportApplicationError(ex); } } } protected async Task FireOnCompleted() { Stack<KeyValuePair<Func<object, Task>, object>>? onCompleted = null; lock (_contextLock) { onCompleted = _onCompleted; _onCompleted = null; } if (onCompleted != null) { foreach (var entry in onCompleted) { try { await entry.Key.Invoke(entry.Value); } catch (Exception ex) { Log.ApplicationError(_logger, ((IHttpConnectionFeature)this).ConnectionId, ((IHttpRequestIdentifierFeature)this).TraceIdentifier, ex); } } } } public void SetBadRequestState(BadHttpRequestException ex) { Log.ConnectionBadRequest(_logger, ((IHttpConnectionFeature)this).ConnectionId, ex); if (!HasResponseStarted) { SetErrorResponseException(ex); } _requestRejectedException = ex; } private void SetErrorResponseException(BadHttpRequestException ex) { SetErrorResponseHeaders(ex.StatusCode); } protected void ReportApplicationError(Exception ex) { if (_applicationException == null) { _applicationException = ex; } else if (_applicationException is AggregateException) { _applicationException = new AggregateException(_applicationException, ex).Flatten(); } else { _applicationException = new AggregateException(_applicationException, ex); } Log.ApplicationError(_logger, ((IHttpConnectionFeature)this).ConnectionId, ((IHttpRequestIdentifierFeature)this).TraceIdentifier, ex); } public void PostCompletion(NativeMethods.REQUEST_NOTIFICATION_STATUS requestNotificationStatus) { NativeMethods.HttpSetCompletionStatus(_requestNativeHandle, requestNotificationStatus); NativeMethods.HttpPostCompletion(_requestNativeHandle, 0); } internal void OnAsyncCompletion(int hr, int bytes) { AsyncIO!.NotifyCompletion(hr, bytes); } private bool disposedValue; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _thisHandle.Free(); } if (WindowsUser?.Identity is WindowsIdentity wi) { wi.Dispose(); } // Lock to prevent CancelRequestAbortedToken from attempting to cancel a disposed CTS. CancellationTokenSource? localAbortCts = null; lock (_abortLock) { localAbortCts = _abortedCts; _abortedCts = null; } localAbortCts?.Dispose(); disposedValue = true; } } public override void Dispose() { Dispose(disposing: true); } private void ThrowResponseAlreadyStartedException(string name) { throw new InvalidOperationException(CoreStrings.FormatParameterReadOnlyAfterResponseStarted(name)); } private WindowsPrincipal? GetWindowsPrincipal() { NativeMethods.HttpGetAuthenticationInformation(_requestNativeHandle, out var authenticationType, out var token); if (token != IntPtr.Zero && authenticationType != null) { if ((authenticationType.Equals(NtlmString, StringComparison.OrdinalIgnoreCase) || authenticationType.Equals(NegotiateString, StringComparison.OrdinalIgnoreCase) || authenticationType.Equals(BasicString, StringComparison.OrdinalIgnoreCase))) { return new WindowsPrincipal(new WindowsIdentity(token, authenticationType)); } } return null; } // Invoked by the thread pool public void Execute() { _ = HandleRequest(); } private async Task HandleRequest() { bool successfulRequest = false; try { successfulRequest = await ProcessRequestAsync(); } catch (Exception ex) { _logger.LogError(0, ex, $"Unexpected exception in {nameof(IISHttpContext)}.{nameof(HandleRequest)}."); } finally { // Post completion after completing the request to resume the state machine PostCompletion(ConvertRequestCompletionResults(successfulRequest)); // After disposing a safe handle, Dispose() will not block waiting for the pinvokes to finish. // Instead Safehandle will call ReleaseHandle on the pinvoke thread when the pinvokes complete // and the reference count goes to zero. // What this means is we need to wait until ReleaseHandle is called to finish disposal. // This is to make sure it is safe to return back to native. // The handle implements IValueTaskSource _requestNativeHandle.Dispose(); await new ValueTask<object?>(_requestNativeHandle, _requestNativeHandle.Version); // Dispose the context Dispose(); } } private static NativeMethods.REQUEST_NOTIFICATION_STATUS ConvertRequestCompletionResults(bool success) { return success ? NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_CONTINUE : NativeMethods.REQUEST_NOTIFICATION_STATUS.RQ_NOTIFICATION_FINISH_REQUEST; } } }
36.414702
176
0.561074
[ "Apache-2.0" ]
Asifshikder/aspnetcore
src/Servers/IIS/IIS/src/Core/IISHttpContext.cs
26,255
C#
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using System.Threading.Tasks; //using Model.Inputs; //using Model.Inputs.Conditions; //namespace Model.Outputs //{ // internal class Result // { // #region Properties // public ICondition Condition { get; } // //public int TimeStampSeed { get; private set; } // // public Random SeedGenerator { get; private set; } // public int IterationCount { get; private set; } = 0; // public bool Converged { get; private set; } = false; // public int MaxIterations { get; set; } = 500000; // //public IList<int> IterationSeedContainer { get; private set; } = new List<int>(); // //public Statistics.Histogram Aep { get; private set; } = new Statistics.Histogram(50, 0.5, 0.001, false); // //public Statistics.Histogram Ead { get; private set; } = new Statistics.Histogram(50, 0, 1000000, false); // public IDictionary<IMetricEnum, Statistics.IHistogram> Metrics = new Dictionary<IMetricEnum, Statistics.IHistogram>(); // public System.Collections.Concurrent.ConcurrentDictionary<int, IDictionary<IMetric, double>> Realizations { get; } // public int Seed { get; } // //public List<IRealization> RealizationIds { get; } // //public int PacketSize { get; } // #endregion // #region Constructor // public Result(ICondition condition) : this(condition, (int)new DateTime().Ticks) // { // } // public Result(ICondition condition, int seed) // { // Condition = condition; // Metrics = new Dictionary<IMetricEnum, Statistics.IHistogram>(); // Realizations = new System.Collections.Concurrent.ConcurrentDictionary<int, IDictionary<IMetric, double>>(); // Seed = seed; // } // #endregion // #region Methods // public void Compute(List<List<double>> allProbabilities) // { // if (Condition.IsValid == false) { Condition.ReportValidationErrors(); return; } // int realizationNumber = allProbabilities.Count; // int numProbs = allProbabilities[0].Count; // IterationCount = 0; // //int randomPacketSize = Condition.TransformFunctions.Count + 1; // //Random randomNumberGenerator = new Random(Seed); // //the current realization // int localIteration = 0; // int batchCount = 1;// 1000; // MaxIterations = 1; // //List<List<double>> allProbabilities = CreateAllProbabilities(randomNumberGenerator, batchCount, randomPacketSize); // while (Converged == false && // IterationCount < MaxIterations) // { // localIteration = IterationCount; // batchCount = Math.Min(batchCount, MaxIterations); // Parallel.For(localIteration, localIteration + batchCount, i => // { // //List<double> randomNumbers = new List<double>(); // //for(int k = 0;k<randomPacketSize;k++) // //{ // // randomNumbers.Add(randomNumberGenerator.NextDouble()); // //} // IDictionary<IMetric, double> conditionResults = Condition.Compute(allProbabilities[i]); // bool success = Realizations.TryAdd(i, conditionResults); // if(!success) // { // throw new Exception("The result compute tried to put the same id into the dictionary a second time."); // } // IterationCount++; // }); // } // } // private List<List<double>> CreateAllProbabilities(Random RNG, int numComputes, int packetSize) // { // List<List<double>> allProbabilities = new List<List<double>>(); // for(int i = 0;i<numComputes;i++) // { // List<double> probs = new List<double>(); // for(int j=0;j<packetSize;j++) // { // probs.Add(RNG.NextDouble()); // } // allProbabilities.Add(probs); // } // return allProbabilities; // } // //private IDictionary<ComputePointUnitTypeEnum, Statistics.Histogram> InitializeMetrics() // //{ // // Metrics = new Dictionary<ComputePointUnitTypeEnum, Statistics.Histogram>(); // // foreach (var point in Condition.ComputePoints) // // { // // Metrics.Add(point.Unit, new Statistics.Histogram(50, )) // // } // //} // //private void AddMetricsTestConvergence() // //{ // // foreach (var metric in Condition.Metrics) // // { // // if (Metrics.ContainsKey(metric.Key)) Metrics[metric.Key] = // // } // //} // #endregion // } //}
42.59322
130
0.549741
[ "MIT" ]
HydrologicEngineeringCenter/HEC-FDA
Model/Outputs/Result.cs
5,028
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.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.Arm { /// <summary> /// This class provides access to the ARM AdvSIMD hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class AdvSimd : ArmBase { internal AdvSimd() { } public static new bool IsSupported { get => IsSupported; } [Intrinsic] public new abstract class Arm64 : ArmBase.Arm64 { internal Arm64() { } public static new bool IsSupported { get => IsSupported; } /// <summary> /// float64x2_t vabsq_f64 (float64x2_t a) /// A64: FABS Vd.2D, Vn.2D /// </summary> public static Vector128<double> Abs(Vector128<double> value) => Abs(value); /// <summary> /// int64x2_t vabsq_s64 (int64x2_t a) /// A64: ABS Vd.2D, Vn.2D /// </summary> public static Vector128<ulong> Abs(Vector128<long> value) => Abs(value); // /// <summary> // /// int64x1_t vabs_s64 (int64x1_t a) // /// A64: ABS Dd, Dn // /// </summary> // public static Vector64<ulong> AbsScalar(Vector64<long> value) => AbsScalar(value); /// <summary> /// float64x2_t vaddq_f64 (float64x2_t a, float64x2_t b) /// A64: FADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) => Add(left, right); /// <summary> /// uint8_t vaddv_u8(uint8x8_t a) /// A64: ADDV Bd, Vn.8B /// </summary> public static byte AddAcross(Vector64<byte> value) => AddAcross(value); /// <summary> /// int16_t vaddv_s16(int16x4_t a) /// A64: ADDV Hd, Vn.4H /// </summary> public static short AddAcross(Vector64<short> value) => AddAcross(value); /// <summary> /// int8_t vaddv_s8(int8x8_t a) /// A64: ADDV Bd, Vn.8B /// </summary> public static sbyte AddAcross(Vector64<sbyte> value) => AddAcross(value); /// <summary> /// uint16_t vaddv_u16(uint16x4_t a) /// A64: ADDV Hd, Vn.4H /// </summary> public static ushort AddAcross(Vector64<ushort> value) => AddAcross(value); /// <summary> /// uint8_t vaddvq_u8(uint8x16_t a) /// A64: ADDV Bd, Vn.16B /// </summary> public static byte AddAcross(Vector128<byte> value) => AddAcross(value); /// <summary> /// int16_t vaddvq_s16(int16x8_t a) /// A64: ADDV Hd, Vn.8H /// </summary> public static short AddAcross(Vector128<short> value) => AddAcross(value); /// <summary> /// int32_t vaddvq_s32(int32x4_t a) /// A64: ADDV Sd, Vn.4S /// </summary> public static int AddAcross(Vector128<int> value) => AddAcross(value); /// <summary> /// int8_t vaddvq_s8(int8x16_t a) /// A64: ADDV Bd, Vn.16B /// </summary> public static sbyte AddAcross(Vector128<sbyte> value) => AddAcross(value); /// <summary> /// uint16_t vaddvq_u16(uint16x8_t a) /// A64: ADDV Hd, Vn.8H /// </summary> public static ushort AddAcross(Vector128<ushort> value) => AddAcross(value); /// <summary> /// uint32_t vaddvq_u32(uint32x4_t a) /// A64: ADDV Sd, Vn.4S /// </summary> public static uint AddAcross(Vector128<uint> value) => AddAcross(value); /// <summary> /// float64x2_t vsubq_f64 (float64x2_t a, float64x2_t b) /// A64: FSUB Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> Subtract(Vector128<double> left, Vector128<double> right) => Add(left, right); /// <summary> /// uint8x8_t vrbit_u8 (uint8x8_t a) /// A64: RBIT Vd.8B, Vn.8B /// </summary> public static Vector64<byte> ReverseElementBits(Vector64<byte> value) => ReverseElementBits(value); /// <summary> /// int8x8_t vrbit_s8 (int8x8_t a) /// A64: RBIT Vd.8B, Vn.8B /// </summary> public static Vector64<sbyte> ReverseElementBits(Vector64<sbyte> value) => ReverseElementBits(value); /// <summary> /// uint8x16_t vrbitq_u8 (uint8x16_t a) /// A64: RBIT Vd.16B, Vn.16B /// </summary> public static Vector128<byte> ReverseElementBits(Vector128<byte> value) => ReverseElementBits(value); /// <summary> /// int8x16_t vrbitq_s8 (int8x16_t a) /// A64: RBIT Vd.16B, Vn.16B /// </summary> public static Vector128<sbyte> ReverseElementBits(Vector128<sbyte> value) => ReverseElementBits(value); /// <summary> /// uint8x8_t vuzp1_u8(uint8x8_t a, uint8x8_t b) /// A64: UZP1 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> UnzipEven(Vector64<byte> left, Vector64<byte> right) => UnzipEven(left, right); /// <summary> /// int16x4_t vuzp1_s16(int16x4_t a, int16x4_t b) /// A64: UZP1 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> UnzipEven(Vector64<short> left, Vector64<short> right) => UnzipEven(left, right); /// <summary> /// int32x2_t vuzp1_s32(int32x2_t a, int32x2_t b) /// A64: UZP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> UnzipEven(Vector64<int> left, Vector64<int> right) => UnzipEven(left, right); /// <summary> /// int8x8_t vuzp1_s8(int8x8_t a, int8x8_t b) /// A64: UZP1 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> UnzipEven(Vector64<sbyte> left, Vector64<sbyte> right) => UnzipEven(left, right); /// <summary> /// float32x2_t vuzp1_f32(float32x2_t a, float32x2_t b) /// A64: UZP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> UnzipEven(Vector64<float> left, Vector64<float> right) => UnzipEven(left, right); /// <summary> /// uint16x4_t vuzp1_u16(uint16x4_t a, uint16x4_t b) /// A64: UZP1 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> UnzipEven(Vector64<ushort> left, Vector64<ushort> right) => UnzipEven(left, right); /// <summary> /// uint32x2_t vuzp1_u32(uint32x2_t a, uint32x2_t b) /// A64: UZP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> UnzipEven(Vector64<uint> left, Vector64<uint> right) => UnzipEven(left, right); /// <summary> /// uint8x16_t vuzp1q_u8(uint8x16_t a, uint8x16_t b) /// A64: UZP1 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> UnzipEven(Vector128<byte> left, Vector128<byte> right) => UnzipEven(left, right); /// <summary> /// float64x2_t vuzp1q_f64(float64x2_t a, float64x2_t b) /// A64: UZP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> UnzipEven(Vector128<double> left, Vector128<double> right) => UnzipEven(left, right); /// <summary> /// int16x8_t vuzp1q_s16(int16x8_t a, int16x8_t b) /// A64: UZP1 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> UnzipEven(Vector128<short> left, Vector128<short> right) => UnzipEven(left, right); /// <summary> /// int32x4_t vuzp1q_s32(int32x4_t a, int32x4_t b) /// A64: UZP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> UnzipEven(Vector128<int> left, Vector128<int> right) => UnzipEven(left, right); /// <summary> /// int64x2_t vuzp1q_s64(int64x2_t a, int64x2_t b) /// A64: UZP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> UnzipEven(Vector128<long> left, Vector128<long> right) => UnzipEven(left, right); /// <summary> /// int8x16_t vuzp1q_u8(int8x16_t a, int8x16_t b) /// A64: UZP1 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> UnzipEven(Vector128<sbyte> left, Vector128<sbyte> right) => UnzipEven(left, right); /// <summary> /// float32x4_t vuzp1q_f32(float32x4_t a, float32x4_t b) /// A64: UZP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> UnzipEven(Vector128<float> left, Vector128<float> right) => UnzipEven(left, right); /// <summary> /// uint16x8_t vuzp1q_u16(uint16x8_t a, uint16x8_t b) /// A64: UZP1 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> UnzipEven(Vector128<ushort> left, Vector128<ushort> right) => UnzipEven(left, right); /// <summary> /// uint32x4_t vuzp1q_u32(uint32x4_t a, uint32x4_t b) /// A64: UZP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> UnzipEven(Vector128<uint> left, Vector128<uint> right) => UnzipEven(left, right); /// <summary> /// uint64x2_t vuzp1q_u64(uint64x2_t a, uint64x2_t b) /// A64: UZP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> UnzipEven(Vector128<ulong> left, Vector128<ulong> right) => UnzipEven(left, right); /// <summary> /// uint8x8_t vuzp2_u8(uint8x8_t a, uint8x8_t b) /// A64: UZP2 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> UnzipOdd(Vector64<byte> left, Vector64<byte> right) => UnzipOdd(left, right); /// <summary> /// int16x4_t vuzp2_s16(int16x4_t a, int16x4_t b) /// A64: UZP2 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> UnzipOdd(Vector64<short> left, Vector64<short> right) => UnzipOdd(left, right); /// <summary> /// int32x2_t vuzp2_s32(int32x2_t a, int32x2_t b) /// A64: UZP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> UnzipOdd(Vector64<int> left, Vector64<int> right) => UnzipOdd(left, right); /// <summary> /// int8x8_t vuzp2_s8(int8x8_t a, int8x8_t b) /// A64: UZP2 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> UnzipOdd(Vector64<sbyte> left, Vector64<sbyte> right) => UnzipOdd(left, right); /// <summary> /// float32x2_t vuzp2_f32(float32x2_t a, float32x2_t b) /// A64: UZP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> UnzipOdd(Vector64<float> left, Vector64<float> right) => UnzipOdd(left, right); /// <summary> /// uint16x4_t vuzp2_u16(uint16x4_t a, uint16x4_t b) /// A64: UZP2 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> UnzipOdd(Vector64<ushort> left, Vector64<ushort> right) => UnzipOdd(left, right); /// <summary> /// uint32x2_t vuzp2_u32(uint32x2_t a, uint32x2_t b) /// A64: UZP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> UnzipOdd(Vector64<uint> left, Vector64<uint> right) => UnzipOdd(left, right); /// <summary> /// uint8x16_t vuzp2q_u8(uint8x16_t a, uint8x16_t b) /// A64: UZP2 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> UnzipOdd(Vector128<byte> left, Vector128<byte> right) => UnzipOdd(left, right); /// <summary> /// float64x2_t vuzp2q_f64(float64x2_t a, float64x2_t b) /// A64: UZP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> UnzipOdd(Vector128<double> left, Vector128<double> right) => UnzipOdd(left, right); /// <summary> /// int16x8_t vuzp2q_s16(int16x8_t a, int16x8_t b) /// A64: UZP2 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> UnzipOdd(Vector128<short> left, Vector128<short> right) => UnzipOdd(left, right); /// <summary> /// int32x4_t vuzp2q_s32(int32x4_t a, int32x4_t b) /// A64: UZP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> UnzipOdd(Vector128<int> left, Vector128<int> right) => UnzipOdd(left, right); /// <summary> /// int64x2_t vuzp2q_s64(int64x2_t a, int64x2_t b) /// A64: UZP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> UnzipOdd(Vector128<long> left, Vector128<long> right) => UnzipOdd(left, right); /// <summary> /// int8x16_t vuzp2q_u8(int8x16_t a, int8x16_t b) /// A64: UZP2 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> UnzipOdd(Vector128<sbyte> left, Vector128<sbyte> right) => UnzipOdd(left, right); /// <summary> /// float32x4_t vuzp2q_f32(float32x4_t a, float32x4_t b) /// A64: UZP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> UnzipOdd(Vector128<float> left, Vector128<float> right) => UnzipOdd(left, right); /// <summary> /// uint16x8_t vuzp2q_u16(uint16x8_t a, uint16x8_t b) /// A64: UZP2 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> UnzipOdd(Vector128<ushort> left, Vector128<ushort> right) => UnzipOdd(left, right); /// <summary> /// uint32x4_t vuzp2q_u32(uint32x4_t a, uint32x4_t b) /// A64: UZP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> UnzipOdd(Vector128<uint> left, Vector128<uint> right) => UnzipOdd(left, right); /// <summary> /// uint64x2_t vuzp2q_u64(uint64x2_t a, uint64x2_t b) /// A64: UZP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> UnzipOdd(Vector128<ulong> left, Vector128<ulong> right) => UnzipOdd(left, right); /// <summary> /// uint8x8_t vzip2_u8(uint8x8_t a, uint8x8_t b) /// A64: ZIP2 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> ZipHigh(Vector64<byte> left, Vector64<byte> right) => ZipHigh(left, right); /// <summary> /// int16x4_t vzip2_s16(int16x4_t a, int16x4_t b) /// A64: ZIP2 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> ZipHigh(Vector64<short> left, Vector64<short> right) => ZipHigh(left, right); /// <summary> /// int32x2_t vzip2_s32(int32x2_t a, int32x2_t b) /// A64: ZIP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> ZipHigh(Vector64<int> left, Vector64<int> right) => ZipHigh(left, right); /// <summary> /// int8x8_t vzip2_s8(int8x8_t a, int8x8_t b) /// A64: ZIP2 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> ZipHigh(Vector64<sbyte> left, Vector64<sbyte> right) => ZipHigh(left, right); /// <summary> /// float32x2_t vzip2_f32(float32x2_t a, float32x2_t b) /// A64: ZIP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> ZipHigh(Vector64<float> left, Vector64<float> right) => ZipHigh(left, right); /// <summary> /// uint16x4_t vzip2_u16(uint16x4_t a, uint16x4_t b) /// A64: ZIP2 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> ZipHigh(Vector64<ushort> left, Vector64<ushort> right) => ZipHigh(left, right); /// <summary> /// uint32x2_t vzip2_u32(uint32x2_t a, uint32x2_t b) /// A64: ZIP2 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> ZipHigh(Vector64<uint> left, Vector64<uint> right) => ZipHigh(left, right); /// <summary> /// uint8x16_t vzip2q_u8(uint8x16_t a, uint8x16_t b) /// A64: ZIP2 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> ZipHigh(Vector128<byte> left, Vector128<byte> right) => ZipHigh(left, right); /// <summary> /// float64x2_t vzip2q_f64(float64x2_t a, float64x2_t b) /// A64: ZIP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> ZipHigh(Vector128<double> left, Vector128<double> right) => ZipHigh(left, right); /// <summary> /// int16x8_t vzip2q_s16(int16x8_t a, int16x8_t b) /// A64: ZIP2 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> ZipHigh(Vector128<short> left, Vector128<short> right) => ZipHigh(left, right); /// <summary> /// int32x4_t vzip2q_s32(int32x4_t a, int32x4_t b) /// A64: ZIP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> ZipHigh(Vector128<int> left, Vector128<int> right) => ZipHigh(left, right); /// <summary> /// int64x2_t vzip2q_s64(int64x2_t a, int64x2_t b) /// A64: ZIP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> ZipHigh(Vector128<long> left, Vector128<long> right) => ZipHigh(left, right); /// <summary> /// int8x16_t vzip2q_u8(int8x16_t a, int8x16_t b) /// A64: ZIP2 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> ZipHigh(Vector128<sbyte> left, Vector128<sbyte> right) => ZipHigh(left, right); /// <summary> /// float32x4_t vzip2q_f32(float32x4_t a, float32x4_t b) /// A64: ZIP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> ZipHigh(Vector128<float> left, Vector128<float> right) => ZipHigh(left, right); /// <summary> /// uint16x8_t vzip2q_u16(uint16x8_t a, uint16x8_t b) /// A64: ZIP2 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> ZipHigh(Vector128<ushort> left, Vector128<ushort> right) => ZipHigh(left, right); /// <summary> /// uint32x4_t vzip2q_u32(uint32x4_t a, uint32x4_t b) /// A64: ZIP2 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> ZipHigh(Vector128<uint> left, Vector128<uint> right) => ZipHigh(left, right); /// <summary> /// uint64x2_t vzip2q_u64(uint64x2_t a, uint64x2_t b) /// A64: ZIP2 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> ZipHigh(Vector128<ulong> left, Vector128<ulong> right) => ZipHigh(left, right); /// <summary> /// uint8x8_t vzip1_u8(uint8x8_t a, uint8x8_t b) /// A64: ZIP1 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> ZipLow(Vector64<byte> left, Vector64<byte> right) => ZipLow(left, right); /// <summary> /// int16x4_t vzip1_s16(int16x4_t a, int16x4_t b) /// A64: ZIP1 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> ZipLow(Vector64<short> left, Vector64<short> right) => ZipLow(left, right); /// <summary> /// int32x2_t vzip1_s32(int32x2_t a, int32x2_t b) /// A64: ZIP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> ZipLow(Vector64<int> left, Vector64<int> right) => ZipLow(left, right); /// <summary> /// int8x8_t vzip1_s8(int8x8_t a, int8x8_t b) /// A64: ZIP1 Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> ZipLow(Vector64<sbyte> left, Vector64<sbyte> right) => ZipLow(left, right); /// <summary> /// float32x2_t vzip1_f32(float32x2_t a, float32x2_t b) /// A64: ZIP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> ZipLow(Vector64<float> left, Vector64<float> right) => ZipLow(left, right); /// <summary> /// uint16x4_t vzip1_u16(uint16x4_t a, uint16x4_t b) /// A64: ZIP1 Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> ZipLow(Vector64<ushort> left, Vector64<ushort> right) => ZipLow(left, right); /// <summary> /// uint32x2_t vzip1_u32(uint32x2_t a, uint32x2_t b) /// A64: ZIP1 Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> ZipLow(Vector64<uint> left, Vector64<uint> right) => ZipLow(left, right); /// <summary> /// uint8x16_t vzip1q_u8(uint8x16_t a, uint8x16_t b) /// A64: ZIP1 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> ZipLow(Vector128<byte> left, Vector128<byte> right) => ZipLow(left, right); /// <summary> /// float64x2_t vzip1q_f64(float64x2_t a, float64x2_t b) /// A64: ZIP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> ZipLow(Vector128<double> left, Vector128<double> right) => ZipLow(left, right); /// <summary> /// int16x8_t vzip1q_s16(int16x8_t a, int16x8_t b) /// A64: ZIP1 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> ZipLow(Vector128<short> left, Vector128<short> right) => ZipLow(left, right); /// <summary> /// int32x4_t vzip1q_s32(int32x4_t a, int32x4_t b) /// A64: ZIP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> ZipLow(Vector128<int> left, Vector128<int> right) => ZipLow(left, right); /// <summary> /// int64x2_t vzip1q_s64(int64x2_t a, int64x2_t b) /// A64: ZIP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> ZipLow(Vector128<long> left, Vector128<long> right) => ZipLow(left, right); /// <summary> /// int8x16_t vzip1q_u8(int8x16_t a, int8x16_t b) /// A64: ZIP1 Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> ZipLow(Vector128<sbyte> left, Vector128<sbyte> right) => ZipLow(left, right); /// <summary> /// float32x4_t vzip1q_f32(float32x4_t a, float32x4_t b) /// A64: ZIP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> ZipLow(Vector128<float> left, Vector128<float> right) => ZipLow(left, right); /// <summary> /// uint16x8_t vzip1q_u16(uint16x8_t a, uint16x8_t b) /// A64: ZIP1 Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> ZipLow(Vector128<ushort> left, Vector128<ushort> right) => ZipLow(left, right); /// <summary> /// uint32x4_t vzip1q_u32(uint32x4_t a, uint32x4_t b) /// A64: ZIP1 Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> ZipLow(Vector128<uint> left, Vector128<uint> right) => ZipLow(left, right); /// <summary> /// uint64x2_t vzip1q_u64(uint64x2_t a, uint64x2_t b) /// A64: ZIP1 Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> ZipLow(Vector128<ulong> left, Vector128<ulong> right) => ZipLow(left, right); } /// <summary> /// int8x8_t vabs_s8 (int8x8_t a) /// A32: VABS.S8 Dd, Dm /// A64: ABS Vd.8B, Vn.8B /// </summary> public static Vector64<byte> Abs(Vector64<sbyte> value) => Abs(value); /// <summary> /// int16x4_t vabs_s16 (int16x4_t a) /// A32: VABS.S16 Dd, Dm /// A64: ABS Vd.4H, Vn.4H /// </summary> public static Vector64<ushort> Abs(Vector64<short> value) => Abs(value); /// <summary> /// int32x2_t vabs_s32 (int32x2_t a) /// A32: VABS.S32 Dd, Dm /// A64: ABS Vd.2S, Vn.2S /// </summary> public static Vector64<uint> Abs(Vector64<int> value) => Abs(value); /// <summary> /// float32x2_t vabs_f32 (float32x2_t a) /// A32: VABS.F32 Dd, Dm /// A64: FABS Vd.2S, Vn.2S /// </summary> public static Vector64<float> Abs(Vector64<float> value) => Abs(value); /// <summary> /// int8x16_t vabsq_s8 (int8x16_t a) /// A32: VABS.S8 Qd, Qm /// A64: ABS Vd.16B, Vn.16B /// </summary> public static Vector128<byte> Abs(Vector128<sbyte> value) => Abs(value); /// <summary> /// int16x8_t vabsq_s16 (int16x8_t a) /// A32: VABS.S16 Qd, Qm /// A64: ABS Vd.8H, Vn.8H /// </summary> public static Vector128<ushort> Abs(Vector128<short> value) => Abs(value); /// <summary> /// int32x4_t vabsq_s32 (int32x4_t a) /// A32: VABS.S32 Qd, Qm /// A64: ABS Vd.4S, Vn.4S /// </summary> public static Vector128<uint> Abs(Vector128<int> value) => Abs(value); /// <summary> /// float32x4_t vabsq_f32 (float32x4_t a) /// A32: VABS.F32 Qd, Qm /// A64: FABS Vd.4S, Vn.4S /// </summary> public static Vector128<float> Abs(Vector128<float> value) => Abs(value); // /// <summary> // /// float64x1_t vabs_f64 (float64x1_t a) // /// A32: VABS.F64 Dd, Dm // /// A64: FABS Dd, Dn // /// </summary> // public static Vector64<double> AbsScalar(Vector64<double> value) => Abs(value); /// <summary> /// A32: VABS.F32 Sd, Sm /// A64: FABS Sd, Sn /// </summary> public static Vector64<float> AbsScalar(Vector64<float> value) => AbsScalar(value); /// <summary> /// uint8x8_t vadd_u8 (uint8x8_t a, uint8x8_t b) /// A32: VADD.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> Add(Vector64<byte> left, Vector64<byte> right) => Add(left, right); /// <summary> /// int16x4_t vadd_s16 (int16x4_t a, int16x4_t b) /// A32: VADD.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> Add(Vector64<short> left, Vector64<short> right) => Add(left, right); /// <summary> /// int32x2_t vadd_s32 (int32x2_t a, int32x2_t b) /// A32: VADD.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> Add(Vector64<int> left, Vector64<int> right) => Add(left, right); /// <summary> /// int8x8_t vadd_s8 (int8x8_t a, int8x8_t b) /// A32: VADD.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> Add(Vector64<sbyte> left, Vector64<sbyte> right) => Add(left, right); /// <summary> /// float32x2_t vadd_f32 (float32x2_t a, float32x2_t b) /// A32: VADD.F32 Dd, Dn, Dm /// A64: FADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> Add(Vector64<float> left, Vector64<float> right) => Add(left, right); /// <summary> /// uint16x4_t vadd_u16 (uint16x4_t a, uint16x4_t b) /// A32: VADD.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> Add(Vector64<ushort> left, Vector64<ushort> right) => Add(left, right); /// <summary> /// uint32x2_t vadd_u32 (uint32x2_t a, uint32x2_t b) /// A32: VADD.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> Add(Vector64<uint> left, Vector64<uint> right) => Add(left, right); /// <summary> /// uint8x16_t vaddq_u8 (uint8x16_t a, uint8x16_t b) /// A32: VADD.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) => Add(left, right); /// <summary> /// int16x8_t vaddq_s16 (int16x8_t a, int16x8_t b) /// A32: VADD.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) => Add(left, right); /// <summary> /// int32x4_t vaddq_s32 (int32x4_t a, int32x4_t b) /// A32: VADD.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) => Add(left, right); /// <summary> /// int64x2_t vaddq_s64 (int64x2_t a, int64x2_t b) /// A32: VADD.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> Add(Vector128<long> left, Vector128<long> right) => Add(left, right); /// <summary> /// int8x16_t vaddq_s8 (int8x16_t a, int8x16_t b) /// A32: VADD.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) => Add(left, right); /// <summary> /// float32x4_t vaddq_f32 (float32x4_t a, float32x4_t b) /// A32: VADD.F32 Qd, Qn, Qm /// A64: FADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) => Add(left, right); /// <summary> /// uint16x8_t vaddq_u16 (uint16x8_t a, uint16x8_t b) /// A32: VADD.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) => Add(left, right); /// <summary> /// uint32x4_t vaddq_u32 (uint32x4_t a, uint32x4_t b) /// A32: VADD.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) => Add(left, right); /// <summary> /// uint64x2_t vaddq_u64 (uint64x2_t a, uint64x2_t b) /// A32: VADD.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> Add(Vector128<ulong> left, Vector128<ulong> right) => Add(left, right); // /// <summary> // /// float64x1_t vadd_f64 (float64x1_t a, float64x1_t b) // /// A32: VADD.F64 Dd, Dn, Dm // /// A64: FADD Dd, Dn, Dm // /// </summary> // public static Vector64<double> AddScalar(Vector64<double> left, Vector64<double> right) => Add(left, right); // /// <summary> // /// int64x1_t vadd_s64 (int64x1_t a, int64x1_t b) // /// A32: VADD.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<long> AddScalar(Vector64<long> left, Vector64<long> right) => AddScalar(left, right); // /// <summary> // /// uint64x1_t vadd_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VADD.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<ulong> AddScalar(Vector64<ulong> left, Vector64<ulong> right) => AddScalar(left, right); /// <summary> /// A32: VADD.F32 Sd, Sn, Sm /// A64: /// </summary> public static Vector64<float> AddScalar(Vector64<float> left, Vector64<float> right) => AddScalar(left, right); /// <summary> /// uint8x8_t vand_u8 (uint8x8_t a, uint8x8_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<byte> And(Vector64<byte> left, Vector64<byte> right) => And(left, right); // /// <summary> // /// float64x1_t vand_f64 (float64x1_t a, float64x1_t b) // /// A32: VAND Dd, Dn, Dm // /// A64: AND Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> And(Vector64<double> left, Vector64<double> right) => And(left, right); /// <summary> /// int16x4_t vand_s16 (int16x4_t a, int16x4_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<short> And(Vector64<short> left, Vector64<short> right) => And(left, right); /// <summary> /// int32x2_t vand_s32(int32x2_t a, int32x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<int> And(Vector64<int> left, Vector64<int> right) => And(left, right); // /// <summary> // /// int64x1_t vand_s64 (int64x1_t a, int64x1_t b) // /// A32: VAND Dd, Dn, Dm // /// A64: AND Vd, Vn, Vm // /// </summary> // public static Vector64<long> And(Vector64<long> left, Vector64<long> right) => And(left, right); /// <summary> /// int8x8_t vand_s8 (int8x8_t a, int8x8_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<sbyte> And(Vector64<sbyte> left, Vector64<sbyte> right) => And(left, right); /// <summary> /// float32x2_t vand_f32 (float32x2_t a, float32x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> And(Vector64<float> left, Vector64<float> right) => And(left, right); /// <summary> /// uint16x4_t vand_u16 (uint16x4_t a, uint16x4_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<ushort> And(Vector64<ushort> left, Vector64<ushort> right) => And(left, right); /// <summary> /// uint32x2_t vand_u32 (uint32x2_t a, uint32x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector64<uint> And(Vector64<uint> left, Vector64<uint> right) => And(left, right); // /// <summary> // /// uint64x1_t vand_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VAND Dd, Dn, Dm // /// A64: AND Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> And(Vector64<ulong> left, Vector64<ulong> right) => And(left, right); /// <summary> /// uint8x16_t vand_u8 (uint8x16_t a, uint8x16_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<byte> And(Vector128<byte> left, Vector128<byte> right) => And(left, right); /// <summary> /// float64x2_t vand_f64 (float64x2_t a, float64x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> And(Vector128<double> left, Vector128<double> right) => And(left, right); /// <summary> /// int16x8_t vand_s16 (int16x8_t a, int16x8_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<short> And(Vector128<short> left, Vector128<short> right) => And(left, right); /// <summary> /// int32x4_t vand_s32(int32x4_t a, int32x4_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<int> And(Vector128<int> left, Vector128<int> right) => And(left, right); /// <summary> /// int64x2_t vand_s64 (int64x2_t a, int64x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<long> And(Vector128<long> left, Vector128<long> right) => And(left, right); /// <summary> /// int8x16_t vand_s8 (int8x16_t a, int8x16_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<sbyte> And(Vector128<sbyte> left, Vector128<sbyte> right) => And(left, right); /// <summary> /// float32x4_t vand_f32 (float32x4_t a, float32x4_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> And(Vector128<float> left, Vector128<float> right) => And(left, right); /// <summary> /// uint16x8_t vand_u16 (uint16x8_t a, uint16x8_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<ushort> And(Vector128<ushort> left, Vector128<ushort> right) => And(left, right); /// <summary> /// uint32x4_t vand_u32 (uint32x4_t a, uint32x4_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<uint> And(Vector128<uint> left, Vector128<uint> right) => And(left, right); /// <summary> /// uint64x2_t vand_u64 (uint64x2_t a, uint64x2_t b) /// A32: VAND Dd, Dn, Dm /// A64: AND Vd, Vn, Vm /// </summary> public static Vector128<ulong> And(Vector128<ulong> left, Vector128<ulong> right) => And(left, right); /// <summary> /// uint8x8_t vbic_u8 (uint8x8_t a, uint8x8_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<byte> AndNot(Vector64<byte> left, Vector64<byte> right) => AndNot(left, right); // /// <summary> // /// float64x1_t vbic_f64 (float64x1_t a, float64x1_t b) // /// A32: VBIC Dd, Dn, Dm // /// A64: BIC Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> AndNot(Vector64<double> left, Vector64<double> right) => AndNot(left, right); /// <summary> /// int16x4_t vbic_s16 (int16x4_t a, int16x4_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<short> AndNot(Vector64<short> left, Vector64<short> right) => AndNot(left, right); /// <summary> /// int32x2_t vbic_s32(int32x2_t a, int32x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<int> AndNot(Vector64<int> left, Vector64<int> right) => AndNot(left, right); // /// <summary> // /// int64x1_t vbic_s64 (int64x1_t a, int64x1_t b) // /// A32: VBIC Dd, Dn, Dm // /// A64: BIC Vd, Vn, Vm // /// </summary> // public static Vector64<long> AndNot(Vector64<long> left, Vector64<long> right) => AndNot(left, right); /// <summary> /// int8x8_t vbic_s8 (int8x8_t a, int8x8_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<sbyte> AndNot(Vector64<sbyte> left, Vector64<sbyte> right) => AndNot(left, right); /// <summary> /// float32x2_t vbic_f32 (float32x2_t a, float32x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> AndNot(Vector64<float> left, Vector64<float> right) => AndNot(left, right); /// <summary> /// uint16x4_t vbic_u16 (uint16x4_t a, uint16x4_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<ushort> AndNot(Vector64<ushort> left, Vector64<ushort> right) => AndNot(left, right); /// <summary> /// uint32x2_t vbic_u32 (uint32x2_t a, uint32x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector64<uint> AndNot(Vector64<uint> left, Vector64<uint> right) => AndNot(left, right); // /// <summary> // /// uint64x1_t vbic_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VBIC Dd, Dn, Dm // /// A64: BIC Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> AndNot(Vector64<ulong> left, Vector64<ulong> right) => AndNot(left, right); /// <summary> /// uint8x16_t vbic_u8 (uint8x16_t a, uint8x16_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<byte> AndNot(Vector128<byte> left, Vector128<byte> right) => AndNot(left, right); /// <summary> /// float64x2_t vbic_f64 (float64x2_t a, float64x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> AndNot(Vector128<double> left, Vector128<double> right) => AndNot(left, right); /// <summary> /// int16x8_t vbic_s16 (int16x8_t a, int16x8_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<short> AndNot(Vector128<short> left, Vector128<short> right) => AndNot(left, right); /// <summary> /// int32x4_t vbic_s32(int32x4_t a, int32x4_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<int> AndNot(Vector128<int> left, Vector128<int> right) => AndNot(left, right); /// <summary> /// int64x2_t vbic_s64 (int64x2_t a, int64x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<long> AndNot(Vector128<long> left, Vector128<long> right) => AndNot(left, right); /// <summary> /// int8x16_t vbic_s8 (int8x16_t a, int8x16_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<sbyte> AndNot(Vector128<sbyte> left, Vector128<sbyte> right) => AndNot(left, right); /// <summary> /// float32x4_t vbic_f32 (float32x4_t a, float32x4_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) => AndNot(left, right); /// <summary> /// uint16x8_t vbic_u16 (uint16x8_t a, uint16x8_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<ushort> AndNot(Vector128<ushort> left, Vector128<ushort> right) => AndNot(left, right); /// <summary> /// uint32x4_t vbic_u32 (uint32x4_t a, uint32x4_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<uint> AndNot(Vector128<uint> left, Vector128<uint> right) => AndNot(left, right); /// <summary> /// uint64x2_t vbic_u64 (uint64x2_t a, uint64x2_t b) /// A32: VBIC Dd, Dn, Dm /// A64: BIC Vd, Vn, Vm /// </summary> public static Vector128<ulong> AndNot(Vector128<ulong> left, Vector128<ulong> right) => AndNot(left, right); /// <summary> /// uint8x8_t vbsl_u8 (uint8x8_t a, uint8x8_t b, uint8x8_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<byte> BitwiseSelect(Vector64<byte> select, Vector64<byte> left, Vector64<byte> right) => BitwiseSelect(select, left, right); // /// <summary> // /// float64x1_t vbsl_f64 (float64x1_t a, float64x1_t b, float64x1_t c) // /// A32: VBSL Dd, Dn, Dm // /// A64: BSL Vd, Vn, Vm // /// </summary> // public static Vector64<double> BitwiseSelect(Vector64<double> select, Vector64<double> left, Vector64<double> right) => BitwiseSelect(select, left, right); /// <summary> /// int16x4_t vbsl_s16 (int16x4_t a, int16x4_t b, int16x4_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<short> BitwiseSelect(Vector64<short> select, Vector64<short> left, Vector64<short> right) => BitwiseSelect(select, left, right); /// <summary> /// int32x2_t vbsl_s32 (int32x2_t a, int32x2_t b, int32x2_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<int> BitwiseSelect(Vector64<int> select, Vector64<int> left, Vector64<int> right) => BitwiseSelect(select, left, right); // /// <summary> // /// int64x1_t vbsl_s64 (int64x1_t a, int64x1_t b, int64x1_t c) // /// A32: VBSL Dd, Dn, Dm // /// A64: BSL Vd, Vn, Vm // /// </summary> // public static Vector64<long> BitwiseSelect(Vector64<long> select, Vector64<long> left, Vector64<long> right) => BitwiseSelect(select, left, right); /// <summary> /// int8x8_t vbsl_s8 (int8x8_t a, int8x8_t b, int8x8_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<sbyte> BitwiseSelect(Vector64<sbyte> select, Vector64<sbyte> left, Vector64<sbyte> right) => BitwiseSelect(select, left, right); /// <summary> /// float32x2_t vbsl_f32 (float32x2_t a, float32x2_t b, float32x2_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<float> BitwiseSelect(Vector64<float> select, Vector64<float> left, Vector64<float> right) => BitwiseSelect(select, left, right); /// <summary> /// uint16x4_t vbsl_u16 (uint16x4_t a, uint16x4_t b, uint16x4_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<ushort> BitwiseSelect(Vector64<ushort> select, Vector64<ushort> left, Vector64<ushort> right) => BitwiseSelect(select, left, right); /// <summary> /// uint32x2_t vbsl_u32 (uint32x2_t a, uint32x2_t b, uint32x2_t c) /// A32: VBSL Dd, Dn, Dm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector64<uint> BitwiseSelect(Vector64<uint> select, Vector64<uint> left, Vector64<uint> right) => BitwiseSelect(select, left, right); // /// <summary> // /// uint64x1_t vbsl_u64 (uint64x1_t a, uint64x1_t b, uint64x1_t c) // /// A32: VBSL Dd, Dn, Dm // /// A64: BSL Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> BitwiseSelect(Vector64<ulong> select, Vector64<ulong> left, Vector64<ulong> right) => BitwiseSelect(select, left, right); /// <summary> /// uint8x16_t vbslq_u8 (uint8x16_t a, uint8x16_t b, uint8x16_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<byte> BitwiseSelect(Vector128<byte> select, Vector128<byte> left, Vector128<byte> right) => BitwiseSelect(select, left, right); /// <summary> /// float64x2_t vbslq_f64 (float64x2_t a, float64x2_t b, float64x2_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<double> BitwiseSelect(Vector128<double> select, Vector128<double> left, Vector128<double> right) => BitwiseSelect(select, left, right); /// <summary> /// int16x8_t vbslq_s16 (int16x8_t a, int16x8_t b, int16x8_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<short> BitwiseSelect(Vector128<short> select, Vector128<short> left, Vector128<short> right) => BitwiseSelect(select, left, right); /// <summary> /// int32x4_t vbslq_s32 (int32x4_t a, int32x4_t b, int32x4_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<int> BitwiseSelect(Vector128<int> select, Vector128<int> left, Vector128<int> right) => BitwiseSelect(select, left, right); /// <summary> /// int64x2_t vbslq_s64 (int64x2_t a, int64x2_t b, int64x2_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<long> BitwiseSelect(Vector128<long> select, Vector128<long> left, Vector128<long> right) => BitwiseSelect(select, left, right); /// <summary> /// int8x16_t vbslq_s8 (int8x16_t a, int8x16_t b, int8x16_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<sbyte> BitwiseSelect(Vector128<sbyte> select, Vector128<sbyte> left, Vector128<sbyte> right) => BitwiseSelect(select, left, right); /// <summary> /// float32x4_t vbslq_f32 (float32x4_t a, float32x4_t b, float32x4_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<float> BitwiseSelect(Vector128<float> select, Vector128<float> left, Vector128<float> right) => BitwiseSelect(select, left, right); /// <summary> /// uint16x8_t vbslq_u16 (uint16x8_t a, uint16x8_t b, uint16x8_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<ushort> BitwiseSelect(Vector128<ushort> select, Vector128<ushort> left, Vector128<ushort> right) => BitwiseSelect(select, left, right); /// <summary> /// uint32x4_t vbslq_u32 (uint32x4_t a, uint32x4_t b, uint32x4_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<uint> BitwiseSelect(Vector128<uint> select, Vector128<uint> left, Vector128<uint> right) => BitwiseSelect(select, left, right); /// <summary> /// uint64x2_t vbslq_u64 (uint64x2_t a, uint64x2_t b, uint64x2_t c) /// A32: VBSL Qd, Qn, Qm /// A64: BSL Vd, Vn, Vm /// </summary> public static Vector128<ulong> BitwiseSelect(Vector128<ulong> select, Vector128<ulong> left, Vector128<ulong> right) => BitwiseSelect(select, left, right); /// <summary> /// int8x8_t vcls_s8 (int8x8_t a) /// A32: VCLS Dd, Dm /// A64: CLS Vd, Vn /// </summary> public static Vector64<sbyte> LeadingSignCount(Vector64<sbyte> value) => LeadingSignCount(value); /// <summary> /// int16x4_t vcls_s16 (int16x4_t a) /// A32: VCLS Dd, Dm /// A64: CLS Vd, Vn /// </summary> public static Vector64<short> LeadingSignCount(Vector64<short> value) => LeadingSignCount(value); /// <summary> /// int32x2_t vcls_s32 (int32x2_t a) /// A32: VCLS Dd, Dm /// A64: CLS Vd, Vn /// </summary> public static Vector64<int> LeadingSignCount(Vector64<int> value) => LeadingSignCount(value); /// <summary> /// int8x16_t vclsq_s8 (int8x16_t a) /// A32: VCLS Qd, Qm /// A64: CLS Vd, Vn /// </summary> public static Vector128<sbyte> LeadingSignCount(Vector128<sbyte> value) => LeadingSignCount(value); /// <summary> /// int16x8_t vclsq_s16 (int16x8_t a) /// A32: VCLS Qd, Qm /// A64: CLS Vd, Vn /// </summary> public static Vector128<short> LeadingSignCount(Vector128<short> value) => LeadingSignCount(value); /// <summary> /// int32x4_t vclsq_s32 (int32x4_t a) /// A32: VCLS Qd, Qm /// A64: CLS Vd, Vn /// </summary> public static Vector128<int> LeadingSignCount(Vector128<int> value) => LeadingSignCount(value); /// <summary> /// int8x8_t vclz_s8 (int8x8_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<sbyte> LeadingZeroCount(Vector64<sbyte> value) => LeadingZeroCount(value); /// <summary> /// uint8x8_t vclz_u8 (uint8x8_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<byte> LeadingZeroCount(Vector64<byte> value) => LeadingZeroCount(value); /// <summary> /// int16x4_t vclz_s16 (int16x4_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<short> LeadingZeroCount(Vector64<short> value) => LeadingZeroCount(value); /// <summary> /// uint16x4_t vclz_u16 (uint16x4_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<ushort> LeadingZeroCount(Vector64<ushort> value) => LeadingZeroCount(value); /// <summary> /// int32x2_t vclz_s32 (int32x2_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<int> LeadingZeroCount(Vector64<int> value) => LeadingZeroCount(value); /// <summary> /// uint32x2_t vclz_u32 (uint32x2_t a) /// A32: VCLZ Dd, Dm /// A64: CLZ Vd, Vn /// </summary> public static Vector64<uint> LeadingZeroCount(Vector64<uint> value) => LeadingZeroCount(value); /// <summary> /// int8x16_t vclzq_s8 (int8x16_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<sbyte> LeadingZeroCount(Vector128<sbyte> value) => LeadingZeroCount(value); /// <summary> /// uint8x16_t vclzq_u8 (uint8x16_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<byte> LeadingZeroCount(Vector128<byte> value) => LeadingZeroCount(value); /// <summary> /// int16x8_t vclzq_s16 (int16x8_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<short> LeadingZeroCount(Vector128<short> value) => LeadingZeroCount(value); /// <summary> /// uint16x8_t vclzq_u16 (uint16x8_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<ushort> LeadingZeroCount(Vector128<ushort> value) => LeadingZeroCount(value); /// <summary> /// int32x4_t vclzq_s32 (int32x4_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<int> LeadingZeroCount(Vector128<int> value) => LeadingZeroCount(value); /// <summary> /// uint32x4_t vclzq_u32 (uint32x4_t a) /// A32: VCLZ Qd, Qm /// A64: CLZ Vd, Vn /// </summary> public static Vector128<uint> LeadingZeroCount(Vector128<uint> value) => LeadingZeroCount(value); /// <summary> /// uint8x8_t vld1_u8 (uint8_t const * ptr) /// A32: VLD1.8 Dd, [Rn] /// A64: LD1 Vt.8B, [Xn] /// </summary> public static unsafe Vector64<byte> LoadVector64(byte* address) => LoadVector64(address); /// <summary> /// int16x4_t vld1_s16 (int16_t const * ptr) /// A32: VLD1.16 Dd, [Rn] /// A64: LD1 Vt.4H, [Xn] /// </summary> public static unsafe Vector64<short> LoadVector64(short* address) => LoadVector64(address); /// <summary> /// int32x2_t vld1_s32 (int32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<int> LoadVector64(int* address) => LoadVector64(address); /// <summary> /// int8x8_t vld1_s8 (int8_t const * ptr) /// A32: VLD1.8 Dd, [Rn] /// A64: LD1 Vt.8B, [Xn] /// </summary> public static unsafe Vector64<sbyte> LoadVector64(sbyte* address) => LoadVector64(address); /// <summary> /// float32x2_t vld1_f32 (float32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<float> LoadVector64(float* address) => LoadVector64(address); /// <summary> /// uint16x4_t vld1_u16 (uint16_t const * ptr) /// A32: VLD1.16 Dd, [Rn] /// A64: LD1 Vt.4H, [Xn] /// </summary> public static unsafe Vector64<ushort> LoadVector64(ushort* address) => LoadVector64(address); /// <summary> /// uint32x2_t vld1_u32 (uint32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<uint> LoadVector64(uint* address) => LoadVector64(address); /// <summary> /// uint8x16_t vld1q_u8 (uint8_t const * ptr) /// A32: VLD1.8 Dd, Dd+1, [Rn] /// A64: LD1 Vt.16B, [Xn] /// </summary> public static unsafe Vector128<byte> LoadVector128(byte* address) => LoadVector128(address); /// <summary> /// float64x2_t vld1q_f64 (float64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<double> LoadVector128(double* address) => LoadVector128(address); /// <summary> /// int16x8_t vld1q_s16 (int16_t const * ptr) /// A32: VLD1.16 Dd, Dd+1, [Rn] /// A64: LD1 Vt.8H, [Xn] /// </summary> public static unsafe Vector128<short> LoadVector128(short* address) => LoadVector128(address); /// <summary> /// int32x4_t vld1q_s32 (int32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<int> LoadVector128(int* address) => LoadVector128(address); /// <summary> /// int64x2_t vld1q_s64 (int64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<long> LoadVector128(long* address) => LoadVector128(address); /// <summary> /// int8x16_t vld1q_s8 (int8_t const * ptr) /// A32: VLD1.8 Dd, Dd+1, [Rn] /// A64: LD1 Vt.16B, [Xn] /// </summary> public static unsafe Vector128<sbyte> LoadVector128(sbyte* address) => LoadVector128(address); /// <summary> /// float32x4_t vld1q_f32 (float32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<float> LoadVector128(float* address) => LoadVector128(address); /// <summary> /// uint16x8_t vld1q_s16 (uint16_t const * ptr) /// A32: VLD1.16 Dd, Dd+1, [Rn] /// A64: LD1 Vt.8H, [Xn] /// </summary> public static unsafe Vector128<ushort> LoadVector128(ushort* address) => LoadVector128(address); /// <summary> /// uint32x4_t vld1q_s32 (uint32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<uint> LoadVector128(uint* address) => LoadVector128(address); /// <summary> /// uint64x2_t vld1q_u64 (uint64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<ulong> LoadVector128(ulong* address) => LoadVector128(address); /// <summary> /// uint8x8_t vmvn_u8 (uint8x8_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<byte> Not(Vector64<byte> value) => Not(value); // /// <summary> // /// float64x1_t vmvn_f64 (float64x1_t a) // /// A32: VMVN Dd, Dn, Dm // /// A64: MVN Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> Not(Vector64<double> value) => Not(value); /// <summary> /// int16x4_t vmvn_s16 (int16x4_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<short> Not(Vector64<short> value) => Not(value); /// <summary> /// int32x2_t vmvn_s32(int32x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<int> Not(Vector64<int> value) => Not(value); // /// <summary> // /// int64x1_t vmvn_s64 (int64x1_t a) // /// A32: VMVN Dd, Dn, Dm // /// A64: MVN Vd, Vn, Vm // /// </summary> // public static Vector64<long> Not(Vector64<long> value) => Not(value); /// <summary> /// int8x8_t vmvn_s8 (int8x8_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<sbyte> Not(Vector64<sbyte> value) => Not(value); /// <summary> /// float32x2_t vmvn_f32 (float32x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> Not(Vector64<float> value) => Not(value); /// <summary> /// uint16x4_t vmvn_u16 (uint16x4_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<ushort> Not(Vector64<ushort> value) => Not(value); /// <summary> /// uint32x2_t vmvn_u32 (uint32x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector64<uint> Not(Vector64<uint> value) => Not(value); // /// <summary> // /// uint64x1_t vmvn_u64 (uint64x1_t a) // /// A32: VMVN Dd, Dn, Dm // /// A64: MVN Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> Not(Vector64<ulong> value) => Not(value); /// <summary> /// uint8x16_t vmvn_u8 (uint8x16_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<byte> Not(Vector128<byte> value) => Not(value); /// <summary> /// float64x2_t vmvn_f64 (float64x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> Not(Vector128<double> value) => Not(value); /// <summary> /// int16x8_t vmvn_s16 (int16x8_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<short> Not(Vector128<short> value) => Not(value); /// <summary> /// int32x4_t vmvn_s32(int32x4_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<int> Not(Vector128<int> value) => Not(value); /// <summary> /// int64x2_t vmvn_s64 (int64x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<long> Not(Vector128<long> value) => Not(value); /// <summary> /// int8x16_t vmvn_s8 (int8x16_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<sbyte> Not(Vector128<sbyte> value) => Not(value); /// <summary> /// float32x4_t vmvn_f32 (float32x4_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> Not(Vector128<float> value) => Not(value); /// <summary> /// uint16x8_t vmvn_u16 (uint16x8_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<ushort> Not(Vector128<ushort> value) => Not(value); /// <summary> /// uint32x4_t vmvn_u32 (uint32x4_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<uint> Not(Vector128<uint> value) => Not(value); /// <summary> /// uint64x2_t vmvn_u64 (uint64x2_t a) /// A32: VMVN Dd, Dn, Dm /// A64: MVN Vd, Vn, Vm /// </summary> public static Vector128<ulong> Not(Vector128<ulong> value) => Not(value); /// <summary> /// uint8x8_t vorr_u8 (uint8x8_t a, uint8x8_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<byte> Or(Vector64<byte> left, Vector64<byte> right) => Or(left, right); // /// <summary> // /// float64x1_t vorr_f64 (float64x1_t a, float64x1_t b) // /// A32: VORR Dd, Dn, Dm // /// A64: ORR Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> Or(Vector64<double> left, Vector64<double> right) => Or(left, right); /// <summary> /// int16x4_t vorr_s16 (int16x4_t a, int16x4_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<short> Or(Vector64<short> left, Vector64<short> right) => Or(left, right); /// <summary> /// int32x2_t vorr_s32(int32x2_t a, int32x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<int> Or(Vector64<int> left, Vector64<int> right) => Or(left, right); // /// <summary> // /// int64x1_t vorr_s64 (int64x1_t a, int64x1_t b) // /// A32: VORR Dd, Dn, Dm // /// A64: ORR Vd, Vn, Vm // /// </summary> // public static Vector64<long> Or(Vector64<long> left, Vector64<long> right) => Or(left, right); /// <summary> /// int8x8_t vorr_s8 (int8x8_t a, int8x8_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<sbyte> Or(Vector64<sbyte> left, Vector64<sbyte> right) => Or(left, right); /// <summary> /// float32x2_t vorr_f32 (float32x2_t a, float32x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> Or(Vector64<float> left, Vector64<float> right) => Or(left, right); /// <summary> /// uint16x4_t vorr_u16 (uint16x4_t a, uint16x4_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<ushort> Or(Vector64<ushort> left, Vector64<ushort> right) => Or(left, right); /// <summary> /// uint32x2_t vorr_u32 (uint32x2_t a, uint32x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector64<uint> Or(Vector64<uint> left, Vector64<uint> right) => Or(left, right); // /// <summary> // /// uint64x1_t vorr_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VORR Dd, Dn, Dm // /// A64: ORR Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> Or(Vector64<ulong> left, Vector64<ulong> right) => Or(left, right); /// <summary> /// uint8x16_t vorr_u8 (uint8x16_t a, uint8x16_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<byte> Or(Vector128<byte> left, Vector128<byte> right) => Or(left, right); /// <summary> /// float64x2_t vorr_f64 (float64x2_t a, float64x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> Or(Vector128<double> left, Vector128<double> right) => Or(left, right); /// <summary> /// int16x8_t vorr_s16 (int16x8_t a, int16x8_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<short> Or(Vector128<short> left, Vector128<short> right) => Or(left, right); /// <summary> /// int32x4_t vorr_s32(int32x4_t a, int32x4_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<int> Or(Vector128<int> left, Vector128<int> right) => Or(left, right); /// <summary> /// int64x2_t vorr_s64 (int64x2_t a, int64x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<long> Or(Vector128<long> left, Vector128<long> right) => Or(left, right); /// <summary> /// int8x16_t vorr_s8 (int8x16_t a, int8x16_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<sbyte> Or(Vector128<sbyte> left, Vector128<sbyte> right) => Or(left, right); /// <summary> /// float32x4_t vorr_f32 (float32x4_t a, float32x4_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) => Or(left, right); /// <summary> /// uint16x8_t vorr_u16 (uint16x8_t a, uint16x8_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<ushort> Or(Vector128<ushort> left, Vector128<ushort> right) => Or(left, right); /// <summary> /// uint32x4_t vorr_u32 (uint32x4_t a, uint32x4_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<uint> Or(Vector128<uint> left, Vector128<uint> right) => Or(left, right); /// <summary> /// uint64x2_t vorr_u64 (uint64x2_t a, uint64x2_t b) /// A32: VORR Dd, Dn, Dm /// A64: ORR Vd, Vn, Vm /// </summary> public static Vector128<ulong> Or(Vector128<ulong> left, Vector128<ulong> right) => Or(left, right); /// <summary> /// uint8x8_t vorn_u8 (uint8x8_t a, uint8x8_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<byte> OrNot(Vector64<byte> left, Vector64<byte> right) => OrNot(left, right); // /// <summary> // /// float64x1_t vorn_f64 (float64x1_t a, float64x1_t b) // /// A32: VORN Dd, Dn, Dm // /// A64: ORN Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> OrNot(Vector64<double> left, Vector64<double> right) => OrNot(left, right); /// <summary> /// int16x4_t vorn_s16 (int16x4_t a, int16x4_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<short> OrNot(Vector64<short> left, Vector64<short> right) => OrNot(left, right); /// <summary> /// int32x2_t vorn_s32(int32x2_t a, int32x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<int> OrNot(Vector64<int> left, Vector64<int> right) => OrNot(left, right); // /// <summary> // /// int64x1_t vorn_s64 (int64x1_t a, int64x1_t b) // /// A32: VORN Dd, Dn, Dm // /// A64: ORN Vd, Vn, Vm // /// </summary> // public static Vector64<long> OrNot(Vector64<long> left, Vector64<long> right) => OrNot(left, right); /// <summary> /// int8x8_t vorn_s8 (int8x8_t a, int8x8_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<sbyte> OrNot(Vector64<sbyte> left, Vector64<sbyte> right) => OrNot(left, right); /// <summary> /// float32x2_t vorn_f32 (float32x2_t a, float32x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> OrNot(Vector64<float> left, Vector64<float> right) => OrNot(left, right); /// <summary> /// uint16x4_t vorn_u16 (uint16x4_t a, uint16x4_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<ushort> OrNot(Vector64<ushort> left, Vector64<ushort> right) => OrNot(left, right); /// <summary> /// uint32x2_t vorn_u32 (uint32x2_t a, uint32x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector64<uint> OrNot(Vector64<uint> left, Vector64<uint> right) => OrNot(left, right); // /// <summary> // /// uint64x1_t vorn_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VORN Dd, Dn, Dm // /// A64: ORN Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> OrNot(Vector64<ulong> left, Vector64<ulong> right) => OrNot(left, right); /// <summary> /// uint8x16_t vorn_u8 (uint8x16_t a, uint8x16_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<byte> OrNot(Vector128<byte> left, Vector128<byte> right) => OrNot(left, right); /// <summary> /// float64x2_t vorn_f64 (float64x2_t a, float64x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> OrNot(Vector128<double> left, Vector128<double> right) => OrNot(left, right); /// <summary> /// int16x8_t vorn_s16 (int16x8_t a, int16x8_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<short> OrNot(Vector128<short> left, Vector128<short> right) => OrNot(left, right); /// <summary> /// int32x4_t vorn_s32(int32x4_t a, int32x4_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<int> OrNot(Vector128<int> left, Vector128<int> right) => OrNot(left, right); /// <summary> /// int64x2_t vorn_s64 (int64x2_t a, int64x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<long> OrNot(Vector128<long> left, Vector128<long> right) => OrNot(left, right); /// <summary> /// int8x16_t vorn_s8 (int8x16_t a, int8x16_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<sbyte> OrNot(Vector128<sbyte> left, Vector128<sbyte> right) => OrNot(left, right); /// <summary> /// float32x4_t vorn_f32 (float32x4_t a, float32x4_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> OrNot(Vector128<float> left, Vector128<float> right) => OrNot(left, right); /// <summary> /// uint16x8_t vorn_u16 (uint16x8_t a, uint16x8_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<ushort> OrNot(Vector128<ushort> left, Vector128<ushort> right) => OrNot(left, right); /// <summary> /// uint32x4_t vorn_u32 (uint32x4_t a, uint32x4_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<uint> OrNot(Vector128<uint> left, Vector128<uint> right) => OrNot(left, right); /// <summary> /// uint64x2_t vorn_u64 (uint64x2_t a, uint64x2_t b) /// A32: VORN Dd, Dn, Dm /// A64: ORN Vd, Vn, Vm /// </summary> public static Vector128<ulong> OrNot(Vector128<ulong> left, Vector128<ulong> right) => OrNot(left, right); /// <summary> /// int8x8_t vcnt_s8 (int8x8_t a) /// A32: VCNT Dd, Dm /// A64: CNT Vd, Vn /// </summary> public static Vector64<sbyte> PopCount(Vector64<sbyte> value) => PopCount(value); /// <summary> /// uint8x8_t vcnt_u8 (uint8x8_t a) /// A32: VCNT Dd, Dm /// A64: CNT Vd, Vn /// </summary> public static Vector64<byte> PopCount(Vector64<byte> value) => PopCount(value); /// <summary> /// int8x16_t vcntq_s8 (int8x16_t a) /// A32: VCNT Qd, Qm /// A64: CNT Vd, Vn /// </summary> public static Vector128<sbyte> PopCount(Vector128<sbyte> value) => PopCount(value); /// <summary> /// uint8x16_t vcntq_u8 (uint8x16_t a) /// A32: VCNT Qd, Qm /// A64: CNT Vd, Vn /// </summary> public static Vector128<byte> PopCount(Vector128<byte> value) => PopCount(value); /// <summary> /// uint8x8_t vsub_u8 (uint8x8_t a, uint8x8_t b) /// A32: VSUB.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> Subtract(Vector64<byte> left, Vector64<byte> right) => Subtract(left, right); /// <summary> /// int16x4_t vsub_s16 (int16x4_t a, int16x4_t b) /// A32: VSUB.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> Subtract(Vector64<short> left, Vector64<short> right) => Subtract(left, right); /// <summary> /// int32x2_t vsub_s32 (int32x2_t a, int32x2_t b) /// A32: VSUB.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> Subtract(Vector64<int> left, Vector64<int> right) => Subtract(left, right); /// <summary> /// int8x8_t vsub_s8 (int8x8_t a, int8x8_t b) /// A32: VSUB.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> Subtract(Vector64<sbyte> left, Vector64<sbyte> right) => Subtract(left, right); /// <summary> /// float32x2_t vsub_f32 (float32x2_t a, float32x2_t b) /// A32: VSUB.F32 Dd, Dn, Dm /// A64: FSUB Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> Subtract(Vector64<float> left, Vector64<float> right) => Subtract(left, right); /// <summary> /// uint16x4_t vsub_u16 (uint16x4_t a, uint16x4_t b) /// A32: VSUB.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> Subtract(Vector64<ushort> left, Vector64<ushort> right) => Subtract(left, right); /// <summary> /// uint32x2_t vsub_u32 (uint32x2_t a, uint32x2_t b) /// A32: VSUB.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> Subtract(Vector64<uint> left, Vector64<uint> right) => Subtract(left, right); /// <summary> /// uint8x16_t vsubq_u8 (uint8x16_t a, uint8x16_t b) /// A32: VSUB.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> Subtract(Vector128<byte> left, Vector128<byte> right) => Subtract(left, right); /// <summary> /// int16x8_t vsubq_s16 (int16x8_t a, int16x8_t b) /// A32: VSUB.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> Subtract(Vector128<short> left, Vector128<short> right) => Subtract(left, right); /// <summary> /// int32x4_t vsubq_s32 (int32x4_t a, int32x4_t b) /// A32: VSUB.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> Subtract(Vector128<int> left, Vector128<int> right) => Subtract(left, right); /// <summary> /// int64x2_t vsubq_s64 (int64x2_t a, int64x2_t b) /// A32: VSUB.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> Subtract(Vector128<long> left, Vector128<long> right) => Subtract(left, right); /// <summary> /// int8x16_t vsubq_s8 (int8x16_t a, int8x16_t b) /// A32: VSUB.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> Subtract(Vector128<sbyte> left, Vector128<sbyte> right) => Subtract(left, right); /// <summary> /// float32x4_t vsubq_f32 (float32x4_t a, float32x4_t b) /// A32: VSUB.F32 Qd, Qn, Qm /// A64: FSUB Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) => Subtract(left, right); /// <summary> /// uint16x8_t vsubq_u16 (uint16x8_t a, uint16x8_t b) /// A32: VSUB.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> Subtract(Vector128<ushort> left, Vector128<ushort> right) => Subtract(left, right); /// <summary> /// uint32x4_t vsubq_u32 (uint32x4_t a, uint32x4_t b) /// A32: VSUB.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> Subtract(Vector128<uint> left, Vector128<uint> right) => Subtract(left, right); /// <summary> /// uint64x2_t vsubq_u64 (uint64x2_t a, uint64x2_t b) /// A32: VSUB.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> Subtract(Vector128<ulong> left, Vector128<ulong> right) => Subtract(left, right); // /// <summary> // /// float64x1_t vsub_f64 (float64x1_t a, float64x1_t b) // /// A32: VSUB.F64 Dd, Dn, Dm // /// A64: FSUB Dd, Dn, Dm // /// </summary> // public static Vector64<double> SubtractScalar(Vector64<double> left, Vector64<double> right) => Subtract(left, right); // /// <summary> // /// int64x1_t vsub_s64 (int64x1_t a, int64x1_t b) // /// A32: VSUB.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<long> SubtractScalar(Vector64<long> left, Vector64<long> right) => SubtractScalar(left, right); // /// <summary> // /// uint64x1_t vsub_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VSUB.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<ulong> SubtractScalar(Vector64<ulong> left, Vector64<ulong> right) => SubtractScalar(left, right); /// <summary> /// A32: VSUB.F32 Sd, Sn, Sm /// A64: /// </summary> public static Vector64<float> SubtractScalar(Vector64<float> left, Vector64<float> right) => SubtractScalar(left, right); /// <summary> /// uint8x8_t veor_u8 (uint8x8_t a, uint8x8_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<byte> Xor(Vector64<byte> left, Vector64<byte> right) => Xor(left, right); // /// <summary> // /// float64x1_t veor_f64 (float64x1_t a, float64x1_t b) // /// A32: VEOR Dd, Dn, Dm // /// A64: EOR Vd, Vn, Vm // /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. // /// </summary> // public static Vector64<double> Xor(Vector64<double> left, Vector64<double> right) => Xor(left, right); /// <summary> /// int16x4_t veor_s16 (int16x4_t a, int16x4_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<short> Xor(Vector64<short> left, Vector64<short> right) => Xor(left, right); /// <summary> /// int32x2_t veor_s32(int32x2_t a, int32x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<int> Xor(Vector64<int> left, Vector64<int> right) => Xor(left, right); // /// <summary> // /// int64x1_t veor_s64 (int64x1_t a, int64x1_t b) // /// A32: VEOR Dd, Dn, Dm // /// A64: EOR Vd, Vn, Vm // /// </summary> // public static Vector64<long> Xor(Vector64<long> left, Vector64<long> right) => Xor(left, right); /// <summary> /// int8x8_t veor_s8 (int8x8_t a, int8x8_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<sbyte> Xor(Vector64<sbyte> left, Vector64<sbyte> right) => Xor(left, right); /// <summary> /// float32x2_t veor_f32 (float32x2_t a, float32x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector64<float> Xor(Vector64<float> left, Vector64<float> right) => Xor(left, right); /// <summary> /// uint16x4_t veor_u16 (uint16x4_t a, uint16x4_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<ushort> Xor(Vector64<ushort> left, Vector64<ushort> right) => Xor(left, right); /// <summary> /// uint32x2_t veor_u32 (uint32x2_t a, uint32x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector64<uint> Xor(Vector64<uint> left, Vector64<uint> right) => Xor(left, right); // /// <summary> // /// uint64x1_t veor_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VEOR Dd, Dn, Dm // /// A64: EOR Vd, Vn, Vm // /// </summary> // public static Vector64<ulong> Xor(Vector64<ulong> left, Vector64<ulong> right) => Xor(left, right); /// <summary> /// uint8x16_t veor_u8 (uint8x16_t a, uint8x16_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<byte> Xor(Vector128<byte> left, Vector128<byte> right) => Xor(left, right); /// <summary> /// float64x2_t veor_f64 (float64x2_t a, float64x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<double> Xor(Vector128<double> left, Vector128<double> right) => Xor(left, right); /// <summary> /// int16x8_t veor_s16 (int16x8_t a, int16x8_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<short> Xor(Vector128<short> left, Vector128<short> right) => Xor(left, right); /// <summary> /// int32x4_t veor_s32(int32x4_t a, int32x4_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<int> Xor(Vector128<int> left, Vector128<int> right) => Xor(left, right); /// <summary> /// int64x2_t veor_s64 (int64x2_t a, int64x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<long> Xor(Vector128<long> left, Vector128<long> right) => Xor(left, right); /// <summary> /// int8x16_t veor_s8 (int8x16_t a, int8x16_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<sbyte> Xor(Vector128<sbyte> left, Vector128<sbyte> right) => Xor(left, right); /// <summary> /// float32x4_t veor_f32 (float32x4_t a, float32x4_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) => Xor(left, right); /// <summary> /// uint16x8_t veor_u16 (uint16x8_t a, uint16x8_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<ushort> Xor(Vector128<ushort> left, Vector128<ushort> right) => Xor(left, right); /// <summary> /// uint32x4_t veor_u32 (uint32x4_t a, uint32x4_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<uint> Xor(Vector128<uint> left, Vector128<uint> right) => Xor(left, right); /// <summary> /// uint64x2_t veor_u64 (uint64x2_t a, uint64x2_t b) /// A32: VEOR Dd, Dn, Dm /// A64: EOR Vd, Vn, Vm /// </summary> public static Vector128<ulong> Xor(Vector128<ulong> left, Vector128<ulong> right) => Xor(left, right); } }
43.101149
167
0.551741
[ "MIT" ]
AaronRobinsonMSFT/runtime
src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Arm/AdvSimd.cs
93,745
C#
using NHM.Common; using NHM.Common.Enums; using NHMCore; using NHMCore.ApplicationState; using NHMCore.Configs; using NHMCore.Mining; using NHMCore.Mining.IdleChecking; using NHMCore.Mining.MiningStats; using NHMCore.Mining.Plugins; using NHMCore.Nhmws; using NHMCore.Notifications; using NHMCore.Switching; using NiceHashMiner.ViewModels.Models; using NiceHashMiner.ViewModels.Plugins; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using System.Timers; using System.Windows.Data; namespace NiceHashMiner.ViewModels { public class MainVM : BaseVM { private readonly Timer _updateTimer; // For syncing mining data listview collection private readonly object _lock = new object(); private IEnumerable<DeviceData> _devices; public IEnumerable<DeviceData> Devices { get => _devices; set { _devices = value; OnPropertyChanged(); OnPropertyChanged(nameof(DeviceGPUCount)); OnPropertyChanged(nameof(DeviceCPUCount)); OnPropertyChanged(nameof(PerDeviceDisplayString)); OnPropertyChanged(nameof(CPUs)); OnPropertyChanged(nameof(GPUs)); } } private IEnumerable<DeviceDataTDP> _devicesTDP; public IEnumerable<DeviceDataTDP> DevicesTDP { get => _devicesTDP; set { _devicesTDP = value; OnPropertyChanged(); } } public IEnumerable<DeviceData> CPUs { get => _devices?.Where(d => d.Dev.DeviceType == DeviceType.CPU) ?? Enumerable.Empty<DeviceData>(); } public IEnumerable<DeviceData> GPUs { get => _devices?.Where(d => d.Dev.DeviceType != DeviceType.CPU) ?? Enumerable.Empty<DeviceData>(); } public int DeviceGPUCount => _devices?.Where(d => d.Dev.DeviceType != DeviceType.CPU).Count() ?? 0; public int DeviceCPUCount => _devices?.Where(d => d.Dev.DeviceType == DeviceType.CPU).Count() ?? 0; private ObservableCollection<IMiningData> _miningDevs; public ObservableCollection<IMiningData> MiningDevs { get => _miningDevs; set { _miningDevs = value; OnPropertyChanged(); } } /// <summary> /// Elements of <see cref="MiningDevs"/> that represent actual devices (i.e. not total rows) and /// are in the mining state. /// </summary> private IEnumerable<MiningData> WorkingMiningDevs => MiningDevs?.OfType<MiningData>().Where(d => d.Dev.State == DeviceState.Mining); #region settingsLists public IEnumerable<TimeUnitType> TimeUnits => GetEnumValues<TimeUnitType>(); public IReadOnlyList<string> ThemeOptions => _themeList; private List<string> _themeList = new List<string> { "Light", "Dark" }; #endregion settingsLists public string PerDeviceDisplayString => $"/ {_devices?.Count() ?? 0}"; public DashboardViewModel Dashboard { get; } = new DashboardViewModel(); #region Exposed settings public BalanceAndExchangeRates BalanceAndExchangeRates => BalanceAndExchangeRates.Instance; public MiningState MiningState => MiningState.Instance; public StratumService StratumService => StratumService.Instance; public CredentialsSettings CredentialsSettings => CredentialsSettings.Instance; public GlobalDeviceSettings GlobalDeviceSettings => GlobalDeviceSettings.Instance; public GUISettings GUISettings => GUISettings.Instance; public IdleMiningSettings IdleMiningSettings => IdleMiningSettings.Instance; public IFTTTSettings IFTTTSettings => IFTTTSettings.Instance; public LoggingDebugConsoleSettings LoggingDebugConsoleSettings => LoggingDebugConsoleSettings.Instance; public MiningProfitSettings MiningProfitSettings => MiningProfitSettings.Instance; public MiningSettings MiningSettings => MiningSettings.Instance; public MiscSettings MiscSettings => MiscSettings.Instance; public SwitchSettings SwitchSettings => SwitchSettings.Instance; public ToSSetings ToSSetings => ToSSetings.Instance; public TranslationsSettings TranslationsSettings => TranslationsSettings.Instance; public WarningSettings WarningSettings => WarningSettings.Instance; public UpdateSettings UpdateSettings => UpdateSettings.Instance; public EthlargementIntegratedPlugin EthlargementIntegratedPlugin => EthlargementIntegratedPlugin.Instance; #endregion Exposed settings #region HelpNotifications private ObservableCollection<Notification> _helpNotificationList; public ObservableCollection<Notification> HelpNotificationList { get => _helpNotificationList; set { _helpNotificationList = value; OnPropertyChanged(); } } private void RefreshNotifications_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { lock (_lock) { // TODO keep it like this for now but update the collection view in the future HelpNotificationList = new ObservableCollection<Notification>(NotificationsManager.Instance.Notifications); OnPropertyChanged(nameof(HelpNotificationList)); } } #endregion HelpNotifications // TODO these versions here will not work public string LocalVersion => VersionState.Instance.ProgramVersion.ToString(); public string OnlineVersion => VersionState.Instance.OnlineVersion?.ToString() ?? "N/A"; #region Currency-related properties // TODO this section getting rather large, maybe good idea to break out into own class private string _timeUnit = TimeFactor.UnitType.ToString(); public string TimeUnit { get => _timeUnit; set { _timeUnit = value; OnPropertyChanged(); OnPropertyChanged(nameof(PerTime)); } } private string PerTime => Translations.Tr($" / {TimeUnit}"); private string _scaledBtcPerTime; public string ScaledBtcPerTime { get => _scaledBtcPerTime; set { if (_scaledBtcPerTime == value) return; _scaledBtcPerTime = value; OnPropertyChanged(); } } public string GlobalRate { get { // sum is in mBTC already var sum = WorkingMiningDevs?.Sum(d => d.Payrate) ?? 0; var scale = 1000; if (GUISettings.Instance.AutoScaleBTCValues && sum < 100) { ScaledBtcPerTime = $"mBTC{PerTime}"; scale = 1; var retScaled = $"{(sum / scale):F5}"; return retScaled; } ScaledBtcPerTime = $"BTC{PerTime}"; var ret = $"{(sum / scale):F8}"; return ret; } } public string GlobalRateFiat => $"≈ {(WorkingMiningDevs?.Sum(d => d.FiatPayrate) ?? 0):F2} {BalanceAndExchangeRates.SelectedFiatCurrency}{PerTime}"; #endregion #region MinerPlugins private ObservableCollection<PluginEntryVM> _plugins; public ObservableCollection<PluginEntryVM> Plugins { get => _plugins; set { _plugins = value; OnPropertyChanged(); } } private void MinerPluginsManagerState_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { lock (_lock) { if (Plugins == null) return; var rankedPlugins = MinerPluginsManagerState.Instance.RankedPlugins; var rankedPluginsArray = rankedPlugins.ToArray(); // add new foreach (var plugin in rankedPluginsArray) { var vm = Plugins.FirstOrDefault(pluginVM => pluginVM.Plugin.PluginUUID == plugin.PluginUUID); if (vm != null) continue; Plugins.Add(new PluginEntryVM(plugin)); } // remove missing var remove = Plugins.Where(plugin => rankedPlugins.FirstOrDefault(rankedPlugin => rankedPlugin.PluginUUID == plugin.Plugin.PluginUUID) == null).ToArray(); foreach (var rem in remove) { Plugins.Remove(rem); } // sort var removeUUIDs = remove.Select(rem => rem.Plugin.PluginUUID); var sorted = rankedPlugins.Where(rankedPlugin => !removeUUIDs.Contains(rankedPlugin.PluginUUID)).ToList(); var pluginsToSort = Plugins.ToList(); for (int i = 0; i < sorted.Count; i++) { var oldIndex = pluginsToSort.FindIndex(p => p.Plugin == sorted[i]); Plugins.Move(oldIndex, i); } } } #endregion MinerPlugins public BenchmarkViewModel BenchmarkSettings { get; } = new BenchmarkViewModel(); public DevicesViewModel DevicesViewModel { get; } = new DevicesViewModel(); public bool NHMWSConnected { get; private set; } = false; public MainVM() : base(ApplicationStateManager.Title) { _updateTimer = new Timer(1000); _updateTimer.Elapsed += UpdateTimerOnElapsed; VersionState.Instance.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(VersionState.OnlineVersion)) { OnPropertyChanged(nameof(OnlineVersion)); } }; TimeFactor.OnUnitTypeChanged += (_, unit) => { TimeUnit = unit.ToString(); }; //MinerPluginsManager.OnCrossReferenceInstalledWithOnlinePlugins += OnCrossReferenceInstalledWithOnlinePlugins; MinerPluginsManagerState.Instance.PropertyChanged += MinerPluginsManagerState_PropertyChanged; NotificationsManager.Instance.PropertyChanged += RefreshNotifications_PropertyChanged; OnPropertyChanged(nameof(NHMWSConnected)); ApplicationStateManager.OnNhmwsConnectionChanged += (_, nhmwsConnected) => { NHMWSConnected = nhmwsConnected; OnPropertyChanged(nameof(NHMWSConnected)); }; } // TODO I don't like this way, a global refresh and notify would be better private void UpdateTimerOnElapsed(object sender, ElapsedEventArgs e) { if (Devices == null) return; foreach (var dev in Devices) { dev.RefreshDiag(); } } public async Task InitializeNhm(IStartupLoader sl) { Plugins = new ObservableCollection<PluginEntryVM>(); HelpNotificationList = new ObservableCollection<Notification>(); await ApplicationStateManager.InitializeManagersAndMiners(sl); Devices = new ObservableCollection<DeviceData>(AvailableDevices.Devices.Select(d => (DeviceData)d)); DevicesTDP = new ObservableCollection<DeviceDataTDP>(AvailableDevices.Devices.Select(d => new DeviceDataTDP(d))); MiningDevs = new ObservableCollection<IMiningData>(AvailableDevices.Devices.Select(d => new MiningData(d))); // This will sync updating of MiningDevs from different threads. Without this, NotifyCollectionChanged doesn't work. BindingOperations.EnableCollectionSynchronization(MiningDevs, _lock); BindingOperations.EnableCollectionSynchronization(Plugins, _lock); BindingOperations.EnableCollectionSynchronization(HelpNotificationList, _lock); MiningDataStats.DevicesMiningStats.CollectionChanged += DevicesMiningStatsOnCollectionChanged; IdleCheckManager.StartIdleCheck(); //RefreshPlugins(); _updateTimer.Start(); ConfigManager.CreateBackup(); if (MiningSettings.Instance.AutoStartMining) await StartMining(); } // This complicated callback will add in total rows to mining stats ListView if they are needed. private void DevicesMiningStatsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Replace: foreach (var stat in e.NewItems.OfType<DeviceMiningStats>()) { // Update this device row var miningDev = MiningDevs.OfType<MiningData>().FirstOrDefault(d => d.Dev.Uuid == stat.DeviceUUID); if (miningDev == null) continue; miningDev.Stats = stat; // Check for existing total row var totalRow = MiningDevs.OfType<TotalMiningData>().FirstOrDefault(d => d.StateName == miningDev.StateName); if (totalRow != null) { totalRow.AddDevice(miningDev); continue; } // Else add new total row totalRow = new TotalMiningData(miningDev); lock (_lock) { MiningDevs.Add(totalRow); } } break; case NotifyCollectionChangedAction.Reset: var toRemove = new List<TotalMiningData>(); foreach (var miningDev in MiningDevs) { if (miningDev is MiningData data) data.Stats = null; else if (miningDev is TotalMiningData total) toRemove.Add(total); } foreach (var remove in toRemove) { MiningDevs.Remove(remove); remove.Dispose(); } break; } OnPropertyChanged(nameof(GlobalRate)); OnPropertyChanged(nameof(GlobalRateFiat)); } public async Task StartMining() { if (!await NHSmaData.WaitOnDataAsync(10)) return; await ApplicationStateManager.StartAllAvailableDevicesTask(); } public async Task StopMining() { await ApplicationStateManager.StopAllDevicesTask(); } } }
38.497487
170
0.591111
[ "MIT" ]
AngusChiang/NiceHashMiner
src/NiceHashMiner/ViewModels/MainVM.cs
15,326
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Fitnesses; using GeneticSharp.Domain.Randomizations; using UnityEngine; namespace GeneticSharp.Extensions.Tsp { public class TspFitness : IFitness { public TspFitness(int numberOfCities, float minX, float maxX, float minY, float maxY) { Cities = new List<TspCity>(numberOfCities); MinX = minX; MaxX = maxX; MinY = minY; MaxY = maxY; if (maxX >= int.MaxValue) { throw new ArgumentOutOfRangeException("maxX"); } if (maxY >= int.MaxValue) { throw new ArgumentOutOfRangeException("maxY"); } for (int i = 0; i < numberOfCities; i++) { var p = GetCityRandomPosition(); var city = new TspCity(p.x, p.y); Cities.Add(city); } } public IList<TspCity> Cities { get; private set; } public float MinX { get; private set; } public float MaxX { get; private set; } public float MinY { get; private set; } public float MaxY { get; private set; } public double Evaluate(IChromosome chromosome) { var genes = chromosome.GetGenes(); var distanceSum = 0.0; var lastCityIndex = Convert.ToInt32(genes[0].Value, CultureInfo.InvariantCulture); var citiesIndexes = new List<int>(); citiesIndexes.Add(lastCityIndex); foreach (var g in genes) { var currentCityIndex = Convert.ToInt32(g.Value, CultureInfo.InvariantCulture); distanceSum += CalcDistanceTwoCities(Cities[currentCityIndex], Cities[lastCityIndex]); lastCityIndex = currentCityIndex; citiesIndexes.Add(lastCityIndex); } distanceSum += CalcDistanceTwoCities(Cities[citiesIndexes.Last()], Cities[citiesIndexes.First()]); var fitness = 1.0 - (distanceSum / (Cities.Count * 1000.0)); ((TspChromosome)chromosome).Distance = distanceSum; // There is repeated cities on the indexes? var diff = Cities.Count - citiesIndexes.Distinct().Count(); if (diff > 0) { fitness /= diff; } if (fitness < 0) { fitness = 0; } return fitness; } private Vector2 GetCityRandomPosition() { return new Vector2(RandomizationProvider.Current.GetFloat(MinX, MaxX + 1), RandomizationProvider.Current.GetFloat(MinY, MaxY + 1)); } private static double CalcDistanceTwoCities(TspCity one, TspCity two) { return Math.Sqrt(Math.Pow(two.X - one.X, 2) + Math.Pow(two.Y - one.Y, 2)); } } }
32.736842
144
0.544695
[ "MIT" ]
JianLoong/GeneticSharp
src/GeneticSharp.Runner.UnityApp/Assets/_runner/tsp/TspFitness.cs
3,110
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SalaryCalculator.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class DailyPayment { public System.Guid DailyId { get; set; } public System.DateTime Date { get; set; } [Display(Name = "Time Start")] public System.TimeSpan TimeStart { get; set; } [Display(Name = "Time End")] public System.TimeSpan TimeEnd { get; set; } [Display(Name = "Total Minutes")] public Nullable<int> TotalMinutes { get; set; } [Display(Name = "Total Hours")] public Nullable<double> TotalHours { get; set; } [Display(Name = "Hourly Rate")] public Nullable<decimal> HourlyRate { get; set; } [Display(Name = "Daily Payment")] public Nullable<decimal> DailyPayment1 { get; set; } } }
38.147059
85
0.562066
[ "MIT" ]
Pixelsavvy72/Salary-Calculator
SalaryCalculator/Models/DailyPayment.cs
1,297
C#
using Shared.DataObjects; using Shared.Messages; using System.Collections.Generic; using System.Threading.Tasks; namespace TradeCube_Services.Services { public interface ITradingBookService { Task<ApiResponseWrapper<IEnumerable<TradingBookDataObject>>> GetTradingBookAsync(string tradingBook, string apiKey); Task<TradingBookDataObject> MapTradingBookAsync(string key, Dictionary<string, MappingDataObject> allMappings, Dictionary<string, SettingDataObject> allSettings, string apiKey); } }
40
185
0.805769
[ "MIT" ]
ctrmcubed/TradeCube-Services
src/TradeCube-Services/Services/ITradingBookService.cs
522
C#
using LuaFramework; using LuaInterface; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; using UnityEngine.EventSystems; namespace Hummingbird.SeaBattle.Controller.CameraControll { public class HandleInputInViewPortRect : MonoBehaviour { public float MatchHeight; public float DisplayWidth; public Camera Camera; public HandleCameraAction CameraActionCtrl; [NoToLua] public Action<Vector3> OnTouchScreenAction; private bool handle = true; [NoToLua] public bool IsIgnoreGUI; private int fingerTouch = 1; private Vector2 oneFingerTouchPos = Vector2.zero; private Vector2 twoFingerTouchPos = Vector2.zero; public void CutViewPortRect(float displayWidth, float rectYRatio, float rectHeightRatio) { this.cutWithMatchHeight(displayWidth, rectYRatio, rectHeightRatio); } public void Handle(bool isHandle) { this.handle = isHandle; } [NoToLua] public void HandleTouchAction() { if (this.CameraActionCtrl != null) { this.CameraActionCtrl.TouchScreen(this.getGetTouchPos(Input.GetTouch(0).position)); } } private void Awake() { this.cutWithMatchHeight(this.DisplayWidth, 0f, 1f); } private void Update() { if (this.fingerTouch == 1) { base.StartCoroutine(this.holdHandle()); return; } if (!this.IsIgnoreGUI && this.touchUgui()) { return; } if (!Util.GetCanTouch()) { return; } this.phoneHandleInput(); } [DebuggerHidden] private IEnumerator holdHandle() { HandleInputInViewPortRect.<holdHandle>c__Iterator4 <holdHandle>c__Iterator = new HandleInputInViewPortRect.<holdHandle>c__Iterator4(); <holdHandle>c__Iterator.<>f__this = this; return <holdHandle>c__Iterator; } private void phoneHandleInput() { if (Input.touchCount > 0) { TouchPhase phase = Input.GetTouch(0).phase; if (Input.touchCount > 1 && this.checkScreenPointInViewPortRect(this.getGetTouchPos(Input.GetTouch(0).position)) && this.checkScreenPointInViewPortRect(this.getGetTouchPos(Input.GetTouch(1).position)) && this.handle) { if (phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved) { this.fingerTouch = 4; if (this.isEnlarge(this.oneFingerTouchPos, this.twoFingerTouchPos, Input.GetTouch(0).position, Input.GetTouch(1).position)) { if (this.CameraActionCtrl != null) { this.CameraActionCtrl.Pinch(true); } } else if (this.CameraActionCtrl != null) { this.CameraActionCtrl.Pinch(false); } this.oneFingerTouchPos = Input.GetTouch(0).position; this.twoFingerTouchPos = Input.GetTouch(1).position; } } else if (this.fingerTouch != 4 && Input.touchCount == 1) { if (this.fingerTouch != 3 && (phase == TouchPhase.Stationary || phase == TouchPhase.Began) && this.checkScreenPointInViewPortRect(this.getGetTouchPos(Input.GetTouch(0).position))) { this.fingerTouch = 2; this.oneFingerTouchPos = Input.GetTouch(0).position; } else if (phase == TouchPhase.Moved && this.checkScreenPointInViewPortRect(this.getGetTouchPos(Input.GetTouch(0).position)) && this.handle) { if (Vector2.Distance(this.oneFingerTouchPos, Input.GetTouch(0).position) > 50f) { this.fingerTouch = 3; if (this.CameraActionCtrl != null) { this.CameraActionCtrl.Move(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")); } this.oneFingerTouchPos = Input.GetTouch(0).position; } } else if (phase == TouchPhase.Ended || phase == TouchPhase.Canceled) { if (this.fingerTouch == 2) { if (this.CameraActionCtrl != null) { this.CameraActionCtrl.TouchScreen(this.getGetTouchPos(Input.GetTouch(0).position)); } if (this.OnTouchScreenAction != null) { this.OnTouchScreenAction(this.getGetTouchPos(Input.GetTouch(0).position)); } } else if (this.fingerTouch == 3) { } this.fingerTouch = 1; } } else if (this.fingerTouch == 4) { this.fingerTouch = 1; this.oneFingerTouchPos = Vector2.zero; this.twoFingerTouchPos = Vector2.zero; } } } private Vector3 getGetTouchPos(Vector2 tPos) { return Vector3.right * tPos.x + Vector3.up * tPos.y; } private bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2) { float num = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y)); float num2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y)); return num < num2; } private void cutWithMatchHeight(float displayWidth, float rectYRatio, float rectHeightRatio) { if (this.Camera && this.MatchHeight > 0f && displayWidth > 0f) { float num = (float)Screen.width * 1f / ((float)Screen.height * 1f); float num2 = this.MatchHeight * num; float num3 = displayWidth / num2; float num4 = (1f - num3) / 2f; num4 = ((num4 >= 0f && num4 <= 1f) ? num4 : 0f); this.Camera.rect = new Rect(num4, rectYRatio, 1f - num4 * 2f, rectHeightRatio); } } private bool checkScreenPointInViewPortRect(Vector3 screenPoint) { if (this.Camera) { float num = this.Camera.rect.x * (float)Screen.width * 1f; float num2 = (this.Camera.rect.x + this.Camera.rect.width) * (float)Screen.width * 1f; float num3 = this.Camera.rect.y * (float)Screen.height * 1f; float num4 = (this.Camera.rect.y + this.Camera.rect.height) * (float)Screen.height * 1f; return screenPoint.x >= num && screenPoint.x <= num2 && screenPoint.y >= num3 && screenPoint.y <= num4; } return false; } private bool touchUgui() { return EventSystem.current && (Input.touchCount == 0 || this.IsPointerOverUIObject()); } private bool IsPointerOverUIObject() { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); List<RaycastResult> list = new List<RaycastResult>(); EventSystem.current.RaycastAll(pointerEventData, list); return list.Count > 0; } } }
29.559242
220
0.669232
[ "MIT" ]
moto2002/wudihanghai
src/Hummingbird.SeaBattle.Controller.CameraControll/HandleInputInViewPortRect.cs
6,237
C#
// ----------------------------------------------------------------------------------------- // <copyright file="SharedAccessQueuePolicies.cs" company="Microsoft"> // Copyright 2013 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. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Queue { using Microsoft.WindowsAzure.Storage.Core.Util; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents the collection of shared access policies defined for a queue. /// </summary> [SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Public APIs should not expose base collection types.")] public sealed class SharedAccessQueuePolicies : IDictionary<string, SharedAccessQueuePolicy> { private Dictionary<string, SharedAccessQueuePolicy> policies = new Dictionary<string, SharedAccessQueuePolicy>(); /// <summary> /// Adds the specified key and <see cref="SharedAccessQueuePolicy"/> value to the collection of shared access policies. /// </summary> /// <param name="key">A string containing the key of the <see cref="SharedAccessQueuePolicy"/> value to add.</param> /// <param name="value">The <see cref="SharedAccessQueuePolicy"/> value to add the collection of shared access policies.</param> public void Add(string key, SharedAccessQueuePolicy value) { this.policies.Add(key, value); } /// <summary> /// Determines whether the collection of shared access policies contains the specified key. /// </summary> /// <param name="key">A string containing the key to locate in the collection of shared access policies.</param> /// <returns><c>true</c> if the collection of shared access policies contains an element with the specified key; otherwise, <c>false</c>.</returns> public bool ContainsKey(string key) { return this.policies.ContainsKey(key); } /// <summary> /// Gets a collection containing the keys in the shared access policies collection. /// </summary> /// <value>A collection of strings containing the keys of the shared access policies collection.</value> public ICollection<string> Keys { get { return this.policies.Keys; } } /// <summary> /// Removes the value with the specified key from the shared access policies collection. /// </summary> /// <param name="key">A string containing the key of the <see cref="SharedAccessQueuePolicy"/> item to remove.</param> /// <returns><c>true</c> if the element is successfully found and removed; otherwise, <c>false</c>. This method returns <c>false</c> if the key is not found.</returns> public bool Remove(string key) { return this.policies.Remove(key); } /// <summary> /// Gets the <see cref="SharedAccessQueuePolicy"/> item associated with the specified key. /// </summary> /// <param name="key">A string containing the key of the value to get.</param> /// <param name="value">The <see cref="SharedAccessQueuePolicy"/> item to get.</param> /// <returns>The <see cref="SharedAccessQueuePolicy"/> item associated with the specified key, if the key is found; otherwise, the default value for the <see cref="SharedAccessQueuePolicy"/> type.</returns> public bool TryGetValue(string key, out SharedAccessQueuePolicy value) { return this.policies.TryGetValue(key, out value); } /// <summary> /// Gets a collection containing the values in the shared access policies collection. /// </summary> /// <value>A collection of <see cref="SharedAccessQueuePolicy"/> items in the shared access policies collection.</value> public ICollection<SharedAccessQueuePolicy> Values { get { return this.policies.Values; } } /// <summary> /// Gets or sets the <see cref="SharedAccessQueuePolicy"/> item associated with the specified key. /// </summary> /// <param name="key">A string containing the key of the value to get or set.</param> /// <returns>The <see cref="SharedAccessQueuePolicy"/> item associated with the specified key, or <c>null</c> if key is not in the shared access policies collection.</returns> public SharedAccessQueuePolicy this[string key] { get { return this.policies[key]; } set { this.policies[key] = value; } } /// <summary> /// Adds the specified key/<see cref="SharedAccessQueuePolicy"/> value, stored in a <see cref="KeyValuePair{TKey,TValue}"/>, to the collection of shared access policies. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> object, containing a key/<see cref="SharedAccessQueuePolicy"/> value pair, to add to the shared access policies collection.</param> public void Add(KeyValuePair<string, SharedAccessQueuePolicy> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all keys and <see cref="SharedAccessQueuePolicy"/> values from the shared access collection. /// </summary> public void Clear() { this.policies.Clear(); } /// <summary> /// Determines whether the collection of shared access policies contains the key and <see cref="SharedAccessQueuePolicy"/> value in the specified <see cref="KeyValuePair{TKey,TValue}"/> object. /// </summary> /// <param name="item">A <see cref="KeyValuePair{TKey,TValue}"/> object containing the key and <see cref="SharedAccessQueuePolicy"/> value to search for.</param> /// <returns><c>true</c> if the shared access policies collection contains the specified key/value; otherwise, <c>false</c>.</returns> public bool Contains(KeyValuePair<string, SharedAccessQueuePolicy> item) { SharedAccessQueuePolicy storedItem; if (this.TryGetValue(item.Key, out storedItem)) { if (string.Equals( SharedAccessQueuePolicy.PermissionsToString(item.Value.Permissions), SharedAccessQueuePolicy.PermissionsToString(storedItem.Permissions), StringComparison.Ordinal)) { return true; } } return false; } /// <summary> /// Copies each key/<see cref="SharedAccessQueuePolicy"/> value pair in the shared access policies collection to a compatible one-dimensional array, starting at the specified index of the target array. /// </summary> /// <param name="array">The one-dimensional array of <see cref="SharedAccessQueuePolicy"/> objects that is the destination of the elements copied from the shared access policies collection.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> public void CopyTo(KeyValuePair<string, SharedAccessQueuePolicy>[] array, int arrayIndex) { CommonUtility.AssertNotNull("array", array); foreach (KeyValuePair<string, SharedAccessQueuePolicy> item in this.policies) { array[arrayIndex++] = item; } } /// <summary> /// Gets the number of key/<see cref="SharedAccessQueuePolicy"/> value pairs contained in the shared access policies collection. /// </summary> /// <value>The number of key/<see cref="SharedAccessQueuePolicy"/> value pairs contained in the shared access policies collection.</value> public int Count { get { return this.policies.Count; } } /// <summary> /// Gets a value indicating whether the collection of shared access policies is read-only. /// </summary> /// <value><c>true</c> if the collection of shared access policies is read-only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the <see cref="SharedAccessQueuePolicy"/> value, specified in the <see cref="KeyValuePair{TKey,TValue}"/> object, from the shared access policies collection. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> object, containing a key and <see cref="SharedAccessQueuePolicy"/> value, to remove from the shared access policies collection.</param> /// <returns><c>true</c> if the item was successfully removed; otherwise, <c>false</c>.</returns> public bool Remove(KeyValuePair<string, SharedAccessQueuePolicy> item) { if (this.Contains(item)) { return this.Remove(item.Key); } else { return false; } } /// <summary> /// Returns an enumerator that iterates through the collection of shared access policies. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> of type <see cref="KeyValuePair{TKey,TValue}"/>.</returns> public IEnumerator<KeyValuePair<string, SharedAccessQueuePolicy>> GetEnumerator() { return this.policies.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection of shared access policies. /// </summary> /// <returns>An <see cref="System.Collections.IEnumerator"/> object that can be used to iterate through the collection of shared access policies.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { System.Collections.IEnumerable enumerable = this.policies; return enumerable.GetEnumerator(); } } }
47.179487
214
0.613043
[ "Apache-2.0" ]
Hitcents/azure-storage-net
Lib/Common/Queue/SharedAccessQueuePolicies.cs
11,042
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("_02.InternationalEmployees")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("_02.InternationalEmployees")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("7933f906-6506-424e-8167-5dc110ca554d")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.472222
84
0.752347
[ "MIT" ]
TeeeeeC/TelerikAcademy2015-2016
05. CSS/01. Overview/02. InternationalEmployees/Properties/AssemblyInfo.cs
1,388
C#
using Dfc.ProviderPortal.Apprenticeships.Models; using System; using System.Collections.Generic; using System.Text; namespace Dfc.ProviderPortal.Apprenticeships.Interfaces.Helper { public interface IReferenceDataServiceWrapper { IEnumerable<FeChoice> GetFeChoicesByUKPRN(string UKPRN); } }
24
64
0.791667
[ "MIT" ]
SkillsFundingAgency/dfc-providerportal-apprenticeships
src/Dfc.ProviderPortal.Apprenticeships/Interfaces/Helper/IReferenceDataServiceWrapper.cs
314
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ComsumerSite.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
19.3
67
0.564767
[ "Apache-2.0" ]
antonjefcoate/JustSaying.Examples.Orderprocessing
exercise 1/ComsumerSite/Controllers/HomeController.cs
581
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("SherlockandSquares")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SherlockandSquares")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("c6112375-8677-46f6-9334-fd739106f281")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.747339
[ "MIT" ]
mikhaelmurmur/HackerRank.com.Tasks
Algo/Implementation/SherlockandSquares/SherlockandSquares/Properties/AssemblyInfo.cs
1,412
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PVPNetConnect.RiotObjects; using PVPNetConnect.RiotObjects.Leagues.Pojo; using PVPNetConnect.RiotObjects.Platform.Catalog.Champion; using PVPNetConnect.RiotObjects.Platform.Clientfacade.Domain; using PVPNetConnect.RiotObjects.Platform.Game; using PVPNetConnect.RiotObjects.Platform.Game.Practice; using PVPNetConnect.RiotObjects.Platform.Harassment; using PVPNetConnect.RiotObjects.Platform.Leagues.Client.Dto; using PVPNetConnect.RiotObjects.Platform.Login; using PVPNetConnect.RiotObjects.Platform.Matchmaking; using PVPNetConnect.RiotObjects.Platform.Reroll.Pojo; using PVPNetConnect.RiotObjects.Platform.Statistics; using PVPNetConnect.RiotObjects.Platform.Statistics.Team; using PVPNetConnect.RiotObjects.Platform.Summoner; using PVPNetConnect.RiotObjects.Platform.Summoner.Boost; using PVPNetConnect.RiotObjects.Platform.Summoner.Masterybook; using PVPNetConnect.RiotObjects.Platform.Summoner.Runes; using PVPNetConnect.RiotObjects.Platform.Summoner.Spellbook; using PVPNetConnect.RiotObjects.Team; using PVPNetConnect.RiotObjects.Team.Dto; namespace PVPNetConnect { public partial class PVPNetConnection { /// 0.) private void Login(AuthenticationCredentials arg0, Session.Callback callback) { Session cb = new Session(callback); InvokeWithCallback("loginService", "login", new object[] { arg0.GetBaseTypedObject() }, cb); } private async Task<Session> Login(AuthenticationCredentials arg0) { int Id = Invoke("loginService", "login", new object[] { arg0.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); Session result = new Session(messageBody); results.Remove(Id); return result; } public async Task<object> Subscribe(string service, double accountId) { TypedObject body = WrapBody(new TypedObject(), "messagingDestination", 0); body.type = "flex.messaging.messages.CommandMessage"; TypedObject headers = body.GetTO("headers"); if (service == "bc") headers.Add("DSSubtopic", "bc"); else headers.Add("DSSubtopic", service + "-" + accountID); headers.Remove("DSRequestTimeout"); body["clientId"] = service + "-" + accountID; int Id = Invoke(body); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject result = GetResult(Id); // Read result and discard return null; } /// 1.) public void GetLoginDataPacketForUser(LoginDataPacket.Callback callback) { LoginDataPacket cb = new LoginDataPacket(callback); InvokeWithCallback("clientFacadeService", "getLoginDataPacketForUser", new object[] { }, cb); } public async Task<LoginDataPacket> GetLoginDataPacketForUser() { int Id = Invoke("clientFacadeService", "getLoginDataPacketForUser", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); LoginDataPacket result = new LoginDataPacket(messageBody); results.Remove(Id); return result; } /// 2.) public async Task<GameQueueConfig[]> GetAvailableQueues() { int Id = Invoke("matchmakerService", "getAvailableQueues", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); GameQueueConfig[] result = new GameQueueConfig[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new GameQueueConfig((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } /// 3.) public void GetSumonerActiveBoosts(SummonerActiveBoostsDTO.Callback callback) { SummonerActiveBoostsDTO cb = new SummonerActiveBoostsDTO(callback); InvokeWithCallback("inventoryService", "getSumonerActiveBoosts", new object[] { }, cb); } public async Task<SummonerActiveBoostsDTO> GetSumonerActiveBoosts() { int Id = Invoke("inventoryService", "getSumonerActiveBoosts", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerActiveBoostsDTO result = new SummonerActiveBoostsDTO(messageBody); results.Remove(Id); return result; } /// 4.) public async Task<ChampionDTO[]> GetAvailableChampions() { int Id = Invoke("inventoryService", "getAvailableChampions", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); ChampionDTO[] result = new ChampionDTO[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new ChampionDTO((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } /// 5.) public void GetSummonerRuneInventory(Double summonerId, SummonerRuneInventory.Callback callback) { SummonerRuneInventory cb = new SummonerRuneInventory(callback); InvokeWithCallback("summonerRuneService", "getSummonerRuneInventory", new object[] { summonerId }, cb); } public async Task<SummonerRuneInventory> GetSummonerRuneInventory(Double summonerId) { int Id = Invoke("summonerRuneService", "getSummonerRuneInventory", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerRuneInventory result = new SummonerRuneInventory(messageBody); results.Remove(Id); return result; } /// 6.) public async Task<String> PerformLCDSHeartBeat(Int32 arg0, String arg1, Int32 arg2, String arg3) { int Id = Invoke("loginService", "performLCDSHeartBeat", new object[] { arg0, arg1, arg2, arg3 }); while (!results.ContainsKey(Id)) await Task.Delay(10); String result = (String)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 7.) public void GetMyLeaguePositions(SummonerLeagueItemsDTO.Callback callback) { SummonerLeagueItemsDTO cb = new SummonerLeagueItemsDTO(callback); InvokeWithCallback("leaguesServiceProxy", "getMyLeaguePositions", new object[] { }, cb); } public async Task<SummonerLeagueItemsDTO> GetMyLeaguePositions() { int Id = Invoke("leaguesServiceProxy", "getMyLeaguePositions", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerLeagueItemsDTO result = new SummonerLeagueItemsDTO(messageBody); results.Remove(Id); return result; } /// 8.) public async Task<object> LoadPreferencesByKey(String arg0, Double arg1, Boolean arg2) { int Id = Invoke("playerPreferencesService", "loadPreferencesByKey", new object[] { arg0, arg1, arg2 }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 9.) public void GetMasteryBook(Double summonerId, MasteryBookDTO.Callback callback) { MasteryBookDTO cb = new MasteryBookDTO(callback); InvokeWithCallback("masteryBookService", "getMasteryBook", new object[] { summonerId }, cb); } public async Task<MasteryBookDTO> GetMasteryBook(Double summonerId) { int Id = Invoke("masteryBookService", "getMasteryBook", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); MasteryBookDTO result = new MasteryBookDTO(messageBody); results.Remove(Id); return result; } /// 10.) public void CreatePlayer(PlayerDTO.Callback callback) { PlayerDTO cb = new PlayerDTO(callback); InvokeWithCallback("summonerTeamService", "createPlayer", new object[] { }, cb); } public async Task<PlayerDTO> CreatePlayer() { int Id = Invoke("summonerTeamService", "createPlayer", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PlayerDTO result = new PlayerDTO(messageBody); results.Remove(Id); return result; } /// 11.) public async Task<String[]> GetSummonerNames(Double[] summonerIds) { int Id = Invoke("summonerService", "getSummonerNames", new object[] { summonerIds.Cast<object>().ToArray() }); while (!results.ContainsKey(Id)) await Task.Delay(10); String[] result = new String[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = (String)results[Id].GetTO("data").GetArray("body")[i]; } results.Remove(Id); return result; } /// 12.) public void GetChallengerLeague(String queueType, LeagueListDTO.Callback callback) { LeagueListDTO cb = new LeagueListDTO(callback); InvokeWithCallback("leaguesServiceProxy", "getChallengerLeague", new object[] { queueType }, cb); } public async Task<LeagueListDTO> GetChallengerLeague(String queueType) { int Id = Invoke("leaguesServiceProxy", "getChallengerLeague", new object[] { queueType }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); LeagueListDTO result = new LeagueListDTO(messageBody); results.Remove(Id); return result; } /// 13.) public void GetAllMyLeagues(SummonerLeaguesDTO.Callback callback) { SummonerLeaguesDTO cb = new SummonerLeaguesDTO(callback); InvokeWithCallback("leaguesServiceProxy", "getAllMyLeagues", new object[] { }, cb); } public async Task<SummonerLeaguesDTO> GetAllMyLeagues() { int Id = Invoke("leaguesServiceProxy", "getAllMyLeagues", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerLeaguesDTO result = new SummonerLeaguesDTO(messageBody); results.Remove(Id); return result; } /// 14.) public void GetAllSummonerDataByAccount(Double accountId, AllSummonerData.Callback callback) { AllSummonerData cb = new AllSummonerData(callback); InvokeWithCallback("summonerService", "getAllSummonerDataByAccount", new object[] { accountId }, cb); } public async Task<AllSummonerData> GetAllSummonerDataByAccount(Double accountId) { int Id = Invoke("summonerService", "getAllSummonerDataByAccount", new object[] { accountId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); AllSummonerData result = new AllSummonerData(messageBody); results.Remove(Id); return result; } /// 15.) public void GetPointsBalance(PointSummary.Callback callback) { PointSummary cb = new PointSummary(callback); InvokeWithCallback("lcdsRerollService", "getPointsBalance", new object[] { }, cb); } public async Task<PointSummary> GetPointsBalance() { int Id = Invoke("lcdsRerollService", "getPointsBalance", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PointSummary result = new PointSummary(messageBody); results.Remove(Id); return result; } /// 16.) public async Task<String> GetSummonerIcons(Double[] summonerIds) { int Id = Invoke("summonerService", "getSummonerIcons", new object[] { summonerIds.Cast<object>().ToArray() }); while (!results.ContainsKey(Id)) await Task.Delay(10); String result = (String)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 17.) public void CallKudos(String arg0, LcdsResponseString.Callback callback) { LcdsResponseString cb = new LcdsResponseString(callback); InvokeWithCallback("clientFacadeService", "callKudos", new object[] { arg0 }, cb); } public async Task<LcdsResponseString> CallKudos(String arg0) { int Id = Invoke("clientFacadeService", "callKudos", new object[] { arg0 }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); LcdsResponseString result = new LcdsResponseString(messageBody); results.Remove(Id); return result; } /// 18.) public void RetrievePlayerStatsByAccountId(Double accountId, String season, PlayerLifetimeStats.Callback callback) { PlayerLifetimeStats cb = new PlayerLifetimeStats(callback); InvokeWithCallback("playerStatsService", "retrievePlayerStatsByAccountId", new object[] { accountId, season }, cb); } public async Task<PlayerLifetimeStats> RetrievePlayerStatsByAccountId(Double accountId, String season) { int Id = Invoke("playerStatsService", "retrievePlayerStatsByAccountId", new object[] { accountId, season }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PlayerLifetimeStats result = new PlayerLifetimeStats(messageBody); results.Remove(Id); return result; } /// 19.) public async Task<ChampionStatInfo[]> RetrieveTopPlayedChampions(Double accountId, String gameMode) { int Id = Invoke("playerStatsService", "retrieveTopPlayedChampions", new object[] { accountId, gameMode }); while (!results.ContainsKey(Id)) await Task.Delay(10); ChampionStatInfo[] result = new ChampionStatInfo[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new ChampionStatInfo((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } /// 20.) public void GetSummonerByName(String summonerName, PublicSummoner.Callback callback) { PublicSummoner cb = new PublicSummoner(callback); InvokeWithCallback("summonerService", "getSummonerByName", new object[] { summonerName }, cb); } public async Task<PublicSummoner> GetSummonerByName(String summonerName) { int Id = Invoke("summonerService", "getSummonerByName", new object[] { summonerName }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PublicSummoner result = new PublicSummoner(messageBody); results.Remove(Id); return result; } /// 21.) public void GetAggregatedStats(Double summonerId, String gameMode, String season, AggregatedStats.Callback callback) { AggregatedStats cb = new AggregatedStats(callback); InvokeWithCallback("playerStatsService", "getAggregatedStats", new object[] { summonerId, gameMode, season }, cb); } public async Task<AggregatedStats> GetAggregatedStats(Double summonerId, String gameMode, String season) { int Id = Invoke("playerStatsService", "getAggregatedStats", new object[] { summonerId, gameMode, season }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); AggregatedStats result = new AggregatedStats(messageBody); results.Remove(Id); return result; } /// 22.) public void GetRecentGames(Double accountId, RecentGames.Callback callback) { RecentGames cb = new RecentGames(callback); InvokeWithCallback("playerStatsService", "getRecentGames", new object[] { accountId }, cb); } public async Task<RecentGames> GetRecentGames(Double accountId) { int Id = Invoke("playerStatsService", "getRecentGames", new object[] { accountId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); RecentGames result = new RecentGames(messageBody); results.Remove(Id); return result; } /// 23.) public void FindTeamById(TeamId teamId, TeamDTO.Callback callback) { TeamDTO cb = new TeamDTO(callback); InvokeWithCallback("summonerTeamService", "findTeamById", new object[] { teamId.GetBaseTypedObject() }, cb); } public async Task<TeamDTO> FindTeamById(TeamId teamId) { int Id = Invoke("summonerTeamService", "findTeamById", new object[] { teamId.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); TeamDTO result = new TeamDTO(messageBody); results.Remove(Id); return result; } /// 24.) public void GetLeaguesForTeam(String teamName, SummonerLeaguesDTO.Callback callback) { SummonerLeaguesDTO cb = new SummonerLeaguesDTO(callback); InvokeWithCallback("leaguesServiceProxy", "getLeaguesForTeam", new object[] { teamName }, cb); } public async Task<SummonerLeaguesDTO> GetLeaguesForTeam(String teamName) { int Id = Invoke("leaguesServiceProxy", "getLeaguesForTeam", new object[] { teamName }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerLeaguesDTO result = new SummonerLeaguesDTO(messageBody); results.Remove(Id); return result; } /// 25.) public async Task<TeamAggregatedStatsDTO[]> GetTeamAggregatedStats(TeamId arg0) { int Id = Invoke("playerStatsService", "getTeamAggregatedStats", new object[] { arg0.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TeamAggregatedStatsDTO[] result = new TeamAggregatedStatsDTO[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new TeamAggregatedStatsDTO((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } /// 26.) public void GetTeamEndOfGameStats(TeamId arg0, Double arg1, EndOfGameStats.Callback callback) { EndOfGameStats cb = new EndOfGameStats(callback); InvokeWithCallback("playerStatsService", "getTeamEndOfGameStats", new object[] { arg0.GetBaseTypedObject(), arg1 }, cb); } public async Task<EndOfGameStats> GetTeamEndOfGameStats(TeamId arg0, Double arg1) { int Id = Invoke("playerStatsService", "getTeamEndOfGameStats", new object[] { arg0.GetBaseTypedObject(), arg1 }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); EndOfGameStats result = new EndOfGameStats(messageBody); results.Remove(Id); return result; } /// 27.) public async Task<object> DisbandTeam(TeamId teamId) { int Id = Invoke("summonerTeamService", "disbandTeam", new object[] { teamId.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 28.) public async Task<Boolean> IsNameValidAndAvailable(String teamName) { int Id = Invoke("summonerTeamService", "isNameValidAndAvailable", new object[] { teamName }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 29.) public async Task<Boolean> IsTagValidAndAvailable(String tagName) { int Id = Invoke("summonerTeamService", "isTagValidAndAvailable", new object[] { tagName }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 30.) public void CreateTeam(String teamName, String tagName, TeamDTO.Callback callback) { TeamDTO cb = new TeamDTO(callback); InvokeWithCallback("summonerTeamService", "createTeam", new object[] { teamName, tagName }, cb); } public async Task<TeamDTO> CreateTeam(String teamName, String tagName) { int Id = Invoke("summonerTeamService", "createTeam", new object[] { teamName, tagName }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); TeamDTO result = new TeamDTO(messageBody); results.Remove(Id); return result; } /// 31.) public void InvitePlayer(Double summonerId, TeamId teamId, TeamDTO.Callback callback) { TeamDTO cb = new TeamDTO(callback); InvokeWithCallback("summonerTeamService", "invitePlayer", new object[] { summonerId, teamId.GetBaseTypedObject() }, cb); } public async Task<TeamDTO> InvitePlayer(Double summonerId, TeamId teamId) { int Id = Invoke("summonerTeamService", "invitePlayer", new object[] { summonerId, teamId.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); TeamDTO result = new TeamDTO(messageBody); results.Remove(Id); return result; } /// 32.) public void KickPlayer(Double summonerId, TeamId teamId, TeamDTO.Callback callback) { TeamDTO cb = new TeamDTO(callback); InvokeWithCallback("summonerTeamService", "kickPlayer", new object[] { summonerId, teamId.GetBaseTypedObject() }, cb); } public async Task<TeamDTO> KickPlayer(Double summonerId, TeamId teamId) { int Id = Invoke("summonerTeamService", "kickPlayer", new object[] { summonerId, teamId.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); TeamDTO result = new TeamDTO(messageBody); results.Remove(Id); return result; } /// 33.) public void GetAllLeaguesForPlayer(Double summonerId, SummonerLeaguesDTO.Callback callback) { SummonerLeaguesDTO cb = new SummonerLeaguesDTO(callback); InvokeWithCallback("leaguesServiceProxy", "getAllLeaguesForPlayer", new object[] { summonerId }, cb); } public async Task<SummonerLeaguesDTO> GetAllLeaguesForPlayer(Double summonerId) { int Id = Invoke("leaguesServiceProxy", "getAllLeaguesForPlayer", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SummonerLeaguesDTO result = new SummonerLeaguesDTO(messageBody); results.Remove(Id); return result; } /// 34.) public void GetAllPublicSummonerDataByAccount(Double accountId, AllPublicSummonerDataDTO.Callback callback) { AllPublicSummonerDataDTO cb = new AllPublicSummonerDataDTO(callback); InvokeWithCallback("summonerService", "getAllPublicSummonerDataByAccount", new object[] { accountId }, cb); } public async Task<AllPublicSummonerDataDTO> GetAllPublicSummonerDataByAccount(Double accountId) { int Id = Invoke("summonerService", "getAllPublicSummonerDataByAccount", new object[] { accountId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); AllPublicSummonerDataDTO result = new AllPublicSummonerDataDTO(messageBody); results.Remove(Id); return result; } /// 35.) public void FindPlayer(Double summonerId, PlayerDTO.Callback callback) { PlayerDTO cb = new PlayerDTO(callback); InvokeWithCallback("summonerTeamService", "findPlayer", new object[] { summonerId }, cb); } public async Task<PlayerDTO> FindPlayer(Double summonerId) { int Id = Invoke("summonerTeamService", "findPlayer", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PlayerDTO result = new PlayerDTO(messageBody); results.Remove(Id); return result; } /// 36.) public void GetSpellBook(Double summonerId, SpellBookDTO.Callback callback) { SpellBookDTO cb = new SpellBookDTO(callback); InvokeWithCallback("spellBookService", "getSpellBook", new object[] { summonerId }, cb); } public async Task<SpellBookDTO> GetSpellBook(Double summonerId) { int Id = Invoke("spellBookService", "getSpellBook", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SpellBookDTO result = new SpellBookDTO(messageBody); results.Remove(Id); return result; } /// 37.) public void AttachToQueue(MatchMakerParams matchMakerParams, SearchingForMatchNotification.Callback callback) { SearchingForMatchNotification cb = new SearchingForMatchNotification(callback); InvokeWithCallback("matchmakerService", "attachToQueue", new object[] { matchMakerParams.GetBaseTypedObject() }, cb); } public async Task<SearchingForMatchNotification> AttachToQueue(MatchMakerParams matchMakerParams) { int Id = Invoke("matchmakerService", "attachToQueue", new object[] { matchMakerParams.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SearchingForMatchNotification result = new SearchingForMatchNotification(messageBody); results.Remove(Id); return result; } /// 38.) public async Task<Boolean> CancelFromQueueIfPossible(Double summonerId) { int Id = Invoke("matchmakerService", "cancelFromQueueIfPossible", new object[] { summonerId }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 39.) public async Task<String> GetStoreUrl() { int Id = Invoke("loginService", "getStoreUrl", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); String result = (String)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 40.) public async Task<PracticeGameSearchResult[]> ListAllPracticeGames() { int Id = Invoke("gameService", "listAllPracticeGames", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); PracticeGameSearchResult[] result = new PracticeGameSearchResult[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new PracticeGameSearchResult((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } /// 41.) /// public async Task<object> JoinGame(Double gameId) { int Id = Invoke("gameService", "joinGame", new object[] { gameId, null }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> JoinGame(Double gameId, string password) { int Id = Invoke("gameService", "joinGame", new object[] { gameId, password }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> ObserveGame(Double gameId) { int Id = Invoke("gameService", "observeGame", new object[] { gameId, null }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> ObserveGame(Double gameId, string password) { int Id = Invoke("gameService", "observeGame", new object[] { gameId, password }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 42.) public async Task<String> GetSummonerInternalNameByName(String summonerName) { int Id = Invoke("summonerService", "getSummonerInternalNameByName", new object[] { summonerName }); while (!results.ContainsKey(Id)) await Task.Delay(10); String result = (String)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 43.) public async Task<Boolean> SwitchTeams(Double gameId) { int Id = Invoke("gameService", "switchTeams", new object[] { gameId }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 44.) public async Task<Boolean> SwitchPlayerToObserver(Double gameId) { int Id = Invoke("gameService", "switchPlayerToObserver", new object[] { gameId }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 44.) public async Task<Boolean> SwitchObserverToPlayer(Double gameId, Int32 team) { int Id = Invoke("gameService", "switchObserverToPlayer", new object[] { gameId, team }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } /// 45.) public async Task<object> QuitGame() { int Id = Invoke("gameService", "quitGame", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 46.) public void CreatePracticeGame(PracticeGameConfig practiceGameConfig, GameDTO.Callback callback) { GameDTO cb = new GameDTO(callback); InvokeWithCallback("gameService", "createPracticeGame", new object[] { practiceGameConfig.GetBaseTypedObject() }, cb); } public async Task<GameDTO> CreatePracticeGame(PracticeGameConfig practiceGameConfig) { int Id = Invoke("gameService", "createPracticeGame", new object[] { practiceGameConfig.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); GameDTO result = new GameDTO(messageBody); results.Remove(Id); return result; } /// 47.) public async Task<object> SelectBotChampion(Int32 arg0, BotParticipant arg1) { int Id = Invoke("gameService", "selectBotChampion", new object[] { arg0, arg1.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 48.) public async Task<object> RemoveBotChampion(Int32 arg0, BotParticipant arg1) { int Id = Invoke("gameService", "removeBotChampion", new object[] { arg0, arg1.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 49.) public void StartChampionSelection(Double gameId, Double optomisticLock, StartChampSelectDTO.Callback callback) { StartChampSelectDTO cb = new StartChampSelectDTO(callback); InvokeWithCallback("gameService", "startChampionSelection", new object[] { gameId, optomisticLock }, cb); } public async Task<StartChampSelectDTO> StartChampionSelection(Double gameId, Double optomisticLock) { int Id = Invoke("gameService", "startChampionSelection", new object[] { gameId, optomisticLock }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); StartChampSelectDTO result = new StartChampSelectDTO(messageBody); results.Remove(Id); return result; } /// 50.) public async Task<object> SetClientReceivedGameMessage(Double gameId, String arg1) { int Id = Invoke("gameService", "setClientReceivedGameMessage", new object[] { gameId, arg1 }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 51.) public void GetLatestGameTimerState(Double arg0, String arg1, Int32 arg2, GameDTO.Callback callback) { GameDTO cb = new GameDTO(callback); InvokeWithCallback("gameService", "getLatestGameTimerState", new object[] { arg0, arg1, arg2 }, cb); } public async Task<GameDTO> GetLatestGameTimerState(Double arg0, String arg1, Int32 arg2) { int Id = Invoke("gameService", "getLatestGameTimerState", new object[] { arg0, arg1, arg2 }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); GameDTO result = new GameDTO(messageBody); results.Remove(Id); return result; } /// 52.) public async Task<object> SelectSpells(Int32 spellOneId, Int32 spellTwoId) { int Id = Invoke("gameService", "selectSpells", new object[] { spellOneId, spellTwoId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 53.) public void SelectDefaultSpellBookPage(SpellBookPageDTO spellBookPage, SpellBookPageDTO.Callback callback) { SpellBookPageDTO cb = new SpellBookPageDTO(callback); InvokeWithCallback("spellBookService", "selectDefaultSpellBookPage", new object[] { spellBookPage.GetBaseTypedObject() }, cb); } public async Task<SpellBookPageDTO> SelectDefaultSpellBookPage(SpellBookPageDTO spellBookPage) { int Id = Invoke("spellBookService", "selectDefaultSpellBookPage", new object[] { spellBookPage.GetBaseTypedObject() }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); SpellBookPageDTO result = new SpellBookPageDTO(messageBody); results.Remove(Id); return result; } /// 54.) public async Task<object> SelectChampion(Int32 championId) { int Id = Invoke("gameService", "selectChampion", new object[] { championId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 55.) public async Task<object> SelectChampionSkin(Int32 championId, Int32 skinId) { int Id = Invoke("gameService", "selectChampionSkin", new object[] { championId, skinId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 56.) public async Task<object> ChampionSelectCompleted() { int Id = Invoke("gameService", "championSelectCompleted", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 57.) public async Task<object> SetClientReceivedMaestroMessage(Double arg0, String arg1) { int Id = Invoke("gameService", "setClientReceivedMaestroMessage", new object[] { arg0, arg1 }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } /// 58.) public void RetrieveInProgressSpectatorGameInfo(String summonerName, PlatformGameLifecycleDTO.Callback callback) { PlatformGameLifecycleDTO cb = new PlatformGameLifecycleDTO(callback); InvokeWithCallback("gameService", "retrieveInProgressSpectatorGameInfo", new object[] { summonerName }, cb); } public async Task<PlatformGameLifecycleDTO> RetrieveInProgressSpectatorGameInfo(String summonerName) { int Id = Invoke("gameService", "retrieveInProgressSpectatorGameInfo", new object[] { summonerName }); while (!results.ContainsKey(Id)) await Task.Delay(10); TypedObject messageBody = results[Id].GetTO("data").GetTO("body"); PlatformGameLifecycleDTO result = new PlatformGameLifecycleDTO(messageBody); results.Remove(Id); return result; } /// 59.) public async Task<Boolean> DeclineObserverReconnect() { int Id = Invoke("gameService", "declineObserverReconnect", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); Boolean result = (Boolean)results[Id].GetTO("data")["body"]; results.Remove(Id); return result; } public async Task<object> AcceptInviteForMatchmakingGame(double gameId) { int Id = Invoke("matchmakerService", "acceptInviteForMatchmakingGame", new object[] { gameId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> AcceptPoppedGame(bool accept) { int Id = Invoke("matchmakerService", "acceptInviteForMatchmakingGame", new object[] { accept }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> UpdateProfileIconId(Int32 iconId) { int Id = Invoke("summonerService", "updateProfileIconId", new object[] { iconId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> BanUserFromGame(double gameId, double accountId) { int Id = Invoke("gameService", "banUserFromGame", new object[] { gameId, accountId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> BanObserverFromGame(double gameId, double accountId) { int Id = Invoke("gameService", "banObserverFromGame", new object[] { gameId, accountId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<object> BanChampion(int championId) { int Id = Invoke("gameService", "banChampion", new object[] { championId }); while (!results.ContainsKey(Id)) await Task.Delay(10); results.Remove(Id); return null; } public async Task<ChampionBanInfoDTO[]> GetChampionsForBan() { int Id = Invoke("gameService", "getChampionsForBan", new object[] { }); while (!results.ContainsKey(Id)) await Task.Delay(10); ChampionBanInfoDTO[] result = new ChampionBanInfoDTO[results[Id].GetTO("data").GetArray("body").Length]; for (int i = 0; i < results[Id].GetTO("data").GetArray("body").Length; i++) { result[i] = new ChampionBanInfoDTO((TypedObject)results[Id].GetTO("data").GetArray("body")[i]); } results.Remove(Id); return result; } } }
38.086996
135
0.627405
[ "BSD-2-Clause" ]
t2hv33/LegendaryClient
GitPVP/PublicMethods.cs
42,469
C#
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.ObjectModel; using System.Linq; using Microsoft.WindowsAPI.Resources; namespace Microsoft.WindowsAPI.Dialogs { /// <summary> /// Strongly typed collection for dialog controls. /// </summary> /// <typeparam name="T">DialogControl</typeparam> public sealed class DialogControlCollection<T> : Collection<T> where T : DialogControl { private IDialogControlHost hostingDialog; internal DialogControlCollection(IDialogControlHost host) { hostingDialog = host; } /// <summary> /// Inserts an dialog control at the specified index. /// </summary> /// <param name="index">The location to insert the control.</param> /// <param name="control">The item to insert.</param> /// <permission cref="System.InvalidOperationException">A control with /// the same name already exists in this collection -or- /// the control is being hosted by another dialog -or- the associated dialog is /// showing and cannot be modified.</permission> protected override void InsertItem(int index, T control) { // Check for duplicates, lack of host, // and during-show adds. if (Items.Contains(control)) { throw new InvalidOperationException(LocalizedMessages.DialogCollectionCannotHaveDuplicateNames); } if (control.HostingDialog != null) { throw new InvalidOperationException(LocalizedMessages.DialogCollectionControlAlreadyHosted); } if (!hostingDialog.IsCollectionChangeAllowed()) { throw new InvalidOperationException(LocalizedMessages.DialogCollectionModifyShowingDialog); } // Reparent, add control. control.HostingDialog = hostingDialog; base.InsertItem(index, control); // Notify that we've added a control. hostingDialog.ApplyCollectionChanged(); } /// <summary> /// Removes the control at the specified index. /// </summary> /// <param name="index">The location of the control to remove.</param> /// <permission cref="System.InvalidOperationException"> /// The associated dialog is /// showing and cannot be modified.</permission> protected override void RemoveItem(int index) { // Notify that we're about to remove a control. // Throw if dialog showing. if (!hostingDialog.IsCollectionChangeAllowed()) { throw new InvalidOperationException(LocalizedMessages.DialogCollectionModifyShowingDialog); } DialogControl control = (DialogControl)Items[index]; // Unparent and remove. control.HostingDialog = null; base.RemoveItem(index); hostingDialog.ApplyCollectionChanged(); } /// <summary> /// Defines the indexer that supports accessing controls by name. /// </summary> /// <remarks> /// <para>Control names are case sensitive.</para> /// <para>This indexer is useful when the dialog is created in XAML /// rather than constructed in code.</para></remarks> ///<exception cref="System.ArgumentException"> /// The name cannot be null or a zero-length string.</exception> /// <remarks>If there is more than one control with the same name, only the <B>first control</B> will be returned.</remarks> public T this[string name] { get { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(LocalizedMessages.DialogCollectionControlNameNull, "name"); } return Items.FirstOrDefault(x => x.Name == name); } } /// <summary> /// Searches for the control who's id matches the value /// passed in the <paramref name="id"/> parameter. /// </summary> /// /// <param name="id">An integer containing the identifier of the /// control being searched for.</param> /// /// <returns>A DialogControl who's id matches the value of the /// <paramref name="id"/> parameter.</returns> internal DialogControl GetControlbyId(int id) { return Items.FirstOrDefault(x => x.Id == id); } } }
38.297521
132
0.596461
[ "MIT" ]
shellscape/Shellscape.Common
Microsoft/Windows API/Dialogs/Common/DialogControlCollection.cs
4,634
C#
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System.Collections.Specialized; using NUnit.Framework; using Quartz.Impl; using System; namespace Quartz.Tests.Unit.Impl { /// <summary> /// Tests for StdSchedulerFactory. /// </summary> /// <author>Marko Lahma (.NET)</author> [TestFixture] public class StdSchedulerFactoryTest { [Test] public void TestFactoryCanBeUsedWithNoProperties() { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.GetScheduler(); } [Test] public void TestFactoryCanBeUsedWithEmptyProperties() { StdSchedulerFactory factory = new StdSchedulerFactory(new NameValueCollection()); factory.GetScheduler(); } [Test] public void TestFactoryShouldThrowConfigurationErrorIfUnknownQuartzSetting() { NameValueCollection properties = new NameValueCollection(); properties["quartz.unknown.property"] = "1"; Assert.Throws<SchedulerConfigException>(() => new StdSchedulerFactory(properties), "Unknown configuration property 'quartz.unknown.property'"); } [Test] public void TestFactoryShouldThrowConfigurationErrorIfCaseErrorInQuartzSetting() { NameValueCollection properties = new NameValueCollection(); properties["quartz.jobstore.type"] = ""; Assert.Throws<SchedulerConfigException>(() => new StdSchedulerFactory(properties), "Unknown configuration property 'quartz.jobstore.type'"); } [Test] public void TestFactoryShouldNotThrowConfigurationErrorIfUnknownQuartzSettingAndCheckingTurnedOff() { NameValueCollection properties = new NameValueCollection(); properties["quartz.checkConfiguration"] = "false"; properties["quartz.unknown.property"] = "1"; new StdSchedulerFactory(properties); } [Test] public void TestFactoryShouldNotThrowConfigurationErrorIfNotQuartzPrefixedProperty() { NameValueCollection properties = new NameValueCollection(); properties["my.unknown.property"] = "1"; new StdSchedulerFactory(properties); } [Test] public void TestFactoryShouldOverrideConfigurationWithSysProperties() { NameValueCollection properties = new NameValueCollection(); var factory = new StdSchedulerFactory(); factory.Initialize(); var scheduler = factory.GetScheduler(); Assert.AreEqual("DefaultQuartzScheduler", scheduler.SchedulerName); Environment.SetEnvironmentVariable("quartz.scheduler.instanceName", "fromSystemProperties"); factory = new StdSchedulerFactory(); scheduler = factory.GetScheduler(); Assert.AreEqual("fromSystemProperties", scheduler.SchedulerName); } [Test] public void ShouldAllowInheritingStdSchedulerFactory() { // check that property names are validated through inheritance hierarchy NameValueCollection collection = new NameValueCollection(); collection["quartz.scheduler.idleWaitTime"] = "123"; collection["quartz.scheduler.test"] = "foo"; StdSchedulerFactory factory = new TestStdSchedulerFactory(collection); } private class TestStdSchedulerFactory : StdSchedulerFactory { public const string PropertyTest = "quartz.scheduler.test"; public TestStdSchedulerFactory(NameValueCollection nameValueCollection) : base(nameValueCollection) { } } } }
36.683333
155
0.664925
[ "Apache-2.0" ]
MrChenJH/Quartz.NET
src/Quartz.Tests.Unit/Impl/StdSchedulerFactoryTest.cs
4,402
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.Collections.Immutable; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMargin { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; public InheritanceMargin( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; InitializeComponent(); var viewModel = InheritanceMarginViewModel.Create(classificationTypeMap, classificationFormatMap, tag); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); _operationExecutor.Execute( new UIThreadOperationExecutionOptions( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false), context => GoToDefinitionHelpers.TryGoToDefinition( ImmutableArray.Create(viewModel.DefinitionItem), _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), _threadingContext, _streamingFindUsagesPresenter, context.UserCancellationToken)); } } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { ResetBorderToInitialColor(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Target1 // -> Target2 // -> method Foo -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } } }
43.101449
121
0.640551
[ "MIT" ]
dpvreony/roslyn
src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMargin.xaml.cs
5,950
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.Gcp.Notebooks { /// <summary> /// A Cloud AI Platform Notebook runtime. /// /// &gt; **Note:** Due to limitations of the Notebooks Runtime API, many fields /// in this resource do not properly detect drift. These fields will also not /// appear in state once imported. /// /// To get more information about Runtime, see: /// /// * [API documentation](https://cloud.google.com/ai-platform/notebooks/docs/reference/rest) /// * How-to Guides /// * [Official Documentation](https://cloud.google.com/ai-platform-notebooks) /// /// ## Example Usage /// ### Notebook Runtime Basic /// /// ```csharp /// using Pulumi; /// using Gcp = Pulumi.Gcp; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var runtime = new Gcp.Notebooks.Runtime("runtime", new Gcp.Notebooks.RuntimeArgs /// { /// AccessConfig = new Gcp.Notebooks.Inputs.RuntimeAccessConfigArgs /// { /// AccessType = "SINGLE_USER", /// RuntimeOwner = "[email protected]", /// }, /// Location = "us-central1", /// VirtualMachine = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineArgs /// { /// VirtualMachineConfig = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigArgs /// { /// DataDisk = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskArgs /// { /// InitializeParams = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskInitializeParamsArgs /// { /// DiskSizeGb = 100, /// DiskType = "PD_STANDARD", /// }, /// }, /// MachineType = "n1-standard-4", /// }, /// }, /// }); /// } /// /// } /// ``` /// ### Notebook Runtime Basic Gpu /// /// ```csharp /// using Pulumi; /// using Gcp = Pulumi.Gcp; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var runtimeGpu = new Gcp.Notebooks.Runtime("runtimeGpu", new Gcp.Notebooks.RuntimeArgs /// { /// AccessConfig = new Gcp.Notebooks.Inputs.RuntimeAccessConfigArgs /// { /// AccessType = "SINGLE_USER", /// RuntimeOwner = "[email protected]", /// }, /// Location = "us-central1", /// SoftwareConfig = new Gcp.Notebooks.Inputs.RuntimeSoftwareConfigArgs /// { /// InstallGpuDriver = true, /// }, /// VirtualMachine = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineArgs /// { /// VirtualMachineConfig = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigArgs /// { /// AcceleratorConfig = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigAcceleratorConfigArgs /// { /// CoreCount = 1, /// Type = "NVIDIA_TESLA_V100", /// }, /// DataDisk = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskArgs /// { /// InitializeParams = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskInitializeParamsArgs /// { /// DiskSizeGb = 100, /// DiskType = "PD_STANDARD", /// }, /// }, /// MachineType = "n1-standard-4", /// }, /// }, /// }); /// } /// /// } /// ``` /// ### Notebook Runtime Basic Container /// /// ```csharp /// using Pulumi; /// using Gcp = Pulumi.Gcp; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var runtimeContainer = new Gcp.Notebooks.Runtime("runtimeContainer", new Gcp.Notebooks.RuntimeArgs /// { /// AccessConfig = new Gcp.Notebooks.Inputs.RuntimeAccessConfigArgs /// { /// AccessType = "SINGLE_USER", /// RuntimeOwner = "[email protected]", /// }, /// Location = "us-central1", /// VirtualMachine = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineArgs /// { /// VirtualMachineConfig = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigArgs /// { /// ContainerImages = /// { /// new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigContainerImageArgs /// { /// Repository = "gcr.io/deeplearning-platform-release/base-cpu", /// Tag = "latest", /// }, /// new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigContainerImageArgs /// { /// Repository = "gcr.io/deeplearning-platform-release/beam-notebooks", /// Tag = "latest", /// }, /// }, /// DataDisk = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskArgs /// { /// InitializeParams = new Gcp.Notebooks.Inputs.RuntimeVirtualMachineVirtualMachineConfigDataDiskInitializeParamsArgs /// { /// DiskSizeGb = 100, /// DiskType = "PD_STANDARD", /// }, /// }, /// MachineType = "n1-standard-4", /// }, /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Runtime can be imported using any of these accepted formats /// /// ```sh /// $ pulumi import gcp:notebooks/runtime:Runtime default projects/{{project}}/locations/{{location}}/runtimes/{{name}} /// ``` /// /// ```sh /// $ pulumi import gcp:notebooks/runtime:Runtime default {{project}}/{{location}}/{{name}} /// ``` /// /// ```sh /// $ pulumi import gcp:notebooks/runtime:Runtime default {{location}}/{{name}} /// ``` /// </summary> [GcpResourceType("gcp:notebooks/runtime:Runtime")] public partial class Runtime : Pulumi.CustomResource { /// <summary> /// The config settings for accessing runtime. /// Structure is documented below. /// </summary> [Output("accessConfig")] public Output<Outputs.RuntimeAccessConfig?> AccessConfig { get; private set; } = null!; /// <summary> /// The health state of this runtime. For a list of possible output values, see /// 'https://cloud.google.com/vertex-ai/docs/workbench/ reference/rest/v1/projects.locations.runtimes#healthstate'. /// </summary> [Output("healthState")] public Output<string> HealthState { get; private set; } = null!; /// <summary> /// A reference to the zone where the machine resides. /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Contains Runtime daemon metrics such as Service status and JupyterLab status /// </summary> [Output("metrics")] public Output<ImmutableArray<Outputs.RuntimeMetric>> Metrics { get; private set; } = null!; /// <summary> /// The name specified for the Notebook instance. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The ID of the project in which the resource belongs. /// If it is not provided, the provider project is used. /// </summary> [Output("project")] public Output<string> Project { get; private set; } = null!; /// <summary> /// The config settings for software inside the runtime. /// Structure is documented below. /// </summary> [Output("softwareConfig")] public Output<Outputs.RuntimeSoftwareConfig> SoftwareConfig { get; private set; } = null!; /// <summary> /// The state of this runtime. /// </summary> [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// Use a Compute Engine VM image to start the managed notebook instance. /// Structure is documented below. /// </summary> [Output("virtualMachine")] public Output<Outputs.RuntimeVirtualMachine?> VirtualMachine { get; private set; } = null!; /// <summary> /// Create a Runtime resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Runtime(string name, RuntimeArgs args, CustomResourceOptions? options = null) : base("gcp:notebooks/runtime:Runtime", name, args ?? new RuntimeArgs(), MakeResourceOptions(options, "")) { } private Runtime(string name, Input<string> id, RuntimeState? state = null, CustomResourceOptions? options = null) : base("gcp:notebooks/runtime:Runtime", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Runtime resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Runtime Get(string name, Input<string> id, RuntimeState? state = null, CustomResourceOptions? options = null) { return new Runtime(name, id, state, options); } } public sealed class RuntimeArgs : Pulumi.ResourceArgs { /// <summary> /// The config settings for accessing runtime. /// Structure is documented below. /// </summary> [Input("accessConfig")] public Input<Inputs.RuntimeAccessConfigArgs>? AccessConfig { get; set; } /// <summary> /// A reference to the zone where the machine resides. /// </summary> [Input("location", required: true)] public Input<string> Location { get; set; } = null!; /// <summary> /// The name specified for the Notebook instance. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The ID of the project in which the resource belongs. /// If it is not provided, the provider project is used. /// </summary> [Input("project")] public Input<string>? Project { get; set; } /// <summary> /// The config settings for software inside the runtime. /// Structure is documented below. /// </summary> [Input("softwareConfig")] public Input<Inputs.RuntimeSoftwareConfigArgs>? SoftwareConfig { get; set; } /// <summary> /// Use a Compute Engine VM image to start the managed notebook instance. /// Structure is documented below. /// </summary> [Input("virtualMachine")] public Input<Inputs.RuntimeVirtualMachineArgs>? VirtualMachine { get; set; } public RuntimeArgs() { } } public sealed class RuntimeState : Pulumi.ResourceArgs { /// <summary> /// The config settings for accessing runtime. /// Structure is documented below. /// </summary> [Input("accessConfig")] public Input<Inputs.RuntimeAccessConfigGetArgs>? AccessConfig { get; set; } /// <summary> /// The health state of this runtime. For a list of possible output values, see /// 'https://cloud.google.com/vertex-ai/docs/workbench/ reference/rest/v1/projects.locations.runtimes#healthstate'. /// </summary> [Input("healthState")] public Input<string>? HealthState { get; set; } /// <summary> /// A reference to the zone where the machine resides. /// </summary> [Input("location")] public Input<string>? Location { get; set; } [Input("metrics")] private InputList<Inputs.RuntimeMetricGetArgs>? _metrics; /// <summary> /// Contains Runtime daemon metrics such as Service status and JupyterLab status /// </summary> public InputList<Inputs.RuntimeMetricGetArgs> Metrics { get => _metrics ?? (_metrics = new InputList<Inputs.RuntimeMetricGetArgs>()); set => _metrics = value; } /// <summary> /// The name specified for the Notebook instance. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The ID of the project in which the resource belongs. /// If it is not provided, the provider project is used. /// </summary> [Input("project")] public Input<string>? Project { get; set; } /// <summary> /// The config settings for software inside the runtime. /// Structure is documented below. /// </summary> [Input("softwareConfig")] public Input<Inputs.RuntimeSoftwareConfigGetArgs>? SoftwareConfig { get; set; } /// <summary> /// The state of this runtime. /// </summary> [Input("state")] public Input<string>? State { get; set; } /// <summary> /// Use a Compute Engine VM image to start the managed notebook instance. /// Structure is documented below. /// </summary> [Input("virtualMachine")] public Input<Inputs.RuntimeVirtualMachineGetArgs>? VirtualMachine { get; set; } public RuntimeState() { } } }
40.059406
145
0.530709
[ "ECL-2.0", "Apache-2.0" ]
pjbizon/pulumi-gcp
sdk/dotnet/Notebooks/Runtime.cs
16,184
C#
using Omnius.Core; using Omnius.Lxna.Ui.Desktop.Configuration; namespace Omnius.Lxna.Ui.Desktop.Windows.Main; public abstract class MainWindowModelBase : AsyncDisposableBase { public MainWindowStatus? Status { get; protected set; } public FileExplorerViewModelBase? FileExplorerViewModel { get; protected set; } } public class MainWindowModel : MainWindowModelBase { public MainWindowModel(UiStatus uiStatus, FileExplorerViewModel FileExplorerViewModel) { this.Status = uiStatus.MainWindow ??= new MainWindowStatus(); this.FileExplorerViewModel = FileExplorerViewModel; } protected override async ValueTask OnDisposeAsync() { if (this.FileExplorerViewModel is not null) await this.FileExplorerViewModel.DisposeAsync(); } }
30.153846
100
0.762755
[ "MIT" ]
OmniusLabs/Lxna
src/Omnius.Lxna.Ui.Desktop/Windows/Main/MainWindowModel.cs
784
C#
// Compute Shader #type compute #version 460 layout(local_size_x = 10, local_size_y = 10, local_size_z = 1) in; layout(rgba8, binding = 0) uniform image2D imgOutput; void main() { vec4 value = vec4(1.0, 0.0, 0.0, 1.0); ivec2 texelCoord = ivec2(gl_GlobalInvocationID.xy); imageStore(imgOutput, texelCoord, value); }
24.615385
66
0.721875
[ "Apache-2.0" ]
ErfanMo77/Syndra-Engine
Syndra-Editor/assets/shaders/computeShader.cs
320
C#